AI-powered virtual executive team — a single coherent executive persona backed by 8 specialist agents (FastAPI + Next.js).
feat(workflows): let a workflow email as its creator, as a draft or sent (#600)
Rufus21e14e407eec
diff --git a/.env.example b/.env.exampleindex 5733a391..4a5fbecf 100644--- a/.env.example+++ b/.env.example@@ -460,6 +460,9 @@ WORKSPACE_MCP_TOOL_TIER=complete# Handle it for me (Settings → Act as me): the most replies the inbox watcher# may send on its own as one person per UTC day (1-500), within its drafts limit.# DELEGATION_HANDLE_IT_MAX_SENDS_PER_DAY=20+# Workflows that send email as their creator (oe__send_email_as_me): the most+# such emails a day per person, within DELEGATION_MAX_DRAFTS_PER_DAY.+# DELEGATION_WORKFLOW_MAX_SENDS_PER_DAY=20# Let the owner turn Act as me on for team members too (each connects their# own Gmail or Outlook and turns it on for themselves; Settings → Act as me). Default off.# DELEGATION_TEAM_MEMBERS=falsediff --git a/CLAUDE.md b/CLAUDE.mdindex 604e85a8..ec8f5b03 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -150,7 +150,7 @@ and deploy configuration for a specific environment are kept outside this repo.## Environment Variables-See `.env.example`. Required: `ANTHROPIC_API_KEY`, `EXEC_EMAIL_ADDRESS` (no default). Signed callers (optional, recommended on a server, and required there for Act as me's Send): `CALLER_ASSERTION_PRIVATE_KEY` on the UI signs who is signed in, and `CALLER_ASSERTION_PUBLIC_KEYS` on the API checks it (`api/caller.py`, `scripts/make-caller-keys.py`, `docs/auth.md`). Routes read the caller only through `api/caller.py`, never the `x-caller-email` header. Optional integrations: `SLACK_BOT_TOKEN`, `SLACK_APP_TOKEN`, `TELEGRAM_BOT_TOKEN` + `TELEGRAM_WEBHOOK_SECRET` (`docs/telegram_setup.md`), `DISCORD_BOT_TOKEN` + `DISCORD_APP_ID`, `GOOGLE_CHAT_PROJECT_NUMBER` + one of `GOOGLE_CHAT_SERVICE_ACCOUNT_FILE` / `_EMAIL` (`docs/google_chat_setup.md`). Email has no IMAP/SMTP settings: the poller (`integrations/email_poller.py`) reads and sends through the configured workspace backend (`integrations/workspace/`, chosen by `EMAIL_PROVIDER` / `CALENDAR_PROVIDER`, default `google`): the Gmail tools of the Google Workspace MCP (`GOOGLE_OAUTH_CLIENT_ID` / `GOOGLE_OAUTH_CLIENT_SECRET`) or the Outlook tools of the Microsoft 365 MCP (`MS365_MCP_CLIENT_ID` + a one-time `ms365-mcp-launch.sh --login`), signed in as `EXEC_EMAIL_ADDRESS`. Act as me (optional) reads the owner's *own* Gmail directly (`delegation/gmail.py`, never the MCP gateway) from a per-person credential in `DELEGATION_GOOGLE_CREDENTIALS_DIR`, minted by `scripts/connect-own-gmail.py` (or an Outlook one, `delegation/outlook.py`, minted by `scripts/connect-own-outlook.py` with the `MS365_MCP_CLIENT_ID` app); `DELEGATION_COMPOSER_MODEL` / `DELEGATION_MAX_DRAFTS_PER_DAY` tune the drafts, and `DELEGATION_INBOX_POLL_MINUTES` / `DELEGATION_INBOX_MAX_DRAFTS_PER_DAY` / `DELEGATION_CLASSIFIER_MODEL` the inbox watcher (`delegation/inbox.py`, off until the owner turns on Draft replies to my inbox); `DELEGATION_HANDLE_IT_MAX_SENDS_PER_DAY` caps the replies it sends on its own under Handle it for me (`delegation/handle_it.py`, off until the person turns it on). Drive folder sync (optional): `DRIVE_SYNC_ENABLED` + `DRIVE_SYNC_SERVICE_ACCOUNT_FILE` + `DRIVE_SYNC_FOLDER_IDS` (`docs/drive_sync_setup.md`) reads shared folders as a `drive.readonly` service account (`knowledge/drive_client.py`, never the MCP gateway) into the isolated `drive_docs` collection. Confluence sync (optional): `CONFLUENCE_SYNC_ENABLED` + `CONFLUENCE_URL` + `CONFLUENCE_PERSONAL_TOKEN` (Server/DC) or `CONFLUENCE_USERNAME` / `CONFLUENCE_API_TOKEN` (Cloud) + `CONFLUENCE_SYNC_SPACE_KEYS` (`docs/confluence_sync_setup.md`) reads the listed spaces over the Confluence REST API (`knowledge/confluence_client.py`, never the MCP gateway; names shared with mcp-atlassian) into the isolated `confluence_wiki` collection, skipping restricted pages unless `CONFLUENCE_SYNC_SKIP_RESTRICTED=false`. OneDrive folder sync (optional): `ONEDRIVE_SYNC_ENABLED` + `ONEDRIVE_SYNC_FOLDERS` (`docs/onedrive_sync_setup.md`) reads as the Executive's Microsoft 365 sign-in, with a token from `ms365-mcp-launch.sh --access-token` (`knowledge/onedrive_account.py`, never the MCP gateway), into the isolated `onedrive_docs` collection.+See `.env.example`. Required: `ANTHROPIC_API_KEY`, `EXEC_EMAIL_ADDRESS` (no default). Signed callers (optional, recommended on a server, and required there for Act as me's Send): `CALLER_ASSERTION_PRIVATE_KEY` on the UI signs who is signed in, and `CALLER_ASSERTION_PUBLIC_KEYS` on the API checks it (`api/caller.py`, `scripts/make-caller-keys.py`, `docs/auth.md`). Routes read the caller only through `api/caller.py`, never the `x-caller-email` header. Optional integrations: `SLACK_BOT_TOKEN`, `SLACK_APP_TOKEN`, `TELEGRAM_BOT_TOKEN` + `TELEGRAM_WEBHOOK_SECRET` (`docs/telegram_setup.md`), `DISCORD_BOT_TOKEN` + `DISCORD_APP_ID`, `GOOGLE_CHAT_PROJECT_NUMBER` + one of `GOOGLE_CHAT_SERVICE_ACCOUNT_FILE` / `_EMAIL` (`docs/google_chat_setup.md`). Email has no IMAP/SMTP settings: the poller (`integrations/email_poller.py`) reads and sends through the configured workspace backend (`integrations/workspace/`, chosen by `EMAIL_PROVIDER` / `CALENDAR_PROVIDER`, default `google`): the Gmail tools of the Google Workspace MCP (`GOOGLE_OAUTH_CLIENT_ID` / `GOOGLE_OAUTH_CLIENT_SECRET`) or the Outlook tools of the Microsoft 365 MCP (`MS365_MCP_CLIENT_ID` + a one-time `ms365-mcp-launch.sh --login`), signed in as `EXEC_EMAIL_ADDRESS`. Act as me (optional) reads the owner's *own* Gmail directly (`delegation/gmail.py`, never the MCP gateway) from a per-person credential in `DELEGATION_GOOGLE_CREDENTIALS_DIR`, minted by `scripts/connect-own-gmail.py` (or an Outlook one, `delegation/outlook.py`, minted by `scripts/connect-own-outlook.py` with the `MS365_MCP_CLIENT_ID` app); `DELEGATION_COMPOSER_MODEL` / `DELEGATION_MAX_DRAFTS_PER_DAY` tune the drafts, and `DELEGATION_INBOX_POLL_MINUTES` / `DELEGATION_INBOX_MAX_DRAFTS_PER_DAY` / `DELEGATION_CLASSIFIER_MODEL` the inbox watcher (`delegation/inbox.py`, off until the owner turns on Draft replies to my inbox); `DELEGATION_HANDLE_IT_MAX_SENDS_PER_DAY` caps the replies it sends on its own under Handle it for me (`delegation/handle_it.py`, off until the person turns it on), and `DELEGATION_WORKFLOW_MAX_SENDS_PER_DAY` the emails a workflow sends as its creator (`delegation/workflow_email.py`). Drive folder sync (optional): `DRIVE_SYNC_ENABLED` + `DRIVE_SYNC_SERVICE_ACCOUNT_FILE` + `DRIVE_SYNC_FOLDER_IDS` (`docs/drive_sync_setup.md`) reads shared folders as a `drive.readonly` service account (`knowledge/drive_client.py`, never the MCP gateway) into the isolated `drive_docs` collection. Confluence sync (optional): `CONFLUENCE_SYNC_ENABLED` + `CONFLUENCE_URL` + `CONFLUENCE_PERSONAL_TOKEN` (Server/DC) or `CONFLUENCE_USERNAME` / `CONFLUENCE_API_TOKEN` (Cloud) + `CONFLUENCE_SYNC_SPACE_KEYS` (`docs/confluence_sync_setup.md`) reads the listed spaces over the Confluence REST API (`knowledge/confluence_client.py`, never the MCP gateway; names shared with mcp-atlassian) into the isolated `confluence_wiki` collection, skipping restricted pages unless `CONFLUENCE_SYNC_SKIP_RESTRICTED=false`. OneDrive folder sync (optional): `ONEDRIVE_SYNC_ENABLED` + `ONEDRIVE_SYNC_FOLDERS` (`docs/onedrive_sync_setup.md`) reads as the Executive's Microsoft 365 sign-in, with a token from `ms365-mcp-launch.sh --access-token` (`knowledge/onedrive_account.py`, never the MCP gateway), into the isolated `onedrive_docs` collection.## Testingdiff --git a/packages/core/openexecutive/api/routes/workflow_designer.py b/packages/core/openexecutive/api/routes/workflow_designer.pyindex 207e35f0..df70ec40 100644--- a/packages/core/openexecutive/api/routes/workflow_designer.py+++ b/packages/core/openexecutive/api/routes/workflow_designer.py@@ -32,7 +32,7 @@ from collections.abc import Iteratorfrom contextlib import contextmanagerfrom dataclasses import dataclass, field-from fastapi import APIRouter, HTTPException+from fastapi import APIRouter, HTTPException, Requestfrom openexecutive.api.models import (WORKFLOW_DESIGNER_MESSAGE_MAX_CHARS,@@ -267,14 +267,16 @@ async def _advance(@router.post("/workflows/designer/start", response_model=WorkflowDesignerTurnResponse)-async def start_designer(body: WorkflowDesignerStartRequest) -> WorkflowDesignerTurnResponse:+async def start_designer(body: WorkflowDesignerStartRequest, request: Request) -> WorkflowDesignerTurnResponse:"""Open a design session from the user's description of the workflow."""text = _check_message(body.message, None)+ from openexecutive.api.routes.chat import _resolve_caller_person_id+ from openexecutive.delegation.workflow_email import available_forsession_id = uuid.uuid4().hexsession = DesignerSession(transcript=[Turn(role="user", text=text)],- context_block=build_context_block(),+ context_block=build_context_block(as_me=available_for(_resolve_caller_person_id(request))),)_designer_sessions[session_id] = session# Sweep AFTER inserting so the cap holds on what is stored.@@ -289,7 +291,7 @@ async def start_designer(body: WorkflowDesignerStartRequest) -> WorkflowDesigner@router.post("/workflows/designer/edit", response_model=WorkflowDesignerTurnResponse)-async def edit_designer(body: WorkflowDesignerEditRequest) -> WorkflowDesignerTurnResponse:+async def edit_designer(body: WorkflowDesignerEditRequest, request: Request) -> WorkflowDesignerTurnResponse:"""Open a design session on a saved workflow, to change it by conversation.No model call: the session starts with the stored definition as its draft@@ -303,9 +305,16 @@ async def edit_designer(body: WorkflowDesignerEditRequest) -> WorkflowDesignerTuif original is None:raise HTTPException(status_code=404, detail="Workflow not found.")+ from openexecutive.api.routes.chat import _resolve_caller_person_id+ from openexecutive.delegation.workflow_email import available_for+ from openexecutive.workflows.dynamic_store import get_owner+session_id = uuid.uuid4().hex+ # Its steps write as its creator: offered only when that is who is editing.+ owner = get_owner(original.name)+ as_me = owner is not None and owner == _resolve_caller_person_id(request) and available_for(owner)_designer_sessions[session_id] = DesignerSession(- context_block=f"{build_context_block()}\n\n{build_edit_note(original.name)}",+ context_block=f"{build_context_block(as_me=as_me)}\n\n{build_edit_note(original.name)}",draft=WorkflowDraft(definition=original),editing=original.name,original=original,diff --git a/packages/core/openexecutive/api/routes/workflows.py b/packages/core/openexecutive/api/routes/workflows.pyindex 84ca2594..63a1ec5b 100644--- a/packages/core/openexecutive/api/routes/workflows.py+++ b/packages/core/openexecutive/api/routes/workflows.py@@ -289,6 +289,16 @@ def _with_owner(defn: DynamicWorkflowDef) -> dict[str, Any]:return {**defn.model_dump(), "owner_person_id": get_owner(defn.name)}+def _refuse_unless_creator_sends(defn: DynamicWorkflowDef, request: Request, owner_id: int | None) -> None:+ """403 when ``defn`` sends email as its creator and the caller isn't that+ creator, verified (``workflow_email.save_refusal``)."""+ from openexecutive.delegation.workflow_email import save_refusal++ refused = save_refusal(defn, api_caller.caller(request), owner_id)+ if refused is not None:+ raise HTTPException(status_code=403, detail=refused)++@router.get("/workflows/custom")async def list_custom_workflows() -> dict[str, Any]:"""All dynamic definitions (active and inactive) for the builder UI."""@@ -311,11 +321,11 @@ async def create_custom_workflow(request: Request) -> dict[str, Any]:errors = await validate_definition_and_tools(defn)if errors:raise HTTPException(status_code=422, detail=errors)+ owner_person_id = _resolve_caller_person_id(request)+ _refuse_unless_creator_sends(defn, request, owner_person_id)# Insert-only: a create racing another save of the same name is a 409,# never a silent overwrite of someone else's workflow (or its owner).- stored = save_if_unchanged(- defn, None, owner_person_id=_resolve_caller_person_id(request)- )+ stored = save_if_unchanged(defn, None, owner_person_id=owner_person_id)if stored is None:raise HTTPException(status_code=409, detail=exists)_sync_cadence(stored)@@ -342,6 +352,12 @@ async def update_custom_workflow(name: str, request: Request) -> dict[str, Any]:errors = await validate_definition_and_tools(defn)if errors:raise HTTPException(status_code=422, detail=errors)+ # Sending as its creator: only they may change it, keeping it or adding it.+ owner = get_owner(name)+ _refuse_unless_creator_sends(defn, request, owner)+ current = get_definition(name)+ if current is not None:+ _refuse_unless_creator_sends(current, request, owner)stored = upsert_definition(defn)_sync_cadence(stored)return stored.model_dump()@@ -434,6 +450,9 @@ async def save_designer_edit(name: str, request: Request) -> dict[str, Any]:errors = await validate_definition_and_tools(defn)if errors:raise HTTPException(status_code=422, detail=errors)+ owner = get_owner(name)+ _refuse_unless_creator_sends(defn, request, owner)+ _refuse_unless_creator_sends(original, request, owner)stored = save_if_unchanged(defn, original)if stored is None:raise HTTPException(@@ -478,6 +497,7 @@ async def activate_custom_workflow(name: str, request: Request) -> dict[str, Anyerrors = await validate_definition_and_tools(current)if errors:raise HTTPException(status_code=422, detail=errors)+ _refuse_unless_creator_sends(current, request, get_owner(name))# The check above may await the gateway, and chat may run in another# process: switch on only if the row is still the revision validated.switched = activate_if_unchanged(current)diff --git a/packages/core/openexecutive/architecture/architecture-facts.yaml b/packages/core/openexecutive/architecture/architecture-facts.yamlindex a0de9c9e..ece816b2 100644--- a/packages/core/openexecutive/architecture/architecture-facts.yaml+++ b/packages/core/openexecutive/architecture/architecture-facts.yaml@@ -7251,6 +7251,29 @@ workflows:list_saved_tools is allowed under the Act as me lockdown (local read)and withheld on a turn private to the principal, like run_script.+ Email as the creator (delegation/workflow_email.py): two built-ins,+ oe__draft_email_as_me (draft in the creator's mailbox, recorded as a+ chat draft) and oe__send_email_as_me (sent through+ reply_send.send_for_workflow, the third door). Written only as the+ workflow's owner; refused when someone else started the run by hand, the+ speaker is unrostered, an unattended Executive pass started the+ outermost run (chat_tools.started_by_a_pass), or another person's+ workflow is in the chain (chat_tools.running). Needs Act as me allowed + on + own mailbox+ connected, else the step is told to use the Executive's email. to/cc are+ write targets (first email to a new address is held). Caps:+ DELEGATION_MAX_DRAFTS_PER_DAY for every email, plus+ DELEGATION_WORKFLOW_MAX_SENDS_PER_DAY (default 20) for sends, counted+ from delegation_drafts rows with source workflow_sent written before+ the send. A workflow with the send tool is created/changed/activated only+ by its creator per verified.caller_refusal (403 from POST/PUT+ /workflows/custom, save-edit, activate; save_refusal); chat's+ save_workflow refuses to replace one at all. At send:+ is_enabled, handle_it.signing_ok, no client slot, draft unchanged+ (recipients exactly as written, from an own address, <=10, never the+ Executive's). Results and the run report carry to/subject, never the+ body; audit rows are private to the creator. The designer gets an+ "Email as the user" line (build_context_block(as_me=...)).+Chat's tools in action steps (workflows/chat_tools.py): one list,`ACCESS`, labels every tool chat offers — use (a step may call it asoe__<name>), as_me (Act as me; chat-only for now), covered (the step@@ -11276,7 +11299,8 @@ delegation:in_a_row (last own message in the thread was an auto-send),daily_limit (DELEGATION_HANDLE_IT_MAX_SENDS_PER_DAY, default 20).The watcher then calls reply_send.send_on_its_own — the second door- into _send, pinned by an AST test to delegation/inbox.py — which runs+ into _send, pinned by an AST test to delegation/inbox.py (the third,+ send_for_workflow, is pinned to delegation/workflow_email.py) — which runsevery send-time check with no caller and adds: gate_mode auto_execute,the switch on and the mode still allowing that sender (follows_up fora follow-up card), signing_ok, and the draftdiff --git a/packages/core/openexecutive/architecture/prebuilt/api.json b/packages/core/openexecutive/architecture/prebuilt/api.jsonindex 65942401..1902b33b 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). A request it lets through is marked `request.state.shared_secret_ok`, which is what lets an MCP request turn on \"may act\" with `x-mcp-client-actions: on` (`mcp_server.may_act`; with no secret the header is ignored and `MCP_CLIENT_ACTIONS` decides). 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`, `GET /chat/voice`, `POST /chat/transcribe` | 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. `GET /chat/voice` says whether the chat mic shows (`available`, `max_seconds`); `POST /chat/transcribe` takes one recording (multipart `file`) and answers `{text}` for the message box, nothing kept: `404` when speech to text isn't set up, `400` for a file that isn't audio, `413` over 25 MB, `502` when the speech server fails. 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`. When the turn held steps for an outside read that still wait on the speaker's go (`outside_content.pending_held`), it then sends one `held_steps` event, `{type, session_id, steps: [plain words]}` (not after a stop or a timeout), which the UI shows as Approve / Not now under the reply; Approve sends \"Go ahead\". `GET /sessions/{id}/messages` puts the same `held_steps` on the last reply while they still wait (never for a shared chat's member). 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 /sessions/topics`, `PATCH\\|DELETE /sessions/topics/{topic_id}`, `POST /sessions/topics/{topic_id}/merge`, `POST /sessions/topic-areas/rename`, `POST /sessions/topic-areas/ungroup`, `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. Each of the owner's chats also carries `topic_id`, the topic it is filed under (`memory.chat_topics`). `GET /sessions/topics` lists the caller's topics (`id`, `name`, `chat_count`, `kept`, `pinned_at`, `area`, `updated_at`) and, when some of their chats have no topic yet or some topics no area, starts filing them in the background from their titles and answers `organizing: true` until done. `PATCH /sessions/topics/{topic_id}` renames (a name another of their topics has merges the two) or pins one, `POST …/merge` moves its chats into another (`into_id`), and `DELETE` ungroups it, leaving its chats under no topic; another person's topic is a 404. `POST /sessions/topic-areas/rename` (`area`, `name`) renames one of the caller's areas and `…/ungroup` (`area`) drops it, its topics standing alone; an area they don't have is a 404. `PATCH /sessions/{id}` also takes `topic_id` (null for none) or `topic_name` (made if new) to file the chat, which then is never refiled on its own. 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`, `POST /today/seen` | Morning-brief aggregation (in the install's first week, for the principal, `first_week_card` `{needs_goal, findings: [{title, summary}], brief_tomorrow}` or null), recent-action rail, Pulse heartbeat heatmap (per-day activity counts), and the owner's month tally for Pulse's Done for you (`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), the same text split for Home's Right now card (`narrative_lead`, `narrative_points` `[{text, since}]`, `narrative_move`), `narrative_seen_at` (this reader's last look, which `POST /today/seen` records and returns as `{seen_at}`) and, for the principal, `morning_brief` `{at, text}` and `calendar_next` `[{title, start, all_day}]`. 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| `contacts` | `GET /contacts/changes?person_id=`, `PUT /contacts/keeper`, `POST /contacts/changes/seen`, `POST /contacts/changes/{id}/undo`, `POST /contacts/changes/{id}/accept`, `POST /contacts/changes/{id}/dismiss`, `GET /contacts/{person_id}/note` | The contact keeper (see Org), principal only (404 for anyone else). `GET /contacts/{person_id}/note` returns what is remembered about one contact or teammate (`note`, `topics`, `last_emailed_at`, `last_heard_at`, `last_met_at`, `next_meeting_at`, `next_meeting_title`, `emailed_count`, `met_count`, `note_written_at`, `updated_at`), 404 when there is nothing yet or they are not active. `GET` returns `{mode, status, last_run_at, changes}`: the switch (`on` / `ask` / `off`), how the last pass went (`ok`, `act_as_me_off`, `not_connected`, …) and the last 30 days of changes (each `id`, `person_id`, `action` add/update, `field`, `email`, `full_name`, `old_value`, `new_value`, `reason`, `evidence`, `status` applied/suggested/undone/dismissed, `seen`, `created_at`); with `person_id`, that person's every change. `PUT` sets the switch; `seen` is Got it; `undo` / `accept` / `dismiss` return the change, 409 when there is nothing to undo or decide. |\n| `chat-directory` | `GET /chat-directory/people`, `GET /chat-directory/channels`, `GET /chat-directory/slack/lookup?email=` | The Slack, Discord and Telegram people and rooms the bots can reach, by name, for the People and department pickers (`integrations/chat_directory.py`). Each answers `{slack, discord, telegram}`, every one `{configured, ok, options: [{id, name, detail, email}], truncated, members_available}`: `configured` false (and no options) when that bot has no token, `ok` false when the provider could not be read, `members_available` false when Discord refuses to list server members (the Server Members intent is off). `lookup` returns `{configured, match}`, the Slack person with that work email or null. Cached in-process for 60 s; tokens are never returned. The principal's alone, like changing the People list (`chat._caller_is_principal_or_unclaimed`); channels also open while no one is principal yet, people and lookup wait for one; a 403 otherwise, and the pickers then keep only the by-hand id field. |\n| `departments` | `GET\\|POST\\|PATCH\\|DELETE /departments`, `.../goals`, `GET\\|POST /goals`, `PATCH\\|DELETE /goals/{id}` | Department state and goals. A goal has an optional department and an optional `owner_person_id` (a non-archived team member, else 422). `GET /goals` lists every goal with `owner_id`/`owner_name` (its own owner, else its department's head, else the principal) and `department_title`. `POST /goals` takes a goal plus `area` (a name, ≤80): an existing department by slug or title, else a new one of that name (no specialist, as with `POST /departments`), else no department when blank. `PATCH /goals/{id}` edits any goal and may move it (`department_slug`, null = none; `owner_person_id`, null = follow the department) — only the fields sent change; `DELETE /goals/{id}` removes any goal. The department-scoped goal routes still reach only that department's goals. `DELETE /departments/{slug}` keeps its goals with no department, on their owners. `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; `delegation_invite`, a meeting invite card, is its approver's alone too, and answers the invite in their own calendar on approve (`edits.answer`) and nothing on reject; `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`, `PUT /delegation/replies/{id}/recipients`, `POST /delegation/replies/{id}/answer`, `GET /delegation/actions`, `GET /delegation/invites`, `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, summary}]}`, the caller's replies and follow-ups (`source` `follow_up`) sent on its own in the last 7 days, and the meeting invites it accepted on its own (`source` `invite`, `subject` the meeting's title, `summary` one line such as \"Accepted Dana's Pilot review, Wed 21 Oct, 14:30\"); 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?, actions_on?}` (any other field is a 422; `actions_on` is Suggested actions On, and `actions` and `actions_on` set true clear each other) and returns the `GET /delegation` shape, whose `training` carries `actions_on` too; putting Replies or Follow-ups in, or Suggested actions out of training or On, 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, a one-line `gist` (what they asked and what the draft says, written with the draft and brought up to date when an answer rewrites it; empty on an older card), 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 with the *on its own next time* tick 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/invites` returns `{cards: [...]}`, the caller's own meeting invite cards (`delegation_invite`, Read my calendar on): `decision_id`, `status`, `created_at`, `from_name`, `from_email`, `relation`, `title`, `when` (in the workspace time zone), `start`, `end`, `all_day`, `clashes` (busy times only, `\"14:00–14:30\"`), `clash_checked`, `can_answer` (false for a sign-in that reads but can't answer the calendar; then `connect_command`), `can_allow` (Replies in training) and `waited_because`. **Accept** / **Decline** is `POST /decisions/{id}/approve` with `edits: {answer: \"accept\" | \"decline\"}` (accept is the default; `allow: true` with accept for the *Accept from them on its own next time* tick), on the same caller checks Send uses (403 `not_yours`, 409 `caller_signing_required`); 409 `calendar_write_needed` when the sign-in can't answer (the card stays), `gone` when the event left their calendar, `expired` once the meeting started, `already_handled`; 502 `calendar_error` leaves the card for another try. **Dismiss** is `POST /decisions/{id}/reject` and answers nothing. `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 the *Do this on its own next time* tick 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| `reflection` | `GET /memories/reflection` (`?person_id=`), `DELETE /memories/reflection/misses/{id}` | Learning: the turns the conversation review graded a miss (`memory.chat_review`), with the person's words, the reply, the tools run, what they wanted instead, the `kind` (`company` / `product`), the finer `cause` (null when the grade gave none) and the signals, plus `weeks` (`{week, graded, misses}` per ISO week, newest first) and `sees_everyone`. The caller is resolved as for `history` (403 `sign_in_required` / `not_on_roster`); each person sees their own, the principal those from chats `chat._session_access` lets them open (a teammate's own web chat or DM and a mail-private conversation stay their owner's; channels and groups are open), or one person's with `?person_id=` (a teammate naming someone else gets 403 `not_yours`); the weekly counts carry no words and are not filtered. The same response carries `lessons` (`memory/lessons.py`: live first, then retired, each with `shown`/`fine_after`/`miss_after` and `retired_reason`), filtered by the same rule, and `DELETE /memories/reflection/lessons/{id}` retires one (204; 404 for a lesson the caller may not see, already retired, or missing). `DELETE` forgets one miss (`is_principal_or_self`; 404 `not_found` otherwise) and writes a `chat_review` audit row. Each miss also carries its nightly replay (`memory/replay.py`): `replay_state` (`open` / `closed` / `evidence`), `replayed_at`, `closed_at`, `replay_notes`; and the response carries `replay` (`{misses, would_pass, evidence, last_run_at}`: of the caller's visible misses from the last 30 days, how many would go right today). |\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`, `GET`/`PUT /executive/outside-content` | 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, name}` — `held_actions` counts due `pending` rows that fire on resume, and `name` is the Executive's name (`EXEC_DISPLAY_NAME`), which the web chat shows over its replies. `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. `GET /executive/outside-content` returns `{mode, can_change}` for the owner's **When I read outside content** setting (`ask`, `outsiders` or `trust`; `orchestrator.outside_mode`), and `PUT` with `{mode}` changes it for the principal only (403 otherwise), writing an `outside_content_mode_changed` audit row. |\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/describe`, `POST /watchlist/{slug}/approve`, `POST /watchlist/{slug}/decline` | External-monitoring watchlist + signals. `POST /watchlist/describe` `{text}` drafts a watch from a sentence (one forced tool call on the utility-fast model, `monitoring.describe`; the company profile's name, competitors, vendors and tickers ride in the user turn) and saves nothing: it returns the create fields (`slug`, `signal_type`, `target`, `display_label`, `trigger`, `cadence`, `mode`, `severity_floor`, `severity_ceiling`, `notes`) plus four plain lines (`watching`, `tell_you_when`, `how_often`, `how_loud`) written by code from those fields, after the create route's checks (registered kind, cadence, severity, the URL guard, the rss feed check, a free slug); 422 with a plain reason when it can't be a watch, 429 past 30 drafts an hour, 502/504 when the model fails. `GET /watchlist/{slug}` also returns `noise` `{recent_alerts, recent_dismissed, noisy}` (its last 8 alerts, noisy at 6 dismissed, `monitoring.noise`), and `PATCH` takes `quiet_noise_nudge: true` to stop that question for the alerts so far. `display_label` on create maps to the adapter's label key for every kind. 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/revise`, `/onboard/interview/{id}` (GET resumes, DELETE starts over), `/onboard/interview/commit` | Conversational company setup. `understand` and `start` take multipart `description`, optional `files` and an optional `website` the server reads itself (a non-address is a 422; an unreadable site is no pages, never an error); `start`'s response lists the pages read in `website_pages`, and the draft's profile carries `website`. The `onboarding_interviewer` agent asks up to four quick questions (a question response carries `question_options`, suggested answers to tap), then emits a draft profile + people + `draft_goals` (each `{title, target, owner_name, department_title}`) + departments only when the user listed people by department. **Nothing is persisted until `POST /onboard/interview/commit`** — the interview itself never writes. `start` is multipart (description + optional deck/one-pager uploads). `revise` changes one earlier answer (0 = the description) and runs the interview again from there. `commit` takes the reviewed `goals` too (422 when one names a person or department not in the draft) and saves them with owners, additively. It 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. | A card the Executive left for something asked in chat (`app_action`, `orchestrator/app_control.py`) is its person's alone too: its payload holds `action`, `id`, `value`, `title` and the `card` line shown; **Confirm** is `POST /decisions/{id}/approve`, which runs the action through the route its button calls with that request (a refusal comes back as that route's status and words, and the card is marked `failed`), and a card older than a day is turned down with 409.\n\n**What it does for you** (`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 does for you.\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 (and the meeting invites it accepted as them, \"Accepted Dana's Pilot review, Wed 21 Oct, 14:30\") and, for the principal, one `contacts_kept` row a day the contact keeper changed something (`detail` like \"2 added, 1 updated\"). 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). A request it lets through is marked `request.state.shared_secret_ok`, which is what lets an MCP request turn on \"may act\" with `x-mcp-client-actions: on` (`mcp_server.may_act`; with no secret the header is ignored and `MCP_CLIENT_ACTIONS` decides). 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`, `GET /chat/voice`, `POST /chat/transcribe` | 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. `GET /chat/voice` says whether the chat mic shows (`available`, `max_seconds`); `POST /chat/transcribe` takes one recording (multipart `file`) and answers `{text}` for the message box, nothing kept: `404` when speech to text isn't set up, `400` for a file that isn't audio, `413` over 25 MB, `502` when the speech server fails. 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`. When the turn held steps for an outside read that still wait on the speaker's go (`outside_content.pending_held`), it then sends one `held_steps` event, `{type, session_id, steps: [plain words]}` (not after a stop or a timeout), which the UI shows as Approve / Not now under the reply; Approve sends \"Go ahead\". `GET /sessions/{id}/messages` puts the same `held_steps` on the last reply while they still wait (never for a shared chat's member). 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 /sessions/topics`, `PATCH\\|DELETE /sessions/topics/{topic_id}`, `POST /sessions/topics/{topic_id}/merge`, `POST /sessions/topic-areas/rename`, `POST /sessions/topic-areas/ungroup`, `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. Each of the owner's chats also carries `topic_id`, the topic it is filed under (`memory.chat_topics`). `GET /sessions/topics` lists the caller's topics (`id`, `name`, `chat_count`, `kept`, `pinned_at`, `area`, `updated_at`) and, when some of their chats have no topic yet or some topics no area, starts filing them in the background from their titles and answers `organizing: true` until done. `PATCH /sessions/topics/{topic_id}` renames (a name another of their topics has merges the two) or pins one, `POST …/merge` moves its chats into another (`into_id`), and `DELETE` ungroups it, leaving its chats under no topic; another person's topic is a 404. `POST /sessions/topic-areas/rename` (`area`, `name`) renames one of the caller's areas and `…/ungroup` (`area`) drops it, its topics standing alone; an area they don't have is a 404. `PATCH /sessions/{id}` also takes `topic_id` (null for none) or `topic_name` (made if new) to file the chat, which then is never refiled on its own. 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`, `POST /today/seen` | Morning-brief aggregation (in the install's first week, for the principal, `first_week_card` `{needs_goal, findings: [{title, summary}], brief_tomorrow}` or null), recent-action rail, Pulse heartbeat heatmap (per-day activity counts), and the owner's month tally for Pulse's Done for you (`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), the same text split for Home's Right now card (`narrative_lead`, `narrative_points` `[{text, since}]`, `narrative_move`), `narrative_seen_at` (this reader's last look, which `POST /today/seen` records and returns as `{seen_at}`) and, for the principal, `morning_brief` `{at, text}` and `calendar_next` `[{title, start, all_day}]`. 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| `contacts` | `GET /contacts/changes?person_id=`, `PUT /contacts/keeper`, `POST /contacts/changes/seen`, `POST /contacts/changes/{id}/undo`, `POST /contacts/changes/{id}/accept`, `POST /contacts/changes/{id}/dismiss`, `GET /contacts/{person_id}/note` | The contact keeper (see Org), principal only (404 for anyone else). `GET /contacts/{person_id}/note` returns what is remembered about one contact or teammate (`note`, `topics`, `last_emailed_at`, `last_heard_at`, `last_met_at`, `next_meeting_at`, `next_meeting_title`, `emailed_count`, `met_count`, `note_written_at`, `updated_at`), 404 when there is nothing yet or they are not active. `GET` returns `{mode, status, last_run_at, changes}`: the switch (`on` / `ask` / `off`), how the last pass went (`ok`, `act_as_me_off`, `not_connected`, …) and the last 30 days of changes (each `id`, `person_id`, `action` add/update, `field`, `email`, `full_name`, `old_value`, `new_value`, `reason`, `evidence`, `status` applied/suggested/undone/dismissed, `seen`, `created_at`); with `person_id`, that person's every change. `PUT` sets the switch; `seen` is Got it; `undo` / `accept` / `dismiss` return the change, 409 when there is nothing to undo or decide. |\n| `chat-directory` | `GET /chat-directory/people`, `GET /chat-directory/channels`, `GET /chat-directory/slack/lookup?email=` | The Slack, Discord and Telegram people and rooms the bots can reach, by name, for the People and department pickers (`integrations/chat_directory.py`). Each answers `{slack, discord, telegram}`, every one `{configured, ok, options: [{id, name, detail, email}], truncated, members_available}`: `configured` false (and no options) when that bot has no token, `ok` false when the provider could not be read, `members_available` false when Discord refuses to list server members (the Server Members intent is off). `lookup` returns `{configured, match}`, the Slack person with that work email or null. Cached in-process for 60 s; tokens are never returned. The principal's alone, like changing the People list (`chat._caller_is_principal_or_unclaimed`); channels also open while no one is principal yet, people and lookup wait for one; a 403 otherwise, and the pickers then keep only the by-hand id field. |\n| `departments` | `GET\\|POST\\|PATCH\\|DELETE /departments`, `.../goals`, `GET\\|POST /goals`, `PATCH\\|DELETE /goals/{id}` | Department state and goals. A goal has an optional department and an optional `owner_person_id` (a non-archived team member, else 422). `GET /goals` lists every goal with `owner_id`/`owner_name` (its own owner, else its department's head, else the principal) and `department_title`. `POST /goals` takes a goal plus `area` (a name, ≤80): an existing department by slug or title, else a new one of that name (no specialist, as with `POST /departments`), else no department when blank. `PATCH /goals/{id}` edits any goal and may move it (`department_slug`, null = none; `owner_person_id`, null = follow the department) — only the fields sent change; `DELETE /goals/{id}` removes any goal. The department-scoped goal routes still reach only that department's goals. `DELETE /departments/{slug}` keeps its goals with no department, on their owners. `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; `delegation_invite`, a meeting invite card, is its approver's alone too, and answers the invite in their own calendar on approve (`edits.answer`) and nothing on reject; `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`, `PUT /delegation/replies/{id}/recipients`, `POST /delegation/replies/{id}/answer`, `GET /delegation/actions`, `GET /delegation/invites`, `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, summary}]}`, the caller's replies and follow-ups (`source` `follow_up`) sent on its own in the last 7 days, and the meeting invites it accepted on its own (`source` `invite`, `subject` the meeting's title, `summary` one line such as \"Accepted Dana's Pilot review, Wed 21 Oct, 14:30\"); 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?, actions_on?}` (any other field is a 422; `actions_on` is Suggested actions On, and `actions` and `actions_on` set true clear each other) and returns the `GET /delegation` shape, whose `training` carries `actions_on` too; putting Replies or Follow-ups in, or Suggested actions out of training or On, 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, a one-line `gist` (what they asked and what the draft says, written with the draft and brought up to date when an answer rewrites it; empty on an older card), 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 with the *on its own next time* tick 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/invites` returns `{cards: [...]}`, the caller's own meeting invite cards (`delegation_invite`, Read my calendar on): `decision_id`, `status`, `created_at`, `from_name`, `from_email`, `relation`, `title`, `when` (in the workspace time zone), `start`, `end`, `all_day`, `clashes` (busy times only, `\"14:00–14:30\"`), `clash_checked`, `can_answer` (false for a sign-in that reads but can't answer the calendar; then `connect_command`), `can_allow` (Replies in training) and `waited_because`. **Accept** / **Decline** is `POST /decisions/{id}/approve` with `edits: {answer: \"accept\" | \"decline\"}` (accept is the default; `allow: true` with accept for the *Accept from them on its own next time* tick), on the same caller checks Send uses (403 `not_yours`, 409 `caller_signing_required`); 409 `calendar_write_needed` when the sign-in can't answer (the card stays), `gone` when the event left their calendar, `expired` once the meeting started, `already_handled`; 502 `calendar_error` leaves the card for another try. **Dismiss** is `POST /decisions/{id}/reject` and answers nothing. `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 the *Do this on its own next time* tick 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| `reflection` | `GET /memories/reflection` (`?person_id=`), `DELETE /memories/reflection/misses/{id}` | Learning: the turns the conversation review graded a miss (`memory.chat_review`), with the person's words, the reply, the tools run, what they wanted instead, the `kind` (`company` / `product`), the finer `cause` (null when the grade gave none) and the signals, plus `weeks` (`{week, graded, misses}` per ISO week, newest first) and `sees_everyone`. The caller is resolved as for `history` (403 `sign_in_required` / `not_on_roster`); each person sees their own, the principal those from chats `chat._session_access` lets them open (a teammate's own web chat or DM and a mail-private conversation stay their owner's; channels and groups are open), or one person's with `?person_id=` (a teammate naming someone else gets 403 `not_yours`); the weekly counts carry no words and are not filtered. The same response carries `lessons` (`memory/lessons.py`: live first, then retired, each with `shown`/`fine_after`/`miss_after` and `retired_reason`), filtered by the same rule, and `DELETE /memories/reflection/lessons/{id}` retires one (204; 404 for a lesson the caller may not see, already retired, or missing). `DELETE` forgets one miss (`is_principal_or_self`; 404 `not_found` otherwise) and writes a `chat_review` audit row. Each miss also carries its nightly replay (`memory/replay.py`): `replay_state` (`open` / `closed` / `evidence`), `replayed_at`, `closed_at`, `replay_notes`; and the response carries `replay` (`{misses, would_pass, evidence, last_run_at}`: of the caller's visible misses from the last 30 days, how many would go right today). |\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`, `GET`/`PUT /executive/outside-content` | 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, name}` — `held_actions` counts due `pending` rows that fire on resume, and `name` is the Executive's name (`EXEC_DISPLAY_NAME`), which the web chat shows over its replies. `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. `GET /executive/outside-content` returns `{mode, can_change}` for the owner's **When I read outside content** setting (`ask`, `outsiders` or `trust`; `orchestrator.outside_mode`), and `PUT` with `{mode}` changes it for the principal only (403 otherwise), writing an `outside_content_mode_changed` audit row. |\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/describe`, `POST /watchlist/{slug}/approve`, `POST /watchlist/{slug}/decline` | External-monitoring watchlist + signals. `POST /watchlist/describe` `{text}` drafts a watch from a sentence (one forced tool call on the utility-fast model, `monitoring.describe`; the company profile's name, competitors, vendors and tickers ride in the user turn) and saves nothing: it returns the create fields (`slug`, `signal_type`, `target`, `display_label`, `trigger`, `cadence`, `mode`, `severity_floor`, `severity_ceiling`, `notes`) plus four plain lines (`watching`, `tell_you_when`, `how_often`, `how_loud`) written by code from those fields, after the create route's checks (registered kind, cadence, severity, the URL guard, the rss feed check, a free slug); 422 with a plain reason when it can't be a watch, 429 past 30 drafts an hour, 502/504 when the model fails. `GET /watchlist/{slug}` also returns `noise` `{recent_alerts, recent_dismissed, noisy}` (its last 8 alerts, noisy at 6 dismissed, `monitoring.noise`), and `PATCH` takes `quiet_noise_nudge: true` to stop that question for the alerts so far. `display_label` on create maps to the adapter's label key for every kind. 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. A workflow with a step that sends email as its creator (`oe__send_email_as_me`) can be created, changed (`PUT`, save-edit) or switched on (`activate`) only by that creator, verified as Send on a reply card is; anyone else gets a 403 (`delegation.workflow_email.save_refusal`). `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/revise`, `/onboard/interview/{id}` (GET resumes, DELETE starts over), `/onboard/interview/commit` | Conversational company setup. `understand` and `start` take multipart `description`, optional `files` and an optional `website` the server reads itself (a non-address is a 422; an unreadable site is no pages, never an error); `start`'s response lists the pages read in `website_pages`, and the draft's profile carries `website`. The `onboarding_interviewer` agent asks up to four quick questions (a question response carries `question_options`, suggested answers to tap), then emits a draft profile + people + `draft_goals` (each `{title, target, owner_name, department_title}`) + departments only when the user listed people by department. **Nothing is persisted until `POST /onboard/interview/commit`** — the interview itself never writes. `start` is multipart (description + optional deck/one-pager uploads). `revise` changes one earlier answer (0 = the description) and runs the interview again from there. `commit` takes the reviewed `goals` too (422 when one names a person or department not in the draft) and saves them with owners, additively. It 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. | A card the Executive left for something asked in chat (`app_action`, `orchestrator/app_control.py`) is its person's alone too: its payload holds `action`, `id`, `value`, `title` and the `card` line shown; **Confirm** is `POST /decisions/{id}/approve`, which runs the action through the route its button calls with that request (a refusal comes back as that route's status and words, and the card is marked `failed`), and a card older than a day is turned down with 409.\n\n**What it does for you** (`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 does for you.\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 (and the meeting invites it accepted as them, \"Accepted Dana's Pilot review, Wed 21 Oct, 14:30\") and, for the principal, one `contacts_kept` row a day the contact keeper changed something (`detail` like \"2 added, 1 updated\"). 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-21T18:00:00Z"+ "generated_at": "2026-10-21T18:27:08.370009+00:00"}diff --git a/packages/core/openexecutive/architecture/prebuilt/delegation.json b/packages/core/openexecutive/architecture/prebuilt/delegation.jsonindex 46107ba4..4730f818 100644--- a/packages/core/openexecutive/architecture/prebuilt/delegation.json+++ b/packages/core/openexecutive/architecture/prebuilt/delegation.json@@ -1,7 +1,7 @@{"section_id": "delegation","title": "Act as Me (Delegation)",- "markdown": "The **delegation** module (`openexecutive.delegation`) is **Act as me**: the one place the Executive writes *as* a person instead of as itself. Everywhere else it has its own Google account and bots and signs as itself. Here — when the person asks, or, with a second switch, for mail in their inbox that needs them — it writes an email in their voice and saves it as a **draft in their own mailbox** — Gmail or Outlook — for them to review and send. The one thing it ever sends is one of those inbox drafts, exactly as it is in their mailbox: when the person taps **Send** on its card, or, with a third switch, **Handle it for me**, on its own when plain-code rules allow it (below); chat never sends. The principal can turn it on for themselves, and so can each team member once the owner lets them. It is off by default, and off changes nothing: the prompts, tool lists and prompt caches are byte-identical to an install without it.\n\n## Who can have it, and when it is offered\n\n`delegation.settings.can_delegate(person)` is the single rule for who may turn it on: the principal (a non-archived team member flagged `is_principal`), and any other non-archived team member — never a contact — once team members may have it (`team_members_enabled`). That takes two things: the install allows it (`DELEGATION_TEAM_MEMBERS`, default off, which offers the owner the switch) and the owner turned on **Let team members use it** (`PUT /delegation/team`, principal only, one row in `delegation_team`). Turning the owner's switch off takes it away from every team member from their next message, and their inbox watchers stop at their next check; their own switches, drafts and cards are kept. Everything is keyed by `person_id`. A person turns it on for themselves (`PUT /delegation`); nobody turns it on for anyone else. The setting is one row per person in `delegation_settings`, and a missing, unreadable or zero row all mean off.\n\nAt the start of every chat turn (`Executive.stream_chat` and the committee path) `pin_turn_delegation(session, speaker_text)` runs next to the workspace-mode pin and records a `TurnDelegation` on the session. `ghostwrite_email` is **offered** only when all of these hold:\n\n- the speaker may have it and turned it on — read fresh every turn, so turning it off applies from the next message;\n- the speaker is on a surface that verified it is them — the principal through `people_tools.is_principal_on_verified_surface`, a team member through `teammate_on_verified_surface` (the web app signed in, their own Slack or Discord, never an email turn) — and a web turn also carried a signed-in caller (`Session.web_caller_signed_in`, set from `x-caller-email`) or runs under local login — a request with no caller header is not a sign-in and never gets it (whoever holds the shared secret is trusted as the UI proxy that stamps that header, as on every principal-only route);\n- the conversation is private to the speaker: the web chat, a Slack or Discord DM, a verified private Telegram chat, or a chat its channel adapter verified the sender of and marked private (`Session.speaker_verified` + `Session.private_chat`) — never a shared channel or thread, where the draft's preview or the matching threads would be posted for everyone and other people's messages sit in the model's context;\n- the turn is neither unattended (the scheduler's proactive run) nor private to the principal (the email poller's turns), so inbound text can never reach it. The MCP server, workflows, reflection and research never carry it at all.\n\nThe mailbox connection is deliberately **not** part of the offer: the handler checks it on every call and says how to fix it, so the cached tool prefix never flips when a token lapses. The pin lives in a context variable for the turn's task as well as on the session, so two turns running at once on one session (a second browser tab) each read their own. It also carries the speaker's own words for the turn (a new email may go to an address they just typed — the turn's message joins the history only once the turn ends), a per-turn draft count, and `touched_mail` (see Privacy). `own_words` reads those words back for every own-words check (addresses here, facts and task assignments elsewhere): it first removes the hydrated `<outbound_reply_context>` backstory by its exact, anchored shape, so a look-alike closing tag quoted inside it cannot pass the rest off as the speaker's, then drops other adapter tag blocks, and returns nothing for a message carrying an attachment.\n\n## The tool: `ghostwrite_email`\n\nIt lives in its own registry (`orchestrator.delegation_tools.DELEGATION_TOOLS` / `DELEGATION_TOOL_HANDLERS`), **never** `_ALL_SKILL_TOOLS`, so no other toolkit can carry it. On a turn it is offered to, the agent loop adds it to the pool *before* the sort and builds that turn's handler map from both registries; on any other turn a call to it is an unknown tool. The handler re-checks the pin and the surface anyway, then:\n\n1. **Caps** — at most 5 drafts per turn, and `DELEGATION_MAX_DRAFTS_PER_DAY` (default 50, at most 1000) per person per UTC day, shared with the inbox watcher (`delegation.caps`). It is counted from `delegation_drafts`, one row of ids per draft saved from either place, with a count kept in the process as a floor in case a row was lost. Each slot is taken before the first await — a round's tool calls run concurrently, so otherwise every call in it would pass the caps before any counted — and handed back if nothing was drafted. If the rows can't be read it refuses rather than guess.\n2. **Marks the turn** — sets `TurnDelegation.touched_mail` *before* its first read of the mailbox.\n3. **Checks the mailbox** — `gmail_status` asks Google or Microsoft whose mailbox the credential opens and compares it with the person's People email, on every call: a roster email can change, and a client slot swaps the roster.\n4. **Finds the thread** — by `thread_id` (checked against the mailbox's own id shape), or a Gmail-style search (`find`; on Outlook, words, `from:`, `to:`, `cc:`, `subject:` and `newer_than:` are kept and other Gmail operators dropped). Several matches return `{status: \"choose\", candidates}` (subject, sender and date — no message text) and draft nothing; none returns `not_found`.\n5. **Sets the recipients in code**, never from the model. A reply goes to the last inbound message's `From` — never its `Reply-To` (a different one is flagged `reply_to_ignored`) — with the thread's other recipients only on `reply_all`. A new email or a forward may go to any well-formed address: it is only a draft, waiting in their own mailbox, where they see who it is to before they send it. An address that is neither on the roster (contacts only when `contacts_reachable_now()`) nor typed by the speaker this turn comes back in `not_in_people`, and the Executive names it for them to check (`delegation_tools.not_in_people`). Mailing-list mail, a thread they replied to last and a reply-all trimmed to 10 recipients are flagged. An address inside a block an adapter added to their message (the backstory hydrated into a DM) is not one they typed, and when the message carries an attachment — a document's inlined text, or a note naming the file — none of its addresses count as typed: neither has an end mark, and a filename is chosen by whoever sent the file, so such an address is named back to check.\n6. **Writes it** (the ghostwriter, below) and saves it with the mailbox client's `create_draft` (Gmail: threaded with `In-Reply-To`, `References` (whole message ids: when the chain is too long for one header the oldest after the thread's first go, never the parent) and `threadId`, and stamped `X-OE-Ghostwritten`; Outlook: Graph's `createReply` on the message it answers, then the text and recipients, and a named property marking it).\n\nThe result is `{status: \"drafted\", draft_id, gmail_link, to, cc, subject, preview, flags, open_questions, note}`, plus `not_in_people` and `check_address` when a recipient needs checking. The link (`gmail.mailbox_link`) is built server-side from a fixed prefix — the thread in Gmail, the draft itself in Outlook on the web — and the note tells the model the preview is the person's draft, to be treated as data. The chat shows an action chip — \"Drafted an email as you to … — in your Drafts\" — that opens it, and only a link under `MAILBOX_LINK_PREFIXES` is ever linked. A sincere \"are you an AI?\" in the thread comes back as an open question for the person to answer themselves.\n\n## Reading their mailbox\n\nFive read-only mail tools ride with `ghostwrite_email` in the same registry (`orchestrator.mail_read_tools`), so they are offered, re-checked and fenced exactly as it is: `search_my_email` (a Gmail-style search through the client's `search_threads`, or with no query the threads that reached their inbox in the last few days through `inbox_message_ids` + `get_message`), `read_my_email` (one thread's last 10 messages, each sender's new text only, drafts left out, with the files attached to them listed by message id and index), `read_my_email_attachment` (one of those files as text: PDF, Word, Excel, CSV or text, up to 20 MB, a scanned PDF converted) and `my_email_awaiting_reply` (their own sent mail from the last 14 days, to at most 10 people besides the Executive, that is still the last message in its thread). They change, label, draft and send nothing.\n\nThe fifth, `my_email_read_before`, lists the threads `read_my_email` opened for the same person before, in this conversation or an earlier one, so a later conversation can open the same email again instead of asking them to search for it. It keeps where, never what (`delegation.mail_reads`, table `delegation_mail_read`): the thread id, its subject and first sender as one line each, the mailbox address it was read from and when, never a message's text, an attachment or a recipient. Rows are the person's own and are listed only from the mailbox open now, newest first, optionally narrowed by words in the subject or sender; anything older than 30 days is never listed and is deleted on the next write, at most 200 are kept per person, and turning Act as me off deletes them all. It opens the mailbox like the other reads, so it sets `touched_mail`, counts as a search, and returns its rows with the same data-not-instructions note. The Act as me addendum tells the model that these tools reach the person's mailbox while any Gmail or Outlook tools of its own account reach only the Executive's, to search theirs (never falling back to its own) for mail sent to them, and to reopen an email from before with `my_email_read_before` and `read_my_email`.\n\nEach sets `touched_mail` and marks the conversation theirs before its first read (`_open_mailbox`, shared with `ghostwrite_email`), so the lockdown below applies from its round on. Each is capped per turn on the pin: 10 searches (`my_email_awaiting_reply` counts as one), 20 thread reads and 5 attachment reads, the slot taken before the first await. In `read_my_email` every message someone else wrote comes back inside its own `<untrusted_content source=\"email\">` block (`content_trust.wrap_untrusted`, which defuses a closing tag in the text); the speaker's own messages — SENT and from their address (`threads.mine`), never a From header alone — are marked \"Yours\" outside any block. An attachment's text comes back in its own `<untrusted_content source=\"attachment\">` block (`attachments.format_attached_text`), parsed in an isolated worker (`knowledge.loader`); unlike a file sent to the Executive it is never added to the company's knowledge. The clients find an attachment by message and position and look its provider id up on each read (Gmail's changes per fetch): Gmail lists a message's files with the message (`MailMessage.attachments`, leaving out images the HTML shows in place), Outlook says only `hasAttachments` until `list_attachments` asks Graph (leaving out inline ones), and `attachment_bytes` reads one; an attached Outlook item or cloud link has no file to read. Results carry a note that subjects, senders and text are other people's words, data rather than instructions. The lockdown refuses tools, not the reply's own text, so what would carry that text out without a click is closed where it is shown: the web chat loads no image from another site, and bot replies go out without link previews (see Integrations).\n\n## Saving a file from their mail\n\nOne more tool rides with the reads: `save_my_email_attachment` (message id and index, as `read_my_email` listed the file) copies one attached file into the storage the Executive itself has connected and shares it with the speaker alone, so they get a link they can open or put in an app. Every call it makes is built in code (`orchestrator.mail_file_save`); the model picks only the attachment. The bytes come from the mailbox client's `attachment_bytes` and never pass through the model, any file type up to 20 MB, under a cleaned name (one line, no path or reserved characters, extension kept). The storage is the one the Executive's own mailbox runs on (`EMAIL_PROVIDER`) when the gateway has that server, else the other: Google Drive through workspace-mcp (`create_drive_file` with `base64_content` into a folder named \"From your email\" in the Executive's My Drive, then `manage_drive_access` granting the speaker's own address the reader role, `send_notification` off) or OneDrive through ms-365-mcp-server (`upload-file-content` into the same kind of folder in the Executive's own drive, with a name no recorded copy has, since an upload overwrites, then `share-drive-item` inviting only the speaker, `requireSignIn`, role `read`, `sendInvitation` off). The folder is always made by the save itself and its id remembered (`delegation_saved_folder`), never found by its name, since a folder someone else made and called that could already be shared with them; when the remembered one is gone or won't take the file, a new one is made and the old id stays recorded. Never a link share, a domain or anyone. Neither connected (or an eval's in-memory mailbox): status `no_storage`, and the model says so and offers to forward the email instead. Saves run one at a time, at most 10 a turn (`TurnDelegation.files_saved`), and the result is the status, the name, where it went and the link (`webViewLink` / `webUrl`); the chat chip says only that a file was saved, never the sender's file name.\n\nIt copies only when the speaker asked in their own words this turn: what they typed (`own_words`, no quoted backstory or attached file's text) must hold one of save, saved, upload or OneDrive, or Drive as a place (\"to my Drive\", \"in Drive\", \"Google Drive\"), checked before a slot is spent or the mailbox opened; otherwise it refuses (`not_asked`) and tells the model to ask them. It stays allowed after the turn read mail (`MAIL_TOUCHED_ALLOWED_TOOLS`): its gateway calls are admitted past the lockdown only as the very objects the handler built (`mcp_gateway.code_built_call`, for its seven Drive and OneDrive tools: folder create, file create or upload, the speaker's share, and OneDrive's `list-drives`), so a model's own `call_tool` on that turn is still refused, and every other gateway gate still runs on them (the acting account, URL fetches, sheet formulas, the share gates' roster check, writes kept to the Executive's own drives).\n\nEach copy is recorded before it is shared (`delegation.saved_files`, table `delegation_saved_files`: the person, the storage, the file id, its name and when; never content or the mail it came from), and the folder in `delegation_saved_folder`. The gateway reads that table on every Google Workspace and Microsoft 365 call: on a turn whose speaker is not the file's owner (the owner is the speaker only when Act as me was offered to them, so a shared chat, a workflow or the poller sees none), a call naming a recorded file id, raw or percent-encoded (OneDrive's `download-bytes` path is decoded by Graph), is refused, and a result, filtered against the table as it stands after the call so a copy recorded while a listing ran is caught too, loses each list entry or line naming one, with any id left masked. It matches ids as text, so a result that names such a file without its id (a notification quoting its title) still shows the name, and a copy someone makes is a new file. The folders are guarded harder, on every turn and for every speaker, the owner too: a model call whose arguments name any recorded folder id, or an OneDrive item path through the folder (`root:/From your email/x.pdf:` or `<folder id>:/x.pdf:`), is refused, so nobody can share, move, rename, copy, list or delete the folder from chat, and folder ids are dropped from or masked in every result; only the save's own code-built calls touch it. When a copy is made but its row can't be written, it is not shared, the save reports `failed` and logs an error, and the copy's id is hidden from every turn, the owner's included, for the life of the process. When the table can't be read, the file tools (`_FILE_TOOL_RE`: Drive, folder, file, Docs, Sheets, Slides and presentation tools, attachment bytes) are refused (fail closed) while mail and calendar run. The rows are kept when Act as me is turned off: the copies stay in the Executive's storage, and the rows keep them out of other people's turns.\n\n## Reading their calendar\n\nA third switch under Act as me, **Read my calendar** (`delegation.calendar`, table `delegation_calendar`: one row per person, absent or unreadable meaning off), lets the Executive read the person's own calendar. The principal's daily briefs read it too: `top_three.read_todays_calendar` merges it with the calendar the Executive reads, listing a meeting on both once. It rides on the same per-person sign-in as their mailbox: `calendar.events` on Google, `Calendars.ReadWrite` on Microsoft, added when they run the connect script with `--calendar` (`scripts/connect-own-gmail.py`, `scripts/connect-own-outlook.py`). The one change it ever makes there is answering a meeting invite (see Meeting invites below); a sign-in made earlier with read-only access (`calendar.readonly`, `Calendars.Read`) keeps reading, and the refresh asks Microsoft for whichever calendar scope the file was minted with. Those scopes are optional, so a mail-only sign-in keeps working for mail; the mailbox clients note the scopes the token refresh reports, and `list_events` raises `CalendarNotGranted` before calling the calendar when the scope is missing (or when the calendar answers 403). Only the person turns it on (`PUT /delegation/calendar`), only while Act as me is on and a one-hour read works; a sign-in without the calendar is refused with `calendar_not_granted` and the command to run. Turning Act as me off turns it off. Changes are audited privately (`delegation_calendar_changed`).\n\n`my_calendar` sits with the mailbox reads, offered and fenced the same way: it refuses while the switch is off (before anything is opened), then takes a search slot, opens the mailbox privately (`_open_mailbox`, so `touched_mail` and the lockdown apply: an invite's title is in the words of whoever sent it) and lists the events from `start` (default today) for `days` days (1 to 31) in the workspace time zone, recurring events expanded and cancelled ones left out: title, start, end, all-day, location, organizer, attendees (25 at most) and the person's own answer, each on one line, with a data-not-instructions note. Google's `events.list` on the primary calendar and Graph's `calendarView` (times asked for in UTC) are its only calls; it changes nothing and keeps nothing. The first week's brief also lists today's meetings from it on the principal's own delivery (see Today).\n\n## Forwarding and reminders\n\n`ghostwrite_email` also forwards: with `forward` (a thread id) and `to`, it drafts a forward of the thread's latest message, or of the earlier one `forward_message_id` names (the one with the files, say, when their own reply came after it), `intent` becoming the short note above it (the ghostwriter writes only the note; the forwarded email's subject, someone else's words, is never put in the intent). Recipients follow the new-email rule (`_new_recipients`: the roster, or addresses the speaker typed this turn). Gmail's draft quotes a forward header and the original's own words under the note and attaches the original's files, up to 10 and 20 MB (`FORWARD_MAX_FILES`, `FORWARD_MAX_BYTES`; any left off are flagged `attachments_left_off`); Outlook uses Graph's `createForward`, which keeps the original and its files, with the note as its comment and the body never patched. It is still only a draft.\n\nThe principal's new email or reply can also carry Google Drive files: `drive_files` takes up to 15 Drive file ids (`drive_attach.MAX_FILES`) (not with a forward; a team member is refused, since the files come from the Executive's own Drive). `orchestrator.drive_attach` sizes each one first and then downloads it with code-built `get_drive_file_permissions` and `get_drive_file_download_url` calls as the Executive's Google account (`mcp_gateway.code_built_call`, so the mail lockdown admits those exact calls). It takes the saved copy only from workspace-mcp's own anchored `Saved to:` line, exactly one, whose name ends in workspace-mcp's uuid (the answer echoes the Drive name first, which whoever shares a file chooses), names the attachment from that saved name, reads the bytes only from the tool download folders, removes the copy, and puts them on the draft under the forward cap's 20 MB. When the turn had read outside content before choosing them, the result asks the Executive to name each file so the person checks it. The file's text never reaches the model, so attaching is not an outside read. A file someone saved from their own mail, or a save folder (`delegation.saved_files`), is refused for anyone else, checked before and after the downloads and failing closed when that record can't be read, and a file that can't be fetched makes no draft. Gmail attaches them in `build_raw`; Outlook uploads each to the new draft (Graph's one-request upload, 3 MB a file, larger ones left off and flagged), and removes the draft if an upload fails. The result lists the attached file names.\n\n`remind_me(text, when)` (`orchestrator.reminder_tools`) rides with the same tools and checks, but opens no mailbox, so it never marks or locks a turn (`MAILBOX_TOOL_NAMES` are the ones that do). It stores the text once cleaned — one line, anything a chat app could turn into a link (a URL of any scheme, an address, a domain-like word, a host and port, an IP address) replaced with \"[link]\", at most 300 characters — with its time (stored in UTC) in `delegation_reminders` (5 a turn, 25 waiting, a year ahead, refused when the person has no channel). When it is due the scheduler sends that text to the person alone, as \"Reminder you set on <date>: …\", running nothing (see Scheduler); the Slack and Discord DMs it may go by turn link previews off. The chat chip shows the text as it will be sent. A reminder that comes due in the person's quiet hours or leave (when `OUTBOUND_RESPECT_QUIET_HOURS` is on) waits unclaimed and goes once they end, rather than being suppressed and lost. It is allowed after mail is read and in later turns of that conversation: it reaches only the speaker, as plain text. `schedule_followup`, which runs a turn with tools and is listed to everyone, stays refused there.\n\n## Approval cards\n\nA turn that read someone's mail may not message anyone, invite anyone or change the roster (see the lockdown above), yet what the mail asks for is often right. `propose_actions` (`orchestrator.action_card_tools`) leaves the speaker a card instead: up to five actions, each spelled out exactly as it will happen, done only when they tap Approve. It rides with the other Act as me tools and checks (`_writer`), opens no mailbox, and is allowed after mail is read because it does nothing on the turn.\n\n- **Kinds.** `invite` (a meeting with people on the roster), `message` (a direct message to someone on the roster, as written) `add_contact` (a new contact; the principal's cards only, since contacts are theirs) and `drive_files` (rename and/or move up to 25 Google Drive files; the principal's cards only). A `drive_files` action always waits for the tap, which is its approval: it runs each change as a code-built `update_drive_file` (`MCPGateway.tapped_drive_change`, `tapped_drive_call`), so the own-file check looks only at the folder it goes to, and a move takes the file out of the folders it was in. The card shows each file's current name and the folder's, read when it is proposed; when Drive isn't connected or a name can't be read, no card is made. A team member's card can't name a contact. Each action is checked when the card is made (`delegation.action_cards.check`) and again when it is carried out, so an archived person or a time that has passed fails that action alone.\n- **Whose.** A card is a `delegation_actions` decision for the speaker, `approver_only` like a reply card: only they see it (`GET /delegation/actions`) or resolve it, a team member's answers 404 to the principal too, and it is never an alert. The same actions still waiting are that card, not a new one. 3 cards a turn, 25 waiting, dropped after 7 days.\n- **Approve.** In the chat, under the reply that left it (the `propose_actions` chip carries the card's `decision_id`, and `ChatActionCards` shows the card while it waits), and on the Briefing's Needs you list, with a box per action. Approve (`POST /decisions/{id}/approve`, `edits.only`) needs the card's person signed in (`verified.caller_refusal`) with Act as me on; the card is claimed first so it runs once, then each ticked action runs as stored with no model call, in an unattended session (the principal's with contact egress) under `rows_for_person`, so every audit row it writes is theirs and nothing reaches the team's activity rail: `message_person` (a direct message or nothing; never its Briefing-alert fallback, which more people read), `create_calendar_event`, or a contact row. Approving also needs the person still allowed Act as me (`can_delegate`) and switched on. An invite is booked straight away when the person approving is the one the meeting gate would ask (`calendar_tools.approved_by`), and otherwise goes to that approver as usual, so a card never widens anyone's authority. Per-action results (`done`, `waiting`, `failed`, `skipped`) are kept on the decision and shown on the card. Dismiss rejects it and does nothing else. With Suggested actions in training the card adds the *Do this on its own next time* tick, and a card of actions all allowed is carried out on its own (see In training above); with Suggested actions On, any card that reaches nobody new is.\n- **Channels.** A card can come from any surface Act as me runs on; it is approved in the web app, since the chat apps have no buttons here.\n\n## The ghostwriter\n\n`delegation.ghostwriter.compose` writes the text. The Executive decides *what* to say (`intent`); this call decides *how* the person would say it, and it is deliberately small:\n\n- a constant `GHOSTWRITER_PROMPT` plus the person's voice block as the system prompt;\n- the thread (each message cut to its sender's own words, every line scrubbed, all labelled alike), then the writer's own earlier words in it (`<writer_said>`, from their sent mail only), the intent and the recipients' names in the user turn — no company profile, memory or roster;\n- with Always in the loop on, `<writer_noted>`: what the writer's own notes say they told these same people in earlier Act as me replies (`memory.history_drafts.notes_for_draft`: only notes from mail **every** recipient of the new draft was on, so nothing told to one person reaches another; chat notes name no recipient and never qualify; at most 8, newest first, the person's own words or their correction, with dates). The prompt's rule 6 makes it a consistency check, never content: a draft that contradicts it is still written as the intent says, and the conflict becomes an open question on the card, which only the writer sees. Both the chat tool and the inbox watcher pass it;\n- **no tools** but the forced `compose_reply` return, so text in the thread can ask for anything and there is nothing to do it with.\n\nIt is not a Council agent — the Council's edit routes have no principal check — and runs on `DELEGATION_COMPOSER_MODEL` (default: the default model), logged as `ghostwriter` usage. `lint` then runs in code on what comes back: a link or an email address survives only if it appears in the intent, the signature or the recipients, so a link planted in the thread is removed and flagged; the Executive's own name is flagged; and the body is capped, cut at a paragraph, line or word break in its last fifth. A draft with nothing left after that is refused. The signature from the person's Gmail settings (or the one already stored, for Outlook) is appended.\n\n## How I write\n\n`delegation.voice` learns how a person writes *their own* email (`attunement.style` learns how the Executive should write *to* someone). `POST /delegation/voice/learn` reads up to 40 recent sent messages, keeps only what they wrote (quoted replies stripped with the email poller's `sender_new_text`), skips automatic mail, every thread chat drafted into, and every sent message that began as a draft written for them (`delegation_drafts.sent_message_id`), and makes one forced-tool call (`record_voice_profile`). Code validates every field before it is stored:\n\n- greetings per audience (their team, their contacts, anyone else), a sign-off of at most two lines, and a usual length and tone (a backslash-n the model wrote instead of a line break is read as one, keeping the first lines that fit, which also repairs a profile stored before that rule);\n- up to 8 habits and 6 things to avoid, through the same deny-list as working-style rules — no actions, links, handles, amounts, tool names or names of people; the conversation review (`memory.chat_review`) adds one when the person states how they write in a chat (`add_conversation_rule`, `updated_by=conversation`; never on a locked or full list, and an edit or lock made meanwhile wins);\n- up to 3 short exemplars, each checked to be verbatim from a sample, with addresses and phone numbers masked — and none while a client slot is active, so one client's mail never lands in another's state.\n\nThe signature comes from Gmail's `sendAs` settings, not the model (Outlook gives apps no way to read one, so a learn keeps the stored signature and `POST /delegation/voice/signature` answers 409 `signature_unavailable` rather than clearing it), as plain text with its lines kept (`gmail.html_to_text`: a `<br>` always ends a line, and a block tag, opening or closing, ends one when it has text, so Gmail's layout of a first line followed by one `<div>` per line comes out line by line). `POST /delegation/voice/signature` reads it again without relearning: nothing else changes and a locked profile stays locked, so it picks up a changed Gmail signature and undoes **Don't add my signature**. A person can also describe their style in their own words: `POST /delegation/voice/describe` applies the description to the profile they have through the same forced tool (a separate system prompt, no exemplars) and the same validation, keeps their signature and writing examples, and returns the result with a short sample reply for them to review. It saves nothing and needs no mailbox; Save stores it as an ordinary edit. The person can edit the profile, lock it (a locked profile is never relearned) and reset it, and every change is kept in `delegation_voice_history`. One learn runs at a time per person, and a lock or an edit made while it runs wins: the learned profile is dropped (`changed`).\n\n## Draft replies to my inbox\n\nA second switch under Act as me, **Draft replies to my inbox** (`delegation.inbox`), has the Executive watch the person's own inbox and write a first reply to mail that needs them. The reply waits on a private card on Today; nothing is sent until they tap **Send** (below). Where the reply lives is the person's choice, **Also save replies in my Gmail Drafts** (`mailbox_drafts`, off by default): off, it lives on the card alone (`delegation.card_drafts`: the card keeps the draft's recipients, subject and thread headers as `draft_spec`, and Send makes the mailbox draft from exactly that just before the send-time checks, taking it back out if they refuse), so their Drafts folder doesn't fill with replies they may never send; on, it is also saved in their Drafts as before. The switch is one row per person in `delegation_inbox_watch`. Turning it on needs Act as me on and their mailbox connected, and sets `watch_since` to now every time, so it never drafts for mail that arrived before; turning Act as me off turns it off too. Off means no mailbox call and no row written, with one exception: a send the person started that the mailbox never confirmed is still followed through until it is settled.\n\n### When it looks\n\nA throttled hook in the scheduler tick (`_maybe_scan_inbox`, after the pause, company-profile and rotation gates) checks each person whose switch is on every `DELEGATION_INBOX_POLL_MINUTES` (default 5). It is not a scheduled action, because those are listed on `/scheduled` for everyone and anyone may cancel them. One scan task runs at a time, one scan per person, and none while a client slot is active. **Check now** on the Settings card runs the same scan. Every row a scan writes is private and the person's own (`audit.rows_for_person`: a team member's rows are hidden from the principal too, see Privacy), and the process log carries counts and codes, never an address or a line of mail. The scan never marks mail read or changes a label.\n\n### What it drafts for\n\nA scan first settles the open cards (below), and stops with `backlog_full` once 25 are waiting, counting the ones it makes. It then lists the inbox since `watch_since` (`inbox_message_ids`) — not chats, not mail from the person, and not the promotions, social, updates or forums tabs (on Outlook: the Focused inbox only) — up to 100 messages, and takes the newest message of each thread that still needs a look, at most 10: settled threads and threads with an open card are passed over first, so a burst of mail, or a pause for a limit or a back-off, never hides older threads for good. `delegation_inbox_messages` is its durable cursor: one row per message (`UNIQUE(person_id, message_id)`) with what happened to it, the reason, how many tries it took, and the draft and card ids. It stores a hash of the sender's address, never the address. A message is skipped, with the reason recorded, when:\n\n- it came before `watch_since`, or more than three days ago;\n- it is from the person or one of their send-as addresses, from the Executive, or one of this module's own drafts;\n- it is automatic — `Auto-Submitted`, a bulk or auto-reply `Precedence`, a bounce, a calendar invite or a no-reply sender — or from a mailing list, or in a Gmail tab, spam or trash (with Read my calendar on, a calendar invite goes to `delegation.invites` instead: see Meeting invites);\n- the person is not in To or Cc, or it has more than 10 recipients;\n- the person replied last, or a draft already sits in the thread.\n\nThree kinds are left unrecorded, so a later scan looks again: mail under 10 minutes old (mail the person answers straight away never gets a card), mail in a thread whose card is still open, and mail a daily limit holds back.\n\n### Deciding, then writing\n\nTwo model calls, and code decides between them. The classifier (`delegation.inbox_classifier`) is one forced-tool call, `classify_email`, returning whether the email needs a personal reply, what kind it is and how sure it is. It sees a few one-lined header lines and the sender's own new words (at most 3000 characters, every line scrubbed) inside one `<email>` block marked as data, after the person's own last email in the thread in a `<their_last_email>` block (`their_last_words`: only mail their own mailbox sent, at most 1500 characters), so a reply to something they asked reads as one: an answer to their request for a call that says when the sender is free, without settling a time, is scheduling and gets a draft even when the sender says they will come back with times. It has no other tools, context or memory, so an email can ask for anything and there is nothing to do it with. A reply is drafted only for a question, a request, scheduling, an introduction or a follow-up, and only when the confidence clears a bar that rises the less the sender is known: 0.6 for their team or a contact (the principal's contacts count only for the principal: a team member's mail is weighed by the team and their own sent mail), 0.7 for someone they have written to before (`has_written_to`, a search of their sent mail), 0.85 for a stranger. Pitches, notes of thanks, FYIs, notifications, newsletters and phishing get nothing, and so does any failure. An email that also went to other people is drafted for only when the person is in To and it asks them themselves: the classifier is told their name, whether they are in To or Cc and how many others it went to, and lists the names the email greets or asks by name (`asked_names`). Code matches those against the person's name, whole name parts only (\"Alexis\" never counts for \"Alex\", and a nickname misses, which means no draft), so mail that greets someone else (\"Good morning, Brennan, could you sign ...\") is never theirs, whatever the model makes of it as a whole. When it names nobody, the model's `asked_of_them` decides, false for a question to the group at large. One that only copies them is never drafted for. Either is recorded `not_needed` with the reason `asks_someone_else`. It runs on `DELEGATION_CLASSIFIER_MODEL`, else the routing model. A sender whose address Gmail couldn't authenticate is handled as a stranger whatever the roster says — anyone can put a colleague's or a client's address in From — so they get the stranger's bar, a holding reply and the stranger limits; the card still says who they claim to be, and that the address isn't verified.\n\nThe reply is written by the same ghostwriter, in the person's voice, but from a fixed intent the module builds rather than words the person typed. Because the intent lets it restate the person's own earlier words, which words are theirs is never written inside the thread, where a sender could imitate any marker with a look-alike: every message there is labelled alike, and the person's own words come in a separate `<writer_said>` block after the thread, taken only from mail their own mailbox sent. Nothing inside the thread can close the thread block or open another. The intent: acknowledge the sender; say again only what the person's *own* earlier messages in the thread already said; commit to nothing new — no yes or no, date, time, price, fact or promise — and say they will get back to them; and put every question it could not answer from their words in **open questions**. A stranger always gets a short holding reply. The lint still strips any link or address that isn't the person's own. The reply goes to the sender (never `Reply-To`) and, on a group email, to everyone else it went to as Cc (reply to all, never the person's own addresses or the Executive); a stranger's holding reply starts with the sender alone. When others were on the email the card offers **Reply to**: the sender only, or everyone (`PUT /delegation/replies/{id}/recipients`, `card_drafts.set_recipients`). It picks between the two lists fixed when the card was written (`reply_others`), never an address from the request, and changes the mailbox draft's To/Cc too. Its `draft_to` lists who it goes to, which Send checks.\n\nThe order: record the message, classify, reserve a slot in the shared daily limit, write, save the draft in Gmail (from the alias the mail went to, when it went to one) and store its id, then create the card (idempotent on the message: a second call finds the open card, and a card dismissed or lapsed under that key doesn't stop a new one, while one sent or settled in the mailbox means no second card, `invites.create_once`) and mark it drafted. Nothing that fails along the way loses the message. A failure that may pass — the classifier or the writer failing, Gmail refusing the draft, a card that couldn't be made (its draft is deleted first, so no draft is left without a card), any other error with that one message — leaves it for a later scan (`retry`), and it is given up on only after three tries; one message's trouble never holds up the rest. A daily limit reached while it was being read leaves it for later without counting as a try.\n\n### The reply cards\n\nA card is a `delegation_reply` decision whose class is **its approver's alone** (`DecisionClassSpec.approver_only`): only the person it was drafted for sees or resolves it on any decisions route — a team member's card answers 404 to the principal too — and it is never an alert: alerts feed chat turns, which would put other people's mail into memory. It carries the sender with who they are to the person and whether Gmail could verify the address (SPF/DKIM/DMARC, through `fact_confirmation.headers_authenticated`), the subject, what they wrote, the draft, the open questions and its warnings. `GET /delegation/replies` lists the open ones from the database alone, so Today never waits on Google.\n\n- **Send** approves the card, which sends its draft exactly as it is in their mailbox (see *Send on your tap*). **Edit** changes the reply's words right on the card (`PUT /delegation/replies/{id}/text`, `card_drafts.edit`): only its own person, from a caller the API can tie to them (as for Send), never while it is being sent on its own; a reply in their Drafts is rewritten there too (`update_draft_text`, every header kept), and only while it is still the version the card last saw, so a change made in the mailbox is never overwritten. A card edit counts as edited (`approved_with_edit`, and **Do it like this next time** keeps it), and one made by hand sets `questions_settled`.\n- **Decide before sending** with taps (`delegation.answers`): the ghostwriter returns each open question with 2 to 4 short answers the person might pick (`choices`) and what it is `about` (time, document, other); plain strings still parse, and `open_questions` stays a list of strings for every other reader, with `question_choices` beside it on the card. After the draft is written, code fills two kinds: a time question gets up to 3 free half hours on the person's own calendar (Read my calendar on; one a day over the next 5 working days, busy times only, no event title reaches a model), \"I checked your calendar: these are free.\"; a document question whose words match a company document's name gets 'I'll send \"<name>\" separately', \"Found \"<name>\" in your documents.\" Nothing is attached: a card's draft is plain text. A tap, or **Something else…**, calls `POST /delegation/replies/{id}/answer`: one composer-model call rewrites the body with the answers in their voice (signature and AI line kept out and put back), `ghostwriter.lint` runs on it, and it is saved through `card_drafts.edit` with the same caller and card checks and the same Drafts update. It returns the card with `changed_sentences`, which the card lightly marks. 30 rewrites an hour per person (429). Send waits until every question with choices is answered, or the words were changed with Edit. A card made before choices shows its plain questions. **Open in Gmail** (or **Open in Outlook**), shown only when the reply is in their Drafts, opens it there.\n- **Dismiss** rejects the card; the class's after-reject step then deletes the draft if nobody edited it — its message id is still the one it was saved with, since Gmail gives an edited draft a new one, and the Outlook client makes a draft's message id `<id>.<changeKey>` so an edit there changes it too — and keeps it otherwise. What happened is recorded even when Gmail fails.\n- Each scan first **settles** what Gmail already settled: a draft sent from Gmail, a draft deleted there, a reply the person wrote themselves, a thread that is gone, or a card left for 7 days (its draft stays in Gmail). Each is a compare-and-set close with the reason. A newer message from someone else flags the card instead. A card being sent at that moment is left alone.\n\n### Send on your tap\n\n`delegation.reply_send` is the only thing in Act as me that sends, and all it can send is the draft on a card, by its id: `DelegateGmail.send_draft` posts `{\"id\": …}` to Gmail's `drafts.send`, and `DelegateOutlook.send_draft` posts an empty body to that draft's Graph `send`, and nothing else, so no text, recipient or header is ever passed. It has two doors: `send_approved_reply`, reached only from `POST /decisions/{id}/approve` — a class only the card's own person may resolve — and `send_on_its_own`, reached only from the inbox watcher under Handle it for me (below). AST tests pin both call sites, so no model, chat turn, workflow, scheduled job or MCP call can. A tap is checked like this: At send time it checks everything again:\n\n1. **Who is asking.** The caller is the card's person and the API knows it: signed callers are on and the request carries that person's signed assertion (or the operator's, under local login), or the API runs for local login and answers this computer only. Anything else is a 409 `caller_signing_required` — with only the shared secret, whoever holds it could send as the owner — so on a server Send needs signed sign-ins.\n2. **The switches.** Act as me and Draft replies to my inbox are on, and no client slot is active.\n3. **The mailbox.** Their mailbox is connected.\n4. **The draft.** It still exists, in the same thread, and they haven't replied there themselves since; otherwise the card closes.\n5. **Who it goes to.** To, Cc and Bcc hold between 1 and 10 addresses, never the Executive's own, and it is from one of their own addresses.\n6. **What changed.** Recipients that differ from the card's, or a newer message from someone else, need a second yes: the first tap gets a 409 `confirm` naming the recipients and the reason, and the person approves again with what they were shown.\n\nThen it claims the card (`claim_for_execution`, proposed → executing, a compare-and-set, so a double tap sends once) and reads the draft once more: `drafts.send` sends whatever the draft is when Gmail gets the request, so if it was edited since the checks read it — in another tab, by a delegate — nothing is sent and the card comes back (`draft_changed`). Then it sends, and records the result: `approved_with_edit` when the draft was edited in Gmail, the sent message's id, the draft row's `sent_message_id`, and a private `delegation_reply_sent` row. A refusal that proves nothing went — a 4xx, a lapsed sign-in, a rate limit, a draft already gone — hands the card back. A failure that leaves it unclear — a timeout, a 5xx — leaves it `executing` and says to check the Sent folder, and the next scans ask Gmail: their message in the thread means it was sent; anything else is judged on the second scan that sees it: the draft still there and nothing sent means it was not (Gmail deletes a draft it sends), and the card comes back, flagged; the draft gone and nothing sent means it was deleted. Nothing is ever retried on its own. Sending is the person's own act, so it works while the Executive is paused.\n\n### Limits and failures\n\nAt most 5 drafts a scan; `DELEGATION_INBOX_MAX_DRAFTS_PER_DAY` (default 20) a day, inside the shared `DELEGATION_MAX_DRAFTS_PER_DAY` it shares with chat; 200 classifications, 2 drafts per sender (1 for a stranger) and 10 for strangers in all per day; and never more than 25 open cards. A lapsed Gmail sign-in sets the status and is looked at again every 30 minutes; a rate limit, an error reaching Gmail or a crash backs off from 5 minutes, doubling up to 2 hours. Neither turns the switch off: the Settings card shows the status in plain words.\n\n## Handle it for me\n\nA third switch under Act as me, **Handle it for me** (`delegation.handle_it`), lets the inbox watcher send some of its replies itself instead of leaving them on a card. It is one row per person in `delegation_handle_it` (`enabled`, `mode`); no row means off. One setting says how much goes without them, the way quality does on the Agent Council (`handle_it.RULES`): **Easy ones** (`careful`) sends only replies to people they know (someone on their team, a contact or someone they have written to) of at most 400 characters when the classifier is at least 0.9 sure; **People I know** (`balanced`), where it starts, sends replies to people they know up to 1200 characters at 0.8; **Most mail** (`bold`) also answers strangers, up to 2000 characters, and lets a link or an amount through when the classifier is at least 0.9 sure. Everything else waits on a card as before, so turning it on never drafts less. A table from before the setting gets the `mode` column on its next open (`schema._add_handle_it_mode`): someone who had strangers set to send keeps that as Bold, everyone else gets Balanced. Only the person turns it on (`PUT /delegation/handle-it`), from a session the API knows is theirs: the same rule Send uses (`delegation.verified.caller_refusal`), so with only the shared secret it answers 409 `caller_signing_required`. Turning it on needs Act as me and Draft replies to my inbox on, and turning the inbox watcher off (or Act as me, which turns it off) turns it off too.\n\n**In training** (`delegation.training`). Like someone new, each Act as me job can be put in training on its own, from that job's card on the Act as me page, the way Take the lead has it: **Write drafts as me** and **Handle it for me** each pick Off / In training / On (Handle it's In training puts Replies and Follow-ups in training together; its steps show under On only, since in training only allowed people go whatever the step), and **Suggested actions** picks Always ask / In training / On (On is the `actions_on` switch: a card is carried out with no allow, under the same checks, and only when it reaches nobody new: a new contact or anyone on the roster under a week waits; In training wins when both are set); what it learned is listed on each tab for its own jobs (Act as me: *What it's learned*, drafts and suggested actions; Handle it for me: *Who it's allowed to handle*, replies and follow-ups), each item named by its job (`PUT /delegation/training`, one row per person and setting in `delegation_training`, absent means not in training). In training it asks first and learns who and how from what the person approves; what it learns is a `take_the_lead_allowed` row (feature `act_as_me`, the person's id), theirs alone.\n\n- **Replies.** Every reply waits on its card (`handle_it_reason` `training`) whatever the dial says, and a reply card adds **Send + allow**: it sends that reply on the person's own tap, exactly as Send does, then allows replies to that sender (key `act_as_me|person:<id>|reply|<address>`). While Handle it for me is on, a reply to an allowed sender goes on its own under the dial's limits (a stranger they allowed included) and every check above (the topics that always wait, links and amounts, new recipients, once a thread a day, the daily limit); it's checked again at send time, so a sender removed since waits. Take the lead as you lifts nothing in training: putting Replies or Follow-ups in training turns it off, and it can't be turned on while they are (409 `in_training`).\n- **Follow-ups.** Every follow-up waits (`follow_up_training`); Send + allow on a follow-up card allows follow-ups to exactly the people it went to (`…|follow_up|<sorted addresses>`), whoever they are, under every other follow-up check.\n- **Suggested actions.** An action card (below) adds **Approve + allow**: it does the actions on the tap, then allows each one that happened (a message to that person, `…|message|person:<id>`; a meeting with exactly those people, the person left out, `…|invite|people:<ids>`). A new contact is never allowed. A card proposed later whose every action is allowed is carried out at once, with no tap (`action_cards.run_on_its_own`, `gate_mode` `auto_execute`, status `executed`), only if plain code finds nothing against it (`on_its_own_refusal`): still in training, Act as me on, a server that ties the switch to the person, nothing sensitive, no link or amount, a message of at most 1200 characters, and at most 10 actions carried out this way a day (checked one card at a time); anything refused is handed back to wait on its card as before. An invite carried out this way is never booked as approved by the person: the meeting gate decides as for any meeting nobody tapped, so a time taken from someone's mail can't land on a calendar unasked. The tool result and chip say what was done. The message text in such an action is model-written from the mail and goes without anyone reading it; the allowance covers who and what kind, not the words, which is why sensitive topics, links, amounts and long messages are held back.\n- **Drafts.** Nothing is sent. When the person changes a reply's draft in their mailbox before tapping Send (plain or + allow) and ticks **Do it like this next time**, what they sent is kept (its new text, quoted replies dropped, at most 1000 characters, `…|style|<address>`), and the ghostwriter gets it in its user turn as `<writer_example>` when it next writes to that person, from the inbox, a follow-up or a chat draft to that one person: style only, never its facts, and nothing in it can open or close a tag.\n\nSend and Approve with the *on its own next time* tick (`allow`; the tick replaced the separate Send + allow and Approve + allow buttons) are refused before anything is done unless their setting is in training (422 `cant_allow`) and the person's list has room (409 `learned_full`, at most 200 a person); allowing failing afterwards never undoes the send. Putting Replies or Follow-ups in, or Suggested actions out of training or On, only holds more back and works without signed sign-ins; anything else needs a caller the API knows is that person. What it learned is the person's alone: listed on `GET /delegation` (`training.learned`, each with its `setting`), removed with `DELETE /delegation/learned/{id}`, and for the owner also in Take the lead's \"What it's learned\" list; it never reaches anyone else's list or Take the lead's prompts. A dial left on In training by an older version (mode `training`) moves to People I know with Replies and Follow-ups in training (`schema._move_training_off_the_dial`).\n\n**No model decides whether a reply goes.** The watcher's two model calls are unchanged and tool-less, so text in an email can at most change the verdict and the draft. After the draft is written, `handle_it.refusal` — plain code — decides, and anything it refuses becomes the usual card with the reason kept on it (`handle_it_reason`). It refuses when:\n\n- it's off, or the sender is a stranger and the setting isn't Bold, or on a server signed sign-ins are off (`signing_ok`: signed callers, or local login);\n- Gmail couldn't authenticate the sender, whatever the roster says;\n- the email isn't a question, request, scheduling, introduction or follow-up, or the classifier was less sure than the setting needs (0.9 on Easy ones, 0.8 otherwise);\n- the reply goes to anyone the email didn't already go to (its From, To and Cc, less the person's own and the Executive's addresses), leaves out the sender, or goes to more than 10;\n- the email's subject, the sender's new words, or the reply touch money, contracts, legal, hiring, pay, layoffs, the board, investors, mergers, the press, health, or credentials and secrets (passwords, logins, tokens, API keys); or the reply carries an amount, a percentage or a link (a scheme, `www.`, a bare host with a path such as `bit.ly/…`, or a bare host on a common top-level domain) unless it's Bold and at least 0.9 sure, or runs over the setting's length (400, 1200 or 2000 characters);\n- the draft carries any flag but *others on the thread* or *Executive on the thread* (they asked if it's an AI, recipients were trimmed, …);\n- it already sent one in this thread in the last day, or the person's last message in the thread was itself sent on its own (no auto-reply ping-pong);\n- the day's limit is reached (`DELEGATION_HANDLE_IT_MAX_SENDS_PER_DAY`, default 20, within the watcher's drafts limit), or it can't be counted. Any error in the rules counts as a refusal.\n\nA reply the rules allow gets a card with `gate_mode` `auto_execute`, and the watcher sends it at once through `reply_send.send_on_its_own`, the second and last door into the send path (an AST test pins both callers: the approve route and the watcher). It runs the same send-time checks as a tap — switches, mailbox, draft, recipients, the claim and the last re-read — with no caller, and adds its own: the card must be `auto_execute`, Handle it for me still on with the setting still allowing that sender (or, for a follow-up, that recipient), signing still on, the once-a-thread-a-day rule and the daily limit counted again, and the draft untouched since it was saved (an edit in Gmail means the person has taken it over: `draft_changed`, the card waits for them). Every refusal hands the card back to the person (`decision_ledger.hand_back`, a compare-and-set to `propose`), with the reason kept on it when there are words for it, and a failure never stops the scan. Every card it left for the person says why on Today (`waited_because` on `GET /delegation/replies`). A reply sent on its own finishes as `executed` (not approved), is recorded in `delegation_handled` (for the per-thread and daily rules) and writes a private `delegation_reply_handled` row; an unconfirmed one is settled by the reconciler the same way. No History note is taken from it, since notes come only from the person's own words. It runs inside the watcher's scan, so it stops while the Executive is paused.\n\n**Follow-ups as you** (`delegation.follow_ups`). While Handle it for me is on, the watcher's scan also looks at the person's own sent mail, at most once an hour (`LOOK_EVERY`), for an email of theirs that asked something (a question mark in their own words), is 3 to 10 days old, went to at most 10 people other than the Executive, and is still the last message in its thread. Plain code picks it; each gets one follow-up ever (its `delegation_inbox_messages` row), at most two a look, within the drafts limit. The ghostwriter, tool-less as always, writes a short nudge in their voice from the thread, saved as a draft in that thread to exactly the people the email went to. `handle_it.follow_up_refusal` — plain code — decides whether it goes: by the setting it never goes on Easy ones, goes to their team and contacts on People I know and to anyone they wrote to on Most mail (`follow_up_refused` otherwise: `follow_up_level`); it also refuses on any change of recipients, a sensitive topic, an amount or a link, more than 600 characters, a flag, and the same per-thread and daily counts as replies. It goes through `send_on_its_own` on an ordinary `delegation_reply` card marked `source: follow_up`, which rechecks the setting for that recipient. A refused one waits on Today as **Follow-up waiting**, and closes by itself (its untouched draft deleted) when anyone answers in the thread first.\n\n**What it sent** is the person's alone: `GET /delegation/handled` lists the last 7 days (who, subject, the reply, the questions it left them and a link to the thread in their mailbox), and the Handle it for me tab shows it with how many went today, under its picker.\n\n### Take the lead as you\n\nOn Settings → Act as me, Handle it for me is one dial: **Off**, **Easy ones**, **People I know**, **Most mail** and, for the owner, **Everything**, which uses **Take the lead** (`PUT /delegation/take-the-lead`, one row `person:<id>` in `take_the_lead`; turning it on turns Handle it for me on). While it is on, `handle_it.refusal` drops the setting's limits: strangers, the classifier's confidence, amounts, and the length up to a 4000-character ceiling. A reply with a link still waits for a tap (refusal `link`). In their place it checks the company's and the person's own added rules (`take_the_lead.reply_hit`, refusal `lead_rule`). Everything Handle it always keeps still holds: signed sign-ins, an authenticated sender, a reply kind, exactly the thread's people, the topics that always wait, draft flags, never twice in a row, one a thread a day and the daily limit. Follow-ups under it may go to anyone the person wrote to, with the same sensitive, amount, link and length checks plus the added rules. `reply_send.send_on_its_own` accepts the card while both switches are on. Each person adds and removes their own rules (`/delegation/take-the-lead/rules`). Removing one needs a caller the API can tie to them.\n\n\n## Meeting invites\n\nWith **Read my calendar** on, a calendar invite in the person's inbox no longer just gets skipped (`delegation.invites`). The watcher applies its usual rules, less the ones about writing a reply (a calendar service's own Sender header doesn't make it automatic; a big meeting isn't too many recipients), and then looks at who sent it: someone the person knows — their team, a contact, or someone they have written to (`inbox.relation_of`), with the sender confirmed by the mail service (`inbox.handling_relation`) — or it is skipped as `invite_stranger` / `invite_unverified`. It then finds the event on their own calendar: on Google by the invite's iCalendar UID (read from its `text/calendar` part, or its attached `.ics`) in their primary calendar, on Outlook as the invite message's own event; only a request counts (a cancellation or someone's answer doesn't). An event that can't be found, isn't organized by the sender, is already answered or has already started is skipped with that reason, as before. **No model is called** for an invite.\n\nWhat's left becomes a card, a `delegation_invite` decision that is its person's alone (`approver_only`) and never an alert, like a reply card: who invited them, the title, when (in the workspace time zone) and any **clash** — the busy times on their calendar that overlap the meeting, computed in code from the calendar read; only start and end times reach the card, never another event's title. **Accept** and **Decline** are `POST /decisions/{id}/approve` with `edits.answer` (`accept`, the default, or `decline`), on the same caller checks Send uses (`verified.caller_refusal`); the card is claimed, then answered with the mailbox client's `answer_invite`. Answering again is harmless, so a failure releases the card for another try; an event that has gone fails it. **Dismiss** (`reject`) answers nothing. A sign-in that reads but can't write the calendar keeps its card, which says to connect again under Read my calendar (with the command) instead of offering Accept. A card closes by itself once the meeting starts or after a week, and its thread waits until it's settled.\n\n**On its own.** Under Handle it for me (On, or Take the lead as you) it accepts with no tap when plain code finds nothing against it (`invites.refusal`): a sender on their team or in their contacts, never one known only from their Sent mail (with Replies in training, only one they ticked **Accept from them on its own next time** for), signed sign-ins or local login, no clash and a calendar it could read, nothing sensitive in the title, a sign-in that can answer, and Handle it for me's daily limit and once-a-day-per-thread rule (`handle_it.count_refusal`, `record_handled`). It never declines on its own. Anything against it leaves the usual card saying why. An accepted invite is listed with the replies it sent: `GET /delegation/handled` (`source: invite`, with a one-line `summary` such as \"Accepted Dana's Pilot review, Wed 21 Oct, 14:30\") and Today's `sent_as_you` activity, the person's alone.\n\n**In training.** With Replies in training, a card has the same tick as a reply card; ticking it and tapping Accept adds `Accept invites from <name>` to their learned list (key `act_as_me|person:<id>|invite_from|<address>`, under Replies), removable like any other.\n\nAudit rows, all private to the person: `delegation_invite_carded`, `delegation_invite_answered`, `delegation_invite_handled`, `delegation_invite_dismissed`.\n\n## AI line on replies\n\nReplies written as a person can end with **\"Drafted and sent by my AI assistant.\"** (`delegation.disclosure.LINE`), by two switches that are each person's own (`PUT /delegation/disclosure`, one row per person in `delegation_disclosure`, NULL following the install): **Handle it**, on by default (`AI_DISCLOSURE_HANDLE_IT`), for a reply Handle it for me will send on its own, which nobody reads before it goes; and **Approved sends**, off by default (`AI_DISCLOSURE_APPROVED_SENDS`), for one that waits on a card for them to send, since they read it first. The line is written into the reply when it is drafted (`disclosure.sign`, in `inbox._consider` and `follow_ups`), once the plain-code checks have decided whether it goes on its own, so the card, the mailbox draft and what is sent are the same words and Send's draft-changed checks see them; a switch changed later applies to the next reply, and a reply drafted to go on its own that is handed back keeps its line for the person to edit. `AI_DISCLOSURE` off turns both off and hides the card. Turning a switch on only adds the line, so it needs no signed sign-in; turning one off does. Each tab shows its own switch under Advanced (**AI line on drafts you send** on Act as me, **AI line on replies it sends** on Handle it for me), and turning off the Handle it line asks first.\n\n## The mailbox client\n\n`delegation.gmail.DelegateGmail` talks to the Gmail REST API directly and is **never registered with the MCP gateway**, so the model reaches the mailbox only through the typed handler. The credential is one file per person in `DELEGATION_GOOGLE_CREDENTIALS_DIR`, named from a hash of the address (0600 in a 0700 directory), minted by `scripts/connect-own-gmail.py` on the Executive's own OAuth client with the scopes `gmail.readonly` and `gmail.compose`. It never lives in `WORKSPACE_MCP_CREDENTIALS_DIR`, where workspace-mcp picks a credential by address. Besides reading threads and saving drafts it lists the inbox and checks whether they have written to an address, reads one message or draft, lists the person's send-as addresses and deletes a draft. Its **one send method**, `send_draft`, sends an existing draft by its id and nothing else — never `messages.send`, which sends any text it is given — and unit tests pin the method set, the endpoint, the request body and its single caller. On the calendar it reads (`list_events`, `find_invite`: an invite's event by its iCalendar UID) and makes one change, `answer_invite`: the person's own attendee answer on one event, with `sendUpdates=all` so the organizer hears (`calendar_write_granted` says whether the sign-in allows it; a read-only one raises `CalendarWriteNotGranted`). A failed request says whether it may have been carried out anyway (a timeout after connecting, a 5xx), which is what the send path needs to know. A parsed message carries when it arrived, whether it is bulk, a bounce or a calendar invite, and whether Gmail's authentication results vouch for its sender.\n\n`gmail_status` answers `connected`, `not_configured`, `needs_reconnect` (Google refused the saved sign-in — an app in Testing mode has its tokens expire after 7 days; a rate limit, though Gmail may send it as a 403, is an `error` to retry, not a reconnect), `mismatch`, `no_email`, `shared_mailbox` or `error`. `shared_mailbox` means the person's address *is* the Executive's; it is refused before asking Google, because then everything the Executive writes would look like theirs. The gateway closes the other door: every `google_workspace__*` call must act as the Executive's own account, and a `user_google_email` naming anyone else is refused and audited (see Integrations).\n\n### Outlook\n\nA person may connect an Outlook mailbox instead (work, school or personal), with `scripts/connect-own-outlook.py`: a device-code sign-in on the Executive's own Entra app (`MS365_MCP_CLIENT_ID`, tenant `MS365_MCP_TENANT_ID` or `common`) asking for `User.Read`, `Mail.ReadWrite`, `Mail.Send` and `offline_access` (and `Calendars.ReadWrite` with `--calendar`; an invite is the invite message's own `eventMessage.event`, answered with Graph's event `accept` or `decline` and `sendResponse`). It writes the same per-person file with `\"provider\": \"microsoft\"`, so a person has one mailbox for Act as me, and `gmail_for` hands back `delegation.outlook.DelegateOutlook`, which keeps `DelegateGmail`'s methods, return types and errors, so every caller above runs unchanged. It talks to Microsoft Graph directly, never through the Microsoft 365 MCP server the Executive's own Outlook uses, and is never registered with the gateway. Microsoft rotates the refresh token on use; the new one is written back into the file (atomically, keeping every other key, and only if the file still holds the old one). Graph is asked for immutable ids, so a sent draft keeps its id; a thread is Outlook's `conversationId`. Gmail's labels are mapped onto what the callers read: `SENT` only for mail in their Sent Items folder (a From line set to their address by someone else never counts), `DRAFT`, `INBOX`, and Focused Inbox's Other read as a tab. A sender counts as authenticated only when the topmost `Authentication-Results` — the one Exchange wrote, above anything the sender added — holds exactly one DMARC verdict, a pass for From's own domain, and Exchange Online Protection's own `compauth=` verdict, so a header the sender wrote on mail EOP never stamped doesn't count. `delete_draft` refuses anything that isn't a draft, and deletes with the draft's etag (`If-Match`), so a draft sent in between — it keeps its id — is left alone. No client secret is ever written into a person's file, and Graph has no signature setting to read.\n\n## Privacy\n\nWhat a person's mailbox touches is theirs. For the principal that means private to the principal, as every private row is. For a team member it means theirs alone, the principal included: an audit row carries `private_to_person` (set by `audit.rows_for_person` around the inbox watcher, a card's Send and Dismiss and their settings changes, and by `people_tools.audit_row_owner` on a turn that read their mail) and is left out of every audit read — the log, a session's timeline, a row by id, the brief — with only the usage totals counting it; their reply cards are theirs alone (above); and the owner's view of their use is counts only (drafts and sends in 30 days, and whether their inbox watcher is on). The conversation itself becomes its owner's alone before the mailbox is first read: `ghostwrite_email` marks the session `mail_private` (`session_store.mark_mail_private`, creating a channel adapter's row early, with its owner) and refuses to read the mailbox if that can't be stored or the conversation already belongs to someone else (which it then leaves unmarked); from then on only its owner may open it (`chat._session_access`), and working-style learning skips it. Every later turn there starts private (`settings.pin_turn_delegation` reads the flag and fails closed, setting `touched_mail`), so a follow-up answered from history alone is still private to its owner and teaches no memory, and the web chat's rows before the turn (the inbound message and the knowledge lookup) are theirs too. It does not start locked down: the lockdown is `read_mail`, set only by a turn that reads the mailbox or notes itself, and it is never carried into the next turn, because history keeps only the speaker's words and the Executive's replies, never the mail a tool returned. Their next message is them asking again, having read that reply, so everything runs again there. Anyone else speaking in it is not offered Act as me.\n\nOnce `touched_mail` is set, every audit row the turn writes is private (`people_tools.audit_row_private_to_principal`), and a team member's is theirs alone: the tool row (its input and result redacted, since `ghostwrite` is a sensitive tool name), the reply's `chat_turn` row that carries the preview, the model-call rows, and the background passes, which run under `private_rows`. The Honcho peer and department syncs are skipped, because peer memory is read on other people's turns. No memory is learned from the turn at all: the episodic, open-loop and working-style passes are skipped too, since its reply quotes a draft built from other people's mail. The `delegation_*` audit events are always private and carry metadata only — ids, counts and flags, never the draft or the thread. The inbox watcher is private the same way: every row a scan or a card action writes is its person's alone, and it starts no chat turn, alert, scheduled action or workflow run and teaches no memory.\n\nThe turn also keeps one door shut (`delegation.lockdown`). Anyone can put text in the inbox, and that text could try to steer the model, so from the round that calls `ghostwrite_email` or one of the mailbox reads — a round's tools run together — until the turn ends, the dispatch guard refuses only what opens the open internet or reaches everyone: outside fetches (`read_document`, research, the watchlist, `load_mcp_server`, and any MCP `call_tool` outside the private-turn set of reads and recipient-checked sends), `run_script` and `run_python_job`, workflows (they run later, unattended, and may fetch or script), broadcasts, department messages and alerts, and changes to who is on the roster or holds authority (`archive_person`, `set_department_head`, `resolve_roster_request`), and text that steers later turns (`schedule_followup`, whose intent runs unattended when due, and goals and decision outcomes, shown to every later turn). Everything else the person asks for runs, because it is fenced on its own: DMs and `message_person` reach only the roster, invites name attendees by person id, the Executive's own email checks every recipient against the roster, standing facts and profile edits keep only the person's own words, and a workflow drafted in chat is saved only once a person confirms it. `upsert_person` runs only for a contact the person asked for (`speaker_named_contact`: a contact, never the team, an approval scope or a chat account, with a word of the name in what they typed, in a message that asks to add, save or change someone, a new contact's address one they typed or one that sent the mail the turn read under the contact's name (`TurnDelegation.mail_senders`), never one the mail's text only mentions, and on an update a changed address they typed), since the roster is what the send checks trust. Any other contact add is refused with a pointer to an approval card (`lockdown.CONTACT_REFUSAL`), so the Executive leaves an `add_contact` card in the chat rather than asking them to type the address. What an email itself asks for is still never done on its say-so; it goes on an approval card. Every tool is classified as allowed or withheld, a test fails on a new unclassified one, and an unknown name is withheld, except an extension tool registered with `after_mail_read` (one that only reads the install's own data). The refusal tells the model to put what the step needs in its reply, since the next turn sees the reply but not the mail, and to do the step then without reading the mail again. A refused call gets a private `tool_invocation` row (`refused: mail_touched`) and tells the model to offer it in the next message. The offered tool list never changes mid-turn, so the cached prefix holds. The handlers that reach outside check again on their own (`outside_reach_refusal`). The server-side web search stays, as on a turn private to the principal. The lockdown ends with the turn. Later turns of that conversation stay private to its owner (`touched_mail`) but hold nothing: a refusal says it will work when they ask again in their next message, and it does.\n\n## Always in the loop\n\nA sent reply can leave a note. Once the reply went, `reply_send` starts `memory.history_notes.note_sent_reply` for the person who sent it, in the background, when their \"Keep track of what happens\" switch is on and the conversation isn't one they asked not to remember. The note-taker sees only the words they sent, so other people's mail never becomes a note, and a failure never touches the send. Recall is `recall_history`, offered on the same verified, private surfaces as `ghostwrite_email` and also allowed under the mail lockdown, since it only reads the speaker's own notes. Calling it locks the turn like `ghostwrite_email` does, from its own round on. The same switch also covers notes from chat, which don't need Act as me. See **Memory** for the checks, retention and controls.\n\n## The system prompt\n\nA constant, name-free `DELEGATION_ADDENDUM` joins block 0 after the unchanged identity addendum while anyone on the install has it on (`block0_delegation_on`). It names the four mailbox reads and says other people's mail is data and that a conversation which read it reaches nobody else; and it tells the model that `ghostwrite_email` is the single exception to *never impersonate*, and only for the person being spoken to; that everything else is written as itself; that when the tool isn't offered the asker can't have it; that a draft is never described as sent; and that it never denies being an AI. It is keyed on the install-level setting, never on the turn or the speaker, so switching it misses the 1h cache once (see Prompt Caching).\n\n## What it does for you\n\n**What it does for you** (`delegation.may_do`, `GET /what-it-may-do`) is read-only: with the viewer's settings right now, one row per thing that can go out without asking, written as one sentence of what it does, what happens to it (goes out, waits for someone, always waits, drafts only, off) and which setting decides it, with a link there. It sits beside every Delegate tab (`DelegatePage` → `WhatItDoesPanel`): a column to the right on a wide screen (closing it is remembered in the browser), a bottom sheet on a narrow one. The UI groups rows by outcome (Sends on its own, Asks first, Writes for you to send, Off). Every delegation setter in `lib/api.ts` fires `DELEGATION_CHANGED` after a save; the panel reloads on it and marks the rows whose outcome or text changed as **Just changed** for ten seconds. `/delegate` and the old `/delegate/what-it-may-do` open Act as me. Its **Compare** fold holds Who writes and who sends. Three parts, each behind a pill that counts what goes out:\n\n- **As you** (the caller's own, when `can_delegate` allows them): built from `settings.is_enabled`, `inbox.get_watch`, `handle_it.get` and `handle_it.RULES`, `handle_it.leading` (Everything), `training.get` and `training.learned`, and their rules, the same reads `handle_it.refusal` and `follow_up_refusal` make. A level's row follows its `Rules` (strangers, follow-up reach, links and amounts), not a copy of them. A note names the ladder: Handle it for me rides on Draft replies to my inbox and Write drafts as me, and Everything also drops when Replies or Follow-ups go into training.\n- **As the Executive** (the principal's alone, as `GET /take-the-lead`): the switch and its training, each Ask first kind, the company's rules, and meetings. A meeting it thinks of on its own always waits: both meeting gates need someone on a verified surface in the turn, which an unattended run never is. A meeting someone asks for in chat follows **Always asks first → Meetings asked for in chat** (on means it waits: `meeting_scheduling`'s class mode is `propose`; off means `auto_execute`) and, in a team workspace, Operations' level too.\n- **Departments**: each level, and what a level covers (department-scoped scheduled work, check-ins, alert review, team members' chat sends, and Operations' meetings), and that it doesn't cover what the Executive does under Take the lead.\n\nIt also says when the Executive is paused, and when nothing can be sent as anyone because signed sign-ins are off. Nothing on it writes or reads mail. A contact, someone not on People, or a request with no caller (outside local login) gets 403.\n\n## How far it goes as you\n\nOne setting replaces the switches that used to turn each other off out of sight. The UI shows it as two pickers (`ReachCard.tsx`): **What it writes as you** (`WritesCard`) on the Act as me tab and **What it sends on its own** (`SendsCard`) on the Handle it for me tab; What it does for you links each row to its own picker. Its steps, each adding to the one before: **Off**, **Drafts when I ask** (Write drafts as me), **Drafts for my inbox** (Draft replies to my inbox), then the Handle it for me steps that send, **Easy ones**, **People I know** and **Most mail** (`careful`, `balanced`, `bold`), and for the owner **Everything** (Take the lead as you). Act as me shows the first three as **Off**, **When I ask** and **Draft replies automatically** (any sending step reads as Draft replies automatically there). Handle it for me shows **Off** (saved as the inbox step) and the sending steps, and opens only once Act as me is at Draft replies automatically, with a button that turns that on; moving Act as me below it says Handle it for me stops too. `PUT /delegation/reach` (`{step}`) moves it, and `reach_of` reads the step back from the switches, so the stored switches stay the source of truth and every gate reads them as before.\n\nGoing down turns the switches above the target off, highest first (`_lead_off`, then Handle it, then the inbox watcher, then Write drafts as me), so nothing is ever on above a switch that's off; the UI says what stops and asks before it saves. A lower sending level only holds more back and is set directly, so it needs no signed sign-in. Going up calls each switch's own route in order, so every check it makes still applies: the mailbox connected, signed sign-ins for sending, the owner alone and not in training for Everything. The first that refuses stops the move at a whole step and answers with that route's error. Handle it for me's own Off / In training / On (Replies and Follow-ups together) and, at Everything, **Your rules** sit with its picker, and **Learn from my edits** (drafts training) under the Act as me one; neither picker changes training.\n\n## Surfaces\n\n- **Settings → Act as me** (`ActAsMeCard`, hidden unless `GET /delegation` answers, so a team member sees it once the owner lets them): the mailbox connection (`provider` says which) with both connect commands (Gmail and Outlook) and **Check again**, **What it writes as you** (above), with the inbox watcher's status under Draft replies automatically (in plain words, when it last checked, **Check now** and **Also save inbox replies in my Gmail Drafts**), and **How I write**: length and tone, a greeting per audience (`{first}` is their first name), the sign-off, habits and never-rules in fields that grow to show every line, the signature with **Refresh from Gmail** and **Don't add my signature** (or **Add my Gmail signature** when none is added; on Outlook only **Don't add my signature**, with why), and each example quoted with **Remove examples**. The owner also gets **Let team members use it** where the install allows it, with each team member who has it on listed by name and counts only.\n- **Today → Replies waiting** (`RepliesWaiting`, the top of the left column; hidden unless `GET /delegation/replies` answers with cards): each card shows who wrote and who they are to you, whether their address was verified, the subject, **They wrote** as plain text, your draft, **Decide before sending** (the open questions, each with answers to tap and **Something else…**, and where they came from) and its warnings, with **Send** (a confirm naming who it goes to, and a second one when that or the thread changed), **Edit** (a text box on the card with Save and Cancel), **Open in Gmail** or **Open in Outlook** when the reply is in their Drafts, and **Dismiss**.\n- **Today → Needs you, invites** (`InviteCards`, next to the reply cards; hidden unless `GET /delegation/invites` answers with cards): the meeting, when, who invited them and who they are to them, any clash (times only), and **Accept**, **Decline** and **Dismiss**, or the reconnect note for a read-only sign-in; with Replies in training, the **Accept from them on its own next time** tick.\n- **Setup status**: a **Your own mailbox (Act as me)** light (`your_gmail`), amber while the inbox watcher can't reach the mailbox, is being rate-limited or has 25 replies waiting.\n- **Delegate** (main menu): **Act as me** (where `/delegate` and `/settings/act-as-me` land), **Handle it for me** (which step the dial is at, with **Change in Act as me**, then **What it sent**: how many went today and what it sent this week, as you) and **Take the lead** (the switch, then **Always asks first**, shown even while the switch is off and ending in **Meetings asked for in chat**, and the company's rules, as the Executive). Each switch that turns another off says so beside it. The pause is on **Settings → Your Executive**.\n- **API**: `GET`/`PUT /delegation`, `GET`/`PUT`/`DELETE /delegation/voice`, `POST /delegation/voice/learn`, `POST /delegation/voice/describe`, `POST /delegation/voice/signature`, `PUT /delegation/inbox` (`{enabled?, mailbox_drafts?}`), `POST /delegation/inbox/check`, `GET /delegation/replies`, `PUT /delegation/replies/{id}/text`, `GET /delegation/invites`, `PUT /delegation/handle-it`, `PUT /delegation/reach` (`{step}`, the dial), `PUT /delegation/training`, `DELETE /delegation/learned/{id}` and `GET /delegation/handled` — the caller's own delegation only — and `PUT /delegation/team`, the owner's switch (see API Reference). `GET /what-it-may-do` is the read-only summary above. Send (and an invite's Accept or Decline, with `edits.answer`) is `POST /decisions/{id}/approve`; Dismiss is `POST /decisions/{id}/reject`.\n- **Evals**: a scenario's `delegation:` block runs the turn against an in-memory mailbox (`evals.mailbox.ScenarioMailbox`) and hands the saved drafts to the judge (`delegation_001`–`003`). A `type: inbox` scenario runs the watcher's two model calls on one thread: whether it drafts must match the scenario, and a draft is judged on saying nothing the person hadn't, copying no link or address, and listing every open question (`delegation_inbox_001`–`007`; the last checks a draft never claims anything was sent).\n\nActing within rules the person sets and standing in for them are later, separate changes, each behind its own switch, off by default.",+ "markdown": "The **delegation** module (`openexecutive.delegation`) is **Act as me**: the one place the Executive writes *as* a person instead of as itself. Everywhere else it has its own Google account and bots and signs as itself. Here — when the person asks, or, with a second switch, for mail in their inbox that needs them — it writes an email in their voice and saves it as a **draft in their own mailbox** — Gmail or Outlook — for them to review and send. The one thing it ever sends is one of those inbox drafts, exactly as it is in their mailbox: when the person taps **Send** on its card, or, with a third switch, **Handle it for me**, on its own when plain-code rules allow it (below); chat never sends. A workflow its creator saved can also write as them: a draft for them to send, or, when they chose **Send as me** when saving it, sent (below). The principal can turn it on for themselves, and so can each team member once the owner lets them. It is off by default, and off changes nothing: the prompts, tool lists and prompt caches are byte-identical to an install without it.\n\n## Who can have it, and when it is offered\n\n`delegation.settings.can_delegate(person)` is the single rule for who may turn it on: the principal (a non-archived team member flagged `is_principal`), and any other non-archived team member — never a contact — once team members may have it (`team_members_enabled`). That takes two things: the install allows it (`DELEGATION_TEAM_MEMBERS`, default off, which offers the owner the switch) and the owner turned on **Let team members use it** (`PUT /delegation/team`, principal only, one row in `delegation_team`). Turning the owner's switch off takes it away from every team member from their next message, and their inbox watchers stop at their next check; their own switches, drafts and cards are kept. Everything is keyed by `person_id`. A person turns it on for themselves (`PUT /delegation`); nobody turns it on for anyone else. The setting is one row per person in `delegation_settings`, and a missing, unreadable or zero row all mean off.\n\nAt the start of every chat turn (`Executive.stream_chat` and the committee path) `pin_turn_delegation(session, speaker_text)` runs next to the workspace-mode pin and records a `TurnDelegation` on the session. `ghostwrite_email` is **offered** only when all of these hold:\n\n- the speaker may have it and turned it on — read fresh every turn, so turning it off applies from the next message;\n- the speaker is on a surface that verified it is them — the principal through `people_tools.is_principal_on_verified_surface`, a team member through `teammate_on_verified_surface` (the web app signed in, their own Slack or Discord, never an email turn) — and a web turn also carried a signed-in caller (`Session.web_caller_signed_in`, set from `x-caller-email`) or runs under local login — a request with no caller header is not a sign-in and never gets it (whoever holds the shared secret is trusted as the UI proxy that stamps that header, as on every principal-only route);\n- the conversation is private to the speaker: the web chat, a Slack or Discord DM, a verified private Telegram chat, or a chat its channel adapter verified the sender of and marked private (`Session.speaker_verified` + `Session.private_chat`) — never a shared channel or thread, where the draft's preview or the matching threads would be posted for everyone and other people's messages sit in the model's context;\n- the turn is neither unattended (the scheduler's proactive run) nor private to the principal (the email poller's turns), so inbound text can never reach it. The MCP server, workflows, reflection and research never carry it at all.\n\nThe mailbox connection is deliberately **not** part of the offer: the handler checks it on every call and says how to fix it, so the cached tool prefix never flips when a token lapses. The pin lives in a context variable for the turn's task as well as on the session, so two turns running at once on one session (a second browser tab) each read their own. It also carries the speaker's own words for the turn (a new email may go to an address they just typed — the turn's message joins the history only once the turn ends), a per-turn draft count, and `touched_mail` (see Privacy). `own_words` reads those words back for every own-words check (addresses here, facts and task assignments elsewhere): it first removes the hydrated `<outbound_reply_context>` backstory by its exact, anchored shape, so a look-alike closing tag quoted inside it cannot pass the rest off as the speaker's, then drops other adapter tag blocks, and returns nothing for a message carrying an attachment.\n\n## The tool: `ghostwrite_email`\n\nIt lives in its own registry (`orchestrator.delegation_tools.DELEGATION_TOOLS` / `DELEGATION_TOOL_HANDLERS`), **never** `_ALL_SKILL_TOOLS`, so no other toolkit can carry it. On a turn it is offered to, the agent loop adds it to the pool *before* the sort and builds that turn's handler map from both registries; on any other turn a call to it is an unknown tool. The handler re-checks the pin and the surface anyway, then:\n\n1. **Caps** — at most 5 drafts per turn, and `DELEGATION_MAX_DRAFTS_PER_DAY` (default 50, at most 1000) per person per UTC day, shared with the inbox watcher (`delegation.caps`). It is counted from `delegation_drafts`, one row of ids per draft saved from either place, with a count kept in the process as a floor in case a row was lost. Each slot is taken before the first await — a round's tool calls run concurrently, so otherwise every call in it would pass the caps before any counted — and handed back if nothing was drafted. If the rows can't be read it refuses rather than guess.\n2. **Marks the turn** — sets `TurnDelegation.touched_mail` *before* its first read of the mailbox.\n3. **Checks the mailbox** — `gmail_status` asks Google or Microsoft whose mailbox the credential opens and compares it with the person's People email, on every call: a roster email can change, and a client slot swaps the roster.\n4. **Finds the thread** — by `thread_id` (checked against the mailbox's own id shape), or a Gmail-style search (`find`; on Outlook, words, `from:`, `to:`, `cc:`, `subject:` and `newer_than:` are kept and other Gmail operators dropped). Several matches return `{status: \"choose\", candidates}` (subject, sender and date — no message text) and draft nothing; none returns `not_found`.\n5. **Sets the recipients in code**, never from the model. A reply goes to the last inbound message's `From` — never its `Reply-To` (a different one is flagged `reply_to_ignored`) — with the thread's other recipients only on `reply_all`. A new email or a forward may go to any well-formed address: it is only a draft, waiting in their own mailbox, where they see who it is to before they send it. An address that is neither on the roster (contacts only when `contacts_reachable_now()`) nor typed by the speaker this turn comes back in `not_in_people`, and the Executive names it for them to check (`delegation_tools.not_in_people`). Mailing-list mail, a thread they replied to last and a reply-all trimmed to 10 recipients are flagged. An address inside a block an adapter added to their message (the backstory hydrated into a DM) is not one they typed, and when the message carries an attachment — a document's inlined text, or a note naming the file — none of its addresses count as typed: neither has an end mark, and a filename is chosen by whoever sent the file, so such an address is named back to check.\n6. **Writes it** (the ghostwriter, below) and saves it with the mailbox client's `create_draft` (Gmail: threaded with `In-Reply-To`, `References` (whole message ids: when the chain is too long for one header the oldest after the thread's first go, never the parent) and `threadId`, and stamped `X-OE-Ghostwritten`; Outlook: Graph's `createReply` on the message it answers, then the text and recipients, and a named property marking it).\n\nThe result is `{status: \"drafted\", draft_id, gmail_link, to, cc, subject, preview, flags, open_questions, note}`, plus `not_in_people` and `check_address` when a recipient needs checking. The link (`gmail.mailbox_link`) is built server-side from a fixed prefix — the thread in Gmail, the draft itself in Outlook on the web — and the note tells the model the preview is the person's draft, to be treated as data. The chat shows an action chip — \"Drafted an email as you to … — in your Drafts\" — that opens it, and only a link under `MAILBOX_LINK_PREFIXES` is ever linked. A sincere \"are you an AI?\" in the thread comes back as an open question for the person to answer themselves.\n\n## Reading their mailbox\n\nFive read-only mail tools ride with `ghostwrite_email` in the same registry (`orchestrator.mail_read_tools`), so they are offered, re-checked and fenced exactly as it is: `search_my_email` (a Gmail-style search through the client's `search_threads`, or with no query the threads that reached their inbox in the last few days through `inbox_message_ids` + `get_message`), `read_my_email` (one thread's last 10 messages, each sender's new text only, drafts left out, with the files attached to them listed by message id and index), `read_my_email_attachment` (one of those files as text: PDF, Word, Excel, CSV or text, up to 20 MB, a scanned PDF converted) and `my_email_awaiting_reply` (their own sent mail from the last 14 days, to at most 10 people besides the Executive, that is still the last message in its thread). They change, label, draft and send nothing.\n\nThe fifth, `my_email_read_before`, lists the threads `read_my_email` opened for the same person before, in this conversation or an earlier one, so a later conversation can open the same email again instead of asking them to search for it. It keeps where, never what (`delegation.mail_reads`, table `delegation_mail_read`): the thread id, its subject and first sender as one line each, the mailbox address it was read from and when, never a message's text, an attachment or a recipient. Rows are the person's own and are listed only from the mailbox open now, newest first, optionally narrowed by words in the subject or sender; anything older than 30 days is never listed and is deleted on the next write, at most 200 are kept per person, and turning Act as me off deletes them all. It opens the mailbox like the other reads, so it sets `touched_mail`, counts as a search, and returns its rows with the same data-not-instructions note. The Act as me addendum tells the model that these tools reach the person's mailbox while any Gmail or Outlook tools of its own account reach only the Executive's, to search theirs (never falling back to its own) for mail sent to them, and to reopen an email from before with `my_email_read_before` and `read_my_email`.\n\nEach sets `touched_mail` and marks the conversation theirs before its first read (`_open_mailbox`, shared with `ghostwrite_email`), so the lockdown below applies from its round on. Each is capped per turn on the pin: 10 searches (`my_email_awaiting_reply` counts as one), 20 thread reads and 5 attachment reads, the slot taken before the first await. In `read_my_email` every message someone else wrote comes back inside its own `<untrusted_content source=\"email\">` block (`content_trust.wrap_untrusted`, which defuses a closing tag in the text); the speaker's own messages — SENT and from their address (`threads.mine`), never a From header alone — are marked \"Yours\" outside any block. An attachment's text comes back in its own `<untrusted_content source=\"attachment\">` block (`attachments.format_attached_text`), parsed in an isolated worker (`knowledge.loader`); unlike a file sent to the Executive it is never added to the company's knowledge. The clients find an attachment by message and position and look its provider id up on each read (Gmail's changes per fetch): Gmail lists a message's files with the message (`MailMessage.attachments`, leaving out images the HTML shows in place), Outlook says only `hasAttachments` until `list_attachments` asks Graph (leaving out inline ones), and `attachment_bytes` reads one; an attached Outlook item or cloud link has no file to read. Results carry a note that subjects, senders and text are other people's words, data rather than instructions. The lockdown refuses tools, not the reply's own text, so what would carry that text out without a click is closed where it is shown: the web chat loads no image from another site, and bot replies go out without link previews (see Integrations).\n\n## Saving a file from their mail\n\nOne more tool rides with the reads: `save_my_email_attachment` (message id and index, as `read_my_email` listed the file) copies one attached file into the storage the Executive itself has connected and shares it with the speaker alone, so they get a link they can open or put in an app. Every call it makes is built in code (`orchestrator.mail_file_save`); the model picks only the attachment. The bytes come from the mailbox client's `attachment_bytes` and never pass through the model, any file type up to 20 MB, under a cleaned name (one line, no path or reserved characters, extension kept). The storage is the one the Executive's own mailbox runs on (`EMAIL_PROVIDER`) when the gateway has that server, else the other: Google Drive through workspace-mcp (`create_drive_file` with `base64_content` into a folder named \"From your email\" in the Executive's My Drive, then `manage_drive_access` granting the speaker's own address the reader role, `send_notification` off) or OneDrive through ms-365-mcp-server (`upload-file-content` into the same kind of folder in the Executive's own drive, with a name no recorded copy has, since an upload overwrites, then `share-drive-item` inviting only the speaker, `requireSignIn`, role `read`, `sendInvitation` off). The folder is always made by the save itself and its id remembered (`delegation_saved_folder`), never found by its name, since a folder someone else made and called that could already be shared with them; when the remembered one is gone or won't take the file, a new one is made and the old id stays recorded. Never a link share, a domain or anyone. Neither connected (or an eval's in-memory mailbox): status `no_storage`, and the model says so and offers to forward the email instead. Saves run one at a time, at most 10 a turn (`TurnDelegation.files_saved`), and the result is the status, the name, where it went and the link (`webViewLink` / `webUrl`); the chat chip says only that a file was saved, never the sender's file name.\n\nIt copies only when the speaker asked in their own words this turn: what they typed (`own_words`, no quoted backstory or attached file's text) must hold one of save, saved, upload or OneDrive, or Drive as a place (\"to my Drive\", \"in Drive\", \"Google Drive\"), checked before a slot is spent or the mailbox opened; otherwise it refuses (`not_asked`) and tells the model to ask them. It stays allowed after the turn read mail (`MAIL_TOUCHED_ALLOWED_TOOLS`): its gateway calls are admitted past the lockdown only as the very objects the handler built (`mcp_gateway.code_built_call`, for its seven Drive and OneDrive tools: folder create, file create or upload, the speaker's share, and OneDrive's `list-drives`), so a model's own `call_tool` on that turn is still refused, and every other gateway gate still runs on them (the acting account, URL fetches, sheet formulas, the share gates' roster check, writes kept to the Executive's own drives).\n\nEach copy is recorded before it is shared (`delegation.saved_files`, table `delegation_saved_files`: the person, the storage, the file id, its name and when; never content or the mail it came from), and the folder in `delegation_saved_folder`. The gateway reads that table on every Google Workspace and Microsoft 365 call: on a turn whose speaker is not the file's owner (the owner is the speaker only when Act as me was offered to them, so a shared chat, a workflow or the poller sees none), a call naming a recorded file id, raw or percent-encoded (OneDrive's `download-bytes` path is decoded by Graph), is refused, and a result, filtered against the table as it stands after the call so a copy recorded while a listing ran is caught too, loses each list entry or line naming one, with any id left masked. It matches ids as text, so a result that names such a file without its id (a notification quoting its title) still shows the name, and a copy someone makes is a new file. The folders are guarded harder, on every turn and for every speaker, the owner too: a model call whose arguments name any recorded folder id, or an OneDrive item path through the folder (`root:/From your email/x.pdf:` or `<folder id>:/x.pdf:`), is refused, so nobody can share, move, rename, copy, list or delete the folder from chat, and folder ids are dropped from or masked in every result; only the save's own code-built calls touch it. When a copy is made but its row can't be written, it is not shared, the save reports `failed` and logs an error, and the copy's id is hidden from every turn, the owner's included, for the life of the process. When the table can't be read, the file tools (`_FILE_TOOL_RE`: Drive, folder, file, Docs, Sheets, Slides and presentation tools, attachment bytes) are refused (fail closed) while mail and calendar run. The rows are kept when Act as me is turned off: the copies stay in the Executive's storage, and the rows keep them out of other people's turns.\n\n## Reading their calendar\n\nA third switch under Act as me, **Read my calendar** (`delegation.calendar`, table `delegation_calendar`: one row per person, absent or unreadable meaning off), lets the Executive read the person's own calendar. The principal's daily briefs read it too: `top_three.read_todays_calendar` merges it with the calendar the Executive reads, listing a meeting on both once. It rides on the same per-person sign-in as their mailbox: `calendar.events` on Google, `Calendars.ReadWrite` on Microsoft, added when they run the connect script with `--calendar` (`scripts/connect-own-gmail.py`, `scripts/connect-own-outlook.py`). The one change it ever makes there is answering a meeting invite (see Meeting invites below); a sign-in made earlier with read-only access (`calendar.readonly`, `Calendars.Read`) keeps reading, and the refresh asks Microsoft for whichever calendar scope the file was minted with. Those scopes are optional, so a mail-only sign-in keeps working for mail; the mailbox clients note the scopes the token refresh reports, and `list_events` raises `CalendarNotGranted` before calling the calendar when the scope is missing (or when the calendar answers 403). Only the person turns it on (`PUT /delegation/calendar`), only while Act as me is on and a one-hour read works; a sign-in without the calendar is refused with `calendar_not_granted` and the command to run. Turning Act as me off turns it off. Changes are audited privately (`delegation_calendar_changed`).\n\n`my_calendar` sits with the mailbox reads, offered and fenced the same way: it refuses while the switch is off (before anything is opened), then takes a search slot, opens the mailbox privately (`_open_mailbox`, so `touched_mail` and the lockdown apply: an invite's title is in the words of whoever sent it) and lists the events from `start` (default today) for `days` days (1 to 31) in the workspace time zone, recurring events expanded and cancelled ones left out: title, start, end, all-day, location, organizer, attendees (25 at most) and the person's own answer, each on one line, with a data-not-instructions note. Google's `events.list` on the primary calendar and Graph's `calendarView` (times asked for in UTC) are its only calls; it changes nothing and keeps nothing. The first week's brief also lists today's meetings from it on the principal's own delivery (see Today).\n\n## Forwarding and reminders\n\n`ghostwrite_email` also forwards: with `forward` (a thread id) and `to`, it drafts a forward of the thread's latest message, or of the earlier one `forward_message_id` names (the one with the files, say, when their own reply came after it), `intent` becoming the short note above it (the ghostwriter writes only the note; the forwarded email's subject, someone else's words, is never put in the intent). Recipients follow the new-email rule (`_new_recipients`: the roster, or addresses the speaker typed this turn). Gmail's draft quotes a forward header and the original's own words under the note and attaches the original's files, up to 10 and 20 MB (`FORWARD_MAX_FILES`, `FORWARD_MAX_BYTES`; any left off are flagged `attachments_left_off`); Outlook uses Graph's `createForward`, which keeps the original and its files, with the note as its comment and the body never patched. It is still only a draft.\n\nThe principal's new email or reply can also carry Google Drive files: `drive_files` takes up to 15 Drive file ids (`drive_attach.MAX_FILES`) (not with a forward; a team member is refused, since the files come from the Executive's own Drive). `orchestrator.drive_attach` sizes each one first and then downloads it with code-built `get_drive_file_permissions` and `get_drive_file_download_url` calls as the Executive's Google account (`mcp_gateway.code_built_call`, so the mail lockdown admits those exact calls). It takes the saved copy only from workspace-mcp's own anchored `Saved to:` line, exactly one, whose name ends in workspace-mcp's uuid (the answer echoes the Drive name first, which whoever shares a file chooses), names the attachment from that saved name, reads the bytes only from the tool download folders, removes the copy, and puts them on the draft under the forward cap's 20 MB. When the turn had read outside content before choosing them, the result asks the Executive to name each file so the person checks it. The file's text never reaches the model, so attaching is not an outside read. A file someone saved from their own mail, or a save folder (`delegation.saved_files`), is refused for anyone else, checked before and after the downloads and failing closed when that record can't be read, and a file that can't be fetched makes no draft. Gmail attaches them in `build_raw`; Outlook uploads each to the new draft (Graph's one-request upload, 3 MB a file, larger ones left off and flagged), and removes the draft if an upload fails. The result lists the attached file names.\n\n`remind_me(text, when)` (`orchestrator.reminder_tools`) rides with the same tools and checks, but opens no mailbox, so it never marks or locks a turn (`MAILBOX_TOOL_NAMES` are the ones that do). It stores the text once cleaned — one line, anything a chat app could turn into a link (a URL of any scheme, an address, a domain-like word, a host and port, an IP address) replaced with \"[link]\", at most 300 characters — with its time (stored in UTC) in `delegation_reminders` (5 a turn, 25 waiting, a year ahead, refused when the person has no channel). When it is due the scheduler sends that text to the person alone, as \"Reminder you set on <date>: …\", running nothing (see Scheduler); the Slack and Discord DMs it may go by turn link previews off. The chat chip shows the text as it will be sent. A reminder that comes due in the person's quiet hours or leave (when `OUTBOUND_RESPECT_QUIET_HOURS` is on) waits unclaimed and goes once they end, rather than being suppressed and lost. It is allowed after mail is read and in later turns of that conversation: it reaches only the speaker, as plain text. `schedule_followup`, which runs a turn with tools and is listed to everyone, stays refused there.\n\n## Approval cards\n\nA turn that read someone's mail may not message anyone, invite anyone or change the roster (see the lockdown above), yet what the mail asks for is often right. `propose_actions` (`orchestrator.action_card_tools`) leaves the speaker a card instead: up to five actions, each spelled out exactly as it will happen, done only when they tap Approve. It rides with the other Act as me tools and checks (`_writer`), opens no mailbox, and is allowed after mail is read because it does nothing on the turn.\n\n- **Kinds.** `invite` (a meeting with people on the roster), `message` (a direct message to someone on the roster, as written) `add_contact` (a new contact; the principal's cards only, since contacts are theirs) and `drive_files` (rename and/or move up to 25 Google Drive files; the principal's cards only). A `drive_files` action always waits for the tap, which is its approval: it runs each change as a code-built `update_drive_file` (`MCPGateway.tapped_drive_change`, `tapped_drive_call`), so the own-file check looks only at the folder it goes to, and a move takes the file out of the folders it was in. The card shows each file's current name and the folder's, read when it is proposed; when Drive isn't connected or a name can't be read, no card is made. A team member's card can't name a contact. Each action is checked when the card is made (`delegation.action_cards.check`) and again when it is carried out, so an archived person or a time that has passed fails that action alone.\n- **Whose.** A card is a `delegation_actions` decision for the speaker, `approver_only` like a reply card: only they see it (`GET /delegation/actions`) or resolve it, a team member's answers 404 to the principal too, and it is never an alert. The same actions still waiting are that card, not a new one. 3 cards a turn, 25 waiting, dropped after 7 days.\n- **Approve.** In the chat, under the reply that left it (the `propose_actions` chip carries the card's `decision_id`, and `ChatActionCards` shows the card while it waits), and on the Briefing's Needs you list, with a box per action. Approve (`POST /decisions/{id}/approve`, `edits.only`) needs the card's person signed in (`verified.caller_refusal`) with Act as me on; the card is claimed first so it runs once, then each ticked action runs as stored with no model call, in an unattended session (the principal's with contact egress) under `rows_for_person`, so every audit row it writes is theirs and nothing reaches the team's activity rail: `message_person` (a direct message or nothing; never its Briefing-alert fallback, which more people read), `create_calendar_event`, or a contact row. Approving also needs the person still allowed Act as me (`can_delegate`) and switched on. An invite is booked straight away when the person approving is the one the meeting gate would ask (`calendar_tools.approved_by`), and otherwise goes to that approver as usual, so a card never widens anyone's authority. Per-action results (`done`, `waiting`, `failed`, `skipped`) are kept on the decision and shown on the card. Dismiss rejects it and does nothing else. With Suggested actions in training the card adds the *Do this on its own next time* tick, and a card of actions all allowed is carried out on its own (see In training above); with Suggested actions On, any card that reaches nobody new is.\n- **Channels.** A card can come from any surface Act as me runs on; it is approved in the web app, since the chat apps have no buttons here.\n\n## The ghostwriter\n\n`delegation.ghostwriter.compose` writes the text. The Executive decides *what* to say (`intent`); this call decides *how* the person would say it, and it is deliberately small:\n\n- a constant `GHOSTWRITER_PROMPT` plus the person's voice block as the system prompt;\n- the thread (each message cut to its sender's own words, every line scrubbed, all labelled alike), then the writer's own earlier words in it (`<writer_said>`, from their sent mail only), the intent and the recipients' names in the user turn — no company profile, memory or roster;\n- with Always in the loop on, `<writer_noted>`: what the writer's own notes say they told these same people in earlier Act as me replies (`memory.history_drafts.notes_for_draft`: only notes from mail **every** recipient of the new draft was on, so nothing told to one person reaches another; chat notes name no recipient and never qualify; at most 8, newest first, the person's own words or their correction, with dates). The prompt's rule 6 makes it a consistency check, never content: a draft that contradicts it is still written as the intent says, and the conflict becomes an open question on the card, which only the writer sees. Both the chat tool and the inbox watcher pass it;\n- **no tools** but the forced `compose_reply` return, so text in the thread can ask for anything and there is nothing to do it with.\n\nIt is not a Council agent — the Council's edit routes have no principal check — and runs on `DELEGATION_COMPOSER_MODEL` (default: the default model), logged as `ghostwriter` usage. `lint` then runs in code on what comes back: a link or an email address survives only if it appears in the intent, the signature or the recipients, so a link planted in the thread is removed and flagged; the Executive's own name is flagged; and the body is capped, cut at a paragraph, line or word break in its last fifth. A draft with nothing left after that is refused. The signature from the person's Gmail settings (or the one already stored, for Outlook) is appended.\n\n## How I write\n\n`delegation.voice` learns how a person writes *their own* email (`attunement.style` learns how the Executive should write *to* someone). `POST /delegation/voice/learn` reads up to 40 recent sent messages, keeps only what they wrote (quoted replies stripped with the email poller's `sender_new_text`), skips automatic mail, every thread chat drafted into, and every sent message that began as a draft written for them (`delegation_drafts.sent_message_id`), and makes one forced-tool call (`record_voice_profile`). Code validates every field before it is stored:\n\n- greetings per audience (their team, their contacts, anyone else), a sign-off of at most two lines, and a usual length and tone (a backslash-n the model wrote instead of a line break is read as one, keeping the first lines that fit, which also repairs a profile stored before that rule);\n- up to 8 habits and 6 things to avoid, through the same deny-list as working-style rules — no actions, links, handles, amounts, tool names or names of people; the conversation review (`memory.chat_review`) adds one when the person states how they write in a chat (`add_conversation_rule`, `updated_by=conversation`; never on a locked or full list, and an edit or lock made meanwhile wins);\n- up to 3 short exemplars, each checked to be verbatim from a sample, with addresses and phone numbers masked — and none while a client slot is active, so one client's mail never lands in another's state.\n\nThe signature comes from Gmail's `sendAs` settings, not the model (Outlook gives apps no way to read one, so a learn keeps the stored signature and `POST /delegation/voice/signature` answers 409 `signature_unavailable` rather than clearing it), as plain text with its lines kept (`gmail.html_to_text`: a `<br>` always ends a line, and a block tag, opening or closing, ends one when it has text, so Gmail's layout of a first line followed by one `<div>` per line comes out line by line). `POST /delegation/voice/signature` reads it again without relearning: nothing else changes and a locked profile stays locked, so it picks up a changed Gmail signature and undoes **Don't add my signature**. A person can also describe their style in their own words: `POST /delegation/voice/describe` applies the description to the profile they have through the same forced tool (a separate system prompt, no exemplars) and the same validation, keeps their signature and writing examples, and returns the result with a short sample reply for them to review. It saves nothing and needs no mailbox; Save stores it as an ordinary edit. The person can edit the profile, lock it (a locked profile is never relearned) and reset it, and every change is kept in `delegation_voice_history`. One learn runs at a time per person, and a lock or an edit made while it runs wins: the learned profile is dropped (`changed`).\n\n## Draft replies to my inbox\n\nA second switch under Act as me, **Draft replies to my inbox** (`delegation.inbox`), has the Executive watch the person's own inbox and write a first reply to mail that needs them. The reply waits on a private card on Today; nothing is sent until they tap **Send** (below). Where the reply lives is the person's choice, **Also save replies in my Gmail Drafts** (`mailbox_drafts`, off by default): off, it lives on the card alone (`delegation.card_drafts`: the card keeps the draft's recipients, subject and thread headers as `draft_spec`, and Send makes the mailbox draft from exactly that just before the send-time checks, taking it back out if they refuse), so their Drafts folder doesn't fill with replies they may never send; on, it is also saved in their Drafts as before. The switch is one row per person in `delegation_inbox_watch`. Turning it on needs Act as me on and their mailbox connected, and sets `watch_since` to now every time, so it never drafts for mail that arrived before; turning Act as me off turns it off too. Off means no mailbox call and no row written, with one exception: a send the person started that the mailbox never confirmed is still followed through until it is settled.\n\n### When it looks\n\nA throttled hook in the scheduler tick (`_maybe_scan_inbox`, after the pause, company-profile and rotation gates) checks each person whose switch is on every `DELEGATION_INBOX_POLL_MINUTES` (default 5). It is not a scheduled action, because those are listed on `/scheduled` for everyone and anyone may cancel them. One scan task runs at a time, one scan per person, and none while a client slot is active. **Check now** on the Settings card runs the same scan. Every row a scan writes is private and the person's own (`audit.rows_for_person`: a team member's rows are hidden from the principal too, see Privacy), and the process log carries counts and codes, never an address or a line of mail. The scan never marks mail read or changes a label.\n\n### What it drafts for\n\nA scan first settles the open cards (below), and stops with `backlog_full` once 25 are waiting, counting the ones it makes. It then lists the inbox since `watch_since` (`inbox_message_ids`) — not chats, not mail from the person, and not the promotions, social, updates or forums tabs (on Outlook: the Focused inbox only) — up to 100 messages, and takes the newest message of each thread that still needs a look, at most 10: settled threads and threads with an open card are passed over first, so a burst of mail, or a pause for a limit or a back-off, never hides older threads for good. `delegation_inbox_messages` is its durable cursor: one row per message (`UNIQUE(person_id, message_id)`) with what happened to it, the reason, how many tries it took, and the draft and card ids. It stores a hash of the sender's address, never the address. A message is skipped, with the reason recorded, when:\n\n- it came before `watch_since`, or more than three days ago;\n- it is from the person or one of their send-as addresses, from the Executive, or one of this module's own drafts;\n- it is automatic — `Auto-Submitted`, a bulk or auto-reply `Precedence`, a bounce, a calendar invite or a no-reply sender — or from a mailing list, or in a Gmail tab, spam or trash (with Read my calendar on, a calendar invite goes to `delegation.invites` instead: see Meeting invites);\n- the person is not in To or Cc, or it has more than 10 recipients;\n- the person replied last, or a draft already sits in the thread.\n\nThree kinds are left unrecorded, so a later scan looks again: mail under 10 minutes old (mail the person answers straight away never gets a card), mail in a thread whose card is still open, and mail a daily limit holds back.\n\n### Deciding, then writing\n\nTwo model calls, and code decides between them. The classifier (`delegation.inbox_classifier`) is one forced-tool call, `classify_email`, returning whether the email needs a personal reply, what kind it is and how sure it is. It sees a few one-lined header lines and the sender's own new words (at most 3000 characters, every line scrubbed) inside one `<email>` block marked as data, after the person's own last email in the thread in a `<their_last_email>` block (`their_last_words`: only mail their own mailbox sent, at most 1500 characters), so a reply to something they asked reads as one: an answer to their request for a call that says when the sender is free, without settling a time, is scheduling and gets a draft even when the sender says they will come back with times. It has no other tools, context or memory, so an email can ask for anything and there is nothing to do it with. A reply is drafted only for a question, a request, scheduling, an introduction or a follow-up, and only when the confidence clears a bar that rises the less the sender is known: 0.6 for their team or a contact (the principal's contacts count only for the principal: a team member's mail is weighed by the team and their own sent mail), 0.7 for someone they have written to before (`has_written_to`, a search of their sent mail), 0.85 for a stranger. Pitches, notes of thanks, FYIs, notifications, newsletters and phishing get nothing, and so does any failure. An email that also went to other people is drafted for only when the person is in To and it asks them themselves: the classifier is told their name, whether they are in To or Cc and how many others it went to, and lists the names the email greets or asks by name (`asked_names`). Code matches those against the person's name, whole name parts only (\"Alexis\" never counts for \"Alex\", and a nickname misses, which means no draft), so mail that greets someone else (\"Good morning, Brennan, could you sign ...\") is never theirs, whatever the model makes of it as a whole. When it names nobody, the model's `asked_of_them` decides, false for a question to the group at large. One that only copies them is never drafted for. Either is recorded `not_needed` with the reason `asks_someone_else`. It runs on `DELEGATION_CLASSIFIER_MODEL`, else the routing model. A sender whose address Gmail couldn't authenticate is handled as a stranger whatever the roster says — anyone can put a colleague's or a client's address in From — so they get the stranger's bar, a holding reply and the stranger limits; the card still says who they claim to be, and that the address isn't verified.\n\nThe reply is written by the same ghostwriter, in the person's voice, but from a fixed intent the module builds rather than words the person typed. Because the intent lets it restate the person's own earlier words, which words are theirs is never written inside the thread, where a sender could imitate any marker with a look-alike: every message there is labelled alike, and the person's own words come in a separate `<writer_said>` block after the thread, taken only from mail their own mailbox sent. Nothing inside the thread can close the thread block or open another. The intent: acknowledge the sender; say again only what the person's *own* earlier messages in the thread already said; commit to nothing new — no yes or no, date, time, price, fact or promise — and say they will get back to them; and put every question it could not answer from their words in **open questions**. A stranger always gets a short holding reply. The lint still strips any link or address that isn't the person's own. The reply goes to the sender (never `Reply-To`) and, on a group email, to everyone else it went to as Cc (reply to all, never the person's own addresses or the Executive); a stranger's holding reply starts with the sender alone. When others were on the email the card offers **Reply to**: the sender only, or everyone (`PUT /delegation/replies/{id}/recipients`, `card_drafts.set_recipients`). It picks between the two lists fixed when the card was written (`reply_others`), never an address from the request, and changes the mailbox draft's To/Cc too. Its `draft_to` lists who it goes to, which Send checks.\n\nThe order: record the message, classify, reserve a slot in the shared daily limit, write, save the draft in Gmail (from the alias the mail went to, when it went to one) and store its id, then create the card (idempotent on the message: a second call finds the open card, and a card dismissed or lapsed under that key doesn't stop a new one, while one sent or settled in the mailbox means no second card, `invites.create_once`) and mark it drafted. Nothing that fails along the way loses the message. A failure that may pass — the classifier or the writer failing, Gmail refusing the draft, a card that couldn't be made (its draft is deleted first, so no draft is left without a card), any other error with that one message — leaves it for a later scan (`retry`), and it is given up on only after three tries; one message's trouble never holds up the rest. A daily limit reached while it was being read leaves it for later without counting as a try.\n\n### The reply cards\n\nA card is a `delegation_reply` decision whose class is **its approver's alone** (`DecisionClassSpec.approver_only`): only the person it was drafted for sees or resolves it on any decisions route — a team member's card answers 404 to the principal too — and it is never an alert: alerts feed chat turns, which would put other people's mail into memory. It carries the sender with who they are to the person and whether Gmail could verify the address (SPF/DKIM/DMARC, through `fact_confirmation.headers_authenticated`), the subject, what they wrote, the draft, the open questions and its warnings. `GET /delegation/replies` lists the open ones from the database alone, so Today never waits on Google.\n\n- **Send** approves the card, which sends its draft exactly as it is in their mailbox (see *Send on your tap*). **Edit** changes the reply's words right on the card (`PUT /delegation/replies/{id}/text`, `card_drafts.edit`): only its own person, from a caller the API can tie to them (as for Send), never while it is being sent on its own; a reply in their Drafts is rewritten there too (`update_draft_text`, every header kept), and only while it is still the version the card last saw, so a change made in the mailbox is never overwritten. A card edit counts as edited (`approved_with_edit`, and **Do it like this next time** keeps it), and one made by hand sets `questions_settled`.\n- **Decide before sending** with taps (`delegation.answers`): the ghostwriter returns each open question with 2 to 4 short answers the person might pick (`choices`) and what it is `about` (time, document, other); plain strings still parse, and `open_questions` stays a list of strings for every other reader, with `question_choices` beside it on the card. After the draft is written, code fills two kinds: a time question gets up to 3 free half hours on the person's own calendar (Read my calendar on; one a day over the next 5 working days, busy times only, no event title reaches a model), \"I checked your calendar: these are free.\"; a document question whose words match a company document's name gets 'I'll send \"<name>\" separately', \"Found \"<name>\" in your documents.\" Nothing is attached: a card's draft is plain text. A tap, or **Something else…**, calls `POST /delegation/replies/{id}/answer`: one composer-model call rewrites the body with the answers in their voice (signature and AI line kept out and put back), `ghostwriter.lint` runs on it, and it is saved through `card_drafts.edit` with the same caller and card checks and the same Drafts update. It returns the card with `changed_sentences`, which the card lightly marks. 30 rewrites an hour per person (429). Send waits until every question with choices is answered, or the words were changed with Edit. A card made before choices shows its plain questions. **Open in Gmail** (or **Open in Outlook**), shown only when the reply is in their Drafts, opens it there.\n- **Dismiss** rejects the card; the class's after-reject step then deletes the draft if nobody edited it — its message id is still the one it was saved with, since Gmail gives an edited draft a new one, and the Outlook client makes a draft's message id `<id>.<changeKey>` so an edit there changes it too — and keeps it otherwise. What happened is recorded even when Gmail fails.\n- Each scan first **settles** what Gmail already settled: a draft sent from Gmail, a draft deleted there, a reply the person wrote themselves, a thread that is gone, or a card left for 7 days (its draft stays in Gmail). Each is a compare-and-set close with the reason. A newer message from someone else flags the card instead. A card being sent at that moment is left alone.\n\n### Send on your tap\n\n`delegation.reply_send` is the only thing in Act as me that sends, and all it can send is the draft on a card, by its id: `DelegateGmail.send_draft` posts `{\"id\": …}` to Gmail's `drafts.send`, and `DelegateOutlook.send_draft` posts an empty body to that draft's Graph `send`, and nothing else, so no text, recipient or header is ever passed. It has three doors: `send_approved_reply`, reached only from `POST /decisions/{id}/approve` — a class only the card's own person may resolve — `send_on_its_own`, reached only from the inbox watcher under Handle it for me (below), and `send_for_workflow`, reached only from a workflow step's `oe__send_email_as_me` (below). AST tests pin all three call sites, so no model, chat turn, scheduled job or MCP call can, and a workflow only through that one tool. A tap is checked like this: At send time it checks everything again:\n\n1. **Who is asking.** The caller is the card's person and the API knows it: signed callers are on and the request carries that person's signed assertion (or the operator's, under local login), or the API runs for local login and answers this computer only. Anything else is a 409 `caller_signing_required` — with only the shared secret, whoever holds it could send as the owner — so on a server Send needs signed sign-ins.\n2. **The switches.** Act as me and Draft replies to my inbox are on, and no client slot is active.\n3. **The mailbox.** Their mailbox is connected.\n4. **The draft.** It still exists, in the same thread, and they haven't replied there themselves since; otherwise the card closes.\n5. **Who it goes to.** To, Cc and Bcc hold between 1 and 10 addresses, never the Executive's own, and it is from one of their own addresses.\n6. **What changed.** Recipients that differ from the card's, or a newer message from someone else, need a second yes: the first tap gets a 409 `confirm` naming the recipients and the reason, and the person approves again with what they were shown.\n\nThen it claims the card (`claim_for_execution`, proposed → executing, a compare-and-set, so a double tap sends once) and reads the draft once more: `drafts.send` sends whatever the draft is when Gmail gets the request, so if it was edited since the checks read it — in another tab, by a delegate — nothing is sent and the card comes back (`draft_changed`). Then it sends, and records the result: `approved_with_edit` when the draft was edited in Gmail, the sent message's id, the draft row's `sent_message_id`, and a private `delegation_reply_sent` row. A refusal that proves nothing went — a 4xx, a lapsed sign-in, a rate limit, a draft already gone — hands the card back. A failure that leaves it unclear — a timeout, a 5xx — leaves it `executing` and says to check the Sent folder, and the next scans ask Gmail: their message in the thread means it was sent; anything else is judged on the second scan that sees it: the draft still there and nothing sent means it was not (Gmail deletes a draft it sends), and the card comes back, flagged; the draft gone and nothing sent means it was deleted. Nothing is ever retried on its own. Sending is the person's own act, so it works while the Executive is paused.\n\n### Limits and failures\n\nAt most 5 drafts a scan; `DELEGATION_INBOX_MAX_DRAFTS_PER_DAY` (default 20) a day, inside the shared `DELEGATION_MAX_DRAFTS_PER_DAY` it shares with chat; 200 classifications, 2 drafts per sender (1 for a stranger) and 10 for strangers in all per day; and never more than 25 open cards. A lapsed Gmail sign-in sets the status and is looked at again every 30 minutes; a rate limit, an error reaching Gmail or a crash backs off from 5 minutes, doubling up to 2 hours. Neither turns the switch off: the Settings card shows the status in plain words.\n\n## Handle it for me\n\nA third switch under Act as me, **Handle it for me** (`delegation.handle_it`), lets the inbox watcher send some of its replies itself instead of leaving them on a card. It is one row per person in `delegation_handle_it` (`enabled`, `mode`); no row means off. One setting says how much goes without them, the way quality does on the Agent Council (`handle_it.RULES`): **Easy ones** (`careful`) sends only replies to people they know (someone on their team, a contact or someone they have written to) of at most 400 characters when the classifier is at least 0.9 sure; **People I know** (`balanced`), where it starts, sends replies to people they know up to 1200 characters at 0.8; **Most mail** (`bold`) also answers strangers, up to 2000 characters, and lets a link or an amount through when the classifier is at least 0.9 sure. Everything else waits on a card as before, so turning it on never drafts less. A table from before the setting gets the `mode` column on its next open (`schema._add_handle_it_mode`): someone who had strangers set to send keeps that as Bold, everyone else gets Balanced. Only the person turns it on (`PUT /delegation/handle-it`), from a session the API knows is theirs: the same rule Send uses (`delegation.verified.caller_refusal`), so with only the shared secret it answers 409 `caller_signing_required`. Turning it on needs Act as me and Draft replies to my inbox on, and turning the inbox watcher off (or Act as me, which turns it off) turns it off too.\n\n**In training** (`delegation.training`). Like someone new, each Act as me job can be put in training on its own, from that job's card on the Act as me page, the way Take the lead has it: **Write drafts as me** and **Handle it for me** each pick Off / In training / On (Handle it's In training puts Replies and Follow-ups in training together; its steps show under On only, since in training only allowed people go whatever the step), and **Suggested actions** picks Always ask / In training / On (On is the `actions_on` switch: a card is carried out with no allow, under the same checks, and only when it reaches nobody new: a new contact or anyone on the roster under a week waits; In training wins when both are set); what it learned is listed on each tab for its own jobs (Act as me: *What it's learned*, drafts and suggested actions; Handle it for me: *Who it's allowed to handle*, replies and follow-ups), each item named by its job (`PUT /delegation/training`, one row per person and setting in `delegation_training`, absent means not in training). In training it asks first and learns who and how from what the person approves; what it learns is a `take_the_lead_allowed` row (feature `act_as_me`, the person's id), theirs alone.\n\n- **Replies.** Every reply waits on its card (`handle_it_reason` `training`) whatever the dial says, and a reply card adds **Send + allow**: it sends that reply on the person's own tap, exactly as Send does, then allows replies to that sender (key `act_as_me|person:<id>|reply|<address>`). While Handle it for me is on, a reply to an allowed sender goes on its own under the dial's limits (a stranger they allowed included) and every check above (the topics that always wait, links and amounts, new recipients, once a thread a day, the daily limit); it's checked again at send time, so a sender removed since waits. Take the lead as you lifts nothing in training: putting Replies or Follow-ups in training turns it off, and it can't be turned on while they are (409 `in_training`).\n- **Follow-ups.** Every follow-up waits (`follow_up_training`); Send + allow on a follow-up card allows follow-ups to exactly the people it went to (`…|follow_up|<sorted addresses>`), whoever they are, under every other follow-up check.\n- **Suggested actions.** An action card (below) adds **Approve + allow**: it does the actions on the tap, then allows each one that happened (a message to that person, `…|message|person:<id>`; a meeting with exactly those people, the person left out, `…|invite|people:<ids>`). A new contact is never allowed. A card proposed later whose every action is allowed is carried out at once, with no tap (`action_cards.run_on_its_own`, `gate_mode` `auto_execute`, status `executed`), only if plain code finds nothing against it (`on_its_own_refusal`): still in training, Act as me on, a server that ties the switch to the person, nothing sensitive, no link or amount, a message of at most 1200 characters, and at most 10 actions carried out this way a day (checked one card at a time); anything refused is handed back to wait on its card as before. An invite carried out this way is never booked as approved by the person: the meeting gate decides as for any meeting nobody tapped, so a time taken from someone's mail can't land on a calendar unasked. The tool result and chip say what was done. The message text in such an action is model-written from the mail and goes without anyone reading it; the allowance covers who and what kind, not the words, which is why sensitive topics, links, amounts and long messages are held back.\n- **Drafts.** Nothing is sent. When the person changes a reply's draft in their mailbox before tapping Send (plain or + allow) and ticks **Do it like this next time**, what they sent is kept (its new text, quoted replies dropped, at most 1000 characters, `…|style|<address>`), and the ghostwriter gets it in its user turn as `<writer_example>` when it next writes to that person, from the inbox, a follow-up or a chat draft to that one person: style only, never its facts, and nothing in it can open or close a tag.\n\nSend and Approve with the *on its own next time* tick (`allow`; the tick replaced the separate Send + allow and Approve + allow buttons) are refused before anything is done unless their setting is in training (422 `cant_allow`) and the person's list has room (409 `learned_full`, at most 200 a person); allowing failing afterwards never undoes the send. Putting Replies or Follow-ups in, or Suggested actions out of training or On, only holds more back and works without signed sign-ins; anything else needs a caller the API knows is that person. What it learned is the person's alone: listed on `GET /delegation` (`training.learned`, each with its `setting`), removed with `DELETE /delegation/learned/{id}`, and for the owner also in Take the lead's \"What it's learned\" list; it never reaches anyone else's list or Take the lead's prompts. A dial left on In training by an older version (mode `training`) moves to People I know with Replies and Follow-ups in training (`schema._move_training_off_the_dial`).\n\n**No model decides whether a reply goes.** The watcher's two model calls are unchanged and tool-less, so text in an email can at most change the verdict and the draft. After the draft is written, `handle_it.refusal` — plain code — decides, and anything it refuses becomes the usual card with the reason kept on it (`handle_it_reason`). It refuses when:\n\n- it's off, or the sender is a stranger and the setting isn't Bold, or on a server signed sign-ins are off (`signing_ok`: signed callers, or local login);\n- Gmail couldn't authenticate the sender, whatever the roster says;\n- the email isn't a question, request, scheduling, introduction or follow-up, or the classifier was less sure than the setting needs (0.9 on Easy ones, 0.8 otherwise);\n- the reply goes to anyone the email didn't already go to (its From, To and Cc, less the person's own and the Executive's addresses), leaves out the sender, or goes to more than 10;\n- the email's subject, the sender's new words, or the reply touch money, contracts, legal, hiring, pay, layoffs, the board, investors, mergers, the press, health, or credentials and secrets (passwords, logins, tokens, API keys); or the reply carries an amount, a percentage or a link (a scheme, `www.`, a bare host with a path such as `bit.ly/…`, or a bare host on a common top-level domain) unless it's Bold and at least 0.9 sure, or runs over the setting's length (400, 1200 or 2000 characters);\n- the draft carries any flag but *others on the thread* or *Executive on the thread* (they asked if it's an AI, recipients were trimmed, …);\n- it already sent one in this thread in the last day, or the person's last message in the thread was itself sent on its own (no auto-reply ping-pong);\n- the day's limit is reached (`DELEGATION_HANDLE_IT_MAX_SENDS_PER_DAY`, default 20, within the watcher's drafts limit), or it can't be counted. Any error in the rules counts as a refusal.\n\n**Workflows that email as their creator** (`delegation.workflow_email`). A workflow step can write an email in its creator's voice with `oe__draft_email_as_me` (a draft in their mailbox for them to send, counted and named in the briefs like a chat draft) or `oe__send_email_as_me` (sent). Which one a step lists is the choice the creator makes when they save it; the gateway's mail tools still send from the Executive's own address. Both write only as the workflow's creator (`dynamic_store.get_owner`), never an address the step names, and refuse a run someone else started by hand, a speaker the roster can't place, a run one of the Executive's own unattended passes started (reflection, research, a proactive run: `chat_tools.started_by_a_pass`, inherited by nested workflows), or a run another person's workflow started (`chat_tools.running`); a scheduled run writes as the creator. The creator must be allowed Act as me, have it on and have their own mailbox connected, or the step is told to use the Executive's own email. `to` and `cc` are write targets, so the step's first email to a new address waits for the creator's approval (`action_step.TargetPolicy`) and is then remembered. Every email counts against `DELEGATION_MAX_DRAFTS_PER_DAY`, and sends against `DELEGATION_WORKFLOW_MAX_SENDS_PER_DAY` (default 20) as well, counted from `delegation_drafts` rows with source `workflow_sent` (written before the send, so a failed send still counts). Sending needs more: a workflow with `oe__send_email_as_me` can only be created, changed or switched on by its creator from a session the API knows is theirs (`workflow_email.save_refusal`, the `verified.caller_refusal` rule Send uses; a 403 otherwise, from `POST`/`PUT /workflows/custom`, save-edit and activate), and chat's `save_workflow` never replaces one, so nobody else can change what it sends. At send time `reply_send.send_for_workflow` checks again that Act as me is on, `handle_it.signing_ok`, no client slot is active, and the draft it just wrote is unchanged: addressed exactly as written, from one of their own addresses, at most 10 recipients and never the Executive's own address. A send the mailbox didn't confirm is reported as possibly sent and never retried. The step's result (and so the run's report) names who it went to and the subject, never the body; the audit rows (`delegation_drafted`, `delegation_workflow_sent`, `delegation_workflow_send_refused`) are the creator's alone. The workflow designer is told whether the person designing it can have email written as them, and to ask when it isn't clear whether an email should come from them or from the Executive.\n\nA reply the rules allow gets a card with `gate_mode` `auto_execute`, and the watcher sends it at once through `reply_send.send_on_its_own`, the second door into the send path (an AST test pins its callers: the approve route, the watcher, and a workflow's `oe__send_email_as_me`). It runs the same send-time checks as a tap — switches, mailbox, draft, recipients, the claim and the last re-read — with no caller, and adds its own: the card must be `auto_execute`, Handle it for me still on with the setting still allowing that sender (or, for a follow-up, that recipient), signing still on, the once-a-thread-a-day rule and the daily limit counted again, and the draft untouched since it was saved (an edit in Gmail means the person has taken it over: `draft_changed`, the card waits for them). Every refusal hands the card back to the person (`decision_ledger.hand_back`, a compare-and-set to `propose`), with the reason kept on it when there are words for it, and a failure never stops the scan. Every card it left for the person says why on Today (`waited_because` on `GET /delegation/replies`). A reply sent on its own finishes as `executed` (not approved), is recorded in `delegation_handled` (for the per-thread and daily rules) and writes a private `delegation_reply_handled` row; an unconfirmed one is settled by the reconciler the same way. No History note is taken from it, since notes come only from the person's own words. It runs inside the watcher's scan, so it stops while the Executive is paused.\n\n**Follow-ups as you** (`delegation.follow_ups`). While Handle it for me is on, the watcher's scan also looks at the person's own sent mail, at most once an hour (`LOOK_EVERY`), for an email of theirs that asked something (a question mark in their own words), is 3 to 10 days old, went to at most 10 people other than the Executive, and is still the last message in its thread. Plain code picks it; each gets one follow-up ever (its `delegation_inbox_messages` row), at most two a look, within the drafts limit. The ghostwriter, tool-less as always, writes a short nudge in their voice from the thread, saved as a draft in that thread to exactly the people the email went to. `handle_it.follow_up_refusal` — plain code — decides whether it goes: by the setting it never goes on Easy ones, goes to their team and contacts on People I know and to anyone they wrote to on Most mail (`follow_up_refused` otherwise: `follow_up_level`); it also refuses on any change of recipients, a sensitive topic, an amount or a link, more than 600 characters, a flag, and the same per-thread and daily counts as replies. It goes through `send_on_its_own` on an ordinary `delegation_reply` card marked `source: follow_up`, which rechecks the setting for that recipient. A refused one waits on Today as **Follow-up waiting**, and closes by itself (its untouched draft deleted) when anyone answers in the thread first.\n\n**What it sent** is the person's alone: `GET /delegation/handled` lists the last 7 days (who, subject, the reply, the questions it left them and a link to the thread in their mailbox), and the Handle it for me tab shows it with how many went today, under its picker.\n\n### Take the lead as you\n\nOn Settings → Act as me, Handle it for me is one dial: **Off**, **Easy ones**, **People I know**, **Most mail** and, for the owner, **Everything**, which uses **Take the lead** (`PUT /delegation/take-the-lead`, one row `person:<id>` in `take_the_lead`; turning it on turns Handle it for me on). While it is on, `handle_it.refusal` drops the setting's limits: strangers, the classifier's confidence, amounts, and the length up to a 4000-character ceiling. A reply with a link still waits for a tap (refusal `link`). In their place it checks the company's and the person's own added rules (`take_the_lead.reply_hit`, refusal `lead_rule`). Everything Handle it always keeps still holds: signed sign-ins, an authenticated sender, a reply kind, exactly the thread's people, the topics that always wait, draft flags, never twice in a row, one a thread a day and the daily limit. Follow-ups under it may go to anyone the person wrote to, with the same sensitive, amount, link and length checks plus the added rules. `reply_send.send_on_its_own` accepts the card while both switches are on. Each person adds and removes their own rules (`/delegation/take-the-lead/rules`). Removing one needs a caller the API can tie to them.\n\n\n## Meeting invites\n\nWith **Read my calendar** on, a calendar invite in the person's inbox no longer just gets skipped (`delegation.invites`). The watcher applies its usual rules, less the ones about writing a reply (a calendar service's own Sender header doesn't make it automatic; a big meeting isn't too many recipients), and then looks at who sent it: someone the person knows — their team, a contact, or someone they have written to (`inbox.relation_of`), with the sender confirmed by the mail service (`inbox.handling_relation`) — or it is skipped as `invite_stranger` / `invite_unverified`. It then finds the event on their own calendar: on Google by the invite's iCalendar UID (read from its `text/calendar` part, or its attached `.ics`) in their primary calendar, on Outlook as the invite message's own event; only a request counts (a cancellation or someone's answer doesn't). An event that can't be found, isn't organized by the sender, is already answered or has already started is skipped with that reason, as before. **No model is called** for an invite.\n\nWhat's left becomes a card, a `delegation_invite` decision that is its person's alone (`approver_only`) and never an alert, like a reply card: who invited them, the title, when (in the workspace time zone) and any **clash** — the busy times on their calendar that overlap the meeting, computed in code from the calendar read; only start and end times reach the card, never another event's title. **Accept** and **Decline** are `POST /decisions/{id}/approve` with `edits.answer` (`accept`, the default, or `decline`), on the same caller checks Send uses (`verified.caller_refusal`); the card is claimed, then answered with the mailbox client's `answer_invite`. Answering again is harmless, so a failure releases the card for another try; an event that has gone fails it. **Dismiss** (`reject`) answers nothing. A sign-in that reads but can't write the calendar keeps its card, which says to connect again under Read my calendar (with the command) instead of offering Accept. A card closes by itself once the meeting starts or after a week, and its thread waits until it's settled.\n\n**On its own.** Under Handle it for me (On, or Take the lead as you) it accepts with no tap when plain code finds nothing against it (`invites.refusal`): a sender on their team or in their contacts, never one known only from their Sent mail (with Replies in training, only one they ticked **Accept from them on its own next time** for), signed sign-ins or local login, no clash and a calendar it could read, nothing sensitive in the title, a sign-in that can answer, and Handle it for me's daily limit and once-a-day-per-thread rule (`handle_it.count_refusal`, `record_handled`). It never declines on its own. Anything against it leaves the usual card saying why. An accepted invite is listed with the replies it sent: `GET /delegation/handled` (`source: invite`, with a one-line `summary` such as \"Accepted Dana's Pilot review, Wed 21 Oct, 14:30\") and Today's `sent_as_you` activity, the person's alone.\n\n**In training.** With Replies in training, a card has the same tick as a reply card; ticking it and tapping Accept adds `Accept invites from <name>` to their learned list (key `act_as_me|person:<id>|invite_from|<address>`, under Replies), removable like any other.\n\nAudit rows, all private to the person: `delegation_invite_carded`, `delegation_invite_answered`, `delegation_invite_handled`, `delegation_invite_dismissed`.\n\n## AI line on replies\n\nReplies written as a person can end with **\"Drafted and sent by my AI assistant.\"** (`delegation.disclosure.LINE`), by two switches that are each person's own (`PUT /delegation/disclosure`, one row per person in `delegation_disclosure`, NULL following the install): **Handle it**, on by default (`AI_DISCLOSURE_HANDLE_IT`), for a reply Handle it for me will send on its own, which nobody reads before it goes; and **Approved sends**, off by default (`AI_DISCLOSURE_APPROVED_SENDS`), for one that waits on a card for them to send, since they read it first. The line is written into the reply when it is drafted (`disclosure.sign`, in `inbox._consider` and `follow_ups`), once the plain-code checks have decided whether it goes on its own, so the card, the mailbox draft and what is sent are the same words and Send's draft-changed checks see them; a switch changed later applies to the next reply, and a reply drafted to go on its own that is handed back keeps its line for the person to edit. `AI_DISCLOSURE` off turns both off and hides the card. Turning a switch on only adds the line, so it needs no signed sign-in; turning one off does. Each tab shows its own switch under Advanced (**AI line on drafts you send** on Act as me, **AI line on replies it sends** on Handle it for me), and turning off the Handle it line asks first.\n\n## The mailbox client\n\n`delegation.gmail.DelegateGmail` talks to the Gmail REST API directly and is **never registered with the MCP gateway**, so the model reaches the mailbox only through the typed handler. The credential is one file per person in `DELEGATION_GOOGLE_CREDENTIALS_DIR`, named from a hash of the address (0600 in a 0700 directory), minted by `scripts/connect-own-gmail.py` on the Executive's own OAuth client with the scopes `gmail.readonly` and `gmail.compose`. It never lives in `WORKSPACE_MCP_CREDENTIALS_DIR`, where workspace-mcp picks a credential by address. Besides reading threads and saving drafts it lists the inbox and checks whether they have written to an address, reads one message or draft, lists the person's send-as addresses and deletes a draft. Its **one send method**, `send_draft`, sends an existing draft by its id and nothing else — never `messages.send`, which sends any text it is given — and unit tests pin the method set, the endpoint, the request body and its single caller. On the calendar it reads (`list_events`, `find_invite`: an invite's event by its iCalendar UID) and makes one change, `answer_invite`: the person's own attendee answer on one event, with `sendUpdates=all` so the organizer hears (`calendar_write_granted` says whether the sign-in allows it; a read-only one raises `CalendarWriteNotGranted`). A failed request says whether it may have been carried out anyway (a timeout after connecting, a 5xx), which is what the send path needs to know. A parsed message carries when it arrived, whether it is bulk, a bounce or a calendar invite, and whether Gmail's authentication results vouch for its sender.\n\n`gmail_status` answers `connected`, `not_configured`, `needs_reconnect` (Google refused the saved sign-in — an app in Testing mode has its tokens expire after 7 days; a rate limit, though Gmail may send it as a 403, is an `error` to retry, not a reconnect), `mismatch`, `no_email`, `shared_mailbox` or `error`. `shared_mailbox` means the person's address *is* the Executive's; it is refused before asking Google, because then everything the Executive writes would look like theirs. The gateway closes the other door: every `google_workspace__*` call must act as the Executive's own account, and a `user_google_email` naming anyone else is refused and audited (see Integrations).\n\n### Outlook\n\nA person may connect an Outlook mailbox instead (work, school or personal), with `scripts/connect-own-outlook.py`: a device-code sign-in on the Executive's own Entra app (`MS365_MCP_CLIENT_ID`, tenant `MS365_MCP_TENANT_ID` or `common`) asking for `User.Read`, `Mail.ReadWrite`, `Mail.Send` and `offline_access` (and `Calendars.ReadWrite` with `--calendar`; an invite is the invite message's own `eventMessage.event`, answered with Graph's event `accept` or `decline` and `sendResponse`). It writes the same per-person file with `\"provider\": \"microsoft\"`, so a person has one mailbox for Act as me, and `gmail_for` hands back `delegation.outlook.DelegateOutlook`, which keeps `DelegateGmail`'s methods, return types and errors, so every caller above runs unchanged. It talks to Microsoft Graph directly, never through the Microsoft 365 MCP server the Executive's own Outlook uses, and is never registered with the gateway. Microsoft rotates the refresh token on use; the new one is written back into the file (atomically, keeping every other key, and only if the file still holds the old one). Graph is asked for immutable ids, so a sent draft keeps its id; a thread is Outlook's `conversationId`. Gmail's labels are mapped onto what the callers read: `SENT` only for mail in their Sent Items folder (a From line set to their address by someone else never counts), `DRAFT`, `INBOX`, and Focused Inbox's Other read as a tab. A sender counts as authenticated only when the topmost `Authentication-Results` — the one Exchange wrote, above anything the sender added — holds exactly one DMARC verdict, a pass for From's own domain, and Exchange Online Protection's own `compauth=` verdict, so a header the sender wrote on mail EOP never stamped doesn't count. `delete_draft` refuses anything that isn't a draft, and deletes with the draft's etag (`If-Match`), so a draft sent in between — it keeps its id — is left alone. No client secret is ever written into a person's file, and Graph has no signature setting to read.\n\n## Privacy\n\nWhat a person's mailbox touches is theirs. For the principal that means private to the principal, as every private row is. For a team member it means theirs alone, the principal included: an audit row carries `private_to_person` (set by `audit.rows_for_person` around the inbox watcher, a card's Send and Dismiss and their settings changes, and by `people_tools.audit_row_owner` on a turn that read their mail) and is left out of every audit read — the log, a session's timeline, a row by id, the brief — with only the usage totals counting it; their reply cards are theirs alone (above); and the owner's view of their use is counts only (drafts and sends in 30 days, and whether their inbox watcher is on). The conversation itself becomes its owner's alone before the mailbox is first read: `ghostwrite_email` marks the session `mail_private` (`session_store.mark_mail_private`, creating a channel adapter's row early, with its owner) and refuses to read the mailbox if that can't be stored or the conversation already belongs to someone else (which it then leaves unmarked); from then on only its owner may open it (`chat._session_access`), and working-style learning skips it. Every later turn there starts private (`settings.pin_turn_delegation` reads the flag and fails closed, setting `touched_mail`), so a follow-up answered from history alone is still private to its owner and teaches no memory, and the web chat's rows before the turn (the inbound message and the knowledge lookup) are theirs too. It does not start locked down: the lockdown is `read_mail`, set only by a turn that reads the mailbox or notes itself, and it is never carried into the next turn, because history keeps only the speaker's words and the Executive's replies, never the mail a tool returned. Their next message is them asking again, having read that reply, so everything runs again there. Anyone else speaking in it is not offered Act as me.\n\nOnce `touched_mail` is set, every audit row the turn writes is private (`people_tools.audit_row_private_to_principal`), and a team member's is theirs alone: the tool row (its input and result redacted, since `ghostwrite` is a sensitive tool name), the reply's `chat_turn` row that carries the preview, the model-call rows, and the background passes, which run under `private_rows`. The Honcho peer and department syncs are skipped, because peer memory is read on other people's turns. No memory is learned from the turn at all: the episodic, open-loop and working-style passes are skipped too, since its reply quotes a draft built from other people's mail. The `delegation_*` audit events are always private and carry metadata only — ids, counts and flags, never the draft or the thread. The inbox watcher is private the same way: every row a scan or a card action writes is its person's alone, and it starts no chat turn, alert, scheduled action or workflow run and teaches no memory.\n\nThe turn also keeps one door shut (`delegation.lockdown`). Anyone can put text in the inbox, and that text could try to steer the model, so from the round that calls `ghostwrite_email` or one of the mailbox reads — a round's tools run together — until the turn ends, the dispatch guard refuses only what opens the open internet or reaches everyone: outside fetches (`read_document`, research, the watchlist, `load_mcp_server`, and any MCP `call_tool` outside the private-turn set of reads and recipient-checked sends), `run_script` and `run_python_job`, workflows (they run later, unattended, and may fetch or script), broadcasts, department messages and alerts, and changes to who is on the roster or holds authority (`archive_person`, `set_department_head`, `resolve_roster_request`), and text that steers later turns (`schedule_followup`, whose intent runs unattended when due, and goals and decision outcomes, shown to every later turn). Everything else the person asks for runs, because it is fenced on its own: DMs and `message_person` reach only the roster, invites name attendees by person id, the Executive's own email checks every recipient against the roster, standing facts and profile edits keep only the person's own words, and a workflow drafted in chat is saved only once a person confirms it. `upsert_person` runs only for a contact the person asked for (`speaker_named_contact`: a contact, never the team, an approval scope or a chat account, with a word of the name in what they typed, in a message that asks to add, save or change someone, a new contact's address one they typed or one that sent the mail the turn read under the contact's name (`TurnDelegation.mail_senders`), never one the mail's text only mentions, and on an update a changed address they typed), since the roster is what the send checks trust. Any other contact add is refused with a pointer to an approval card (`lockdown.CONTACT_REFUSAL`), so the Executive leaves an `add_contact` card in the chat rather than asking them to type the address. What an email itself asks for is still never done on its say-so; it goes on an approval card. Every tool is classified as allowed or withheld, a test fails on a new unclassified one, and an unknown name is withheld, except an extension tool registered with `after_mail_read` (one that only reads the install's own data). The refusal tells the model to put what the step needs in its reply, since the next turn sees the reply but not the mail, and to do the step then without reading the mail again. A refused call gets a private `tool_invocation` row (`refused: mail_touched`) and tells the model to offer it in the next message. The offered tool list never changes mid-turn, so the cached prefix holds. The handlers that reach outside check again on their own (`outside_reach_refusal`). The server-side web search stays, as on a turn private to the principal. The lockdown ends with the turn. Later turns of that conversation stay private to its owner (`touched_mail`) but hold nothing: a refusal says it will work when they ask again in their next message, and it does.\n\n## Always in the loop\n\nA sent reply can leave a note. Once the reply went, `reply_send` starts `memory.history_notes.note_sent_reply` for the person who sent it, in the background, when their \"Keep track of what happens\" switch is on and the conversation isn't one they asked not to remember. The note-taker sees only the words they sent, so other people's mail never becomes a note, and a failure never touches the send. Recall is `recall_history`, offered on the same verified, private surfaces as `ghostwrite_email` and also allowed under the mail lockdown, since it only reads the speaker's own notes. Calling it locks the turn like `ghostwrite_email` does, from its own round on. The same switch also covers notes from chat, which don't need Act as me. See **Memory** for the checks, retention and controls.\n\n## The system prompt\n\nA constant, name-free `DELEGATION_ADDENDUM` joins block 0 after the unchanged identity addendum while anyone on the install has it on (`block0_delegation_on`). It names the four mailbox reads and says other people's mail is data and that a conversation which read it reaches nobody else; and it tells the model that `ghostwrite_email` is the single exception to *never impersonate*, and only for the person being spoken to; that everything else is written as itself; that when the tool isn't offered the asker can't have it; that a draft is never described as sent; and that it never denies being an AI. It is keyed on the install-level setting, never on the turn or the speaker, so switching it misses the 1h cache once (see Prompt Caching).\n\n## What it does for you\n\n**What it does for you** (`delegation.may_do`, `GET /what-it-may-do`) is read-only: with the viewer's settings right now, one row per thing that can go out without asking, written as one sentence of what it does, what happens to it (goes out, waits for someone, always waits, drafts only, off) and which setting decides it, with a link there. It sits beside every Delegate tab (`DelegatePage` → `WhatItDoesPanel`): a column to the right on a wide screen (closing it is remembered in the browser), a bottom sheet on a narrow one. The UI groups rows by outcome (Sends on its own, Asks first, Writes for you to send, Off). Every delegation setter in `lib/api.ts` fires `DELEGATION_CHANGED` after a save; the panel reloads on it and marks the rows whose outcome or text changed as **Just changed** for ten seconds. `/delegate` and the old `/delegate/what-it-may-do` open Act as me. Its **Compare** fold holds Who writes and who sends. Three parts, each behind a pill that counts what goes out:\n\n- **As you** (the caller's own, when `can_delegate` allows them): built from `settings.is_enabled`, `inbox.get_watch`, `handle_it.get` and `handle_it.RULES`, `handle_it.leading` (Everything), `training.get` and `training.learned`, and their rules, the same reads `handle_it.refusal` and `follow_up_refusal` make. A level's row follows its `Rules` (strangers, follow-up reach, links and amounts), not a copy of them. A note names the ladder: Handle it for me rides on Draft replies to my inbox and Write drafts as me, and Everything also drops when Replies or Follow-ups go into training.\n- **As the Executive** (the principal's alone, as `GET /take-the-lead`): the switch and its training, each Ask first kind, the company's rules, and meetings. A meeting it thinks of on its own always waits: both meeting gates need someone on a verified surface in the turn, which an unattended run never is. A meeting someone asks for in chat follows **Always asks first → Meetings asked for in chat** (on means it waits: `meeting_scheduling`'s class mode is `propose`; off means `auto_execute`) and, in a team workspace, Operations' level too.\n- **Departments**: each level, and what a level covers (department-scoped scheduled work, check-ins, alert review, team members' chat sends, and Operations' meetings), and that it doesn't cover what the Executive does under Take the lead.\n\nIt also says when the Executive is paused, and when nothing can be sent as anyone because signed sign-ins are off. Nothing on it writes or reads mail. A contact, someone not on People, or a request with no caller (outside local login) gets 403.\n\n## How far it goes as you\n\nOne setting replaces the switches that used to turn each other off out of sight. The UI shows it as two pickers (`ReachCard.tsx`): **What it writes as you** (`WritesCard`) on the Act as me tab and **What it sends on its own** (`SendsCard`) on the Handle it for me tab; What it does for you links each row to its own picker. Its steps, each adding to the one before: **Off**, **Drafts when I ask** (Write drafts as me), **Drafts for my inbox** (Draft replies to my inbox), then the Handle it for me steps that send, **Easy ones**, **People I know** and **Most mail** (`careful`, `balanced`, `bold`), and for the owner **Everything** (Take the lead as you). Act as me shows the first three as **Off**, **When I ask** and **Draft replies automatically** (any sending step reads as Draft replies automatically there). Handle it for me shows **Off** (saved as the inbox step) and the sending steps, and opens only once Act as me is at Draft replies automatically, with a button that turns that on; moving Act as me below it says Handle it for me stops too. `PUT /delegation/reach` (`{step}`) moves it, and `reach_of` reads the step back from the switches, so the stored switches stay the source of truth and every gate reads them as before.\n\nGoing down turns the switches above the target off, highest first (`_lead_off`, then Handle it, then the inbox watcher, then Write drafts as me), so nothing is ever on above a switch that's off; the UI says what stops and asks before it saves. A lower sending level only holds more back and is set directly, so it needs no signed sign-in. Going up calls each switch's own route in order, so every check it makes still applies: the mailbox connected, signed sign-ins for sending, the owner alone and not in training for Everything. The first that refuses stops the move at a whole step and answers with that route's error. Handle it for me's own Off / In training / On (Replies and Follow-ups together) and, at Everything, **Your rules** sit with its picker, and **Learn from my edits** (drafts training) under the Act as me one; neither picker changes training.\n\n## Surfaces\n\n- **Settings → Act as me** (`ActAsMeCard`, hidden unless `GET /delegation` answers, so a team member sees it once the owner lets them): the mailbox connection (`provider` says which) with both connect commands (Gmail and Outlook) and **Check again**, **What it writes as you** (above), with the inbox watcher's status under Draft replies automatically (in plain words, when it last checked, **Check now** and **Also save inbox replies in my Gmail Drafts**), and **How I write**: length and tone, a greeting per audience (`{first}` is their first name), the sign-off, habits and never-rules in fields that grow to show every line, the signature with **Refresh from Gmail** and **Don't add my signature** (or **Add my Gmail signature** when none is added; on Outlook only **Don't add my signature**, with why), and each example quoted with **Remove examples**. The owner also gets **Let team members use it** where the install allows it, with each team member who has it on listed by name and counts only.\n- **Today → Replies waiting** (`RepliesWaiting`, the top of the left column; hidden unless `GET /delegation/replies` answers with cards): each card shows who wrote and who they are to you, whether their address was verified, the subject, **They wrote** as plain text, your draft, **Decide before sending** (the open questions, each with answers to tap and **Something else…**, and where they came from) and its warnings, with **Send** (a confirm naming who it goes to, and a second one when that or the thread changed), **Edit** (a text box on the card with Save and Cancel), **Open in Gmail** or **Open in Outlook** when the reply is in their Drafts, and **Dismiss**.\n- **Today → Needs you, invites** (`InviteCards`, next to the reply cards; hidden unless `GET /delegation/invites` answers with cards): the meeting, when, who invited them and who they are to them, any clash (times only), and **Accept**, **Decline** and **Dismiss**, or the reconnect note for a read-only sign-in; with Replies in training, the **Accept from them on its own next time** tick.\n- **Setup status**: a **Your own mailbox (Act as me)** light (`your_gmail`), amber while the inbox watcher can't reach the mailbox, is being rate-limited or has 25 replies waiting.\n- **Delegate** (main menu): **Act as me** (where `/delegate` and `/settings/act-as-me` land), **Handle it for me** (which step the dial is at, with **Change in Act as me**, then **What it sent**: how many went today and what it sent this week, as you) and **Take the lead** (the switch, then **Always asks first**, shown even while the switch is off and ending in **Meetings asked for in chat**, and the company's rules, as the Executive). Each switch that turns another off says so beside it. The pause is on **Settings → Your Executive**.\n- **API**: `GET`/`PUT /delegation`, `GET`/`PUT`/`DELETE /delegation/voice`, `POST /delegation/voice/learn`, `POST /delegation/voice/describe`, `POST /delegation/voice/signature`, `PUT /delegation/inbox` (`{enabled?, mailbox_drafts?}`), `POST /delegation/inbox/check`, `GET /delegation/replies`, `PUT /delegation/replies/{id}/text`, `GET /delegation/invites`, `PUT /delegation/handle-it`, `PUT /delegation/reach` (`{step}`, the dial), `PUT /delegation/training`, `DELETE /delegation/learned/{id}` and `GET /delegation/handled` — the caller's own delegation only — and `PUT /delegation/team`, the owner's switch (see API Reference). `GET /what-it-may-do` is the read-only summary above. Send (and an invite's Accept or Decline, with `edits.answer`) is `POST /decisions/{id}/approve`; Dismiss is `POST /decisions/{id}/reject`.\n- **Evals**: a scenario's `delegation:` block runs the turn against an in-memory mailbox (`evals.mailbox.ScenarioMailbox`) and hands the saved drafts to the judge (`delegation_001`–`003`). A `type: inbox` scenario runs the watcher's two model calls on one thread: whether it drafts must match the scenario, and a draft is judged on saying nothing the person hadn't, copying no link or address, and listing every open question (`delegation_inbox_001`–`007`; the last checks a draft never claims anything was sent).\n\nActing within rules the person sets and standing in for them are later, separate changes, each behind its own switch, off by default.","mermaid": "flowchart TD\n Ask[\"Principal or team member, verified<br/>'reply to Dana as me: yes'\"] --> Pin[\"pin_turn_delegation<br/>may have it? on? verified? private? attended?\"]\n Pin -->|\"offered\"| Loop[\"Executive tool loop<br/>with ghostwrite_email\"]\n Pin -->|\"not offered\"| Self[\"writes as itself<br/>(unknown tool this turn)\"]\n Loop --> Tool[\"ghostwrite_email handler<br/>caps, mailbox check, recipients in code\"]\n Tool -->|\"touched_mail\"| Private[\"turn's rows and conversation<br/>theirs alone, no memory\"]\n Tool --> Client[\"DelegateGmail or DelegateOutlook<br/>REST, outside the MCP gateway\"]\n Tick[\"Scheduler tick or Check now<br/>Draft replies to my inbox on\"] --> Scan[\"inbox scan, rows theirs alone<br/>skip rules, limits, ledger\"]\n Scan --> Client\n Client --> Box[(\"The person's own Gmail or Outlook\")]\n Scan --> Classify[\"classifier, no tools<br/>needs a reply? kind, confidence\"]\n Classify -->|\"worth a draft\"| Gw\n Voice[(\"delegation_voice<br/>How I write\")] --> Gw[\"ghostwriter<br/>no tools: voice + intent + thread\"]\n Tool --> Gw\n Gw --> Lint[\"lint: links and addresses<br/>only the person's own\"]\n Lint --> Draft[\"create_draft, threaded\"]\n Draft --> Box\n Draft --> Chip[\"chat chip: open the draft<br/>chat never sends\"]\n Draft --> Card[\"Today: Replies waiting<br/>their own card\"]\n Card -->|\"Send, confirmed\"| SendPath[\"reply_send: checks again,<br/>claim, send the draft by id\"]\n SendPath --> Box\n class Ask entry\n class Pin compute\n class Loop compute\n class Self compute\n class Tool compute\n class Private compute\n class Client compute\n class Tick entry\n class Scan compute\n class Classify compute\n class Box external\n class Voice storage\n class Gw compute\n class Lint compute\n class Draft hot\n class Chip entry\n class Card entry\n class SendPath hot",- "generated_at": "2026-10-21T13:00:00Z"+ "generated_at": "2026-10-21T18:34:37.571288+00:00"}diff --git a/packages/core/openexecutive/architecture/prebuilt/workflows.json b/packages/core/openexecutive/architecture/prebuilt/workflows.jsonindex cb72be86..5c3fece8 100644--- a/packages/core/openexecutive/architecture/prebuilt/workflows.json+++ b/packages/core/openexecutive/architecture/prebuilt/workflows.json@@ -1,7 +1,7 @@{"section_id": "workflows","title": "Workflows",- "markdown": "Workflows are deterministic, multi-step orchestrations. The built-ins are registered in `openexecutive.workflows.WORKFLOW_REGISTRY`; user-created (dynamic) workflows are stored as data (see below). Each follows the same contract: structured input feeds an ordered list of named steps that render a Markdown artifact, persisted via `complete_run` into `workflow_runs.artifact`. The activity feed never shows a run's log title (`\"Executive Research (periodic)\"`): `workflows/run_outcome.py` gives each finished run a plain name (\"Researched your market\", \"Checked in with Sales\", or the name it started with, less its date) and one line on what came of it, read from that stored artifact, so older runs read the same and nothing extra is written or called. Every step emits a `WorkflowEvent` (start/progress/complete) streamed over SSE at `/workflows/{name}/runs`.\n\nThe registry holds 25 built-in workflows, plus any number of user-created ones. Representative built-ins:\n\n- `board_prep`, `quarterly_plan`, `annual_plan` — planning and governance deliverables.\n- `performance_review`, `comp_refresh`, `org_design`, `exec_search_brief` — people and org artifacts (the last is an advisory hiring brief / scorecard from the CHRO, with input from the hired function's specialist — `sales` for a sales role — kept when the recruiting pipeline was removed).\n- `crisis_comms`, `churn_deep_dive`, `competitive_teardown` — situational analyses.\n- `department_check_in` — runs on department cadence; its `goal_status` step returns structured verdicts persisted back to `department_goals.status` (`department_check_in.persist_goal_verdicts`, shared with `weekly_review` and the weekly `goal_review`, which grades the goals no check-in covers; see Scheduler).\n- `weekly_review` — the principal's weekly look back and ahead (see *Weekly review* below).\n\n**Standing facts in unattended output.** `end_of_day_digest`, the weekly review's top-three call and the morning reflection append the standing facts (`memory.facts.with_standing_facts`; a teammate's marked `(per <name>)`) to their user turn, and the morning brief gets them through `render_briefing_context`. A workflow step that consults a specialist gets them through `route_to_specialist`. A correction made in chat therefore holds in every recurring brief and run. The morning brief also reads `facts.render_teammate_changes(since)` off the event loop and passes it to both `render_briefing_context` (a TEAMMATE CORRECTIONS SINCE LAST BRIEF block) and `build_brief_fingerprint`, so the principal hears of each correction a teammate made in the window, and that alone un-suppresses an otherwise unchanged brief. Proposals waiting for approval are listed only in a brief the principal reads privately (`include_proposed=_private_ok()`), and then mark the run private to them. The principal's own Always in the loop notes (`memory.history_brief`, only with their switch on) come in by a stricter rule, only on the scheduler's delivery (`PRINCIPAL_DELIVERY`), never a run from chat, whose tool result reaches the turn's shared audit row and peer memory: the morning brief's FROM YOUR NOTES — DUE SOON block and the end-of-day digest's FROM YOUR NOTES — TODAY block (what they committed to since the last digest, then what is due tomorrow). Either marks the run `private_to_principal` and moves its fingerprint; the digest, which had no private reads before, now emits that flag too. In the install's first week (`briefing.first_week`, seven days from the principal's People row) the morning brief also passes a GETTING STARTED block to `render_briefing_context(getting_started=)` and its keys to `build_brief_fingerprint`: onboarding goals, departments with no leader and, on the scheduler's delivery with Act as me and Draft replies to my inbox on, who wrote to the owner's own mailbox (sender and subject only) and, with Read my calendar on, today's meetings on their own calendar (time and title), either of which marks the run `private_to_principal`. The brief opens with **Getting started** and is never the quiet line while the block has anything in it (see Today).\n\n### Change-aware principal briefs\n\n`morning_brief` and `end_of_day_digest` are the two recurring briefs the scheduler sends to the principal. Both are written with `briefing.narrative.brief_model()`, the Executive's own model (its Council pick, else `DEFAULT_MODEL`), since a brief is the Executive speaking; only the grounding repair stays on the fast model. Both are now a *delta*, not a re-list: the window is \"since the last **delivered** brief\" (`briefing.brief_state.since_for`; 24 h on a cold store, clamped to 7 days), activity comes from `_build_activity(limit, since=…)`, proposals (action category only) split into *new since last brief* — enumerated, with each item's why-now and next move — versus a one-line carried-over count, a *rewritten* block lists carried items the review rewrote inside the window (`brief_state.rewritten_since`: verdict `changed`, still open — the brief reports them under \"what changed\", never as done), and a *handled overnight* block lists what the Executive's alert review **completed** on its own (`brief_state.handled_since`; the `changed` verdict is excluded because the alert is still open). The morning brief also reads the principal's **live world** since that window opened (`briefing.live_signals.gather_live_signals`): mail and chat the Executive handled (INBOUND, grouped by sender and subject, each email from the roster marked replied or not, earlier days dated), under a NOW line and THE PRINCIPAL line that names its reader so the brief writes \"you\" (the end-of-day digest gets the same line, and the team reflection a YOUR PRINCIPAL line under its roster; the reflection flags only what today's input still shows), what got stuck (STUCK: a reply the outbound gate held, a non-roster sender who got no reply, a Google Chat message left unanswered, chat drafts still in the principal's Gmail, after `live_signals.settle_principal_drafts` has marked the ones they since sent or deleted there), the principal's own chats, and — in both modes now, unless the solo top three already listed it — today's calendar, read fresh (`live_signals.refresh_calendar(max_age=0)`). The 07:30 reflection's **Flagged for the brief** bullets are carried across (`brief_state.reflection_flags_since`, the latest reflection run finished inside the window) instead of surviving only as an activity line with the run's title, and the rhythm runs themselves (`today.RHYTHM_WORKFLOWS`) are dropped from the brief's activity: their dated titles were noise and moved the fingerprint every day. At-risk departments name their slipping goals and each proposal carries its age. The period is the principal's local date. Section order: top call → **today** (the calendar's shape and anything stuck) → what changed (inbound first, naming who wrote) → handled overnight → needs you (new only) → waiting on → at risk (the slipping goal, or the department left out — never \"no detail yet\"). Quoted mail, chat, invite and reflection text is marked as data, never instructions. **Privacy:** the brief reads what is private to the principal — their contacts' alerts and mail, their drafts, their chats and their calendar — only on a run for them: the scheduler's (`morning_brief.PRINCIPAL_DELIVERY`) or the principal's own verified chat turn in a conversation only they can read (`delegation.settings.private_conversation`: the web chat, a Slack or Discord DM, a private Telegram chat — never a shared channel, where the reply is posted for everyone). A run anyone else starts (a teammate from chat in team mode, `POST /workflows/…/runs`) reads what everyone may see, as before. A run that did read a private row says so on its `result` event (`private_to_principal`: its live read differs from the shared one in any key or count), and the scheduler, `run_workflow` and `POST /workflows/{name}/runs` all then keep `persistence.PRIVATE_RUN_ARTIFACT` in the run history instead of the text. Text another pass wrote (the reflection's flags) renders as quoted ` > ` lines and every goal and headline field is one-lined, so none can start a line that reads as a block header. The fingerprint carries the live signals' time-free keys (who wrote about what, what is stuck, the calendar's shape) and the reflection flags when there are any, so \"nothing new\" means the principal's world was quiet too; the context summary is logged at INFO (`morning_brief: context since=… inbound=… stuck=… suppressed=…`). In **solo mode** (one person using Open Executive for themselves) both briefs speak to the principal, whatever their role: the morning brief runs top call → top three today → what changed (inbound and stuck first) → handled overnight → needs you → due this week (the principal's open loops overdue or due within 7 days, from `open_loops.principal_due_soon`) → goals at risk (named by area), the end-of-day digest what I did → open decisions → goals at risk tomorrow → sleep on this, over a context with goals at risk by area and no people-waiting or department block; the fingerprint carries the mode and ignores who is awaiting, and carries the due items as `(loop_id, state)` pairs when there are any. **Top three today** is picked in code, not by the model (`briefing.top_three`: overdue then due-today commitments, off-track then at-risk goals, commitments due later this week, then active projects, stalest first). The solo Briefing's *Top three today* card shows the same pick from the same code (`GET /today/top-three`, see Today). When the MCP gateway runs the Google Workspace server, one `google_workspace__get_events` call (4 s timeout) lists today's events on the principal's calendar — their address as the calendar id, read with the Executive's account (`primary` when the Executive is signed in as them) — and on a business day (`calendar_tools.is_business_day`, the rule the booking tools apply; at the weekend the day's events are still listed but no slot is suggested) each item gets its own free block inside `CALENDAR_BUSINESS_HOURS_START`–`_END`, rendered with a TODAY'S CALENDAR block — only a date-only event is all day, a zero-length one blocks nothing, and one whose times can't be read is left out; no gateway, no principal address, an error, a timeout or a reply it cannot read all mean no calendar and no slots, never a failed brief; the log records only the reply's length or the error's type, never calendar text. When the principal has Act as me and **Read my calendar** on (`delegation.calendar`) and their mailbox opens as theirs, `top_three.read_todays_calendar` also reads their own calendar through their own sign-in (Gmail or Outlook, same 4 s timeout, declined events left out), at the same time as the Executive's read, and merges the two: an event with the same title and times on both is listed once, and either read alone is enough. This read feeds the morning brief, the /today calendar cache (`live_signals.refresh_calendar`) and so the end-of-day digest and Right now; the solo top three adds it only on a run for the principal (`build_top_three(include_own=private_ok)`). The fingerprint carries the three items' keys (no dates, no slot times) and only a coarse hash of the day (busy blocks rounded to 15 minutes, no titles, no dates), so an unchanged day still suppresses. A day whose calendar read fails after one that worked (or the reverse) changes the fingerprint once, so that brief is written in full. A date-free fingerprint of the inputs is compared to the last delivered one; if unchanged the artifact is the one-liner \"Nothing new since yesterday's brief — N items still waiting on you.\" and no model call is made (`PRINCIPAL_BRIEF_SUPPRESS_UNCHANGED`; `force_full=true` on a manual run bypasses it). The workflow yields a `result` event with the fingerprint; only the scheduler records it, after a successful delivery, in `briefing_narrative` under scope `brief:<kind>` — so manual runs never advance the window. Both are written to their reader in code (`briefing.reader`): the principal's full name and addresses are masked to \"the reader\" throughout the context under a THE READER line, the prompt says \"you\" for the reader, nobody is \"the principal\" and the Executive is \"I\" / \"me\", and a draft that still slips is rewritten once (the morning brief) and fixed in code. **The end-of-day digest reads the day itself.** On the scheduler's delivery to the principal alone it leads with TODAY WITH YOU (`session_store.own_conversation_since`: the principal's own conversations with the Executive since the last digest, their words and its replies, never a conversation someone else owns) and the live blocks (`live_signals.render_live_blocks`: mail in, what got stuck), then COMING UP (the Executive's own follow-ups due in the next two days). It leaves out its own rhythm runs (`today.RHYTHM_WORKFLOWS`) and gets the reader's leave-out list (`brief_requests.render_parts`). Its shape is **Today**, **Done for you**, **Next** and an optional **Sleep on this**, at most 150 words, with no header for an empty section. Before this it read only the Executive's own bookkeeping, so on a day of real work it reported its own briefs and missed every number decided in chat.\n\n**Brief delivery.** `scheduler.runner._deliver_to_principal` maps the principal's `preferred_channel` (`slack` / `discord` / `telegram` / `email`) to its delivery channel and tries it first, then the other chat channels the principal has an id for, in the order Slack → Discord → Telegram. Email goes through the active MCP gateway (`google_workspace__send_gmail_message` as the Executive's own address, to the principal, subject `<title> — <date>`) and is used only for an explicit `email` preference, or for `any` when no chat channel resolves — an owner linked by email at setup has `any`, so one who also has Slack does not start getting two emails a day. When nothing can deliver (a web-only principal, or email with no gateway), the brief is still generated and stored as a run with its artifact, as before — a web-only principal reads it on the Artifacts page — it is just not delivered (audited), so the window does not advance, and the next occurrence is chained. The same delivery path carries the client-rotation digest and the weekly review.\n\n**Grounding.** Nothing an unattended pass writes is read by anyone before it goes, so `openexecutive.briefing.grounding` checks it deterministically — no model judges the model. A name (a run of two or more capitalised words once section headers, weekdays, imperative openers and org nouns are trimmed, or one capitalised word in a person slot like \"ask Marcus\" or \"Marcus wrote\") is grounded only when a single line of the pass's inputs holds all of it, or it belongs to a roster person some input mentions — being on the roster alone is not enough. A figure (money, a percentage, a k/M/B number, any bare number of 11 or more; never a date, time, year, duration, id, list marker, `Q3` or small count) is grounded when an input number matches it within the precision it is written with (`$1.2M` matches `$1,234,567`; `47 units` does not match 48). The inputs are the rendered context split into lines labelled by section (a header also carries its bullet count), the company profile and the department titles. `morning_brief` renders its context itself and hands it to the synthesizer as `rendered_context`, so the check reads exactly what the model read; after the quiet fallback, `ground_brief` runs on both briefs. When something is ungrounded it makes one repair call to the fast model (same system prompt, the list of items, \"remove or correct using only the context\"), re-checks, then drops each line still ungrounded and any header left empty, and appends \"_I left out N lines that named people or figures I couldn't match to your data. They're under Left out of your brief on Home._\" (everything ungrounded → one held-back line). Every held line goes in the `grounding` audit row's untruncated `full` payload (up to 30, 400 chars each; `details` keeps a five-line preview), and `grounding.recent_held_back` reads the last day's back for `GET /today`'s `held_back`, which Home lists under **Left out of your brief** for the principal alone — after the narrative inputs are taken, so the held lines never reach a prompt. Then each grounded figure gets a server-chosen ` [n]` — the matching input line with the most words in common with the figure's clause — and a `**Sources**` list closes the brief (`- [n] <section> — <snippet>`, at most 9, snippets quote inbound mail, so links are masked (\"(link removed)\"), Markdown, angle brackets and @-mentions stripped, and they are cut to 90 chars; never `[n]:` at a line start, which Markdown reads as a link definition). Text with nothing to change comes back byte-identical, the fingerprint hashes the inputs so suppression is unaffected, and the grounded text is what is delivered, stored and recorded as delivered. Both brief prompts and the digest prompts say the rule up front. `executive_reflection` wraps its handlers in a `GroundingScope`: `create_alert`, `message_person`, `send_department_message`, `send_company_broadcast` and `schedule_followup` refuse text with an ungrounded name or figure, returning a JSON error that names the items so the model can look the person up or leave the figure out (every tool result joins the inputs, so a `lookup_person` answer grounds the DM after it; the recipient's own name always counts). Its **Flagged for the brief** bullets are filtered the same way before the tool log is appended — the next brief quotes them, where they would ground themselves — and `brief_state.reflection_flags_since` now stops at the tool log's `---`. The reflection's `grounding` rows are private when a private-to-principal alert reached its context, and the digest's always are (its HANDLED block can quote one). Everything fails open. `GROUNDING_CHECKS=enforce` (default) acts, `report` only writes the `grounding` audit rows, `off` skips it; `GROUNDING_CITATIONS=false` drops the markers. Not yet grounded: the /today header (its cards sit beside it), `weekly_review`, the research synthesis, dates and meetings, and a real person named in the wrong role.\n\n### Weekly review (solo)\n\n`weekly_review` (background, inputs all defaulted) closes out the principal's week in six steps. **Goals**: every area with goals is graded by its own specialist, concurrently, with the department check-in's verdict contract (`_parse_verdicts`) and write-back (`persist_goal_verdicts` → `record_goal_review`, one `goal_status_review` audit row per area with actor `weekly_review`); an area with no goals is skipped, one without a specialist is listed ungraded, and one whose specialist fails is shown as last recorded. **Commitments**: `open_loops.principal_due_soon` — overdue or due within 7 days. **Projects**: active initiatives with no update for 7+ days. **Decisions**: the week's (`episodic.decisions_since`). **Revisit**: up to three decisions older than 30 days with an empty outcome (`episodic.decisions_awaiting_outcome`, newest first), listed as `[decision N]` under *How did these turn out?* — the principal's answer is recorded with `record_decision_outcome` (see Agents). **Assemble**: every section always renders (a one-line note when empty), ending with *Next week's top 3* from one fast-model call that follows the `weekly-review` playbook (a constant system prompt; the playbook rides in the user turn), trimmed to at most three list items — or, when that call fails or returns nothing, the same ranked pick the morning brief uses. In solo mode the scheduler fires it weekly (`principal_weekly_review`, see Scheduler) and delivers it through `_deliver_to_principal` like the briefs, recording the delivery outcome. The solo Briefing also shows the latest completed run to the principal (`GET /today/weekly-review`, see Today): `weekly_review.summarize_review` reads the artifact's title line (`TITLE_PREFIX`) and its last `TOP_THREE_HEADING` section back as plain text, so a principal no channel reaches still sees next week's top three. Wording is role-neutral; run by hand in team mode it says *department* instead of *area*.\n\n**Principal-only workflows.** A workflow can name the workspace modes in which only the principal may start it (`Workflow.principal_only_modes`): `weekly_review` in both modes (built from the principal's decision log, commitments and goals, and it re-grades the goals) and `morning_brief` in solo (built from the principal's commitments and calendar). Team `morning_brief` and every other workflow can be started by anyone as before. This decides who may start or trigger a run, not who may read one: stored runs, the scheduled briefs and weekly reviews included, are read under the existing `/workflows/runs` rules — which is why a morning brief that drew on the principal's private rows is stored as `PRIVATE_RUN_ARTIFACT`, not as its text.\n\n- **From chat**, `run_workflow` checks at dispatch, before any run row is created, that the turn is the principal on a verified surface — `create_goal`'s rule — and otherwise refuses with a plain error that does not spell out the rule.\n- **Over HTTP**, the Jobs page's `POST /workflows/{name}/runs` and `POST /evals/runs` (a workflow scenario runs the workflow on live data) call `refuse_principal_only_run`: only a caller signed in as the principal, or a request with no caller email (the CLI or local login), may start the run. Unlike the workspace settings, an install with no principal on the roster lets no signed-in caller in, as in chat. Anyone else gets a 403 (\"Only the principal can run this workflow.\") before any run row exists. The mode is the stored one, or an eval scenario's own `workspace_mode`. The eval route runs exactly the scenario list it checked.\n\nEvery refusal is audited `refused=true` with the workflow, the mode and the caller. The checks fail closed: a mode that cannot be read counts as principal-only, and a check that cannot read the roster refuses.\n\n**Knowledge in the reflection.** A chat turn looks the knowledge base up before the Executive answers; the reflection reads the org's state instead, so nothing looked it up for it. It now carries its own `search_knowledge` tool (`orchestrator.knowledge_tools`, not in the shared `_ALL_SKILL_TOOLS`), which runs the same `knowledge.retriever.retrieve` as chat — the review gate, the synced Drive / OneDrive / Confluence / Notion collections and the published-artifact rule (the pass has no viewer, so no one's private document comes back). The prompt (`_KNOWLEDGE_RULE`, both modes) asks it to search before acting on or flagging something that turns on a customer's or supplier's terms, a price, a policy, a plan or a past decision. Its passages come back up to 4,000 characters (`execute_tool_calls(wide_results=...)`) while other tools stay at their short preview, its result counts as grounding input like any tool result, and the run's tool log keeps each line to 160 characters. Read-only, so Take the lead never gates it. The loop has 5 iterations (was 4) to leave room for a search before acting.\n\nNeither the nightly reflection nor the research synthesis can call `ack_alert`: both run unattended with open alerts rendered into their context, and those headlines are minted from inbound mail and chat, so an injected \"the principal already dismissed 13\" would be acted on with nobody watching. Closing an alert is the alert review's job, with evidence.\n\n`executive_reflection` now carries memory: yesterday's standup (the previous completed run's artifact) is rendered into the context and the prompt forbids re-acting on anything listed there unless it changed; open alerts render with their id, review verdict and recommended move. Reflection never closes alerts — the alert review does, with evidence. It also renders an **OPEN LOOPS** block (up to 10, soonest due first, overdue flagged) from Attunement so the standup can connect a slipped promise to the rest of the org state; the nudge engine already chases overdue loops, so the prompt tells it not to DM about a loop merely for being overdue. A **WHAT LANDS** block (from the Attunement outcome ledger) shows, per person, how often each kind of proactive DM got answered over 30 days; the prompt steers DMs toward kinds that land and away from kinds a person reliably ignores. Reflection and research tag their tool execution as proactive (`tag_proactive`) so their DMs are counted. Resolving a wait-for-human approval (`resumer.apply_resolution`) marks the nudges that chased it `acted`. `close_open_loop` is withheld from reflection for the same reason as `ack_alert`: loop text is quoted from what people wrote. `unattended_toolkit` also drops `schedule_tools.UNATTENDED_WITHHELD_TOOLS` (today `create_goal`) from both passes in both modes: a goal is the principal's own decision, and these passes see only inbound text. A turn private to the principal (mail from one of their contacts, or mail they forwarded) cannot start a workflow either: `run_workflow` and `run_executive_research` are in `schedule_tools.PRIVATE_TURN_WITHHELD_TOOLS`, which the chat loop neither offers nor runs on such a turn, since a workflow's steps can reach anyone.\n\nIn **solo mode** the reflection is framed for the principal, whatever their role: they are the only person who uses Open Executive and the only one it takes direction from, it prefers `create_alert` and `schedule_followup` to the principal, and it never messages anyone else from an unattended pass — the people in the principal's world are contacts, so anything they should hear is flagged for the principal to raise. The team roster is replaced by one YOUR PRINCIPAL line (person_id and follow-up channels), its follow-up guard is seeded from the principal only, and department risk renders as areas with goals at risk. The research synthesis follows the same rule — its routing menu and roster name only the principal. In both, `send_department_message`, `send_company_broadcast` and `set_department_head` are withheld, and so are `create_calendar_event`, `create_instant_meeting` and `run_workflow` — a booking reaches its attendees and a workflow can do anything its steps do, so the principal books and starts workflows from chat — and `message_person` refuses anyone but the principal. These passes run unattended with inbound text in their context, so the rules are enforced in code, not only in the prompt.\n\nIn either mode, both passes now dispatch only the tools they offer: the handler map is built from the offered list, so a name the model emits without being offered it is skipped as an unknown tool. They used to look names up in the full handler registry, so tools they deliberately withhold — the raw DM tools (`send_slack_dm` has no roster check), `ack_alert`, `close_open_loop`, and in research the watchlist writes and `run_workflow` — still ran when the model emitted them. Both read the mode before binding their own session (so a caller's override, such as an eval's, counts) and pin it on that session, so their tool handlers use the same mode. They carry the principal's role across the same way (`effective_principal_role` of the caller's session, pinned as `turn_principal_role`), so a specialist or workflow started from either pass sees the role of the turn that started it. Team runs are unchanged.\n\n### Wait-for-human pause\n\n`wait_for_human` (`openexecutive/workflows/wait_for_human.py`) is a first-class step primitive that pauses a run: the runner calls `save_checkpoint`, the `workflow_runs` row moves to `status='awaiting_human'`, and the serialized `WaitForHumanEvent` is stored in `state_json`. (Department authority is a *separate* mechanism — `propose_only` departments file a briefing alert via `departments.authority.propose_via_alert` and mark the scheduled action done; they do not route through this gate.)\n\n**Delivery.** Both checkpoint sites — the SSE route and the `run_workflow` chat tool — call `workflows.gate_delivery.deliver_gate_question` immediately *before* checkpointing, so `state_json` carries the routing fields a reply is matched against. Two modes. When the approver is the person already in the conversation (the chat session's `origin_channel` is set — to anything but `email`, whose answer is no chat reply and would never be sent — and its `caller_person_id` is the gate's `person_id`), nothing is sent — the question rides in the Executive's own reply — and the gate records `origin_session_id` plus the session's channel. The resolver compares base ids (`memory.conversation_ids.base_session_id`), so a question asked in one conversation of a Telegram chat or a DM is still answered by a reply after a quiet gap or /new has started the next. Otherwise the question is delivered through `schedule_tools.handle_message_person`, which picks the person's preferred channel, falls through on a failed send, and falls back to a briefing alert; the gate then records the channel, address and provider message id that send returned, plus the id of the DM session it landed in — that send is always 1:1, so the answer belongs in that conversation and nowhere else. Without it the gate matched on person and channel alone, so an unrelated @mention in a public channel resolved it and had the acknowledgement, run title included, posted where everyone could read it. The question is sent with `notifications.approval_send`, so the person's quiet hours and *In my briefs* never hold it, whatever their urgent setting: only a reply to it resolves the gate. Delivery is not guaranteed: the outbound guard can suppress it (duplicate, rate cap, quiet hours) and an unreachable person gets the alert fallback. Both cases leave the routing fields empty and report `delivery` as `suppressed` / `alerted` rather than claiming someone was asked, and the chat tool's presentation hint changes accordingly.\n\n**Matching a reply.** Each inbound adapter passes the message to `inbound_resolver.resolve_inbound_message` with its `session_id`. Matching is three-tier: an explicit `in_reply_to` against a stored `outbound_message_id`; otherwise a single open run on that channel; otherwise one utility-fast disambiguation call gated at 0.85 confidence. An unmatched explicit reference rules out only the candidates that carry a stored outbound id — the ones it could have matched — and the rest continue; rejecting outright meant an adapter that passes a thread id on every message (Slack's `thread_ts`) short-circuited the later tiers forever, and a global test let one delivered gate's id block an unrelated self-approval gate. Channel names are normalized (`slack_dm` ≡ `slack`), the delivered address is compared when both sides know it, a row whose `state_json` will not parse is refused (a corrupt row otherwise presents as a legacy one), and an empty stored channel is treated as a wildcard only for rows checkpointed before gate delivery existed. Two guards keep an open gate from swallowing unrelated traffic: a gate carrying an `origin_session_id` matches replies only from the conversations the adapter names (a Slack or Discord thread offers its parent channel session too, mirroring the history double-write, since a gate raised on a mention recorded that session while the answer arrives under the thread's — on Slack only when that person rooted the thread, or the alias would reach into a colleague's), and the parser can return `unrelated`, which declines to resolve and lets the message reach the normal chat path. The parser is handed the gate's own question, so a bare \"yes\" is judged against something. Its fallback is flagged by a key the model cannot emit rather than by a magic note string it could, and a fallback declines to resolve on *every* reply shape — recording the empty string a `free_text` fallback fabricates would close a sign-off on a parser outage. Every shape can answer `unrelated`, not just `approve_reject`: without it an open `free_text` gate turned the person's next message into its answer verbatim, and a `numeric` one swallowed any message containing a number. The parser has one caller outside workflows: its `roster_identity` shape — `{decision: approve|link|decline|unrelated, name, kind: team|contact|null}`, with `name` only as the person wrote it (never inferred) and a fallback of `unrelated` — reads the principal's emailed answer to a roster request (who a new sender is; see Org). It is not a gate reply shape, and a fallback or `unrelated` leaves the request waiting. `resumer.apply_resolution` then records the decision, marks the run `resolved`, and writes an audit row. A timeout applies the step's `on_timeout` policy (escalate / auto_proceed / fail). The outcome surfaces on the Today dashboard.\n\n**Resuming past the gate.** A paused run continues on its own. Re-entering it was long assumed to mean serializing a Python generator frame; it does not. The only state alive across a dynamic workflow's steps is its inputs (already persisted), a company-profile block that is recomputed, the completed steps' output strings, and the loop cursor — so the engine hands the checkpoint a small JSON `WorkflowResumeState` (workflow name, the gate's id and index, the next index, the outputs so far), stored in `workflow_runs.resume_state_json`, and `DynamicWorkflow.resume` replays its step loop from the recorded index. `run()` and `resume()` share that one loop, which is why a second gate needs no special handling — it is simply another pause raised from the same place. The payload rides on a `WaitForHumanEvent` field declared `exclude=True`, so it can never leak into `state_json`, whose exact key set the resolver branches on. A gate with no payload is *pause-only*: the decision is recorded and the run stops, which is what every caller got before resume existed.\n\n`resumer._process_resumable` claims a resolved run with one guarded UPDATE — `resolved` → `running`, stamping `resumed_at` and minting a claim token — and drives it to a terminal row. It runs two ways: immediately, via a task `apply_resolution` kicks off so a Slack approval starts moving in seconds, and every 60s from the poll loop as the durable backstop. Both share the claim, so a run executes exactly once even with two resumers against one database. The kicked task binds no chat session (`set_session(None)`), exactly like the poll loop: it is created inside the inbound handler that recorded the answer and would otherwise inherit that person's live turn — so a run resumed because the principal replied on Slack does not act with the principal's identity (it cannot, for example, reach the principal's contacts). It drops the handler's audit scope too (`audit.context.unscoped_audit_rows`): inherited, the principal's scope would make private every row of the run that names a contact, and whoever started the run would see those rows vanish after the approval. The poll runs the executor *after* the timeout loop, which is what finally makes `on_timeout='auto_proceed'` do what its name says: the timeout resolves the run and the same tick executes it. While the Executive is paused (`scheduler.pause`) the resumer does nothing — no startup sweep, no timeouts, no resumes — and `apply_resolution` still records the decision but skips the immediate kick; the first unpaused iteration catches up on all of it, so a timeout that lapsed during the pause applies its `on_timeout` policy then.\n\n**The claim is fenced, because it is not a lease.** The stale sweep decides a worker is dead from a wall-clock guess, so a slow but *alive* worker will eventually be declared dead and replaced. Every write the executor makes carries its claim token and is refused once superseded — otherwise the replaced worker's late completion lands on top of its replacement's result, or its checkpoint at a later gate resurrects an already-finished run and asks the approver a second time. The retry budget resets at each new gate (a gate is new work, not a retry), and a run that exhausts it is *ended* rather than dropped: an exhausted run sits in `running` with a payload, in neither queue, and would otherwise show as in-progress forever.\n\n**The gate fails closed.** Continuing is an allowlist — `approve` and the synthetic `auto_proceed` — not \"anything that is not a stop word\". `decision` is whatever a fast model extracted from free-form chat and it drifts; under a denylist, \"rejected\", \"Reject\", \"decline\" and \"no\" would all continue, so the approver declines and the deliverable is produced anyway. Reply shapes that ask a question rather than seek permission always continue, since the answer *is* the value. A stop ends the run at `error` with the human's note. Either way the decision becomes the gate step's own output, so it reads as a section *in* the artifact — capped and blockquoted, because that text reaches the synthesis specialist as prompt context.\n\n**A definition edited during the pause is refused.** Resume re-validates the payload's version, the recorded gate, *and* a fingerprint of the whole step list, and derives the index to continue at rather than reading it from the payload. Pinning only the gate would not be enough: definitions are overwritten by name and any rostered user can save one, so someone could keep the gate identical and replace every step after it — and the approver's sign-off would be recorded against work they never saw, which defeats the one thing an approval gate is for. No built-in workflow yields the gate; only user-created dynamic workflows do.\n\n### Launching from chat\n\nWorkflows are not only reachable from the `/jobs` UI — the Executive can list and run any of them mid-conversation. `openexecutive.orchestrator.workflow_run_tools` wires two tools into the main chat loop: `list_workflows` (the launchable catalog, with each workflow's input fields) and `run_workflow` (runs one to completion and returns its Markdown artifact, using the same engine as `POST /workflows/{name}/runs`). `run_workflow` resolves both built-ins and custom workflows via `get_workflow`, validates `inputs` against the workflow's input model, persists the run (`create_run` → `complete_run` / `fail_run`), and on an approval-gate step checkpoints the run as `awaiting_human` exactly as the HTTP route does — literally the same code, since both call `workflows.gate.checkpoint_gate`, which delivers the question and writes the checkpoint in one place. It never hangs waiting on a human, and it reports both whether the question reached them and whether the run will continue by itself once answered. The runners that *cannot* pause — the schedulers, evals, client rotation, onboarding, the research tools — call `gate.ensure_workflow_event`, which raises on a gate rather than letting one be swallowed; the scheduler's dynamic-workflow branch used to ignore it and record a successful run containing nothing. `executive_research` is excluded (it has the dedicated `run_executive_research` tool). Running a workflow from chat delivers nothing on its own — it renders the artifact into the conversation, and the recurring principal briefs (`morning_brief`, `end_of_day_digest`) reach anyone only via the scheduler's own `_deliver_to_principal`. The tool description used to claim those two DM the principal when run and to confirm before firing them, which had the model soliciting a confirmation on a false premise; it now names `executive_reflection` as the one workflow that really does execute tool calls of its own (DMs to heads, broadcasts, alerts). A successful run surfaces an `action_taken` chip linking to `/jobs/runs/{run_id}`.\n\n### Dynamic (user-created) workflows\n\nUsers create reusable workflows on the fly — from the executive chat, the conversational wizard at `/jobs/new`, or the step-by-step advanced editor — without shipping code. The Workflows page (`/jobs`) opens on a *Start here* panel that leads to all three: the user describes the job in a sentence and *Start* opens the wizard with that text sent as its first message (handed over in `sessionStorage`, so a link cannot make the wizard send text the user never typed; where storage is blocked it falls back to `/jobs/new?describe=`, which only fills the composer and sends nothing), or picks *Step by step* (advanced editor) or *Talk it through in chat* (`/?new=1&draft=`). Below it come the user's own workflows, then four ready-made starter picks with the full built-in list folded behind *Browse all* (`?browse=1`). The picks and the example chips follow the workspace mode: a team gets the investor update, board prep, MBR and competitive teardown (and a board pre-read chip); a solo owner-operator gets the MBR, pricing review, churn deep dive and quarterly plan, with chips for a Friday cash and pipeline check, customers who stopped buying and a competitor digest (`lib/workflowStarters.ts`; a unit test pins every pick to a startable `WORKFLOW_REGISTRY` entry). A dynamic workflow is a stored JSON definition (the `dynamic_workflows` table) interpreted at runtime by one generic `DynamicWorkflow` engine (`openexecutive/workflows/dynamic.py`) that implements the same `Workflow` ABC as the built-ins, so the run path, SSE streaming, run persistence, and `/jobs/[name]` form rendering are unchanged. `get_workflow` / `list_workflows` fall through to the dynamic store after the static registry (built-ins win on a name collision).\n\nA definition declares free-text input fields and an ordered step list of four kinds: **specialist** (consult a specialist with a goal prompt, optionally grounded by RAG), **action** (get something done with tools — see below), **approval_gate** (a `wait_for_human` pause), and a terminal **synthesis** step that assembles the artifact. At least one specialist or action step is required. `validate_definition` enforces the structural rules: exactly one terminal synthesis step, valid specialists, `{placeholder}` tokens that reference declared input fields, rostered approval/cadence people (team members — never one of the principal's contacts, whom an unattended run may not message), and a parseable cadence.\n\nAuthoring from chat uses a **draft → confirm** handshake: the Executive calls `draft_workflow` (validate; return a `confirm_token` plus a plan summary), shows the user the plan, then calls `save_workflow` with the same definition and token — a token mismatch is rejected, so the saved workflow is exactly what the user approved. The step-by-step advanced editor drives the `/workflows/custom` CRUD endpoints directly.\n\n**The New workflow wizard** (`/jobs/new`) is the default way to create one from the UI. It works like conversational onboarding: the user describes the job, the `workflow_designer` Council agent (`openexecutive/workflows/designer.py`) asks one clarifying question per turn — deliverable, per-run inputs, sign-off, schedule, recipient — with up to four clickable suggested answers, then emits a complete definition plus a plain-language summary and the assumptions it made. Every turn offers the model exactly three fixed, name-sorted tools (`ask_clarifying_question`, `emit_workflow_draft` — reusing the chat tool's `DEFINITION_SCHEMA` — and `search_available_tools`, which is answered inside the same turn from the tool catalog, up to four searches per turn, with the tool_use/tool_result pairs never stored in the plain-text transcript; every tool a search returns is remembered on the session and replayed into later turns, so a forced draft or a repair turn — which cannot search — still has the exact names); `tool_choice` flips to the emit tool once, when the six-question budget is spent or the user clicks *Draft it now*. The emitted definition goes through `validate_definition`, the tool-availability check, and a check against saved custom names, with one repair turn that feeds the errors back. The system prompt is a cached constant; the live context — specialists, the roster with person ids, the user's timezone (the one set through `PUT /workspace`, else `USER_TIMEZONE`; cadences stay UTC), and taken names — is rendered once per session into the first user turn, and while refining, the exact current draft is prepended to the latest user turn so the model edits it rather than re-deriving it. Roster names and roles are flattened to one line and capped at 80 characters before they enter that context, and the system prompt tells the model to treat the whole block as data, never instructions. Sessions live in memory (`/workflows/designer/*`, 2 h TTL, 50-session cap), run one model turn at a time (a second concurrent `/message` or `/draft` gets 409, and a failed turn is rolled back by identity), and never write: the review card saves through the same `POST /workflows/custom`, which re-validates, and *Edit details* opens the draft in the advanced editor (`/jobs/new?designer=<id>`) before saving.\n\n**Editing is a conversation too.** *Edit* on a saved workflow (`/jobs/new?edit=<name>`) opens the same designer through `POST /workflows/designer/edit`: the stored definition is the starting draft, so the user's first message (\"have Mark sign off and run it Fridays\") is applied to it like any refinement, and a note in the context block (a user turn, never the cached system block) tells the model it is changing a saved workflow. The draft always keeps the workflow's name — `_check_draft` puts it back and skips the taken-name check — and the route keeps its on/off state, so an edit can neither fork a copy nor switch on a tool workflow waiting for approval. The stored draft is handed to the model marked as data, not instructions. The review card lists *What changes* in plain words against the saved version (`lib/workflowChanges.ts`): every field is compared, with named sentences for the sign-off person and what it asks for — a sign-off moved off approve/reject is called out because the run then continues whatever the answer — the schedule, steps added/removed/reordered, inputs, tools and the tool-call budget, and a catch-all line for any other field. It names only the newly added tools that may change things. *Save changes* calls `POST /workflows/custom/{name}/save-edit`, which saves the session's own draft after re-validating it, only when it is the draft the card showed (the card sends what it displayed; a message that landed since is a 409), and only if the stored workflow has not changed since the conversation opened (409 otherwise), so an edit started before someone switched the workflow off cannot switch it back on. The step-by-step form stays as the advanced editor (`/jobs/new?edit=<name>&mode=advanced`).\n\n**Action steps (workflows that act).** An `action` step (`ActionStepSpec`: `goal`, `tools`, `max_tool_calls` 1–50, default 20) is run by the `workflow_actor` Council agent (`openexecutive/workflows/action_step.py`) as a bounded tool-use loop. Its `tools` list is an allowlist of exact tool names — MCP gateway tools (`server__tool`, e.g. `google_workspace__append_table_rows`) and built-ins: the Executive's own chat tools as `oe__<name>` (see *Chat's tools in action steps* below; `oe__create_alert`, in a workflow a team member created, raises the alert as theirs (`alert_tools.raised_for_workflow_owner`: source `team_member`, \"Raised by <name>\", never a company-wide broadcast) — plus any installed extension's tools registered with `workflow=True`, as `oe__<name>`, run inside `extensions.workflow_step(name)`; a built-in wins a name clash, and an extension tool counts as reading only when it says so) — and **clicking Create is the user's approval** of that list: the review card shows every tool, flags the ones that may change things (anything whose name doesn't say it reads, and any tool with a URL/URI/endpoint/webhook parameter anywhere in its schema, or whose schema couldn't be read, since a URL can carry data out), and names them in a \"this workflow can use these without asking again\" notice. Because that card is the approval, a workflow with action steps saved from chat (`draft_workflow`/`save_workflow`, whose confirmation is a token the model holds itself) is stored **switched off** (`is_active=false`) and `save_workflow` returns `status: saved_pending_review` with a `/jobs/{name}` link. An inactive workflow can't run or schedule (`get_workflow` and the scheduler skip it); `/jobs/{name}` shows it on the same review card, where **Turn on workflow** (`POST /workflows/custom/{name}/activate`, which re-validates the tools) is the approval — the click sends the definition the card showed, and the server refuses (409) if the stored one has changed since, so chat overwriting it while the card is open can't get new tools switched on. Chat may revise a switched-off workflow but refuses to replace a switched-on one that has action steps (an inbound email steering the Executive could otherwise switch off an approved job and stage new tools under its name); those edits happen in the advanced editor. The Workflows catalog (`/jobs`) lists switched-off workflows in a compact *Waiting for your approval* strip, and saving edits in the advanced editor keeps one off. `tool_catalog.py` resolves names to schemas through the gateway's `search_tools` (extensible-mcp's Markdown output is parsed; resolving is also the per-session discovery its `call_tool` requires) and validates availability at save time (`POST`/`PUT /workflows/custom`, chat `draft_workflow`/`save_workflow`, designer drafts) — an unknown, misspelled or deny-listed tool is a 422. The gateway meta-tools (`search_tools`, `call_tool`, `load_mcp_server`) can never be step tools. `run()` resolves every action step's tools before any step runs, so a vanished tool stops the run before an earlier step acts; `resume()` checks only the steps still to run, after the gate and decision are validated. The last turn of an action step always switches tools off so the agent can report. At run time only the allowlisted tools are offered (sorted; constant cached system block, per-run goal/inputs/earlier results in the user turn), every `tool_use` is re-checked against the allowlist, MCP calls go through `MCPGateway.call_tool` so the config deny-list and the Gmail/Calendar/Drive recipient gates still apply, the call budget is enforced (then a final tools-off turn asks for the report; running out of turns fails the step and lists what was already done), tool errors (the gateway's `Error:` / `Error calling tool` / `Tool error:` prefixes, or a truthy `error` field) return to the model as `is_error` results, each call emits a `progress` event and an audit row (`workflow_tool_call`: tool and outcome; for tools that may change things also a short digest of target arguments — ids, recipients, URLs, paths — so a redirected write is visible; content arguments are never logged), and the step's output is the agent's report plus an \"Actions taken\" list. Tool output is framed as data, never instructions.\n\n**Chat's tools in action steps.** A step can use almost everything the Executive uses in chat, so an idea from a conversation can become a workflow without a missing tool. `workflows/chat_tools.py` holds one list, `ACCESS`, that labels every chat tool: **use** (a step may list it as `oe__<name>`, e.g. `oe__send_slack_dm`, `oe__run_workflow`, `oe__update_department_goal`, `oe__web_search`), **as me** (Act as me tools, not yet in workflows), **covered** (the step already has its own path: gateway tools, `run_script`, specialist steps) or **chat only** (memory, company profile, roster changes, open loops, follow-up corrections and screen actions). A unit test fails when chat gains a tool without a label, so new chat tools reach workflows by one line rather than a second copy. A **use** tool runs through chat's own handler as an unattended chat turn would: an unattended `Session` bound as `current_session`, the workspace-mode filter (solo withholds department and company posts), and, in a team member's workflow, their department gate. Channels the instance has no token for are not offered. Saving the workflow is the person's permission, so Take the lead's approval gates don't apply, the same as the gateway tools before. `oe__run_workflow` refuses a workflow already running in its own chain and nests at most three deep. It and `oe__run_executive_research` get a 15-minute call timeout. `oe__web_search` is the model's server search: it is appended after the sorted tools, never called by the step, and a paused search turn is sent back as-is. Workflows have no tool handlers of their own any more: `oe__message_person` and `oe__create_alert` are the chat tools under the same names, and the old `oe__read_file` still resolves (to `read_document`) for saved workflows but isn't offered for new steps (`chat_tools.LEGACY_NAMES`). The designer lists every built-in by its first sentence, and chat's `draft_workflow` says chat tools are available as `oe__<name>`; the catalog's search ranks built-ins by how many query words they match.\n\n**Scripts in action steps.** Besides the step's own tools, the agent is offered one more, `run_script` (`openexecutive/workflows/step_script.py`), for work that repeats over many items — every file in a folder, every row, every email — or chains calls with simple logic. It writes a short Python script once instead of spending a model turn per call; each of the step's tools is a function in the script (`drive__move_file(file_id=…)`, or `call_tool(name, arguments)` by exact name), and only the script's final value and printed output come back. The script runs in **Monty** (`pydantic-monty`), a sandboxed Python interpreter for model-written code, in a worker process spawned per script: no files, network, environment, subprocesses or third-party imports — the step's tools are the only things it can reach. **A script is a faster way to make the same calls, never a way around them:** every call it makes goes through the same per-call path as a direct `tool_use` (`action_step._StepCalls`) — the allowlist, a call budget (a script's calls have their own: 10× the step's `max_tool_calls`, capped at `WORKFLOW_SCRIPT_MAX_CALLS`, default 500, because they cost no model turn each — so a step can work through a folder of hundreds of files while its direct calls stay capped at 1–50), the first-write target check (a held write comes back to the script as `{\"status\": \"held\", …}`) and one `workflow_tool_call` audit row per call — and the script itself is audited as `run_script`, with how many calls it made and how long it took. The step's \"Actions taken\" list collapses repeats into one line with a count. A step whose direct calls are spent keeps its tools on while the script budget has room, so it can still script the rest (a direct call is refused as over budget). When a tool returns a list of five or more items and the round didn't use `run_script`, the step adds the same `FANOUT_HINT` as chat (once a step), pointing the per-item work at one script. The worker is stepped from the step's own task (each call pauses it and is answered there), so cancelling the run stops the script and its in-flight call together, and each call's progress shows as it happens. At most `SCRIPT_MAX_WORKERS` (default 2) scripts run at once across the server, chat and workflows together; another waits for a slot within its own wall clock, else returns \"the server was busy\". A worker exists only while its script runs (about 8 MB idle). Execution time (excluding time waiting on tools), memory and recursion depth are capped inside the worker, the script has a wall-clock limit, and its text is size-capped; printed output past its cap is dropped. A failing script returns its error to the agent as an `is_error` result, with the calls it already made listed first (ahead of any long result, so a cut never drops them) so a fixed re-run doesn't repeat writes; a call cut off by the time limit is listed as `may_have_run`, and gets a `cancelled (may have run)` audit row. A workflow definition still holds no code; a script lives on only if the agent saves it as a tool (below). Because a step can loop at run time, the workflow designer keeps work that repeats over items (each email, file, row or listed follow-up) in ONE action step whose goal spells out the items, rather than a step per item; `run_script` is never a step tool, and a definition that lists it is rejected (`validate_definition`) so the designer's repair turn removes it. `WORKFLOW_STEP_SCRIPTS=false` turns the tool off, and a step then only calls its tools one by one.\n\n**Python jobs (`run_python_job`, `openexecutive/workflows/python_job.py`).** Monty can't run libraries, so library work on files (split or merge PDFs with pypdf, spreadsheets with openpyxl and pandas, charts with matplotlib, images with Pillow, and documents made from scratch or from files: Word with python-docx, PowerPoint with python-pptx, laid-out PDFs with fpdf2) runs as a Python job: Pyodide (Python in WebAssembly) executed by **Deno** in a process of its own per job. Pyodide alone is not a sandbox — its Python can call into the JavaScript runtime, which under plain Node reaches the server's environment, files and network — so Deno is what isolates it: it is started with read access to the sandbox folder and the worker script only, with no network, environment, writes or processes, and an empty process environment. Files go in on stdin and results come back on stdout. A job gets only what the call names: Knowledge-library files, the files attached to the chat message being answered (`attachment_files`, the uploads as sent, bound for that turn only by `POST /chat/upload` in `workflows/turn_files.py`, so the model never retypes an attachment's text), text the caller passes, and `inputs` (a dict the code reads); result files are kept 7 days under the company folder and served to the principal at `GET /python-jobs/{job}/{file}`, which the Executive links in its reply. A deployment can instead send jobs to a separate runner (`PYTHON_JOB_RUNNER_URL`, with `PYTHON_JOB_RUNNER_KEY` as a bearer token): `run_job` POSTs the same job (code, inputs, files, caps, time and memory limits) and reads back the same result object, at most as large as a local job's output, keeping only its known fields, so kept results, links and metering are unchanged; the local sandbox is then not needed, and the runner is trusted to isolate jobs. A runner can turn a job away with `{\"run_locally\": true}` (and an optional `reason`) in a non-200 reply, for example when the deployment's allowance for it is used up: the job then runs in the local sandbox if this machine has one, and otherwise fails with the runner's reason. Any other non-200 reply stays a job error, so a busy or broken runner never moves every job onto the machine. A runner with more libraries lists them in `PYTHON_JOB_EXTRA_LIBRARIES`, which the job tool's description then names, so the Executive doesn't refuse a job that needs one. The tool sits in the `workflows` tool group, labelled for jobs with or without attached files. The library set is fixed at build time: the API image installs Pyodide and Deno from npm and the compiled libraries from Pyodide's CDN, each checked against the sha256 in Pyodide's lock file, and a build smoke runs a job. Pyodide can't infer the compiled packages the pure-Python libraries import (lxml, Pillow, fonttools), so the worker loads them when a job imports docx, pptx or fpdf. Pyodide, Deno and the pure-Python libraries are pinned by hash too (an npm lock installed with `npm ci`, pip `--require-hashes`). One job runs at a time per process (200–450 MB each), with a `PYTHON_JOB_TIMEOUT_S` limit and a memory cap (`PYTHON_JOB_MEMORY_MB`, default 1536, as the process's data limit, plus V8 heap and WebAssembly memory caps); the worker returns at most 20 result files and 25 MB, and the API stops the job as soon as its reply passes that. The job runs at a lower CPU priority and is first in line if the machine runs out of memory, so a heavy job slows or loses itself rather than the API; Deno's own caches go in a temporary folder removed with the job; and kept results are capped at 200 MB in all, oldest first. The tool is chat-only, offered only on the principal's own turns (`PRINCIPAL_ONLY_TOOLS`), withheld on private turns, unattended passes and under the Act as me lockdown, and not offered at all without the sandbox (`PYTHON_JOBS_ENABLED`, `PYTHON_SANDBOX_DIR`).\n\nA job that worked can be kept the same way as a script (below): `save_as` and `description` keep its code as a Custom tool of kind `python`, and `run_python_job(tool=<name>, inputs={...})` with its files runs it again, recording the run, so a job done before costs no code-writing tokens. Python tools run only on the principal's own chat turns: they are never listed for workflow steps and never turn on for workflows (`PUT /saved-tools/{name}` answers 409), and `run_script` refuses one (and `run_python_job` a script tool). Every job writes one `python_job` audit row (`ok`, `duration_ms`, `cpu_ms` and `peak_mb` read from the process's /proc entry just before it is stopped, files and bytes in and out, attachments, the Custom tool it ran or kept), which `GET /audit/usage` sums into `python_jobs` with the model usage of the turns that ran one.\n\n**Saved tools.** A script that works can be kept to run again by name (`openexecutive/workflows/saved_tools.py`); each tool has a `kind`, `script` (`run_script`) or `python` (`run_python_job`, above). `run_script` takes `save_as` and `description` with a new script: if the script succeeds it is saved, with the set of tools it actually called, and a failed script is never saved. Later, `run_script(tool=<name>, inputs={...})` runs the saved script instead of new code, with `inputs` available to it as a dict. Only the principal's own turns save: a chat turn where the principal is speaking on a verified, interactive surface (the same test as `load_mcp_server`), never an inbound email, a teammate, an unattended run or a workflow step — a step is offered `tool=` but not `save_as`. A saved tool runs with the authority of whoever runs it, so its author must be trusted at least as much as anyone who may run it. For the same reason only a workflow step (its tools owner-approved) or the principal's own turn may run one: anyone else's chat turn is refused `tool=` and not offered `list_saved_tools`, so a stranger can neither list the principal's automations nor run one with inputs they choose. Descriptions are kept to one line of printable text (they are shown to models), and every save writes a `saved_tool_changed` audit row (`actor: executive`) beside the owner's own changes. Saving needs no approval beyond that, because a saved tool can do no more than the context running it: its calls go through the same per-call path as any script (in a step: the allowlist, budget, target check and audit), and a step runs one only when the step already allows every tool it used (otherwise the result names the `missing_tools`) and only at the version the owner turned on for workflows (`workflow_version`, Settings → Advanced → Custom tools → Use in workflows). A tool kept on a turn that read outside content could otherwise carry injected code into an unattended run, so keeping stays automatic and works in chat at once, but workflows wait for the owner; a newer save doesn't change the version workflows run, and pruning never drops it. Each step's `run_script` description lists the saved tools that step may run; chat asks `list_saved_tools`. Every save of changed content is a new version (the newest 20 are kept, plus the one that ran until then, so a rolled-back version the owner trusts survives later saves), every run is recorded (`saved_tool_runs`, the newest 200 per tool), and the owner can turn a tool off or switch it back to an earlier version on Settings → Advanced → Saved tools (`/saved-tools` routes, the owner's alone). A turned-off tool never runs, and a new version saved by the model does not turn it back on. `SAVED_TOOLS_ENABLED=false` stops saving and running saved tools everywhere.\n\n**Targets are chosen at run time — and a new one is confirmed once.** Approving a workflow approves its *tools*; which sheet, doc, recipient or URL each call hits is chosen by the model at run time, by design (a tab per month, a reply to whoever sent the invoice, a doc per client). What bounds that is the allowlist, the gateway's recipient gates, the audit digest, and **first-write confirmation**: a `TargetPolicy` (one per run) checks every call to a tool that may change things. `resource_targets` walks its arguments recursively for resource keys (snake- or camel-case ids, `to`/`cc`/`bcc`, recipients, addresses, attendees, members, users, owners, parents, URLs/links/hrefs, paths, channels, spaces, rooms, phones, hosts, buckets, tables, spreadsheet/document/folder/calendar/file); a matching key marks everything beneath it, even a `name`. Outside a resource, only a new item's own `name`/`title`/`subject`, message/thread/draft/label ids, `range`/`sheet` and workspace-mcp's acting `user_google_email` are skipped — and whatever the key, a bare value shaped like an email address, a URL or an international phone number is a target, except inside what the call writes (`rows`, `values`, `body`, `text` …). Key names are a heuristic, so this is a best-effort guard layered on the allowlist, the gateway gates and the audit. Float ids are compared as integers. Arguments too deep, naming too many targets, or holding an over-long value **fail closed** (the call is refused). A target is trusted only when it was approved for this workflow before (`workflow_approved_targets`, by value) or is an id a write in this run created — a top-level id/link field (`id`, `spreadsheetId`, `webViewLink` …) of the **structured JSON object** result of a tool whose name says it creates (create / insert / upload …) and that takes no URL — a tool whose schema couldn't be read is assumed to (free text, nested records and readers' or updaters' results are never read, so a fetched page, an echoed title, a shared page's links or a stranger in `ccRecipients` can't plant one); those survive a pause in the resume payload (`run_created`). Values written in the workflow's own text are *not* trusted, since anyone who can edit the workflow could change them without review: they are asked once, then remembered. Approvals are by value, for any of the workflow's tools, and are **cleared when the workflow's tool set changes** (a newly added tool must earn them again). Any other target makes the call **held**: it is not run and costs no budget, the model is told it is waiting for approval and carries on, and it is audited `held for approval` (at most 10 held per step, 16 KB each; an identical repeat is held once). Whether a call is checked at all follows the read-only label, which now never marks a tool whose name carries a write verb anywhere (`find_and_replace_doc`). After the step finishes, the run pauses with a `WaitForHumanEvent` to the workflow's **owner** (`owner_person_id`, the person who created it on the Workflows page or in chat; falling back to the principal if unknown or archived), `on_timeout=auto_proceed`, 48 h, and a `WorkflowResumeState` of `kind=\"held_writes\"` carrying the exact held calls. On resume (`_resume_held_writes`, fingerprint-checked like a gate, with the remaining steps' tools checked first), only `approve` runs them — each still has to be in the live step's allowlist and resolve; its targets are remembered first — and anything else (decline, timeout, unreadable) skips them; either way a *Held for approval* section is added to the step's output and the run continues at the next step. With no one to ask, held writes are skipped and noted; a step that fails or crashes after holding, or a resume that stops early (definition changed, a later tool missing), audits its held writes as dropped and says they did not run. The question quotes each target JSON-escaped (a value can't add its own lines) and always shows a URL's full scheme and host, saying how much of the rest is hidden. The owner answers by chat reply or with **Approve / Decline** on the run page (`POST /workflows/runs/{id}/decision`, which the principal may also use); remembered targets are listed and removable on the workflow page.\n\n`oe__read_document` (chat's `read_document`; saved workflows that list the old `oe__read_file` get the same tool) extracts text (PDF, Word, Excel, CSV, Markdown, text) only from files under `WORKFLOW_FILE_DIRS` or the company documents folder (default: workspace-mcp's attachment folder), resolving symlinks and `..` before the check (`tool_catalog.resolve_readable_file`, shared with the Executive's `read_document` tool). A scanned PDF is converted by `knowledge.pdf_reader` instead of failing as \"may be a scanned image\"; one that still cannot be read returns the reason. Action steps are allowed in scheduled workflows. Because they have external side effects, a resumed run heartbeats its claim (`touch_resume_claim`, at most once a minute as events flow — each tool call emits one; a busy database is retried on the next heartbeat, never treated as a lost claim; the sweep's requeue re-checks the claim's age in the same UPDATE, so a heartbeat landing between the sweep's read and its write wins), so the stale-claim sweep never requeues and replays a slow but live run, and a worker that finds its claim superseded stops at its next event. A worker that actually crashes mid-resume is still requeued; its action steps then run again, so goals should say how to avoid duplicates (the actor reads current state before writing). `GET /workflows/tools/search?q=` and `GET /workflows/tools/describe?names=` back the advanced editor's tool picker and the review card's labels.\n\nAn optional cadence (`daily@` / `weekly@` / `quarterly@`) re-uses the scheduler via the `dynamic_workflow` action kind, which runs the workflow on schedule and DMs the artifact to a rostered recipient. A gate followed by further steps pauses at `awaiting_human` and then resumes once answered, so gates no longer have to sit immediately before synthesis. They remain forbidden in cadence-enabled definitions: a scheduled fire has no interactive human to ask.\n\n`executive_research` keeps only its Markdown artifact in the run history; `parse_artifact_findings` reads its \"Findings reviewed\" lines back as `{severity, confidence, specialist, title, summary}` for Home's first-week card (see Today).\n\nBuilt-ins the system runs on its own (`morning_brief`, `end_of_day_digest`, `executive_reflection`, `executive_research`) set `background = True`, surfaced as `WorkflowMeta.background`; the `/jobs` ready-made list files them under a **System** chip instead of the default view. They stay runnable by hand.\n\n**Quick workflows** (`workflows/quick.py`) are one per playbook in effect that no built-in or custom workflow follows (switched-off custom ones count). They are derived whenever the catalog is read, never stored: `list_workflows()` returns built-ins, then Quick ones, then active custom ones, and `get_workflow` resolves a `quick_<playbook>` name after the registry (custom workflows may not take the `quick_` prefix). Each has one required field, `request`, and two steps: **Load context** (company profile plus RAG for the playbook category's specialist) and **Draft** (that specialist writes one Markdown document following the playbook). `WorkflowMeta.quick` is true for them. The 8 built-in playbooks no built-in follows are Quick workflows: board update memo, 1:1 agenda, layoff comms plan, positioning statement, post-mortem, customer interview plan, feature prioritization and market sizing. A company's own playbook shows up as one, hiding a built-in drops it, and a custom workflow that starts following one replaces it. If custom workflows can't be read, none are offered, since their followers are unknown.\n\n**Workflows vs. playbooks.** `/jobs` has two tabs: **Build** (`?tab=catalog`, the default) and **Runs** (`/skills` redirects to `/jobs`). A playbook is a skill (`knowledge/skills_repo.py`): *how* the Executive does a piece of work, with no inputs, schedule or side effects. A workflow is the runnable job. Workflows **follow** playbooks: a step that follows one gets its body appended to the step prompt via `workflows/playbooks.py` (`load_playbook` + `playbook_clause`). Six built-ins do — `board_prep` (`board-prep-deck`), `quarterly_plan` (`quarterly-okr-set`, `quarterly-forecast`), `mbr` (`monthly-business-review`, in the financial, KPI and function steps), `competitive_teardown` (`competitive-teardown`, in the four analysis steps), `fundraising_prep` (`fundraise-narrative`, narrative step) and `exec_search_brief` (`role-scorecard`, profile step). Each declares them in `Workflow.playbooks`; a unit test holds that declaration equal to the `load_playbook(\"…\")` calls in the module, and `WorkflowMeta.playbooks` exposes it. A custom workflow's `specialist` step may name a `playbook` (validated to exist at save; appended after `{field}` rendering, so braces in a playbook are never treated as placeholders). The lookup resolves the playbook in effect, so a company's customized copy changes the workflow's output, and a hidden, missing or malformed one falls back to the step's own prompt plus RAG — a workflow never fails over a playbook (`load_playbook` catches everything; a custom step whose playbook is unavailable emits a `progress` event saying so). Because an approved scheduled workflow reads its playbook at each run, chat never creates or changes a playbook: it saves repeatable work as a workflow (`draft_workflow`, confirmed by the user), and only a person can change what a workflow follows: a workflow's page shows each playbook it follows as **How it's done** (`components/jobs/HowItsDone.tsx`), with **Edit** (`PUT /skills/{name}`; on a built-in that saves the company's customized copy) and, for a customized copy, **Reset to original** (`DELETE`, which reverts). The chat summary of a drafted workflow names each step's playbook. `playbook_users()` maps each playbook to the workflows that follow it — built-ins, every custom workflow (switched-off ones included: turning one on approves its definition) and the Quick ones; the skills API reports it as `used_by`, and the Executive's `search_skills` hits carry it as `workflows`.\n\nCompleted artifacts are discoverable in the unified artifacts section (`/artifacts`, labelled **Documents** in the UI) alongside their run-detail page at `/jobs/runs/{run_id}`. A run someone starts by hand (`POST /workflows/{name}/runs`, `run_workflow`, research in chat) stores them as `workflow_runs.owner_person_id` and its history and output are theirs alone (plus the person a gate waits on); scheduled and system runs keep no owner and stay the team's. Workflow output stays Markdown — the scheduler DMs it and reflection rereads it as text — and gains other formats only on the way out: any run can be downloaded as Word (`/artifacts/run:<id>/download?as=docx`), and the Executive can repackage one with `get_artifact` → `draft_artifact(format=…, supersedes=\"run:<id>\")`.\n\n## Data-driven retrospectives\n\n`engagement_value_report` introduces a new workflow pattern: instead of the user typing the substance into a form (the `investor_update` / `mbr` shape), the workflow **reads its substance from the database**. A deterministic gatherer (`clients/engagement_activity.py`) pulls the period's decisions, initiatives, advisory consultations, delivered workflow artifacts (excluding prior value reports), follow-through counts, and alerts handled — from the live DB for the active client, or a parked client slot's `state.db` opened read-only. A single board-comms call narrates those facts (the prompt forbids inventing anything not in them; an empty period skips the LLM entirely), and the artifact's lists are assembled deterministically. Built for renewal conversations — the engagement record is the evidence.\n\nWith Take the lead as the Executive on (`orchestrator.take_the_lead`), reflection and research build their toolkit through `unattended_toolkit(..., source=...)`. That keeps solo's booking and `run_workflow` tools and an unrestricted `message_person` (teammates as well as the principal). Every acting tool goes through the gate, and a held action waits on Today as a `take_the_lead_action` decision. Reflection also gets the MCP gateway's `search_tools` and `call_tool` (`_with_lead_tools`; `call_tool` behind the gate, `load_mcp_server` left out), so it can find and use whatever the deployment has connected, such as building a sheet to track something. A note in the user turn (never the cached system prompt) tells it to act rather than only report, and it gets more room: 10 iterations, 4000 tokens, and tool results up to 4000 characters. The grounding check still refuses outward text naming people or figures the pass didn't see. New mail and chat also wake the reflection early (scheduler section). In training (`take_the_lead.training`) every acting call that isn't allowed waits too, as a training card for the principal, and both passes append `take_the_lead.learned_note()` to their user turn: that it's in training, and the principal's own edits on earlier cards as examples of how they want those done (never in the cached system blocks).",+ "markdown": "Workflows are deterministic, multi-step orchestrations. The built-ins are registered in `openexecutive.workflows.WORKFLOW_REGISTRY`; user-created (dynamic) workflows are stored as data (see below). Each follows the same contract: structured input feeds an ordered list of named steps that render a Markdown artifact, persisted via `complete_run` into `workflow_runs.artifact`. The activity feed never shows a run's log title (`\"Executive Research (periodic)\"`): `workflows/run_outcome.py` gives each finished run a plain name (\"Researched your market\", \"Checked in with Sales\", or the name it started with, less its date) and one line on what came of it, read from that stored artifact, so older runs read the same and nothing extra is written or called. Every step emits a `WorkflowEvent` (start/progress/complete) streamed over SSE at `/workflows/{name}/runs`.\n\nThe registry holds 25 built-in workflows, plus any number of user-created ones. Representative built-ins:\n\n- `board_prep`, `quarterly_plan`, `annual_plan` — planning and governance deliverables.\n- `performance_review`, `comp_refresh`, `org_design`, `exec_search_brief` — people and org artifacts (the last is an advisory hiring brief / scorecard from the CHRO, with input from the hired function's specialist — `sales` for a sales role — kept when the recruiting pipeline was removed).\n- `crisis_comms`, `churn_deep_dive`, `competitive_teardown` — situational analyses.\n- `department_check_in` — runs on department cadence; its `goal_status` step returns structured verdicts persisted back to `department_goals.status` (`department_check_in.persist_goal_verdicts`, shared with `weekly_review` and the weekly `goal_review`, which grades the goals no check-in covers; see Scheduler).\n- `weekly_review` — the principal's weekly look back and ahead (see *Weekly review* below).\n\n**Standing facts in unattended output.** `end_of_day_digest`, the weekly review's top-three call and the morning reflection append the standing facts (`memory.facts.with_standing_facts`; a teammate's marked `(per <name>)`) to their user turn, and the morning brief gets them through `render_briefing_context`. A workflow step that consults a specialist gets them through `route_to_specialist`. A correction made in chat therefore holds in every recurring brief and run. The morning brief also reads `facts.render_teammate_changes(since)` off the event loop and passes it to both `render_briefing_context` (a TEAMMATE CORRECTIONS SINCE LAST BRIEF block) and `build_brief_fingerprint`, so the principal hears of each correction a teammate made in the window, and that alone un-suppresses an otherwise unchanged brief. Proposals waiting for approval are listed only in a brief the principal reads privately (`include_proposed=_private_ok()`), and then mark the run private to them. The principal's own Always in the loop notes (`memory.history_brief`, only with their switch on) come in by a stricter rule, only on the scheduler's delivery (`PRINCIPAL_DELIVERY`), never a run from chat, whose tool result reaches the turn's shared audit row and peer memory: the morning brief's FROM YOUR NOTES — DUE SOON block and the end-of-day digest's FROM YOUR NOTES — TODAY block (what they committed to since the last digest, then what is due tomorrow). Either marks the run `private_to_principal` and moves its fingerprint; the digest, which had no private reads before, now emits that flag too. In the install's first week (`briefing.first_week`, seven days from the principal's People row) the morning brief also passes a GETTING STARTED block to `render_briefing_context(getting_started=)` and its keys to `build_brief_fingerprint`: onboarding goals, departments with no leader and, on the scheduler's delivery with Act as me and Draft replies to my inbox on, who wrote to the owner's own mailbox (sender and subject only) and, with Read my calendar on, today's meetings on their own calendar (time and title), either of which marks the run `private_to_principal`. The brief opens with **Getting started** and is never the quiet line while the block has anything in it (see Today).\n\n### Change-aware principal briefs\n\n`morning_brief` and `end_of_day_digest` are the two recurring briefs the scheduler sends to the principal. Both are written with `briefing.narrative.brief_model()`, the Executive's own model (its Council pick, else `DEFAULT_MODEL`), since a brief is the Executive speaking; only the grounding repair stays on the fast model. Both are now a *delta*, not a re-list: the window is \"since the last **delivered** brief\" (`briefing.brief_state.since_for`; 24 h on a cold store, clamped to 7 days), activity comes from `_build_activity(limit, since=…)`, proposals (action category only) split into *new since last brief* — enumerated, with each item's why-now and next move — versus a one-line carried-over count, a *rewritten* block lists carried items the review rewrote inside the window (`brief_state.rewritten_since`: verdict `changed`, still open — the brief reports them under \"what changed\", never as done), and a *handled overnight* block lists what the Executive's alert review **completed** on its own (`brief_state.handled_since`; the `changed` verdict is excluded because the alert is still open). The morning brief also reads the principal's **live world** since that window opened (`briefing.live_signals.gather_live_signals`): mail and chat the Executive handled (INBOUND, grouped by sender and subject, each email from the roster marked replied or not, earlier days dated), under a NOW line and THE PRINCIPAL line that names its reader so the brief writes \"you\" (the end-of-day digest gets the same line, and the team reflection a YOUR PRINCIPAL line under its roster; the reflection flags only what today's input still shows), what got stuck (STUCK: a reply the outbound gate held, a non-roster sender who got no reply, a Google Chat message left unanswered, chat drafts still in the principal's Gmail, after `live_signals.settle_principal_drafts` has marked the ones they since sent or deleted there), the principal's own chats, and — in both modes now, unless the solo top three already listed it — today's calendar, read fresh (`live_signals.refresh_calendar(max_age=0)`). The 07:30 reflection's **Flagged for the brief** bullets are carried across (`brief_state.reflection_flags_since`, the latest reflection run finished inside the window) instead of surviving only as an activity line with the run's title, and the rhythm runs themselves (`today.RHYTHM_WORKFLOWS`) are dropped from the brief's activity: their dated titles were noise and moved the fingerprint every day. At-risk departments name their slipping goals and each proposal carries its age. The period is the principal's local date. Section order: top call → **today** (the calendar's shape and anything stuck) → what changed (inbound first, naming who wrote) → handled overnight → needs you (new only) → waiting on → at risk (the slipping goal, or the department left out — never \"no detail yet\"). Quoted mail, chat, invite and reflection text is marked as data, never instructions. **Privacy:** the brief reads what is private to the principal — their contacts' alerts and mail, their drafts, their chats and their calendar — only on a run for them: the scheduler's (`morning_brief.PRINCIPAL_DELIVERY`) or the principal's own verified chat turn in a conversation only they can read (`delegation.settings.private_conversation`: the web chat, a Slack or Discord DM, a private Telegram chat — never a shared channel, where the reply is posted for everyone). A run anyone else starts (a teammate from chat in team mode, `POST /workflows/…/runs`) reads what everyone may see, as before. A run that did read a private row says so on its `result` event (`private_to_principal`: its live read differs from the shared one in any key or count), and the scheduler, `run_workflow` and `POST /workflows/{name}/runs` all then keep `persistence.PRIVATE_RUN_ARTIFACT` in the run history instead of the text. Text another pass wrote (the reflection's flags) renders as quoted ` > ` lines and every goal and headline field is one-lined, so none can start a line that reads as a block header. The fingerprint carries the live signals' time-free keys (who wrote about what, what is stuck, the calendar's shape) and the reflection flags when there are any, so \"nothing new\" means the principal's world was quiet too; the context summary is logged at INFO (`morning_brief: context since=… inbound=… stuck=… suppressed=…`). In **solo mode** (one person using Open Executive for themselves) both briefs speak to the principal, whatever their role: the morning brief runs top call → top three today → what changed (inbound and stuck first) → handled overnight → needs you → due this week (the principal's open loops overdue or due within 7 days, from `open_loops.principal_due_soon`) → goals at risk (named by area), the end-of-day digest what I did → open decisions → goals at risk tomorrow → sleep on this, over a context with goals at risk by area and no people-waiting or department block; the fingerprint carries the mode and ignores who is awaiting, and carries the due items as `(loop_id, state)` pairs when there are any. **Top three today** is picked in code, not by the model (`briefing.top_three`: overdue then due-today commitments, off-track then at-risk goals, commitments due later this week, then active projects, stalest first). The solo Briefing's *Top three today* card shows the same pick from the same code (`GET /today/top-three`, see Today). When the MCP gateway runs the Google Workspace server, one `google_workspace__get_events` call (4 s timeout) lists today's events on the principal's calendar — their address as the calendar id, read with the Executive's account (`primary` when the Executive is signed in as them) — and on a business day (`calendar_tools.is_business_day`, the rule the booking tools apply; at the weekend the day's events are still listed but no slot is suggested) each item gets its own free block inside `CALENDAR_BUSINESS_HOURS_START`–`_END`, rendered with a TODAY'S CALENDAR block — only a date-only event is all day, a zero-length one blocks nothing, and one whose times can't be read is left out; no gateway, no principal address, an error, a timeout or a reply it cannot read all mean no calendar and no slots, never a failed brief; the log records only the reply's length or the error's type, never calendar text. When the principal has Act as me and **Read my calendar** on (`delegation.calendar`) and their mailbox opens as theirs, `top_three.read_todays_calendar` also reads their own calendar through their own sign-in (Gmail or Outlook, same 4 s timeout, declined events left out), at the same time as the Executive's read, and merges the two: an event with the same title and times on both is listed once, and either read alone is enough. This read feeds the morning brief, the /today calendar cache (`live_signals.refresh_calendar`) and so the end-of-day digest and Right now; the solo top three adds it only on a run for the principal (`build_top_three(include_own=private_ok)`). The fingerprint carries the three items' keys (no dates, no slot times) and only a coarse hash of the day (busy blocks rounded to 15 minutes, no titles, no dates), so an unchanged day still suppresses. A day whose calendar read fails after one that worked (or the reverse) changes the fingerprint once, so that brief is written in full. A date-free fingerprint of the inputs is compared to the last delivered one; if unchanged the artifact is the one-liner \"Nothing new since yesterday's brief — N items still waiting on you.\" and no model call is made (`PRINCIPAL_BRIEF_SUPPRESS_UNCHANGED`; `force_full=true` on a manual run bypasses it). The workflow yields a `result` event with the fingerprint; only the scheduler records it, after a successful delivery, in `briefing_narrative` under scope `brief:<kind>` — so manual runs never advance the window. Both are written to their reader in code (`briefing.reader`): the principal's full name and addresses are masked to \"the reader\" throughout the context under a THE READER line, the prompt says \"you\" for the reader, nobody is \"the principal\" and the Executive is \"I\" / \"me\", and a draft that still slips is rewritten once (the morning brief) and fixed in code. **The end-of-day digest reads the day itself.** On the scheduler's delivery to the principal alone it leads with TODAY WITH YOU (`session_store.own_conversation_since`: the principal's own conversations with the Executive since the last digest, their words and its replies, never a conversation someone else owns) and the live blocks (`live_signals.render_live_blocks`: mail in, what got stuck), then COMING UP (the Executive's own follow-ups due in the next two days). It leaves out its own rhythm runs (`today.RHYTHM_WORKFLOWS`) and gets the reader's leave-out list (`brief_requests.render_parts`). Its shape is **Today**, **Done for you**, **Next** and an optional **Sleep on this**, at most 150 words, with no header for an empty section. Before this it read only the Executive's own bookkeeping, so on a day of real work it reported its own briefs and missed every number decided in chat.\n\n**Brief delivery.** `scheduler.runner._deliver_to_principal` maps the principal's `preferred_channel` (`slack` / `discord` / `telegram` / `email`) to its delivery channel and tries it first, then the other chat channels the principal has an id for, in the order Slack → Discord → Telegram. Email goes through the active MCP gateway (`google_workspace__send_gmail_message` as the Executive's own address, to the principal, subject `<title> — <date>`) and is used only for an explicit `email` preference, or for `any` when no chat channel resolves — an owner linked by email at setup has `any`, so one who also has Slack does not start getting two emails a day. When nothing can deliver (a web-only principal, or email with no gateway), the brief is still generated and stored as a run with its artifact, as before — a web-only principal reads it on the Artifacts page — it is just not delivered (audited), so the window does not advance, and the next occurrence is chained. The same delivery path carries the client-rotation digest and the weekly review.\n\n**Grounding.** Nothing an unattended pass writes is read by anyone before it goes, so `openexecutive.briefing.grounding` checks it deterministically — no model judges the model. A name (a run of two or more capitalised words once section headers, weekdays, imperative openers and org nouns are trimmed, or one capitalised word in a person slot like \"ask Marcus\" or \"Marcus wrote\") is grounded only when a single line of the pass's inputs holds all of it, or it belongs to a roster person some input mentions — being on the roster alone is not enough. A figure (money, a percentage, a k/M/B number, any bare number of 11 or more; never a date, time, year, duration, id, list marker, `Q3` or small count) is grounded when an input number matches it within the precision it is written with (`$1.2M` matches `$1,234,567`; `47 units` does not match 48). The inputs are the rendered context split into lines labelled by section (a header also carries its bullet count), the company profile and the department titles. `morning_brief` renders its context itself and hands it to the synthesizer as `rendered_context`, so the check reads exactly what the model read; after the quiet fallback, `ground_brief` runs on both briefs. When something is ungrounded it makes one repair call to the fast model (same system prompt, the list of items, \"remove or correct using only the context\"), re-checks, then drops each line still ungrounded and any header left empty, and appends \"_I left out N lines that named people or figures I couldn't match to your data. They're under Left out of your brief on Home._\" (everything ungrounded → one held-back line). Every held line goes in the `grounding` audit row's untruncated `full` payload (up to 30, 400 chars each; `details` keeps a five-line preview), and `grounding.recent_held_back` reads the last day's back for `GET /today`'s `held_back`, which Home lists under **Left out of your brief** for the principal alone — after the narrative inputs are taken, so the held lines never reach a prompt. Then each grounded figure gets a server-chosen ` [n]` — the matching input line with the most words in common with the figure's clause — and a `**Sources**` list closes the brief (`- [n] <section> — <snippet>`, at most 9, snippets quote inbound mail, so links are masked (\"(link removed)\"), Markdown, angle brackets and @-mentions stripped, and they are cut to 90 chars; never `[n]:` at a line start, which Markdown reads as a link definition). Text with nothing to change comes back byte-identical, the fingerprint hashes the inputs so suppression is unaffected, and the grounded text is what is delivered, stored and recorded as delivered. Both brief prompts and the digest prompts say the rule up front. `executive_reflection` wraps its handlers in a `GroundingScope`: `create_alert`, `message_person`, `send_department_message`, `send_company_broadcast` and `schedule_followup` refuse text with an ungrounded name or figure, returning a JSON error that names the items so the model can look the person up or leave the figure out (every tool result joins the inputs, so a `lookup_person` answer grounds the DM after it; the recipient's own name always counts). Its **Flagged for the brief** bullets are filtered the same way before the tool log is appended — the next brief quotes them, where they would ground themselves — and `brief_state.reflection_flags_since` now stops at the tool log's `---`. The reflection's `grounding` rows are private when a private-to-principal alert reached its context, and the digest's always are (its HANDLED block can quote one). Everything fails open. `GROUNDING_CHECKS=enforce` (default) acts, `report` only writes the `grounding` audit rows, `off` skips it; `GROUNDING_CITATIONS=false` drops the markers. Not yet grounded: the /today header (its cards sit beside it), `weekly_review`, the research synthesis, dates and meetings, and a real person named in the wrong role.\n\n### Weekly review (solo)\n\n`weekly_review` (background, inputs all defaulted) closes out the principal's week in six steps. **Goals**: every area with goals is graded by its own specialist, concurrently, with the department check-in's verdict contract (`_parse_verdicts`) and write-back (`persist_goal_verdicts` → `record_goal_review`, one `goal_status_review` audit row per area with actor `weekly_review`); an area with no goals is skipped, one without a specialist is listed ungraded, and one whose specialist fails is shown as last recorded. **Commitments**: `open_loops.principal_due_soon` — overdue or due within 7 days. **Projects**: active initiatives with no update for 7+ days. **Decisions**: the week's (`episodic.decisions_since`). **Revisit**: up to three decisions older than 30 days with an empty outcome (`episodic.decisions_awaiting_outcome`, newest first), listed as `[decision N]` under *How did these turn out?* — the principal's answer is recorded with `record_decision_outcome` (see Agents). **Assemble**: every section always renders (a one-line note when empty), ending with *Next week's top 3* from one fast-model call that follows the `weekly-review` playbook (a constant system prompt; the playbook rides in the user turn), trimmed to at most three list items — or, when that call fails or returns nothing, the same ranked pick the morning brief uses. In solo mode the scheduler fires it weekly (`principal_weekly_review`, see Scheduler) and delivers it through `_deliver_to_principal` like the briefs, recording the delivery outcome. The solo Briefing also shows the latest completed run to the principal (`GET /today/weekly-review`, see Today): `weekly_review.summarize_review` reads the artifact's title line (`TITLE_PREFIX`) and its last `TOP_THREE_HEADING` section back as plain text, so a principal no channel reaches still sees next week's top three. Wording is role-neutral; run by hand in team mode it says *department* instead of *area*.\n\n**Principal-only workflows.** A workflow can name the workspace modes in which only the principal may start it (`Workflow.principal_only_modes`): `weekly_review` in both modes (built from the principal's decision log, commitments and goals, and it re-grades the goals) and `morning_brief` in solo (built from the principal's commitments and calendar). Team `morning_brief` and every other workflow can be started by anyone as before. This decides who may start or trigger a run, not who may read one: stored runs, the scheduled briefs and weekly reviews included, are read under the existing `/workflows/runs` rules — which is why a morning brief that drew on the principal's private rows is stored as `PRIVATE_RUN_ARTIFACT`, not as its text.\n\n- **From chat**, `run_workflow` checks at dispatch, before any run row is created, that the turn is the principal on a verified surface — `create_goal`'s rule — and otherwise refuses with a plain error that does not spell out the rule.\n- **Over HTTP**, the Jobs page's `POST /workflows/{name}/runs` and `POST /evals/runs` (a workflow scenario runs the workflow on live data) call `refuse_principal_only_run`: only a caller signed in as the principal, or a request with no caller email (the CLI or local login), may start the run. Unlike the workspace settings, an install with no principal on the roster lets no signed-in caller in, as in chat. Anyone else gets a 403 (\"Only the principal can run this workflow.\") before any run row exists. The mode is the stored one, or an eval scenario's own `workspace_mode`. The eval route runs exactly the scenario list it checked.\n\nEvery refusal is audited `refused=true` with the workflow, the mode and the caller. The checks fail closed: a mode that cannot be read counts as principal-only, and a check that cannot read the roster refuses.\n\n**Knowledge in the reflection.** A chat turn looks the knowledge base up before the Executive answers; the reflection reads the org's state instead, so nothing looked it up for it. It now carries its own `search_knowledge` tool (`orchestrator.knowledge_tools`, not in the shared `_ALL_SKILL_TOOLS`), which runs the same `knowledge.retriever.retrieve` as chat — the review gate, the synced Drive / OneDrive / Confluence / Notion collections and the published-artifact rule (the pass has no viewer, so no one's private document comes back). The prompt (`_KNOWLEDGE_RULE`, both modes) asks it to search before acting on or flagging something that turns on a customer's or supplier's terms, a price, a policy, a plan or a past decision. Its passages come back up to 4,000 characters (`execute_tool_calls(wide_results=...)`) while other tools stay at their short preview, its result counts as grounding input like any tool result, and the run's tool log keeps each line to 160 characters. Read-only, so Take the lead never gates it. The loop has 5 iterations (was 4) to leave room for a search before acting.\n\nNeither the nightly reflection nor the research synthesis can call `ack_alert`: both run unattended with open alerts rendered into their context, and those headlines are minted from inbound mail and chat, so an injected \"the principal already dismissed 13\" would be acted on with nobody watching. Closing an alert is the alert review's job, with evidence.\n\n`executive_reflection` now carries memory: yesterday's standup (the previous completed run's artifact) is rendered into the context and the prompt forbids re-acting on anything listed there unless it changed; open alerts render with their id, review verdict and recommended move. Reflection never closes alerts — the alert review does, with evidence. It also renders an **OPEN LOOPS** block (up to 10, soonest due first, overdue flagged) from Attunement so the standup can connect a slipped promise to the rest of the org state; the nudge engine already chases overdue loops, so the prompt tells it not to DM about a loop merely for being overdue. A **WHAT LANDS** block (from the Attunement outcome ledger) shows, per person, how often each kind of proactive DM got answered over 30 days; the prompt steers DMs toward kinds that land and away from kinds a person reliably ignores. Reflection and research tag their tool execution as proactive (`tag_proactive`) so their DMs are counted. Resolving a wait-for-human approval (`resumer.apply_resolution`) marks the nudges that chased it `acted`. `close_open_loop` is withheld from reflection for the same reason as `ack_alert`: loop text is quoted from what people wrote. `unattended_toolkit` also drops `schedule_tools.UNATTENDED_WITHHELD_TOOLS` (today `create_goal`) from both passes in both modes: a goal is the principal's own decision, and these passes see only inbound text. A turn private to the principal (mail from one of their contacts, or mail they forwarded) cannot start a workflow either: `run_workflow` and `run_executive_research` are in `schedule_tools.PRIVATE_TURN_WITHHELD_TOOLS`, which the chat loop neither offers nor runs on such a turn, since a workflow's steps can reach anyone.\n\nIn **solo mode** the reflection is framed for the principal, whatever their role: they are the only person who uses Open Executive and the only one it takes direction from, it prefers `create_alert` and `schedule_followup` to the principal, and it never messages anyone else from an unattended pass — the people in the principal's world are contacts, so anything they should hear is flagged for the principal to raise. The team roster is replaced by one YOUR PRINCIPAL line (person_id and follow-up channels), its follow-up guard is seeded from the principal only, and department risk renders as areas with goals at risk. The research synthesis follows the same rule — its routing menu and roster name only the principal. In both, `send_department_message`, `send_company_broadcast` and `set_department_head` are withheld, and so are `create_calendar_event`, `create_instant_meeting` and `run_workflow` — a booking reaches its attendees and a workflow can do anything its steps do, so the principal books and starts workflows from chat — and `message_person` refuses anyone but the principal. These passes run unattended with inbound text in their context, so the rules are enforced in code, not only in the prompt.\n\nIn either mode, both passes now dispatch only the tools they offer: the handler map is built from the offered list, so a name the model emits without being offered it is skipped as an unknown tool. They used to look names up in the full handler registry, so tools they deliberately withhold — the raw DM tools (`send_slack_dm` has no roster check), `ack_alert`, `close_open_loop`, and in research the watchlist writes and `run_workflow` — still ran when the model emitted them. Both read the mode before binding their own session (so a caller's override, such as an eval's, counts) and pin it on that session, so their tool handlers use the same mode. They carry the principal's role across the same way (`effective_principal_role` of the caller's session, pinned as `turn_principal_role`), so a specialist or workflow started from either pass sees the role of the turn that started it. Team runs are unchanged.\n\n### Wait-for-human pause\n\n`wait_for_human` (`openexecutive/workflows/wait_for_human.py`) is a first-class step primitive that pauses a run: the runner calls `save_checkpoint`, the `workflow_runs` row moves to `status='awaiting_human'`, and the serialized `WaitForHumanEvent` is stored in `state_json`. (Department authority is a *separate* mechanism — `propose_only` departments file a briefing alert via `departments.authority.propose_via_alert` and mark the scheduled action done; they do not route through this gate.)\n\n**Delivery.** Both checkpoint sites — the SSE route and the `run_workflow` chat tool — call `workflows.gate_delivery.deliver_gate_question` immediately *before* checkpointing, so `state_json` carries the routing fields a reply is matched against. Two modes. When the approver is the person already in the conversation (the chat session's `origin_channel` is set — to anything but `email`, whose answer is no chat reply and would never be sent — and its `caller_person_id` is the gate's `person_id`), nothing is sent — the question rides in the Executive's own reply — and the gate records `origin_session_id` plus the session's channel. The resolver compares base ids (`memory.conversation_ids.base_session_id`), so a question asked in one conversation of a Telegram chat or a DM is still answered by a reply after a quiet gap or /new has started the next. Otherwise the question is delivered through `schedule_tools.handle_message_person`, which picks the person's preferred channel, falls through on a failed send, and falls back to a briefing alert; the gate then records the channel, address and provider message id that send returned, plus the id of the DM session it landed in — that send is always 1:1, so the answer belongs in that conversation and nowhere else. Without it the gate matched on person and channel alone, so an unrelated @mention in a public channel resolved it and had the acknowledgement, run title included, posted where everyone could read it. The question is sent with `notifications.approval_send`, so the person's quiet hours and *In my briefs* never hold it, whatever their urgent setting: only a reply to it resolves the gate. Delivery is not guaranteed: the outbound guard can suppress it (duplicate, rate cap, quiet hours) and an unreachable person gets the alert fallback. Both cases leave the routing fields empty and report `delivery` as `suppressed` / `alerted` rather than claiming someone was asked, and the chat tool's presentation hint changes accordingly.\n\n**Matching a reply.** Each inbound adapter passes the message to `inbound_resolver.resolve_inbound_message` with its `session_id`. Matching is three-tier: an explicit `in_reply_to` against a stored `outbound_message_id`; otherwise a single open run on that channel; otherwise one utility-fast disambiguation call gated at 0.85 confidence. An unmatched explicit reference rules out only the candidates that carry a stored outbound id — the ones it could have matched — and the rest continue; rejecting outright meant an adapter that passes a thread id on every message (Slack's `thread_ts`) short-circuited the later tiers forever, and a global test let one delivered gate's id block an unrelated self-approval gate. Channel names are normalized (`slack_dm` ≡ `slack`), the delivered address is compared when both sides know it, a row whose `state_json` will not parse is refused (a corrupt row otherwise presents as a legacy one), and an empty stored channel is treated as a wildcard only for rows checkpointed before gate delivery existed. Two guards keep an open gate from swallowing unrelated traffic: a gate carrying an `origin_session_id` matches replies only from the conversations the adapter names (a Slack or Discord thread offers its parent channel session too, mirroring the history double-write, since a gate raised on a mention recorded that session while the answer arrives under the thread's — on Slack only when that person rooted the thread, or the alias would reach into a colleague's), and the parser can return `unrelated`, which declines to resolve and lets the message reach the normal chat path. The parser is handed the gate's own question, so a bare \"yes\" is judged against something. Its fallback is flagged by a key the model cannot emit rather than by a magic note string it could, and a fallback declines to resolve on *every* reply shape — recording the empty string a `free_text` fallback fabricates would close a sign-off on a parser outage. Every shape can answer `unrelated`, not just `approve_reject`: without it an open `free_text` gate turned the person's next message into its answer verbatim, and a `numeric` one swallowed any message containing a number. The parser has one caller outside workflows: its `roster_identity` shape — `{decision: approve|link|decline|unrelated, name, kind: team|contact|null}`, with `name` only as the person wrote it (never inferred) and a fallback of `unrelated` — reads the principal's emailed answer to a roster request (who a new sender is; see Org). It is not a gate reply shape, and a fallback or `unrelated` leaves the request waiting. `resumer.apply_resolution` then records the decision, marks the run `resolved`, and writes an audit row. A timeout applies the step's `on_timeout` policy (escalate / auto_proceed / fail). The outcome surfaces on the Today dashboard.\n\n**Resuming past the gate.** A paused run continues on its own. Re-entering it was long assumed to mean serializing a Python generator frame; it does not. The only state alive across a dynamic workflow's steps is its inputs (already persisted), a company-profile block that is recomputed, the completed steps' output strings, and the loop cursor — so the engine hands the checkpoint a small JSON `WorkflowResumeState` (workflow name, the gate's id and index, the next index, the outputs so far), stored in `workflow_runs.resume_state_json`, and `DynamicWorkflow.resume` replays its step loop from the recorded index. `run()` and `resume()` share that one loop, which is why a second gate needs no special handling — it is simply another pause raised from the same place. The payload rides on a `WaitForHumanEvent` field declared `exclude=True`, so it can never leak into `state_json`, whose exact key set the resolver branches on. A gate with no payload is *pause-only*: the decision is recorded and the run stops, which is what every caller got before resume existed.\n\n`resumer._process_resumable` claims a resolved run with one guarded UPDATE — `resolved` → `running`, stamping `resumed_at` and minting a claim token — and drives it to a terminal row. It runs two ways: immediately, via a task `apply_resolution` kicks off so a Slack approval starts moving in seconds, and every 60s from the poll loop as the durable backstop. Both share the claim, so a run executes exactly once even with two resumers against one database. The kicked task binds no chat session (`set_session(None)`), exactly like the poll loop: it is created inside the inbound handler that recorded the answer and would otherwise inherit that person's live turn — so a run resumed because the principal replied on Slack does not act with the principal's identity (it cannot, for example, reach the principal's contacts). It drops the handler's audit scope too (`audit.context.unscoped_audit_rows`): inherited, the principal's scope would make private every row of the run that names a contact, and whoever started the run would see those rows vanish after the approval. The poll runs the executor *after* the timeout loop, which is what finally makes `on_timeout='auto_proceed'` do what its name says: the timeout resolves the run and the same tick executes it. While the Executive is paused (`scheduler.pause`) the resumer does nothing — no startup sweep, no timeouts, no resumes — and `apply_resolution` still records the decision but skips the immediate kick; the first unpaused iteration catches up on all of it, so a timeout that lapsed during the pause applies its `on_timeout` policy then.\n\n**The claim is fenced, because it is not a lease.** The stale sweep decides a worker is dead from a wall-clock guess, so a slow but *alive* worker will eventually be declared dead and replaced. Every write the executor makes carries its claim token and is refused once superseded — otherwise the replaced worker's late completion lands on top of its replacement's result, or its checkpoint at a later gate resurrects an already-finished run and asks the approver a second time. The retry budget resets at each new gate (a gate is new work, not a retry), and a run that exhausts it is *ended* rather than dropped: an exhausted run sits in `running` with a payload, in neither queue, and would otherwise show as in-progress forever.\n\n**The gate fails closed.** Continuing is an allowlist — `approve` and the synthetic `auto_proceed` — not \"anything that is not a stop word\". `decision` is whatever a fast model extracted from free-form chat and it drifts; under a denylist, \"rejected\", \"Reject\", \"decline\" and \"no\" would all continue, so the approver declines and the deliverable is produced anyway. Reply shapes that ask a question rather than seek permission always continue, since the answer *is* the value. A stop ends the run at `error` with the human's note. Either way the decision becomes the gate step's own output, so it reads as a section *in* the artifact — capped and blockquoted, because that text reaches the synthesis specialist as prompt context.\n\n**A definition edited during the pause is refused.** Resume re-validates the payload's version, the recorded gate, *and* a fingerprint of the whole step list, and derives the index to continue at rather than reading it from the payload. Pinning only the gate would not be enough: definitions are overwritten by name and any rostered user can save one, so someone could keep the gate identical and replace every step after it — and the approver's sign-off would be recorded against work they never saw, which defeats the one thing an approval gate is for. No built-in workflow yields the gate; only user-created dynamic workflows do.\n\n### Launching from chat\n\nWorkflows are not only reachable from the `/jobs` UI — the Executive can list and run any of them mid-conversation. `openexecutive.orchestrator.workflow_run_tools` wires two tools into the main chat loop: `list_workflows` (the launchable catalog, with each workflow's input fields) and `run_workflow` (runs one to completion and returns its Markdown artifact, using the same engine as `POST /workflows/{name}/runs`). `run_workflow` resolves both built-ins and custom workflows via `get_workflow`, validates `inputs` against the workflow's input model, persists the run (`create_run` → `complete_run` / `fail_run`), and on an approval-gate step checkpoints the run as `awaiting_human` exactly as the HTTP route does — literally the same code, since both call `workflows.gate.checkpoint_gate`, which delivers the question and writes the checkpoint in one place. It never hangs waiting on a human, and it reports both whether the question reached them and whether the run will continue by itself once answered. The runners that *cannot* pause — the schedulers, evals, client rotation, onboarding, the research tools — call `gate.ensure_workflow_event`, which raises on a gate rather than letting one be swallowed; the scheduler's dynamic-workflow branch used to ignore it and record a successful run containing nothing. `executive_research` is excluded (it has the dedicated `run_executive_research` tool). Running a workflow from chat delivers nothing on its own — it renders the artifact into the conversation, and the recurring principal briefs (`morning_brief`, `end_of_day_digest`) reach anyone only via the scheduler's own `_deliver_to_principal`. The tool description used to claim those two DM the principal when run and to confirm before firing them, which had the model soliciting a confirmation on a false premise; it now names `executive_reflection` as the one workflow that really does execute tool calls of its own (DMs to heads, broadcasts, alerts). A successful run surfaces an `action_taken` chip linking to `/jobs/runs/{run_id}`.\n\n### Dynamic (user-created) workflows\n\nUsers create reusable workflows on the fly — from the executive chat, the conversational wizard at `/jobs/new`, or the step-by-step advanced editor — without shipping code. The Workflows page (`/jobs`) opens on a *Start here* panel that leads to all three: the user describes the job in a sentence and *Start* opens the wizard with that text sent as its first message (handed over in `sessionStorage`, so a link cannot make the wizard send text the user never typed; where storage is blocked it falls back to `/jobs/new?describe=`, which only fills the composer and sends nothing), or picks *Step by step* (advanced editor) or *Talk it through in chat* (`/?new=1&draft=`). Below it come the user's own workflows, then four ready-made starter picks with the full built-in list folded behind *Browse all* (`?browse=1`). The picks and the example chips follow the workspace mode: a team gets the investor update, board prep, MBR and competitive teardown (and a board pre-read chip); a solo owner-operator gets the MBR, pricing review, churn deep dive and quarterly plan, with chips for a Friday cash and pipeline check, customers who stopped buying and a competitor digest (`lib/workflowStarters.ts`; a unit test pins every pick to a startable `WORKFLOW_REGISTRY` entry). A dynamic workflow is a stored JSON definition (the `dynamic_workflows` table) interpreted at runtime by one generic `DynamicWorkflow` engine (`openexecutive/workflows/dynamic.py`) that implements the same `Workflow` ABC as the built-ins, so the run path, SSE streaming, run persistence, and `/jobs/[name]` form rendering are unchanged. `get_workflow` / `list_workflows` fall through to the dynamic store after the static registry (built-ins win on a name collision).\n\nA definition declares free-text input fields and an ordered step list of four kinds: **specialist** (consult a specialist with a goal prompt, optionally grounded by RAG), **action** (get something done with tools — see below), **approval_gate** (a `wait_for_human` pause), and a terminal **synthesis** step that assembles the artifact. At least one specialist or action step is required. `validate_definition` enforces the structural rules: exactly one terminal synthesis step, valid specialists, `{placeholder}` tokens that reference declared input fields, rostered approval/cadence people (team members — never one of the principal's contacts, whom an unattended run may not message), and a parseable cadence.\n\nAuthoring from chat uses a **draft → confirm** handshake: the Executive calls `draft_workflow` (validate; return a `confirm_token` plus a plan summary), shows the user the plan, then calls `save_workflow` with the same definition and token — a token mismatch is rejected, so the saved workflow is exactly what the user approved. The step-by-step advanced editor drives the `/workflows/custom` CRUD endpoints directly.\n\n**The New workflow wizard** (`/jobs/new`) is the default way to create one from the UI. It works like conversational onboarding: the user describes the job, the `workflow_designer` Council agent (`openexecutive/workflows/designer.py`) asks one clarifying question per turn — deliverable, per-run inputs, sign-off, schedule, recipient — with up to four clickable suggested answers, then emits a complete definition plus a plain-language summary and the assumptions it made. Every turn offers the model exactly three fixed, name-sorted tools (`ask_clarifying_question`, `emit_workflow_draft` — reusing the chat tool's `DEFINITION_SCHEMA` — and `search_available_tools`, which is answered inside the same turn from the tool catalog, up to four searches per turn, with the tool_use/tool_result pairs never stored in the plain-text transcript; every tool a search returns is remembered on the session and replayed into later turns, so a forced draft or a repair turn — which cannot search — still has the exact names); `tool_choice` flips to the emit tool once, when the six-question budget is spent or the user clicks *Draft it now*. The emitted definition goes through `validate_definition`, the tool-availability check, and a check against saved custom names, with one repair turn that feeds the errors back. The system prompt is a cached constant; the live context — specialists, the roster with person ids, the user's timezone (the one set through `PUT /workspace`, else `USER_TIMEZONE`; cadences stay UTC), and taken names — is rendered once per session into the first user turn, and while refining, the exact current draft is prepended to the latest user turn so the model edits it rather than re-deriving it. Roster names and roles are flattened to one line and capped at 80 characters before they enter that context, and the system prompt tells the model to treat the whole block as data, never instructions. Sessions live in memory (`/workflows/designer/*`, 2 h TTL, 50-session cap), run one model turn at a time (a second concurrent `/message` or `/draft` gets 409, and a failed turn is rolled back by identity), and never write: the review card saves through the same `POST /workflows/custom`, which re-validates, and *Edit details* opens the draft in the advanced editor (`/jobs/new?designer=<id>`) before saving.\n\n**Editing is a conversation too.** *Edit* on a saved workflow (`/jobs/new?edit=<name>`) opens the same designer through `POST /workflows/designer/edit`: the stored definition is the starting draft, so the user's first message (\"have Mark sign off and run it Fridays\") is applied to it like any refinement, and a note in the context block (a user turn, never the cached system block) tells the model it is changing a saved workflow. The draft always keeps the workflow's name — `_check_draft` puts it back and skips the taken-name check — and the route keeps its on/off state, so an edit can neither fork a copy nor switch on a tool workflow waiting for approval. The stored draft is handed to the model marked as data, not instructions. The review card lists *What changes* in plain words against the saved version (`lib/workflowChanges.ts`): every field is compared, with named sentences for the sign-off person and what it asks for — a sign-off moved off approve/reject is called out because the run then continues whatever the answer — the schedule, steps added/removed/reordered, inputs, tools and the tool-call budget, and a catch-all line for any other field. It names only the newly added tools that may change things. *Save changes* calls `POST /workflows/custom/{name}/save-edit`, which saves the session's own draft after re-validating it, only when it is the draft the card showed (the card sends what it displayed; a message that landed since is a 409), and only if the stored workflow has not changed since the conversation opened (409 otherwise), so an edit started before someone switched the workflow off cannot switch it back on. The step-by-step form stays as the advanced editor (`/jobs/new?edit=<name>&mode=advanced`).\n\n**Action steps (workflows that act).** An `action` step (`ActionStepSpec`: `goal`, `tools`, `max_tool_calls` 1–50, default 20) is run by the `workflow_actor` Council agent (`openexecutive/workflows/action_step.py`) as a bounded tool-use loop. Its `tools` list is an allowlist of exact tool names — MCP gateway tools (`server__tool`, e.g. `google_workspace__append_table_rows`) and built-ins: the Executive's own chat tools as `oe__<name>` (see *Chat's tools in action steps* below; `oe__create_alert`, in a workflow a team member created, raises the alert as theirs (`alert_tools.raised_for_workflow_owner`: source `team_member`, \"Raised by <name>\", never a company-wide broadcast) — plus any installed extension's tools registered with `workflow=True`, as `oe__<name>`, run inside `extensions.workflow_step(name)`; a built-in wins a name clash, and an extension tool counts as reading only when it says so) — and **clicking Create is the user's approval** of that list: the review card shows every tool, flags the ones that may change things (anything whose name doesn't say it reads, and any tool with a URL/URI/endpoint/webhook parameter anywhere in its schema, or whose schema couldn't be read, since a URL can carry data out), and names them in a \"this workflow can use these without asking again\" notice. Because that card is the approval, a workflow with action steps saved from chat (`draft_workflow`/`save_workflow`, whose confirmation is a token the model holds itself) is stored **switched off** (`is_active=false`) and `save_workflow` returns `status: saved_pending_review` with a `/jobs/{name}` link. An inactive workflow can't run or schedule (`get_workflow` and the scheduler skip it); `/jobs/{name}` shows it on the same review card, where **Turn on workflow** (`POST /workflows/custom/{name}/activate`, which re-validates the tools) is the approval — the click sends the definition the card showed, and the server refuses (409) if the stored one has changed since, so chat overwriting it while the card is open can't get new tools switched on. Chat may revise a switched-off workflow but refuses to replace a switched-on one that has action steps (an inbound email steering the Executive could otherwise switch off an approved job and stage new tools under its name); those edits happen in the advanced editor. The Workflows catalog (`/jobs`) lists switched-off workflows in a compact *Waiting for your approval* strip, and saving edits in the advanced editor keeps one off. `tool_catalog.py` resolves names to schemas through the gateway's `search_tools` (extensible-mcp's Markdown output is parsed; resolving is also the per-session discovery its `call_tool` requires) and validates availability at save time (`POST`/`PUT /workflows/custom`, chat `draft_workflow`/`save_workflow`, designer drafts) — an unknown, misspelled or deny-listed tool is a 422. The gateway meta-tools (`search_tools`, `call_tool`, `load_mcp_server`) can never be step tools. `run()` resolves every action step's tools before any step runs, so a vanished tool stops the run before an earlier step acts; `resume()` checks only the steps still to run, after the gate and decision are validated. The last turn of an action step always switches tools off so the agent can report. At run time only the allowlisted tools are offered (sorted; constant cached system block, per-run goal/inputs/earlier results in the user turn), every `tool_use` is re-checked against the allowlist, MCP calls go through `MCPGateway.call_tool` so the config deny-list and the Gmail/Calendar/Drive recipient gates still apply, the call budget is enforced (then a final tools-off turn asks for the report; running out of turns fails the step and lists what was already done), tool errors (the gateway's `Error:` / `Error calling tool` / `Tool error:` prefixes, or a truthy `error` field) return to the model as `is_error` results, each call emits a `progress` event and an audit row (`workflow_tool_call`: tool and outcome; for tools that may change things also a short digest of target arguments — ids, recipients, URLs, paths — so a redirected write is visible; content arguments are never logged), and the step's output is the agent's report plus an \"Actions taken\" list. Tool output is framed as data, never instructions.\n\n**Chat's tools in action steps.** A step can use almost everything the Executive uses in chat, so an idea from a conversation can become a workflow without a missing tool. `workflows/chat_tools.py` holds one list, `ACCESS`, that labels every chat tool: **use** (a step may list it as `oe__<name>`, e.g. `oe__send_slack_dm`, `oe__run_workflow`, `oe__update_department_goal`, `oe__web_search`), **as me** (Act as me tools, not yet in workflows), **covered** (the step already has its own path: gateway tools, `run_script`, specialist steps) or **chat only** (memory, company profile, roster changes, open loops, follow-up corrections and screen actions). A unit test fails when chat gains a tool without a label, so new chat tools reach workflows by one line rather than a second copy. A **use** tool runs through chat's own handler as an unattended chat turn would: an unattended `Session` bound as `current_session`, the workspace-mode filter (solo withholds department and company posts), and, in a team member's workflow, their department gate. Channels the instance has no token for are not offered. Saving the workflow is the person's permission, so Take the lead's approval gates don't apply, the same as the gateway tools before. `oe__run_workflow` refuses a workflow already running in its own chain and nests at most three deep. It and `oe__run_executive_research` get a 15-minute call timeout. `oe__web_search` is the model's server search: it is appended after the sorted tools, never called by the step, and a paused search turn is sent back as-is. Workflows have no tool handlers of their own any more: `oe__message_person` and `oe__create_alert` are the chat tools under the same names, and the old `oe__read_file` still resolves (to `read_document`) for saved workflows but isn't offered for new steps (`chat_tools.LEGACY_NAMES`). The designer lists every built-in by its first sentence, and chat's `draft_workflow` says chat tools are available as `oe__<name>`; the catalog's search ranks built-ins by how many query words they match.\n\n**Email as the creator.** Besides the chat tools, a step may use `oe__draft_email_as_me` (a draft in the workflow creator's own mailbox for them to send) or `oe__send_email_as_me` (sent as them), Act as me's two workflow tools (`delegation.workflow_email`, see the delegation section). The creator picks one when saving the workflow, by asking for it in chat or the designer, which is told whether they can; the gateway's mail tools still send from the Executive's own address. A workflow that sends as its creator can only be created, changed or switched on by that creator, verified (a 403 otherwise), and the first email to a new address waits for their approval like any other first write.\n\n**Scripts in action steps.** Besides the step's own tools, the agent is offered one more, `run_script` (`openexecutive/workflows/step_script.py`), for work that repeats over many items — every file in a folder, every row, every email — or chains calls with simple logic. It writes a short Python script once instead of spending a model turn per call; each of the step's tools is a function in the script (`drive__move_file(file_id=…)`, or `call_tool(name, arguments)` by exact name), and only the script's final value and printed output come back. The script runs in **Monty** (`pydantic-monty`), a sandboxed Python interpreter for model-written code, in a worker process spawned per script: no files, network, environment, subprocesses or third-party imports — the step's tools are the only things it can reach. **A script is a faster way to make the same calls, never a way around them:** every call it makes goes through the same per-call path as a direct `tool_use` (`action_step._StepCalls`) — the allowlist, a call budget (a script's calls have their own: 10× the step's `max_tool_calls`, capped at `WORKFLOW_SCRIPT_MAX_CALLS`, default 500, because they cost no model turn each — so a step can work through a folder of hundreds of files while its direct calls stay capped at 1–50), the first-write target check (a held write comes back to the script as `{\"status\": \"held\", …}`) and one `workflow_tool_call` audit row per call — and the script itself is audited as `run_script`, with how many calls it made and how long it took. The step's \"Actions taken\" list collapses repeats into one line with a count. A step whose direct calls are spent keeps its tools on while the script budget has room, so it can still script the rest (a direct call is refused as over budget). When a tool returns a list of five or more items and the round didn't use `run_script`, the step adds the same `FANOUT_HINT` as chat (once a step), pointing the per-item work at one script. The worker is stepped from the step's own task (each call pauses it and is answered there), so cancelling the run stops the script and its in-flight call together, and each call's progress shows as it happens. At most `SCRIPT_MAX_WORKERS` (default 2) scripts run at once across the server, chat and workflows together; another waits for a slot within its own wall clock, else returns \"the server was busy\". A worker exists only while its script runs (about 8 MB idle). Execution time (excluding time waiting on tools), memory and recursion depth are capped inside the worker, the script has a wall-clock limit, and its text is size-capped; printed output past its cap is dropped. A failing script returns its error to the agent as an `is_error` result, with the calls it already made listed first (ahead of any long result, so a cut never drops them) so a fixed re-run doesn't repeat writes; a call cut off by the time limit is listed as `may_have_run`, and gets a `cancelled (may have run)` audit row. A workflow definition still holds no code; a script lives on only if the agent saves it as a tool (below). Because a step can loop at run time, the workflow designer keeps work that repeats over items (each email, file, row or listed follow-up) in ONE action step whose goal spells out the items, rather than a step per item; `run_script` is never a step tool, and a definition that lists it is rejected (`validate_definition`) so the designer's repair turn removes it. `WORKFLOW_STEP_SCRIPTS=false` turns the tool off, and a step then only calls its tools one by one.\n\n**Python jobs (`run_python_job`, `openexecutive/workflows/python_job.py`).** Monty can't run libraries, so library work on files (split or merge PDFs with pypdf, spreadsheets with openpyxl and pandas, charts with matplotlib, images with Pillow, and documents made from scratch or from files: Word with python-docx, PowerPoint with python-pptx, laid-out PDFs with fpdf2) runs as a Python job: Pyodide (Python in WebAssembly) executed by **Deno** in a process of its own per job. Pyodide alone is not a sandbox — its Python can call into the JavaScript runtime, which under plain Node reaches the server's environment, files and network — so Deno is what isolates it: it is started with read access to the sandbox folder and the worker script only, with no network, environment, writes or processes, and an empty process environment. Files go in on stdin and results come back on stdout. A job gets only what the call names: Knowledge-library files, the files attached to the chat message being answered (`attachment_files`, the uploads as sent, bound for that turn only by `POST /chat/upload` in `workflows/turn_files.py`, so the model never retypes an attachment's text), text the caller passes, and `inputs` (a dict the code reads); result files are kept 7 days under the company folder and served to the principal at `GET /python-jobs/{job}/{file}`, which the Executive links in its reply. A deployment can instead send jobs to a separate runner (`PYTHON_JOB_RUNNER_URL`, with `PYTHON_JOB_RUNNER_KEY` as a bearer token): `run_job` POSTs the same job (code, inputs, files, caps, time and memory limits) and reads back the same result object, at most as large as a local job's output, keeping only its known fields, so kept results, links and metering are unchanged; the local sandbox is then not needed, and the runner is trusted to isolate jobs. A runner can turn a job away with `{\"run_locally\": true}` (and an optional `reason`) in a non-200 reply, for example when the deployment's allowance for it is used up: the job then runs in the local sandbox if this machine has one, and otherwise fails with the runner's reason. Any other non-200 reply stays a job error, so a busy or broken runner never moves every job onto the machine. A runner with more libraries lists them in `PYTHON_JOB_EXTRA_LIBRARIES`, which the job tool's description then names, so the Executive doesn't refuse a job that needs one. The tool sits in the `workflows` tool group, labelled for jobs with or without attached files. The library set is fixed at build time: the API image installs Pyodide and Deno from npm and the compiled libraries from Pyodide's CDN, each checked against the sha256 in Pyodide's lock file, and a build smoke runs a job. Pyodide can't infer the compiled packages the pure-Python libraries import (lxml, Pillow, fonttools), so the worker loads them when a job imports docx, pptx or fpdf. Pyodide, Deno and the pure-Python libraries are pinned by hash too (an npm lock installed with `npm ci`, pip `--require-hashes`). One job runs at a time per process (200–450 MB each), with a `PYTHON_JOB_TIMEOUT_S` limit and a memory cap (`PYTHON_JOB_MEMORY_MB`, default 1536, as the process's data limit, plus V8 heap and WebAssembly memory caps); the worker returns at most 20 result files and 25 MB, and the API stops the job as soon as its reply passes that. The job runs at a lower CPU priority and is first in line if the machine runs out of memory, so a heavy job slows or loses itself rather than the API; Deno's own caches go in a temporary folder removed with the job; and kept results are capped at 200 MB in all, oldest first. The tool is chat-only, offered only on the principal's own turns (`PRINCIPAL_ONLY_TOOLS`), withheld on private turns, unattended passes and under the Act as me lockdown, and not offered at all without the sandbox (`PYTHON_JOBS_ENABLED`, `PYTHON_SANDBOX_DIR`).\n\nA job that worked can be kept the same way as a script (below): `save_as` and `description` keep its code as a Custom tool of kind `python`, and `run_python_job(tool=<name>, inputs={...})` with its files runs it again, recording the run, so a job done before costs no code-writing tokens. Python tools run only on the principal's own chat turns: they are never listed for workflow steps and never turn on for workflows (`PUT /saved-tools/{name}` answers 409), and `run_script` refuses one (and `run_python_job` a script tool). Every job writes one `python_job` audit row (`ok`, `duration_ms`, `cpu_ms` and `peak_mb` read from the process's /proc entry just before it is stopped, files and bytes in and out, attachments, the Custom tool it ran or kept), which `GET /audit/usage` sums into `python_jobs` with the model usage of the turns that ran one.\n\n**Saved tools.** A script that works can be kept to run again by name (`openexecutive/workflows/saved_tools.py`); each tool has a `kind`, `script` (`run_script`) or `python` (`run_python_job`, above). `run_script` takes `save_as` and `description` with a new script: if the script succeeds it is saved, with the set of tools it actually called, and a failed script is never saved. Later, `run_script(tool=<name>, inputs={...})` runs the saved script instead of new code, with `inputs` available to it as a dict. Only the principal's own turns save: a chat turn where the principal is speaking on a verified, interactive surface (the same test as `load_mcp_server`), never an inbound email, a teammate, an unattended run or a workflow step — a step is offered `tool=` but not `save_as`. A saved tool runs with the authority of whoever runs it, so its author must be trusted at least as much as anyone who may run it. For the same reason only a workflow step (its tools owner-approved) or the principal's own turn may run one: anyone else's chat turn is refused `tool=` and not offered `list_saved_tools`, so a stranger can neither list the principal's automations nor run one with inputs they choose. Descriptions are kept to one line of printable text (they are shown to models), and every save writes a `saved_tool_changed` audit row (`actor: executive`) beside the owner's own changes. Saving needs no approval beyond that, because a saved tool can do no more than the context running it: its calls go through the same per-call path as any script (in a step: the allowlist, budget, target check and audit), and a step runs one only when the step already allows every tool it used (otherwise the result names the `missing_tools`) and only at the version the owner turned on for workflows (`workflow_version`, Settings → Advanced → Custom tools → Use in workflows). A tool kept on a turn that read outside content could otherwise carry injected code into an unattended run, so keeping stays automatic and works in chat at once, but workflows wait for the owner; a newer save doesn't change the version workflows run, and pruning never drops it. Each step's `run_script` description lists the saved tools that step may run; chat asks `list_saved_tools`. Every save of changed content is a new version (the newest 20 are kept, plus the one that ran until then, so a rolled-back version the owner trusts survives later saves), every run is recorded (`saved_tool_runs`, the newest 200 per tool), and the owner can turn a tool off or switch it back to an earlier version on Settings → Advanced → Saved tools (`/saved-tools` routes, the owner's alone). A turned-off tool never runs, and a new version saved by the model does not turn it back on. `SAVED_TOOLS_ENABLED=false` stops saving and running saved tools everywhere.\n\n**Targets are chosen at run time — and a new one is confirmed once.** Approving a workflow approves its *tools*; which sheet, doc, recipient or URL each call hits is chosen by the model at run time, by design (a tab per month, a reply to whoever sent the invoice, a doc per client). What bounds that is the allowlist, the gateway's recipient gates, the audit digest, and **first-write confirmation**: a `TargetPolicy` (one per run) checks every call to a tool that may change things. `resource_targets` walks its arguments recursively for resource keys (snake- or camel-case ids, `to`/`cc`/`bcc`, recipients, addresses, attendees, members, users, owners, parents, URLs/links/hrefs, paths, channels, spaces, rooms, phones, hosts, buckets, tables, spreadsheet/document/folder/calendar/file); a matching key marks everything beneath it, even a `name`. Outside a resource, only a new item's own `name`/`title`/`subject`, message/thread/draft/label ids, `range`/`sheet` and workspace-mcp's acting `user_google_email` are skipped — and whatever the key, a bare value shaped like an email address, a URL or an international phone number is a target, except inside what the call writes (`rows`, `values`, `body`, `text` …). Key names are a heuristic, so this is a best-effort guard layered on the allowlist, the gateway gates and the audit. Float ids are compared as integers. Arguments too deep, naming too many targets, or holding an over-long value **fail closed** (the call is refused). A target is trusted only when it was approved for this workflow before (`workflow_approved_targets`, by value) or is an id a write in this run created — a top-level id/link field (`id`, `spreadsheetId`, `webViewLink` …) of the **structured JSON object** result of a tool whose name says it creates (create / insert / upload …) and that takes no URL — a tool whose schema couldn't be read is assumed to (free text, nested records and readers' or updaters' results are never read, so a fetched page, an echoed title, a shared page's links or a stranger in `ccRecipients` can't plant one); those survive a pause in the resume payload (`run_created`). Values written in the workflow's own text are *not* trusted, since anyone who can edit the workflow could change them without review: they are asked once, then remembered. Approvals are by value, for any of the workflow's tools, and are **cleared when the workflow's tool set changes** (a newly added tool must earn them again). Any other target makes the call **held**: it is not run and costs no budget, the model is told it is waiting for approval and carries on, and it is audited `held for approval` (at most 10 held per step, 16 KB each; an identical repeat is held once). Whether a call is checked at all follows the read-only label, which now never marks a tool whose name carries a write verb anywhere (`find_and_replace_doc`). After the step finishes, the run pauses with a `WaitForHumanEvent` to the workflow's **owner** (`owner_person_id`, the person who created it on the Workflows page or in chat; falling back to the principal if unknown or archived), `on_timeout=auto_proceed`, 48 h, and a `WorkflowResumeState` of `kind=\"held_writes\"` carrying the exact held calls. On resume (`_resume_held_writes`, fingerprint-checked like a gate, with the remaining steps' tools checked first), only `approve` runs them — each still has to be in the live step's allowlist and resolve; its targets are remembered first — and anything else (decline, timeout, unreadable) skips them; either way a *Held for approval* section is added to the step's output and the run continues at the next step. With no one to ask, held writes are skipped and noted; a step that fails or crashes after holding, or a resume that stops early (definition changed, a later tool missing), audits its held writes as dropped and says they did not run. The question quotes each target JSON-escaped (a value can't add its own lines) and always shows a URL's full scheme and host, saying how much of the rest is hidden. The owner answers by chat reply or with **Approve / Decline** on the run page (`POST /workflows/runs/{id}/decision`, which the principal may also use); remembered targets are listed and removable on the workflow page.\n\n`oe__read_document` (chat's `read_document`; saved workflows that list the old `oe__read_file` get the same tool) extracts text (PDF, Word, Excel, CSV, Markdown, text) only from files under `WORKFLOW_FILE_DIRS` or the company documents folder (default: workspace-mcp's attachment folder), resolving symlinks and `..` before the check (`tool_catalog.resolve_readable_file`, shared with the Executive's `read_document` tool). A scanned PDF is converted by `knowledge.pdf_reader` instead of failing as \"may be a scanned image\"; one that still cannot be read returns the reason. Action steps are allowed in scheduled workflows. Because they have external side effects, a resumed run heartbeats its claim (`touch_resume_claim`, at most once a minute as events flow — each tool call emits one; a busy database is retried on the next heartbeat, never treated as a lost claim; the sweep's requeue re-checks the claim's age in the same UPDATE, so a heartbeat landing between the sweep's read and its write wins), so the stale-claim sweep never requeues and replays a slow but live run, and a worker that finds its claim superseded stops at its next event. A worker that actually crashes mid-resume is still requeued; its action steps then run again, so goals should say how to avoid duplicates (the actor reads current state before writing). `GET /workflows/tools/search?q=` and `GET /workflows/tools/describe?names=` back the advanced editor's tool picker and the review card's labels.\n\nAn optional cadence (`daily@` / `weekly@` / `quarterly@`) re-uses the scheduler via the `dynamic_workflow` action kind, which runs the workflow on schedule and DMs the artifact to a rostered recipient. A gate followed by further steps pauses at `awaiting_human` and then resumes once answered, so gates no longer have to sit immediately before synthesis. They remain forbidden in cadence-enabled definitions: a scheduled fire has no interactive human to ask.\n\n`executive_research` keeps only its Markdown artifact in the run history; `parse_artifact_findings` reads its \"Findings reviewed\" lines back as `{severity, confidence, specialist, title, summary}` for Home's first-week card (see Today).\n\nBuilt-ins the system runs on its own (`morning_brief`, `end_of_day_digest`, `executive_reflection`, `executive_research`) set `background = True`, surfaced as `WorkflowMeta.background`; the `/jobs` ready-made list files them under a **System** chip instead of the default view. They stay runnable by hand.\n\n**Quick workflows** (`workflows/quick.py`) are one per playbook in effect that no built-in or custom workflow follows (switched-off custom ones count). They are derived whenever the catalog is read, never stored: `list_workflows()` returns built-ins, then Quick ones, then active custom ones, and `get_workflow` resolves a `quick_<playbook>` name after the registry (custom workflows may not take the `quick_` prefix). Each has one required field, `request`, and two steps: **Load context** (company profile plus RAG for the playbook category's specialist) and **Draft** (that specialist writes one Markdown document following the playbook). `WorkflowMeta.quick` is true for them. The 8 built-in playbooks no built-in follows are Quick workflows: board update memo, 1:1 agenda, layoff comms plan, positioning statement, post-mortem, customer interview plan, feature prioritization and market sizing. A company's own playbook shows up as one, hiding a built-in drops it, and a custom workflow that starts following one replaces it. If custom workflows can't be read, none are offered, since their followers are unknown.\n\n**Workflows vs. playbooks.** `/jobs` has two tabs: **Build** (`?tab=catalog`, the default) and **Runs** (`/skills` redirects to `/jobs`). A playbook is a skill (`knowledge/skills_repo.py`): *how* the Executive does a piece of work, with no inputs, schedule or side effects. A workflow is the runnable job. Workflows **follow** playbooks: a step that follows one gets its body appended to the step prompt via `workflows/playbooks.py` (`load_playbook` + `playbook_clause`). Six built-ins do — `board_prep` (`board-prep-deck`), `quarterly_plan` (`quarterly-okr-set`, `quarterly-forecast`), `mbr` (`monthly-business-review`, in the financial, KPI and function steps), `competitive_teardown` (`competitive-teardown`, in the four analysis steps), `fundraising_prep` (`fundraise-narrative`, narrative step) and `exec_search_brief` (`role-scorecard`, profile step). Each declares them in `Workflow.playbooks`; a unit test holds that declaration equal to the `load_playbook(\"…\")` calls in the module, and `WorkflowMeta.playbooks` exposes it. A custom workflow's `specialist` step may name a `playbook` (validated to exist at save; appended after `{field}` rendering, so braces in a playbook are never treated as placeholders). The lookup resolves the playbook in effect, so a company's customized copy changes the workflow's output, and a hidden, missing or malformed one falls back to the step's own prompt plus RAG — a workflow never fails over a playbook (`load_playbook` catches everything; a custom step whose playbook is unavailable emits a `progress` event saying so). Because an approved scheduled workflow reads its playbook at each run, chat never creates or changes a playbook: it saves repeatable work as a workflow (`draft_workflow`, confirmed by the user), and only a person can change what a workflow follows: a workflow's page shows each playbook it follows as **How it's done** (`components/jobs/HowItsDone.tsx`), with **Edit** (`PUT /skills/{name}`; on a built-in that saves the company's customized copy) and, for a customized copy, **Reset to original** (`DELETE`, which reverts). The chat summary of a drafted workflow names each step's playbook. `playbook_users()` maps each playbook to the workflows that follow it — built-ins, every custom workflow (switched-off ones included: turning one on approves its definition) and the Quick ones; the skills API reports it as `used_by`, and the Executive's `search_skills` hits carry it as `workflows`.\n\nCompleted artifacts are discoverable in the unified artifacts section (`/artifacts`, labelled **Documents** in the UI) alongside their run-detail page at `/jobs/runs/{run_id}`. A run someone starts by hand (`POST /workflows/{name}/runs`, `run_workflow`, research in chat) stores them as `workflow_runs.owner_person_id` and its history and output are theirs alone (plus the person a gate waits on); scheduled and system runs keep no owner and stay the team's. Workflow output stays Markdown — the scheduler DMs it and reflection rereads it as text — and gains other formats only on the way out: any run can be downloaded as Word (`/artifacts/run:<id>/download?as=docx`), and the Executive can repackage one with `get_artifact` → `draft_artifact(format=…, supersedes=\"run:<id>\")`.\n\n## Data-driven retrospectives\n\n`engagement_value_report` introduces a new workflow pattern: instead of the user typing the substance into a form (the `investor_update` / `mbr` shape), the workflow **reads its substance from the database**. A deterministic gatherer (`clients/engagement_activity.py`) pulls the period's decisions, initiatives, advisory consultations, delivered workflow artifacts (excluding prior value reports), follow-through counts, and alerts handled — from the live DB for the active client, or a parked client slot's `state.db` opened read-only. A single board-comms call narrates those facts (the prompt forbids inventing anything not in them; an empty period skips the LLM entirely), and the artifact's lists are assembled deterministically. Built for renewal conversations — the engagement record is the evidence.\n\nWith Take the lead as the Executive on (`orchestrator.take_the_lead`), reflection and research build their toolkit through `unattended_toolkit(..., source=...)`. That keeps solo's booking and `run_workflow` tools and an unrestricted `message_person` (teammates as well as the principal). Every acting tool goes through the gate, and a held action waits on Today as a `take_the_lead_action` decision. Reflection also gets the MCP gateway's `search_tools` and `call_tool` (`_with_lead_tools`; `call_tool` behind the gate, `load_mcp_server` left out), so it can find and use whatever the deployment has connected, such as building a sheet to track something. A note in the user turn (never the cached system prompt) tells it to act rather than only report, and it gets more room: 10 iterations, 4000 tokens, and tool results up to 4000 characters. The grounding check still refuses outward text naming people or figures the pass didn't see. New mail and chat also wake the reflection early (scheduler section). In training (`take_the_lead.training`) every acting call that isn't allowed waits too, as a training card for the principal, and both passes append `take_the_lead.learned_note()` to their user turn: that it's in training, and the principal's own edits on earlier cards as examples of how they want those done (never in the cached system blocks).","mermaid": "flowchart TD\n Input[\"Structured input\"]\n Steps[\"Ordered named steps\"]\n Wait[\"wait_for_human pause\"]\n Sched[\"workflow_runs<br/>(awaiting_human)\"]\n Resolver[\"inbound_resolver<br/>+ resumer\"]\n Artifact[\"Markdown artifact<br/>(workflow_runs.artifact)\"]\n Today[\"Today / Documents\"]\n Input --> Steps\n Steps --> Wait\n Wait --> Sched\n Sched -- \"human reply\" --> Resolver\n Resolver -- \"resolved → claim\" --> Steps\n Steps -- \"complete_run\" --> Artifact\n Artifact --> Today\n class Input entry\n class Steps compute\n class Wait compute\n class Sched storage\n class Resolver compute\n class Artifact storage\n class Today external",- "generated_at": "2026-10-21T17:54:33.773956+00:00"+ "generated_at": "2026-10-21T18:26:32.956652+00:00"}diff --git a/packages/core/openexecutive/config.py b/packages/core/openexecutive/config.pyindex 2b5a0efb..607c8be6 100644--- a/packages/core/openexecutive/config.py+++ b/packages/core/openexecutive/config.py@@ -1223,6 +1223,12 @@ class Settings(BaseSettings):delegation_handle_it_max_sends_per_day: int = Field(20, alias="DELEGATION_HANDLE_IT_MAX_SENDS_PER_DAY", ge=1, le=500)+ # Workflows that send email as their creator (delegation.workflow_email,+ # oe__send_email_as_me): the most such emails a day per person, within+ # the drafts limit above. Past it the step is told to stop.+ delegation_workflow_max_sends_per_day: int = Field(+ 20, alias="DELEGATION_WORKFLOW_MAX_SENDS_PER_DAY", ge=1, le=500+ )# Whether the owner may let team members use Act as me for themselves# (Delegate → Act as me → "Let team members use it", off until they turn# it on). Off: the owner alone, as before (delegation.settings).diff --git a/packages/core/openexecutive/delegation/drafts.py b/packages/core/openexecutive/delegation/drafts.pyindex a3944856..56af0dec 100644--- a/packages/core/openexecutive/delegation/drafts.py+++ b/packages/core/openexecutive/delegation/drafts.py@@ -30,7 +30,10 @@ logger = logging.getLogger(__name__)SOURCE_CHAT = "chat"SOURCE_INBOX = "inbox"-_SOURCES = frozenset({SOURCE_CHAT, SOURCE_INBOX})+# Written and sent by a workflow as its creator (delegation.workflow_email);+# a workflow's drafts for the person to send are SOURCE_CHAT, like a chat draft.+SOURCE_WORKFLOW_SENT = "workflow_sent"+_SOURCES = frozenset({SOURCE_CHAT, SOURCE_INBOX, SOURCE_WORKFLOW_SENT})# How far back ``settle_waiting`` looks for chat drafts still open. The# briefs only name drafts from their own window (today, or since the lastdiff --git a/packages/core/openexecutive/delegation/reply_send.py b/packages/core/openexecutive/delegation/reply_send.pyindex 3bd5468e..1ec54ba5 100644--- a/packages/core/openexecutive/delegation/reply_send.py+++ b/packages/core/openexecutive/delegation/reply_send.py@@ -1,11 +1,13 @@"""Send a reply the inbox watcher drafted, when the person taps Send, or-on its own under Handle it for me.+on its own under Handle it for me, or an email a workflow wrote as its+creator.-The one path in Act as me that sends anything, and all it can send is the-exact draft on a ``delegation_reply`` card, by its id-(``DelegateGmail.send_draft`` posts ``{"id": ...}`` to ``drafts.send``;-``DelegateOutlook.send_draft`` posts nothing to that draft's ``send``). Two-callers reach it, and a unit test walks the code to keep it that way:+The one path in Act as me that sends anything, and all it can send is a+draft by its id: the exact draft on a ``delegation_reply`` card, or the one a+workflow step just wrote (``DelegateGmail.send_draft`` posts ``{"id": ...}``+to ``drafts.send``; ``DelegateOutlook.send_draft`` posts nothing to that+draft's ``send``). Three callers reach it, and a unit test walks the code to+keep it that way:- ``send_approved_reply``, after the person approved that card(``POST /decisions/{id}/approve``, a class only the card's own person sees@@ -19,7 +21,17 @@ callers reach it, and a unit test walks the code to keep it that way:anything the tap path would ask a second yes for.The watcher runs inside the scheduler's pause gate, so a pause stops it.-No model, chat turn, workflow or MCP call can reach either.+- ``send_for_workflow``, called only by ``workflow_email``'s+ ``oe__send_email_as_me``: a workflow its creator saved, from a session the+ API knows is theirs, with that tool in it (``workflow_email.save_refusal``),+ sending the draft it wrote a moment ago to the people it was written to.+ It checks again that Act as me is on, the API can tie a save to a person+ (``handle_it.signing_ok``), no client slot is active, and the draft is+ unchanged, addressed as written, from their own address and never to the+ Executive's.++No model, chat turn or MCP call can reach any of them, and no workflow but+through ``oe__send_email_as_me``.At send time it checks again, in this order:@@ -571,3 +583,57 @@ def _note_sent(person_id: int, message: Any, thread: Any, recipients: list[str],task.add_done_callback(_NOTE_TASKS.discard)except Exception as exc:logger.warning("delegation.reply_send: couldn't start noting a sent reply (%s)", type(exc).__name__)+++async def send_for_workflow(person: Any, client: Any, *, draft_id: str, recipients: list[str]) -> str:+ """Send the draft ``draft_id`` a workflow step just wrote as ``person``,+ to exactly ``recipients``. Returns the sent message's id; raises+ ``SendRefused`` (``send_unconfirmed`` when the mailbox didn't say whether+ it went). The caller (``workflow_email``) checked who and the limits."""+ from openexecutive.config import get_settings+ from openexecutive.delegation import handle_it+ from openexecutive.delegation.gmail import (+ STATUS_MESSAGES,+ GmailAuthError,+ GmailError,+ normalize_email,+ )+ from openexecutive.delegation.inbox import _client_slot_active+ from openexecutive.delegation.settings import can_delegate, is_enabled+ from openexecutive.delegation.threads import MAX_RECIPIENTS++ if person is None or person.id is None or not person.email or not can_delegate(person):+ raise SendRefused(403, "not_yours", _NOT_YOURS)+ if not is_enabled(person.id):+ raise SendRefused(409, "act_as_me_off", "Act as me is off.")+ if not handle_it.signing_ok():+ raise SendRefused(409, "caller_signing_required", handle_it.REASONS["signing_off"])+ if _client_slot_active():+ raise SendRefused(409, "client_slot", "Sending is paused while a client is active.")+ email = normalize_email(person.email)+ try:+ draft = await client.get_draft(draft_id)+ own = {email, *(normalize_email(a) for a in await client.send_as_addresses())}+ except GmailError as exc:+ raise SendRefused(502, "gmail_error", "Couldn't read the draft in their mailbox.") from exc+ if draft is None:+ raise SendRefused(409, "draft_gone", "The draft isn't in their mailbox any more.")+ sent_to = sorted({normalize_email(a) for a in [*draft.message.to, *draft.message.cc, *draft.message.bcc]})+ exec_address = normalize_email(get_settings().exec_email_address)+ if not sent_to or sent_to != sorted({normalize_email(a) for a in recipients}):+ raise SendRefused(409, "recipients_changed", "The draft's recipients aren't the ones it was written to.")+ if len(sent_to) > MAX_RECIPIENTS:+ raise SendRefused(409, "too_many_recipients", f"At most {MAX_RECIPIENTS} recipients.")+ if exec_address and exec_address in sent_to:+ raise SendRefused(409, "executive_recipient", "It is addressed to the Executive's own mailbox.")+ if normalize_email(draft.message.from_addr) not in own:+ raise SendRefused(409, "not_from_you", "The draft isn't from one of their own addresses.")+ try:+ sent = await client.send_draft(draft_id)+ except GmailError as exc:+ if exc.maybe_done:+ raise SendRefused(502, "send_unconfirmed", "Their mailbox didn't confirm it was sent.") from exc+ if isinstance(exc, GmailAuthError):+ raise SendRefused(409, "gmail_needs_reconnect", STATUS_MESSAGES["needs_reconnect"]) from exc+ raise SendRefused(502, "gmail_error", "Their mailbox refused to send it. Nothing was sent.") from exc+ return str(sent.id or "")diff --git a/packages/core/openexecutive/delegation/workflow_email.py b/packages/core/openexecutive/delegation/workflow_email.pynew file mode 100644index 00000000..0830697a--- /dev/null+++ b/packages/core/openexecutive/delegation/workflow_email.py@@ -0,0 +1,471 @@+"""Workflows that email as their creator (Act as me): ``oe__draft_email_as_me``+saves a draft in the creator's own mailbox for them to send, and+``oe__send_email_as_me`` sends it. Which one a step has is the choice the+creator made when they saved the workflow ("Draft for me to send" or "Send+as me"); a workflow that emails from the Executive's own address uses the+gateway's mail tools, as before.++Both write in the creator's voice (``ghostwriter.compose``, as chat's+``ghostwrite_email`` does) and are fenced in code:++- **Whose mailbox.** Always the workflow's creator (``dynamic_store.get_owner``),+ never an address the step names. Nothing is written on a run someone else+ started by hand, by a speaker the roster can't place, by one of the+ Executive's own unattended passes (``chat_tools.started_by_a_pass``), or+ when another person's workflow started this one (``chat_tools.running``): the email+ would be in the creator's name on someone else's say-so. A scheduled run+ (nobody's) writes as the creator.+- **Only when they turned it on.** The creator may use Act as me+ (``settings.can_delegate``), turned it on (``settings.is_enabled``) and+ their own mailbox is connected (``gmail_status``). Otherwise the call fails+ telling the step to use the Executive's own email, and nothing is written.+- **Sending needs more.** A workflow with ``oe__send_email_as_me`` can only+ be saved or switched on by its creator, from a session the API knows is+ theirs (``save_refusal``: ``verified.caller_refusal``, the rule Send on a+ reply card uses), and nobody else may change it. At send time the API must+ still be able to tie a save to a person (``handle_it.signing_ok``), and the+ draft goes through ``reply_send.send_for_workflow``, the one send path.+- **First email to a new address asks once.** ``to`` and ``cc`` are write+ targets, so a step's first email to an address waits for the creator's+ approval (``action_step.TargetPolicy``), then is remembered.+- **Capped.** Every draft counts against ``DELEGATION_MAX_DRAFTS_PER_DAY``+ (shared with chat and the inbox, ``caps``), and sends against+ ``DELEGATION_WORKFLOW_MAX_SENDS_PER_DAY`` as well.+- **Private.** The result the step sees (and the run's report) names who it+ is to, the subject and a link, never the body. The audit row is the+ creator's alone.+"""+from __future__ import annotations++import asyncio+import json+import logging+import re+from dataclasses import dataclass+from datetime import UTC, datetime+from typing import Any++logger = logging.getLogger(__name__)++# The composer's model call plus the mailbox calls; longer than a step's+# default so a slow composer doesn't cut a send short.+TIMEOUT_S = 300.0+DRAFT_TOOL = "oe__draft_email_as_me"+SEND_TOOL = "oe__send_email_as_me"+TOOLS = frozenset({DRAFT_TOOL, SEND_TOOL})+MAX_INTENT_CHARS = 4000+_EMAIL_RE = re.compile(r"[\w.+\-]+@[\w\-]+(?:\.[\w\-]+)+")++# The step's report says so, and a step that also has the gateway's mail+# tools can fall back on its own.+_FALL_BACK = " Use the Executive's own email for this instead, if this step has a tool for it."++_WHAT = (+ "Pass `to` (and optionally `cc`) and `intent`: the points, figures and dates "+ "the email should carry, from this run's results. The tool writes the subject "+ "and the words. Works only when they connected their own mailbox under Act as "+ "me; otherwise use the Executive's own email."+)+DRAFT_DESCRIPTION = (+ "Write an email AS the person who created this workflow, in their own voice, "+ "saved as a DRAFT in their own mailbox (Gmail or Outlook) for them to review "+ "and send themselves. It never sends anything. " + _WHAT+)+SEND_DESCRIPTION = (+ "Write an email AS the person who created this workflow, in their own voice, "+ "and SEND it from their own mailbox (Gmail or Outlook). Use only when they "+ "chose to have this workflow send as them. " + _WHAT+)+INPUT_SCHEMA: dict[str, Any] = {+ "type": "object",+ "properties": {+ "to": {"type": "array", "items": {"type": "string"}, "description": "Recipient email addresses."},+ "cc": {"type": "array", "items": {"type": "string"}, "description": "Optional Cc addresses."},+ "intent": {+ "type": "string",+ "description": "What the email should say: the points, decision, dates and figures, in plain words.",+ },+ },+ "required": ["to", "intent"],+}++# Sends being made right now, per person: counted with today's, so two runs+# at once can't both take the last one.+_SENDING: dict[int, int] = {}+++def available_for(person_id: int | None) -> bool:+ """Whether ``person_id``'s workflows may write as them: they may use Act+ as me and turned it on. Their mailbox is checked when one is written.+ Never raises."""+ from openexecutive.delegation.settings import can_delegate, is_enabled+ from openexecutive.people.store import get_person++ if person_id is None:+ return False+ try:+ return can_delegate(get_person(person_id)) and is_enabled(person_id)+ except Exception:+ logger.warning("workflow email: couldn't read the setting", exc_info=True)+ return False+++def sends(defn: Any) -> bool:+ """Whether a workflow definition has a step that sends as its creator."""+ return any(SEND_TOOL in (getattr(step, "tools", None) or []) for step in getattr(defn, "steps", []))+++def save_refusal(defn: Any, caller: Any, owner_id: int | None) -> str | None:+ """Why ``caller`` may not save or switch on ``defn`` with its creator+ ``owner_id``, or None. Only a workflow that sends as its creator is+ checked: then the caller must be that creator, and the API must know it+ (``verified.caller_refusal``). Never raises; a lookup that fails refuses."""+ from openexecutive.delegation.gmail import normalize_email+ from openexecutive.delegation.verified import NOT_YOURS, caller_refusal+ from openexecutive.people.store import get_person++ if not sends(defn):+ return None+ try:+ owner = get_person(owner_id) if owner_id is not None else None+ refused = caller_refusal(caller, normalize_email(owner.email)) if owner is not None else NOT_YOURS+ except Exception:+ logger.warning("workflow email: couldn't check who is saving", exc_info=True)+ refused = NOT_YOURS+ if refused is None:+ return None+ if refused == NOT_YOURS:+ return (+ "Only the person who created this workflow can save or switch on a workflow "+ "that sends email as them."+ )+ return (+ "A workflow that sends email as you needs signed sign-ins on this server, so "+ "nobody else can save one in your name. Have it save drafts for you to send instead."+ )+++def _error(message: str, **extra: Any) -> str:+ return json.dumps({"error": message, **extra})+++def _addresses(raw: Any, field: str) -> list[str] | str:+ if raw is None:+ return []+ items = raw if isinstance(raw, list) else [raw]+ wanted = [str(a).strip().lower() for a in items if isinstance(a, str) and a.strip()]+ malformed = [a for a in wanted if not _EMAIL_RE.fullmatch(a)]+ if malformed:+ return f"Not an email address in `{field}`: {', '.join(malformed[:5])}."+ return list(dict.fromkeys(wanted))+++def _someone_else(creator_id: int, chain: tuple[str, ...]) -> bool:+ """Whether someone other than the creator is behind this run: a run they+ started by hand, a speaker the roster can't place, one of the+ Executive's own unattended passes (its context is inbound or stored text+ with nobody watching), or another person's workflow that started this one."""+ from openexecutive.orchestrator.artifact_records import runs_refused_for_nobody, turn_owner+ from openexecutive.workflows.chat_tools import started_by_a_pass+ from openexecutive.workflows.dynamic_store import get_owner++ if runs_refused_for_nobody() or started_by_a_pass():+ return True+ runner = turn_owner()+ if runner is not None and runner != creator_id:+ return True+ return any(get_owner(name) != creator_id for name in chain)+++def _roster_by_email(include_contacts: bool) -> dict[str, Any]:+ from openexecutive.people.store import list_people++ people = list_people(include_contacts=include_contacts)+ return {a.lower(): p for p in people for a in [p.email, *p.email_aliases] if a}+++def _recipient(email: str, roster: dict[str, Any]) -> Any:+ from openexecutive.delegation.ghostwriter import Recipient++ person = roster.get(email)+ if person is None:+ return Recipient(email=email)+ relation = "on their team" if person.kind == "team" else "one of their contacts"+ if person.role:+ relation = f"{relation}, {person.role}"+ return Recipient(email=email, name=person.full_name, relation=relation)+++def _audit(person_id: int, event: str, summary: str, details: dict[str, Any]) -> None:+ from openexecutive.audit import log_event++ log_event(+ event, summary, actor="executive",+ details={"person_id": person_id, "source": "workflow", **details},+ private=True, private_to_person=person_id,+ )+++@dataclass+class _Ask:+ person: Any+ email: str+ client: Any+ to: list[str]+ cc: list[str]+ intent: str+++async def _ask(tool_input: dict[str, Any], *, mailbox: Any) -> _Ask | str:+ """Who writes, to whom, and what: or the error result."""+ from openexecutive.delegation.gmail import (+ STATUS_MESSAGES,+ gmail_for,+ gmail_status,+ normalize_email,+ )+ from openexecutive.delegation.settings import can_delegate, is_enabled+ from openexecutive.delegation.threads import MAX_RECIPIENTS+ from openexecutive.people.store import get_person+ from openexecutive.workflows.chat_tools import running++ chain, creator_id = running()+ if creator_id is None:+ return _error("This workflow has no creator on record to write as." + _FALL_BACK)+ if _someone_else(creator_id, chain):+ return _error(+ "Only the person who created this workflow can have it write as them, "+ "and someone else is behind this run." + _FALL_BACK+ )+ try:+ person = get_person(creator_id)+ except Exception:+ logger.warning("workflow email: roster unreadable", exc_info=True)+ return _error("Couldn't read the People list just now. Try again later.")+ if not can_delegate(person) or not is_enabled(creator_id):+ return _error("Its creator hasn't turned on Act as me (writing email as them)." + _FALL_BACK)+ if person is None or person.id is None: # can_delegate checked both; for the type checker+ return _error("I can't tell whose mailbox this is.")++ intent = str(tool_input.get("intent") or "").strip()+ if not intent:+ return _error("Pass `intent`: what the email should say.")+ if len(intent) > MAX_INTENT_CHARS:+ return _error(f"`intent` is too long (at most {MAX_INTENT_CHARS} characters).")+ to = _addresses(tool_input.get("to"), "to")+ if isinstance(to, str):+ return _error(to)+ cc = _addresses(tool_input.get("cc"), "cc")+ if isinstance(cc, str):+ return _error(cc)+ cc = [a for a in cc if a not in to]+ if not to:+ return _error("Pass `to`: who the email is for.")+ if len(to) + len(cc) > MAX_RECIPIENTS:+ return _error(f"At most {MAX_RECIPIENTS} recipients.")++ email = normalize_email(person.email)+ try:+ client = mailbox if mailbox is not None else gmail_for(email)+ except Exception:+ logger.warning("workflow email: couldn't open the mailbox", exc_info=True)+ return _error("Couldn't open their mailbox just now." + _FALL_BACK)+ status = await gmail_status(email, gmail=client)+ if status != "connected":+ return _error(STATUS_MESSAGES[status] + _FALL_BACK, status=status)+ return _Ask(person=person, email=email, client=client, to=to, cc=cc, intent=intent)+++def _send_slot(person_id: int) -> str | None:+ """Take one of today's sends for ``person_id``, or say why not.+ Synchronous: nothing runs between the check and the take."""+ from openexecutive.config import get_settings+ from openexecutive.delegation import drafts++ start = datetime.now(UTC).replace(hour=0, minute=0, second=0, microsecond=0)+ try:+ today = drafts.count_since(person_id, start, source=drafts.SOURCE_WORKFLOW_SENT)+ except Exception:+ logger.warning("workflow email: can't count today's sends — refusing", exc_info=True)+ return "Couldn't check today's sending limit just now. Try again later."+ if today + _SENDING.get(person_id, 0) >= get_settings().delegation_workflow_max_sends_per_day:+ return "Today's limit of emails sent as them from workflows is reached." + _FALL_BACK+ _SENDING[person_id] = _SENDING.get(person_id, 0) + 1+ return None+++def _send_done(person_id: int) -> None:+ left = _SENDING.get(person_id, 0) - 1+ if left > 0:+ _SENDING[person_id] = left+ else:+ _SENDING.pop(person_id, None)+++async def _write(ask: _Ask, *, sending: bool) -> str:+ """Compose, save the draft, and send it when ``sending``. Never raises."""+ from openexecutive.config import get_settings+ from openexecutive.delegation import caps, drafts+ from openexecutive.delegation.ghostwriter import ComposeError, compose+ from openexecutive.delegation.gmail import (+ STATUS_MESSAGES,+ DraftSpec,+ GmailAuthError,+ GmailError,+ mailbox_link,+ )+ from openexecutive.delegation.reply_send import SendRefused, send_for_workflow+ from openexecutive.delegation.training import example_for+ from openexecutive.delegation.voice import composer_model, get_voice, render_voice_block+ from openexecutive.memory.history_drafts import notes_for_draft++ person, settings = ask.person, get_settings()+ if sending:+ refused_send = _send_slot(person.id)+ if refused_send is not None:+ return _error(refused_send)+ refused = caps.reserve(person.id, settings.delegation_max_drafts_per_day)+ if refused is not None:+ if sending:+ _send_done(person.id)+ if refused == caps.UNCOUNTABLE:+ return _error("Couldn't check today's draft limit just now. Try again later.")+ return _error("Today's limit of drafts written as them is reached." + _FALL_BACK)+ saved = False+ try:+ roster = _roster_by_email(include_contacts=bool(person.is_principal))+ recipients = [*ask.to, *ask.cc]+ stored = get_voice(person.id)+ names = (person.full_name or "").split()+ composed = await compose(+ writer_name=" ".join(names) or ask.email,+ voice_block=render_voice_block(stored.profile, first_name=names[0] if names else "them"),+ thread_text=None,+ reply_subject=None,+ writer_noted=notes_for_draft(person.id, recipients),+ intent=ask.intent,+ recipients=[_recipient(a, roster) for a in recipients],+ signature=stored.profile.signature,+ exec_name=settings.exec_display_name,+ model=composer_model(),+ writer_example=example_for(person.id, recipients[0]) if len(recipients) == 1 else None,+ )+ if not composed.subject:+ return _error("The email came back without a subject. Try again with a clearer intent.")+ draft = await ask.client.create_draft(DraftSpec(+ to=ask.to, cc=ask.cc, subject=composed.subject, body=composed.body, thread_id=None,+ in_reply_to=None, references=None, from_name=" ".join(names),+ ))+ saved = True+ except GmailAuthError:+ return _error(STATUS_MESSAGES["needs_reconnect"] + _FALL_BACK, status="needs_reconnect")+ except (GmailError, ComposeError):+ logger.warning("workflow email: drafting failed", exc_info=True)+ return _error("Couldn't write the email just now. Try again later.")+ except Exception:+ # The composer's model call and the voice/notes reads raise their own errors.+ logger.warning("workflow email: drafting failed unexpectedly", exc_info=True)+ return _error("Couldn't write the email just now. Try again later." + _FALL_BACK)+ finally:+ caps.release(person.id, saved=saved)+ if sending and not saved:+ _send_done(person.id)++ source = drafts.SOURCE_WORKFLOW_SENT if sending else drafts.SOURCE_CHAT+ try:+ # A send's row is written before it goes: the daily limit counts it+ # even if the send then fails, never the other way round.+ drafts.record(+ person.id, source=source, thread_id=None,+ draft_id=draft.draft_id, message_id=draft.message_id, now=datetime.now(UTC),+ )+ except Exception:+ logger.warning("workflow email: couldn't record the draft", exc_info=True)+ if sending:+ _send_done(person.id)+ return _error(+ "The email is saved as a draft in their mailbox but wasn't sent, because "+ "today's sends couldn't be counted. Say it is waiting in their Drafts."+ )+ sent_id = ""+ if sending:++ async def send_and_record() -> str:+ try:+ sent = await send_for_workflow(+ person, ask.client, draft_id=draft.draft_id, recipients=[*ask.to, *ask.cc],+ )+ if sent:+ try:+ drafts.mark_sent(person.id, draft.draft_id, sent)+ except Exception:+ logger.warning("workflow email: couldn't record the send", exc_info=True)+ return sent+ finally:+ _send_done(person.id)++ try:+ # Shielded: a step timeout must not cancel between the mailbox+ # accepting the send and recording it, or the email goes while+ # the step sees a plain timeout and may write it again.+ sent_id = await asyncio.shield(asyncio.ensure_future(send_and_record()))+ except SendRefused as exc:+ _safe_audit(person.id, "delegation_workflow_send_refused", f"A workflow email as person {person.id} wasn't sent", {+ "draft_id": draft.draft_id, "code": exc.code,+ })+ if exc.code == "send_unconfirmed":+ return _error(+ "Their mailbox didn't confirm the email was sent. Don't try again: say it "+ "may have gone and they should check their Sent folder."+ )+ return _error(+ f"The email wasn't sent: {exc.message} It is waiting in their Drafts; say so in your report."+ )++ details = {"draft_id": draft.draft_id, "recipients": len(recipients), "flags": list(composed.flags)}+ if sending:+ _safe_audit(person.id, "delegation_workflow_sent", f"Sent an email as person {person.id} from a workflow", {+ **details, "sent_message_id": sent_id,+ })+ else:+ _safe_audit(person.id, "delegation_drafted", f"Drafted an email as person {person.id} from a workflow", details)+ outside = [a for a in recipients if a not in roster]+ return json.dumps({+ "status": "sent" if sending else "drafted",+ "to": ask.to,+ "cc": ask.cc,+ "subject": composed.subject,+ **({} if sending else {+ "link": mailbox_link(ask.email, message_id=draft.message_id, draft_id=draft.draft_id),+ "open_questions": list(composed.open_questions),+ }),+ **({"not_in_people": outside} if outside else {}),+ "note": (+ "Sent from their own mailbox, as them. Say in your report who it went to and the subject."+ if sending else+ "Saved as a draft in their own mailbox; nothing was sent. Say in your report that it "+ "is waiting in their Drafts for them to review and send."+ ),+ })+++def _safe_audit(person_id: int, event: str, summary: str, details: dict[str, Any]) -> None:+ try:+ _audit(person_id, event, summary, details)+ except Exception:+ # The email is written: an error here would only invite a second one.+ logger.warning("workflow email: couldn't audit", exc_info=True)+++async def handle_draft_email_as_me(tool_input: dict[str, Any], *, mailbox: Any = None) -> str:+ """``oe__draft_email_as_me``. ``mailbox`` replaces the creator's own+ client (tests). Never raises."""+ ask = await _ask(tool_input, mailbox=mailbox)+ return ask if isinstance(ask, str) else await _write(ask, sending=False)+++async def handle_send_email_as_me(tool_input: dict[str, Any], *, mailbox: Any = None) -> str:+ """``oe__send_email_as_me``. ``mailbox`` replaces the creator's own client+ (tests). Never raises."""+ ask = await _ask(tool_input, mailbox=mailbox)+ return ask if isinstance(ask, str) else await _write(ask, sending=True)diff --git a/packages/core/openexecutive/orchestrator/workflow_authoring_tools.py b/packages/core/openexecutive/orchestrator/workflow_authoring_tools.pyindex 40f405fb..4510f0f3 100644--- a/packages/core/openexecutive/orchestrator/workflow_authoring_tools.py+++ b/packages/core/openexecutive/orchestrator/workflow_authoring_tools.py@@ -71,7 +71,11 @@ DEFINITION_SCHEMA: dict[str, Any] = {"tools — 'tools' is the exact list of tool names the step may call, e.g. ""'google_workspace__append_table_rows' or 'oe__read_document'. The tools you ""use in chat are available to steps as 'oe__<name>', e.g. "- "'oe__send_slack_dm', 'oe__web_search' or 'oe__run_workflow'; max_tool_calls "+ "'oe__send_slack_dm', 'oe__web_search' or 'oe__run_workflow'. To email as "+ "the user (only when they turned on Act as me and connected their "+ "mailbox): 'oe__draft_email_as_me' saves a draft for them to send, "+ "'oe__send_email_as_me' sends it as them; ask which they want, or the "+ "Executive's own email, when it isn't clear; max_tool_calls ""is optional — omit it for the default budget), ""'approval_gate' {id,title,person_id,question,timeout_hours?,on_timeout?}, ""or 'synthesis' {id,title,instructions?,specialist?}. "@@ -287,6 +291,7 @@ async def handle_save_workflow(tool_input: dict[str, Any]) -> str:from openexecutive.audit import log_event as audit_logfrom openexecutive.config import get_settingsfrom openexecutive.delegation.lockdown import outside_reach_refusal+ from openexecutive.delegation.workflow_email import sends as sends_as_creatorfrom openexecutive.workflows.dynamic_store import get_definition, save_if_unchangedif (refused := outside_reach_refusal("save_workflow")) is not None:@@ -313,6 +318,17 @@ async def handle_save_workflow(tool_input: dict[str, Any]) -> str:approved_error = _approved_tool_workflow_error(defn.name, existing)if approved_error is not None:return json.dumps({"error": approved_error})+ if existing is not None and (sends_as_creator(existing) or sends_as_creator(defn)):+ # Only its creator, verified, may change one that sends+ # (workflow_email.save_refusal), and chat can't verify anyone: nor+ # may chat add a send to an existing one, which would send as its+ # creator, not as whoever asked.+ base = get_settings().ui_base_url.rstrip("/")+ return json.dumps({"error": (+ f"{defn.name!r} would send email as the person who created it, so it can't be "+ "replaced from chat. Pick a different name, or tell the user to edit it at "+ f"{base}/jobs/new?edit={defn.name}"+ )})overwrite = bool(tool_input.get("overwrite", False))if existing is not None and not overwrite:diff --git a/packages/core/openexecutive/workflows/chat_tools.py b/packages/core/openexecutive/workflows/chat_tools.pyindex 1b3f512f..e9e9c99e 100644--- a/packages/core/openexecutive/workflows/chat_tools.py+++ b/packages/core/openexecutive/workflows/chat_tools.py@@ -200,11 +200,21 @@ def workflow_name_for(chat_name: str) -> str:# the innermost one (set by ``action_step._dispatch``)._chain: contextvars.ContextVar[tuple[str, ...]] = contextvars.ContextVar("workflow_chain", default=())_creator: contextvars.ContextVar[int | None] = contextvars.ContextVar("workflow_tool_creator", default=None)+# Whether the outermost of them was started by one of the Executive's own+# unattended passes (the reflection, research, a proactive run): their+# context is stored or inbound text with nobody watching.+_by_a_pass: contextvars.ContextVar[bool] = contextvars.ContextVar("workflow_started_by_a_pass", default=False)@contextlib.contextmanagerdef in_workflow(workflow_name: str, creator_id: int | None) -> Iterator[None]:"""Run the block as a step of ``workflow_name``, created by ``creator_id``."""+ from openexecutive.orchestrator.schedule_tools import current_session++ outermost = not _chain.get()+ by_a_pass = _by_a_pass.set(+ bool(getattr(current_session.get(), "unattended", False)) if outermost else _by_a_pass.get()+ )chain = _chain.set((*_chain.get(), workflow_name))creator = _creator.set(creator_id)try:@@ -212,6 +222,19 @@ def in_workflow(workflow_name: str, creator_id: int | None) -> Iterator[None]:finally:_creator.reset(creator)_chain.reset(chain)+ _by_a_pass.reset(by_a_pass)+++def running() -> tuple[tuple[str, ...], int | None]:+ """The workflows running in this task, outermost first, and the creator+ of the innermost one (``in_workflow``)."""+ return _chain.get(), _creator.get()+++def started_by_a_pass() -> bool:+ """Whether the outermost running workflow was started by one of the+ Executive's unattended passes rather than a person or its schedule."""+ return _by_a_pass.get()def _error(message: str) -> str:diff --git a/packages/core/openexecutive/workflows/designer.py b/packages/core/openexecutive/workflows/designer.pyindex 6348db04..3401e1a1 100644--- a/packages/core/openexecutive/workflows/designer.py+++ b/packages/core/openexecutive/workflows/designer.py@@ -209,9 +209,31 @@ def _one_line(text: str, limit: int) -> str:return flat[:limit]-def build_context_block() -> str:+def _email_as_line(as_me: bool) -> str:+ """How this user's workflow emails can go."""+ from openexecutive.delegation.workflow_email import DRAFT_TOOL, SEND_TOOL++ if as_me:+ return (+ "Email as the user: their own mailbox is connected (Act as me). When an "+ f"email should come from them, in their voice, use {DRAFT_TOOL} (saves a "+ f"draft in their mailbox for them to send) or {SEND_TOOL} (sends it as "+ "them). When it should come from the Executive, use the gateway's email "+ "tools. If it isn't clear which of the three they want, ask."+ )+ return (+ "Email as the user: not available, since they haven't connected their own "+ f"mailbox under Act as me. Do not use {DRAFT_TOOL} or {SEND_TOOL}; emails "+ "come from the Executive's own address through the gateway's email tools."+ )+++def build_context_block(*, as_me: bool = False) -> str:"""Render the live facts the designer needs, for the FIRST user turn.+ ``as_me``: the person designing it may have its emails written as them+ (``workflow_email.available_for``).+Read once per session by the route and stored, so the replayed first turnstays identical across the conversation. Every source degrades to anempty list rather than failing the session.@@ -278,6 +300,7 @@ def build_context_block() -> str:"Built-in tools (always available; the oe__ tools are the same tools ""the Executive uses in chat, so anything it did in chat a step can ""do too):\n" + "\n".join(builtins) + "\n\n"+ + _email_as_line(as_me) + "\n\n""Workflow names already taken (do not reuse): " + ", ".join(taken))diff --git a/packages/core/openexecutive/workflows/tool_catalog.py b/packages/core/openexecutive/workflows/tool_catalog.pyindex a265b92e..74df7c6e 100644--- a/packages/core/openexecutive/workflows/tool_catalog.py+++ b/packages/core/openexecutive/workflows/tool_catalog.py@@ -390,10 +390,33 @@ def _chat_specs() -> dict[str, tuple[ToolInfo, Handler]]:return {}+def _email_as_me_specs() -> dict[str, tuple[ToolInfo, Handler]]:+ """Email as the workflow's creator (Act as me): a draft for them to send,+ or sent as them (``delegation.workflow_email``)."""+ from openexecutive.delegation import workflow_email as we++ return {+ we.DRAFT_TOOL: (+ ToolInfo(+ we.DRAFT_TOOL, we.DRAFT_DESCRIPTION, we.INPUT_SCHEMA, None, "builtin",+ timeout_s=we.TIMEOUT_S,+ ),+ we.handle_draft_email_as_me,+ ),+ we.SEND_TOOL: (+ ToolInfo(+ we.SEND_TOOL, we.SEND_DESCRIPTION, we.INPUT_SCHEMA, None, "builtin",+ timeout_s=we.TIMEOUT_S,+ ),+ we.handle_send_email_as_me,+ ),+ }++def _all_builtin_specs() -> dict[str, tuple[ToolInfo, Handler]]:# The chat's tools (workflows.chat_tools) win a name clash with an# extension's.- return {**_extension_specs(), **_chat_specs()}+ return {**_extension_specs(), **_chat_specs(), **_email_as_me_specs()}def builtin_tools() -> list[ToolInfo]:diff --git a/packages/core/tests/unit/test_delegation_reply_send.py b/packages/core/tests/unit/test_delegation_reply_send.pyindex eee23a7b..81bcb919 100644--- a/packages/core/tests/unit/test_delegation_reply_send.py+++ b/packages/core/tests/unit/test_delegation_reply_send.py@@ -412,19 +412,22 @@ def _importers(module: str) -> set[str]:return set(_index()[1].get(module, set()))-def test_only_the_send_path_sends_and_only_the_approve_route_and_the_watcher_reach_it() -> None:- """Two doors and no more: the person's tap (the approve route) and Handle- it for me (the inbox watcher, under the person's own switch)."""+def test_only_the_send_path_sends_and_only_its_three_doors_reach_it() -> None:+ """Three doors and no more: the person's tap (the approve route), Handle+ it for me (the inbox watcher, under the person's own switch), and a+ workflow its creator saved to send as them (``oe__send_email_as_me``)."""assert _uses("send_draft") == {"delegation/reply_send.py"}assert _uses("send_approved_reply") == {"api/routes/decisions.py"}assert _uses("send_on_its_own") == {"delegation/inbox.py"}+ assert _uses("send_for_workflow") == {"delegation/workflow_email.py"}+ assert _uses("handle_send_email_as_me") == {"workflows/tool_catalog.py"}# card_drafts, answers and the edit routes use its refusals and caller check only.assert _importers("openexecutive.delegation.reply_send") == {"api/routes/decisions.py", "api/routes/delegation.py", "delegation/inbox.py", "delegation/card_drafts.py",- "delegation/answers.py",+ "delegation/answers.py", "delegation/workflow_email.py",}assert _importers("openexecutive.delegation.reply_send.SendRefused") >= {"delegation/answers.py"}- assert not ({"send_draft", "send_approved_reply", "send_on_its_own"} & {+ assert not ({"send_draft", "send_approved_reply", "send_on_its_own", "send_for_workflow"} & {n for n, files in _index()[0].items() if "delegation/answers.py" in files})diff --git a/packages/core/tests/unit/test_workflow_designer_route.py b/packages/core/tests/unit/test_workflow_designer_route.pyindex dcef72f6..d192eb2d 100644--- a/packages/core/tests/unit/test_workflow_designer_route.py+++ b/packages/core/tests/unit/test_workflow_designer_route.py@@ -85,7 +85,7 @@ def client(dynamic_store.initialize_dynamic_workflows_db(db_path)monkeypatch.setattr(dynamic_store, "DB_PATH", db_path)monkeypatch.setattr(route, "_designer_sessions", OrderedDict())- monkeypatch.setattr(route, "build_context_block", lambda: "CTX")+ monkeypatch.setattr(route, "build_context_block", lambda **_: "CTX")monkeypatch.delenv("BACKEND_SHARED_SECRET", raising=False)with TestClient(create_app()) as c:yield c@@ -580,3 +580,52 @@ def test_save_edit_refusals(client: TestClient, seeded: _Queue) -> None:seeded.append(_draft(name="brand_new_workflow"))create_sid = _start(client)["session_id"]assert client.post(url, json={"session_id": create_sid}).status_code == 409+++def as_me_seen(monkeypatch: pytest.MonkeyPatch) -> list[bool]:+ """Record what the route tells the designer about drafting as the user.+ Act as me is on for person 7 only."""+ from openexecutive.delegation import workflow_email++ seen: list[bool] = []++ def _context(*, as_me: bool = False) -> str:+ seen.append(as_me)+ return "CTX"++ monkeypatch.setattr(route, "build_context_block", _context)+ monkeypatch.setattr(workflow_email, "available_for", lambda person_id: person_id == 7)+ return seen++[email protected](("caller", "expected"), [(7, True), (8, False), (None, False)])+def test_start_tells_the_designer_whether_the_caller_can_have_drafts_as_them(+ client: TestClient, seeded: _Queue, as_me_seen: list[bool], monkeypatch: pytest.MonkeyPatch,+ caller: int | None, expected: bool,+) -> None:+ from openexecutive.api.routes import chat as chat_route++ monkeypatch.setattr(chat_route, "_resolve_caller_person_id", lambda request: caller)+ seeded.append(wd.DesignerQuestion(question="Which competitors?"))+ _start(client)+ assert as_me_seen == [expected]+++ ("owner", "caller", "expected"),+ [(7, 7, True), (7, 9, False), (None, 7, False)],+)+def test_edit_offers_drafts_as_the_creator_only_to_the_creator(+ client: TestClient, seeded: _Queue, as_me_seen: list[bool], monkeypatch: pytest.MonkeyPatch,+ owner: int | None, caller: int, expected: bool,+) -> None:+ from openexecutive.api.routes import chat as chat_route++ _save(client)+ as_me_seen.clear()+ monkeypatch.setattr(dynamic_store, "get_owner", lambda name: owner)+ monkeypatch.setattr(chat_route, "_resolve_caller_person_id", lambda request: caller)+ resp = client.post("/workflows/designer/edit", json={"name": "weekly_competitor_digest"})+ assert resp.status_code == 200, resp.text+ assert as_me_seen == [expected]diff --git a/packages/core/tests/unit/test_workflow_email.py b/packages/core/tests/unit/test_workflow_email.pynew file mode 100644index 00000000..5afa1980--- /dev/null+++ b/packages/core/tests/unit/test_workflow_email.py@@ -0,0 +1,476 @@+"""Workflows that email as their creator (delegation/workflow_email.py):+``oe__draft_email_as_me`` drafts, ``oe__send_email_as_me`` sends, under+Act as me's rules plus the ones a send needs."""+from __future__ import annotations++import asyncio+import json+from collections.abc import Iterator+from pathlib import Path+from types import SimpleNamespace+from typing import Any++import pytest++from openexecutive.audit import logger as audit_logger+from openexecutive.audit.logger import AuditLogger+from openexecutive.delegation import caps, handle_it, inbox, workflow_email+from openexecutive.delegation import drafts as ddrafts+from openexecutive.delegation import ghostwriter as gw+from openexecutive.delegation import settings as dsettings+from openexecutive.delegation.gmail import (+ CreatedDraft,+ DraftInfo,+ DraftSpec,+ GmailError,+ MailMessage,+ SentMessage,+)+from openexecutive.memory import episodic+from openexecutive.orchestrator.artifact_records import pinned_viewer, viewer_for_person+from openexecutive.orchestrator.schedule_tools import current_session+from openexecutive.people import registry as people_registry+from openexecutive.people import store as people_store+from openexecutive.workflows import action_step, chat_tools, dynamic_store, tool_catalog+from openexecutive.workflows.designer import build_context_block++OWNER = "[email protected]"+TEAM = "[email protected]"+INPUT = {"to": [TEAM], "intent": "Send Ben the Q3 revenue: up 12%."}++[email protected](autouse=True)+def db(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Iterator[Path]:+ path = tmp_path / "episodic.db"+ monkeypatch.setattr(episodic, "DB_PATH", path)+ monkeypatch.setattr(people_store, "DB_PATH", path)+ episodic.initialize_db(path)+ people_store.initialize_db(path)+ people_registry.invalidate()+ monkeypatch.setattr(audit_logger, "_default_logger", AuditLogger(db_path=path))+ monkeypatch.setattr(handle_it, "signing_ok", lambda: True)+ monkeypatch.setattr(inbox, "_client_slot_active", lambda: False)+ caps._SAVED_TODAY.clear()+ caps._IN_FLIGHT.clear()+ workflow_email._SENDING.clear()+ token = current_session.set(None)+ yield path+ current_session.reset(token)+ caps._SAVED_TODAY.clear()+ caps._IN_FLIGHT.clear()+ workflow_email._SENDING.clear()+ people_registry.invalidate()+++def people(monkeypatch: pytest.MonkeyPatch) -> tuple[int, int]:+ owner_id = people_store.upsert_person(full_name="Olivia Owner", is_principal=True, email=OWNER)+ teammate_id = people_store.upsert_person(full_name="Ben Teammate", role="Ops", email=TEAM)+ people_registry.invalidate()+ # Every workflow in these tests is Olivia's unless a test says otherwise.+ monkeypatch.setattr(dynamic_store, "get_owner", lambda name: owner_id)+ return owner_id, teammate_id+++def on(people: tuple[int, int]) -> int:+ owner_id, _ = people+ dsettings.set_enabled(owner_id, True, updated_by=OWNER)+ return owner_id+++def composed(monkeypatch: pytest.MonkeyPatch) -> list[dict[str, Any]]:+ calls: list[dict[str, Any]] = []++ async def fake_compose(**kwargs: Any) -> gw.ComposedDraft:+ calls.append(kwargs)+ return gw.ComposedDraft(subject="Q3 numbers", body="Hi Ben, revenue is up 12%.")++ monkeypatch.setattr(gw, "compose", fake_compose)+ return calls+++class FakeMailbox:+ def __init__(self, opened: str = OWNER) -> None:+ self.opened = opened+ self.drafts: list[DraftSpec] = []+ self.sent: list[str] = []+ self.send_error: GmailError | None = None+ self.retarget: list[str] | None = None++ async def profile_email(self) -> str:+ return self.opened++ async def create_draft(self, spec: DraftSpec) -> CreatedDraft:+ self.drafts.append(spec)+ return CreatedDraft(draft_id="d1", message_id="m99", thread_id="tnew")++ async def get_draft(self, draft_id: str) -> DraftInfo | None:+ spec = self.drafts[-1]+ return DraftInfo(draft_id=draft_id, message=MailMessage(+ id="m99", thread_id="tnew", from_addr=OWNER, to=self.retarget or spec.to, cc=spec.cc,+ ))++ async def send_as_addresses(self) -> list[str]:+ return [OWNER]++ async def send_draft(self, draft_id: str) -> SentMessage:+ if self.send_error is not None:+ raise self.send_error+ self.sent.append(draft_id)+ return SentMessage(id="sent1", thread_id="tnew")+++def _run(+ tool_input: dict[str, Any], mailbox: FakeMailbox, *, send: bool = False,+ creator: int | None = None, chain: tuple[str, ...] = ("wf",),+) -> dict[str, Any]:+ handler = workflow_email.handle_send_email_as_me if send else workflow_email.handle_draft_email_as_me++ async def go() -> str:+ outer = [chat_tools.in_workflow(name, creator) for name in chain]+ for block in outer:+ block.__enter__()+ try:+ return await handler(tool_input, mailbox=mailbox)+ finally:+ for block in reversed(outer):+ block.__exit__(None, None, None)++ return json.loads(asyncio.run(go()))+++# ── Drafts ───────────────────────────────────────────────────────────────────+++def test_drafts_in_the_creators_mailbox_and_returns_no_body(on, composed) -> None:+ mailbox = FakeMailbox()++ result = _run(INPUT, mailbox, creator=on)++ assert result["status"] == "drafted"+ assert result["to"] == [TEAM] and result["subject"] == "Q3 numbers"+ assert "body" not in result+ assert [d.to for d in mailbox.drafts] == [[TEAM]] and mailbox.sent == []+ assert composed[0]["intent"] == INPUT["intent"]+++def test_refused_with_the_fallback_when_act_as_me_is_off(people, composed) -> None:+ owner_id, _ = people+ mailbox = FakeMailbox()++ result = _run(INPUT, mailbox, creator=owner_id)++ assert "Act as me" in result["error"] and "Executive's own email" in result["error"]+ assert mailbox.drafts == [] and composed == []+++def test_refused_when_the_mailbox_is_not_theirs(on, composed) -> None:+ result = _run(INPUT, FakeMailbox(opened="[email protected]"), creator=on)++ assert result["status"] == "mismatch" and composed == []+++def test_refused_without_a_creator(people, composed) -> None:+ assert "no creator" in _run(INPUT, FakeMailbox())["error"] and composed == []++[email protected]("send", [False, True])+def test_refused_when_someone_else_started_the_run(people, on, composed, send: bool) -> None:+ _, teammate_id = people+ mailbox = FakeMailbox()++ with pinned_viewer(viewer_for_person(teammate_id)):+ result = _run(INPUT, mailbox, creator=on, send=send)++ assert "someone else is behind this run" in result["error"]+ assert mailbox.drafts == [] and mailbox.sent == []+++def test_refused_when_another_persons_workflow_started_it(+ people, on, composed, monkeypatch: pytest.MonkeyPatch+) -> None:+ _, teammate_id = people+ monkeypatch.setattr(dynamic_store, "get_owner", lambda name: teammate_id if name == "bens" else on)+ mailbox = FakeMailbox()++ result = _run(INPUT, mailbox, creator=on, send=True, chain=("bens", "wf"))++ assert "someone else is behind this run" in result["error"] and mailbox.sent == []+++def test_the_creator_starting_it_by_hand_may(on, composed) -> None:+ with pinned_viewer(viewer_for_person(on)):+ assert _run(INPUT, FakeMailbox(), creator=on)["status"] == "drafted"++[email protected]("tool_input", [+ {"to": [TEAM]},+ {"to": [], "intent": "hi"},+ {"to": ["not-an-address"], "intent": "hi"},+ {"to": [f"p{i}@x.example" for i in range(11)], "intent": "hi"},+])+def test_bad_input_writes_nothing(on, composed, tool_input) -> None:+ mailbox = FakeMailbox()++ assert "error" in _run(tool_input, mailbox, creator=on, send=True)+ assert mailbox.drafts == [] and mailbox.sent == []+++def test_a_composer_failure_is_an_error_not_a_raise(on, monkeypatch: pytest.MonkeyPatch) -> None:+ async def boom(**kwargs: Any) -> gw.ComposedDraft:+ raise TimeoutError++ monkeypatch.setattr(gw, "compose", boom)+ mailbox = FakeMailbox()++ result = _run(INPUT, mailbox, creator=on, send=True)++ assert "Executive's own email" in result["error"]+ assert mailbox.drafts == [] and caps._IN_FLIGHT.get(on, 0) == 0 and workflow_email._SENDING == {}+++def test_draft_limit_is_shared(on, composed, monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setenv("DELEGATION_MAX_DRAFTS_PER_DAY", "1")+ mailbox = FakeMailbox()++ assert _run(INPUT, mailbox, creator=on)["status"] == "drafted"+ assert "limit" in _run(INPUT, mailbox, creator=on)["error"]+ assert len(mailbox.drafts) == 1+++# ── Sends ────────────────────────────────────────────────────────────────────+++def test_sends_from_the_creators_mailbox(on, composed) -> None:+ mailbox = FakeMailbox()++ result = _run(INPUT, mailbox, creator=on, send=True)++ assert result["status"] == "sent" and result["subject"] == "Q3 numbers"+ assert "body" not in result and "link" not in result+ assert mailbox.sent == ["d1"]+ since = ddrafts.datetime(2000, 1, 1, tzinfo=ddrafts.UTC)+ assert ddrafts.count_since(on, since, source=ddrafts.SOURCE_WORKFLOW_SENT) == 1+ assert ddrafts.sent_message_ids(on) == {"sent1"}+++def test_send_limit(on, composed, monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setenv("DELEGATION_WORKFLOW_MAX_SENDS_PER_DAY", "1")+ mailbox = FakeMailbox()++ assert _run(INPUT, mailbox, creator=on, send=True)["status"] == "sent"+ assert "limit" in _run(INPUT, mailbox, creator=on, send=True)["error"]+ assert mailbox.sent == ["d1"] and len(mailbox.drafts) == 1 and workflow_email._SENDING == {}+++def test_no_send_without_signed_sign_ins(on, composed, monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(handle_it, "signing_ok", lambda: False)+ mailbox = FakeMailbox()++ result = _run(INPUT, mailbox, creator=on, send=True)++ assert "wasn't sent" in result["error"] and "Drafts" in result["error"] and mailbox.sent == []+++def test_a_draft_readdressed_before_sending_is_not_sent(on, composed) -> None:+ mailbox = FakeMailbox()+ mailbox.retarget = ["[email protected]"]++ result = _run(INPUT, mailbox, creator=on, send=True)++ assert "wasn't sent" in result["error"] and mailbox.sent == []+++def test_never_sends_to_the_executive(on, composed, monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setenv("EXEC_EMAIL_ADDRESS", "[email protected]")+ mailbox = FakeMailbox()++ result = _run({**INPUT, "to": ["[email protected]"]}, mailbox, creator=on, send=True)++ assert "Executive" in result["error"] and mailbox.sent == []+++def test_an_unconfirmed_send_says_not_to_retry(on, composed) -> None:+ mailbox = FakeMailbox()+ mailbox.send_error = GmailError("timeout", maybe_done=True)++ result = _run(INPUT, mailbox, creator=on, send=True)++ assert "Don't try again" in result["error"] and workflow_email._SENDING == {}+++# ── Wiring ───────────────────────────────────────────────────────────────────++[email protected]("name", [workflow_email.DRAFT_TOOL, workflow_email.SEND_TOOL])+def test_builtins_are_writes_and_recipients_are_targets(name: str) -> None:+ info = {t.name: t for t in tool_catalog.builtin_tools()}[name]+ assert info.read_only is None and info.source == "builtin"+ targets, complete = action_step.resource_targets({"to": [TEAM], "cc": ["[email protected]"], "intent": "x"})+ assert complete and {v for _, v in targets} == {TEAM, "[email protected]"}+++def test_dispatch_writes_as_the_workflows_creator(people, monkeypatch: pytest.MonkeyPatch) -> None:+ owner_id, _ = people+ seen: list[Any] = []++ async def handler(tool_input: dict[str, Any]) -> str:+ seen.append(chat_tools.running())+ return "{}"++ info = {t.name: t for t in tool_catalog.builtin_tools()}[workflow_email.SEND_TOOL]+ monkeypatch.setattr(tool_catalog, "builtin_handler", lambda name: handler)++ asyncio.run(action_step._dispatch(workflow_email.SEND_TOOL, {}, info, "wf"))++ assert seen == [(("wf",), owner_id)] and chat_tools.running() == ((), None)+++def test_designer_is_told_whether_it_can_write_as_them(people) -> None:+ owner_id, _ = people+ assert workflow_email.available_for(owner_id) is False+ dsettings.set_enabled(owner_id, True, updated_by=OWNER)+ assert workflow_email.available_for(owner_id) is True++ yes = build_context_block(as_me=True)+ assert "their own mailbox is connected" in yes and workflow_email.SEND_TOOL in yes+ assert "Do not use oe__draft_email_as_me or oe__send_email_as_me" in build_context_block(as_me=False)+++# ── Saving a workflow that sends ─────────────────────────────────────────────+++def _defn(tools: list[str]) -> Any:+ return SimpleNamespace(steps=[SimpleNamespace(tools=tools)])+++def test_only_a_sending_workflow_is_checked_at_save(people) -> None:+ owner_id, _ = people+ nobody = SimpleNamespace(kind="open", email="")+ assert workflow_email.save_refusal(_defn([workflow_email.DRAFT_TOOL]), nobody, owner_id) is None+++def test_a_sending_workflow_needs_its_verified_creator(people, monkeypatch: pytest.MonkeyPatch) -> None:+ owner_id, teammate_id = people+ monkeypatch.setattr("openexecutive.api.caller.signing_on", lambda: True)+ defn = _defn([workflow_email.SEND_TOOL])+ olivia = SimpleNamespace(kind="user", email=OWNER)+ ben = SimpleNamespace(kind="user", email=TEAM)++ assert workflow_email.save_refusal(defn, olivia, owner_id) is None+ assert "Only the person who created" in str(workflow_email.save_refusal(defn, ben, owner_id))+ assert "Only the person who created" in str(workflow_email.save_refusal(defn, olivia, None))+ assert "Only the person who created" in str(workflow_email.save_refusal(defn, olivia, teammate_id))+++def test_a_sending_workflow_needs_signed_sign_ins(people, monkeypatch: pytest.MonkeyPatch) -> None:+ owner_id, _ = people+ monkeypatch.setattr("openexecutive.api.caller.signing_on", lambda: False)+ monkeypatch.setattr("openexecutive.utils.deployment.is_local_login", lambda: False)++ refused = workflow_email.save_refusal(+ _defn([workflow_email.SEND_TOOL]), SimpleNamespace(kind="open", email=OWNER), owner_id,+ )+ assert "signed sign-ins" in str(refused)+++def test_refused_when_one_of_the_executives_own_passes_started_it(on, composed) -> None:+ """The reflection or research running the workflow: inbound text with+ nobody watching chose its inputs. A nested workflow inherits that."""+ mailbox = FakeMailbox()+ token = current_session.set(SimpleNamespace(unattended=True))+ try:+ result = _run(INPUT, mailbox, creator=on, send=True, chain=("wf", "inner"))+ finally:+ current_session.reset(token)++ assert "someone else is behind this run" in result["error"] and mailbox.sent == []+ assert chat_tools.started_by_a_pass() is False+++def test_chat_cannot_replace_a_workflow_that_sends(people, monkeypatch: pytest.MonkeyPatch) -> None:+ from openexecutive.orchestrator import workflow_authoring_tools as wat++ existing = SimpleNamespace(is_active=False, steps=[SimpleNamespace(tools=[workflow_email.SEND_TOOL])])+ monkeypatch.setattr(dynamic_store, "get_definition", lambda name: existing)+ monkeypatch.setattr(wat, "_canonical_token", lambda definition: "tok")+ saved: list[Any] = []+ monkeypatch.setattr(dynamic_store, "save_if_unchanged", lambda *a, **k: saved.append(a))+ definition = {+ "name": "weekly_update", "title": "Weekly update",+ "steps": [+ {"kind": "specialist", "id": "numbers", "title": "S", "specialist": "cfo", "goal": "Numbers."},+ {"kind": "synthesis", "id": "assemble", "title": "A"},+ ],+ }++ out = json.loads(asyncio.run(wat.handle_save_workflow(+ {"definition": definition, "confirm_token": "tok", "overwrite": True},+ )))++ assert "can't be replaced from chat" in out["error"] and saved == []+++def test_a_step_timeout_cannot_cut_a_send_short(on, composed) -> None:+ # The step's wait_for cancels the call mid-send; the send still finishes,+ # is recorded, and frees the send slot.+ mailbox = FakeMailbox()+ sending = asyncio.Event()+ release = asyncio.Event()+ plain_send = mailbox.send_draft++ async def slow_send(draft_id: str) -> SentMessage:+ sending.set()+ await release.wait()+ return await plain_send(draft_id)++ mailbox.send_draft = slow_send # type: ignore[method-assign]++ async def go() -> None:+ with chat_tools.in_workflow("wf", on):+ call = asyncio.ensure_future(workflow_email.handle_send_email_as_me(INPUT, mailbox=mailbox))+ await sending.wait()+ call.cancel()+ with pytest.raises(asyncio.CancelledError):+ await call+ release.set()+ for _ in range(20):+ await asyncio.sleep(0)++ asyncio.run(go())++ assert mailbox.sent == ["d1"] and workflow_email._SENDING == {}+ assert ddrafts.sent_message_ids(on) == {"sent1"}+++def test_email_tools_get_more_than_the_default_step_timeout() -> None:+ tools = {t.name: t for t in tool_catalog.builtin_tools()}+ for name in workflow_email.TOOLS:+ assert (tools[name].timeout_s or 0) > action_step._TOOL_CALL_TIMEOUT_S+++def test_chat_cannot_add_a_send_to_someone_elses_workflow(people, monkeypatch: pytest.MonkeyPatch) -> None:+ # Saved over an existing workflow, the send would go as its creator,+ # not as whoever asked in chat.+ from openexecutive.orchestrator import workflow_authoring_tools as wat++ existing = SimpleNamespace(is_active=False, steps=[SimpleNamespace(tools=[])])+ incoming = SimpleNamespace(name="weekly_update", steps=[SimpleNamespace(tools=[workflow_email.SEND_TOOL])])+ monkeypatch.setattr(dynamic_store, "get_definition", lambda name: existing)++ async def build(definition: Any) -> tuple[Any, None]:+ return incoming, None++ monkeypatch.setattr(wat, "_build_def", build)+ monkeypatch.setattr(wat, "_canonical_token", lambda definition: "tok")+ monkeypatch.setattr(wat, "_approved_tool_workflow_error", lambda name, existing: None)+ saved: list[Any] = []+ monkeypatch.setattr(dynamic_store, "save_if_unchanged", lambda *a, **k: saved.append(a))++ out = json.loads(asyncio.run(wat.handle_save_workflow(+ {"definition": {"name": "weekly_update"}, "confirm_token": "tok", "overwrite": True},+ )))++ assert "can't be replaced from chat" in out["error"] and saved == []diff --git a/packages/core/tests/unit/test_workflows_custom_routes.py b/packages/core/tests/unit/test_workflows_custom_routes.pyindex 9dae0a98..1046c718 100644--- a/packages/core/tests/unit/test_workflows_custom_routes.py+++ b/packages/core/tests/unit/test_workflows_custom_routes.py@@ -308,3 +308,52 @@ def test_tool_describe_ignores_malformed_and_duplicate_names(params={"names": "srv__a,srv__a,has space,semi;colon," + "x" * 70},)assert searched == ["srv__a"]+++def creator_check(monkeypatch: pytest.MonkeyPatch) -> dict[str, Any]:+ """The send-as-creator save check, recording what it was asked: refuses+ a sending workflow unless ``state["ok"]``."""+ from openexecutive.delegation import workflow_email++ state: dict[str, Any] = {"ok": False, "owners": []}++ def refusal(defn: Any, caller: Any, owner_id: int | None) -> str | None:+ if not workflow_email.sends(defn):+ return None+ state["owners"].append(owner_id)+ return None if state["ok"] else "Only the person who created this workflow can."++ monkeypatch.setattr(workflow_email, "save_refusal", refusal)+ monkeypatch.setattr("openexecutive.api.routes.chat._resolve_caller_person_id", lambda request: 1)+ return state+++def test_only_its_verified_creator_saves_a_workflow_that_sends_as_them(+ client: TestClient, creator_check: dict[str, Any], monkeypatch: pytest.MonkeyPatch,+) -> None:+ send = _action_definition(["oe__send_email_as_me"])+ r = client.post("/workflows/custom", json=send)+ assert r.status_code == 403 and "created" in r.json()["detail"]+ assert creator_check["owners"] == [1]+ # A drafts-only workflow isn't checked.+ assert client.post("/workflows/custom", json=_action_definition(["oe__draft_email_as_me"])).status_code == 201+ client.delete("/workflows/custom/file_bills")++ creator_check["ok"] = True+ assert client.post("/workflows/custom", json=send).status_code == 201, client.get("/workflows/custom").text++ # Someone else can't change it, even to take the send out, or switch it on.+ creator_check["ok"] = False+ monkeypatch.setattr(dynamic_store, "get_owner", lambda name: 1)+ assert client.put("/workflows/custom/file_bills", json=send).status_code == 403+ assert client.put(+ "/workflows/custom/file_bills", json=_action_definition(["oe__draft_email_as_me"]),+ ).status_code == 403+ assert client.post("/workflows/custom/file_bills/activate", json={"is_active": False}).status_code == 200+ stored = client.get("/workflows/custom/file_bills").json()+ r = client.post("/workflows/custom/file_bills/activate", json={"is_active": True, "definition": stored})+ assert r.status_code == 403+ creator_check["ok"] = True+ r = client.post("/workflows/custom/file_bills/activate", json={"is_active": True, "definition": stored})+ assert r.status_code == 200, r.text