AI-powered virtual executive team — a single coherent executive persona backed by 8 specialist agents (FastAPI + Next.js).
feat(delegation): edit a waiting reply on its card and keep replies out of Drafts by default (#423)
Rufusc480289ace44
diff --git a/packages/core/openexecutive/api/routes/delegation.py b/packages/core/openexecutive/api/routes/delegation.pyindex 9d9651db..9b7b9823 100644--- a/packages/core/openexecutive/api/routes/delegation.py+++ b/packages/core/openexecutive/api/routes/delegation.py@@ -21,13 +21,21 @@ Routes:PUT /delegation — {enabled}; turning it on needs the caller'sown Gmail connected (409 otherwise); turningit off turns the inbox watcher off too- PUT /delegation/inbox — {enabled}: "Draft replies to my inbox";- turning it on needs Act as me on and Gmail- connected (409), and starts from now+ PUT /delegation/inbox — {enabled?, mailbox_drafts?}: "Draft+ replies to my inbox"; turning it on needs+ Act as me on and Gmail connected (409),+ and starts from now. mailbox_drafts: also+ save each reply in their Drafts (off by+ default: on its card alone)POST /delegation/inbox/check — check the inbox now (202; 409 when theswitch is off or a check is running)GET /delegation/replies — the reply cards waiting for the caller(from the database; no Gmail call)+ PUT /delegation/replies/{id}/text — {text}: change a reply's words+ before Send, on its card and in their+ Drafts when it is there too. Needs a+ caller the API knows is that person, like+ Send (delegation.card_drafts)PUT /delegation/handle-it — {enabled?, mode?}: Handle it for me,the inbox watcher sending some replies onits own, mode careful | balanced | bold@@ -153,6 +161,8 @@ class InboxOut(BaseModel):watch_since: str | None = Nonelast_poll_at: str | None = Nonechecking: bool = False+ # Also save each reply in their mailbox's Drafts (off: on its card alone).+ mailbox_drafts: bool = Falseclass TeamMemberUse(BaseModel):@@ -286,7 +296,9 @@ class TeamUpdate(BaseModel):class InboxUpdate(BaseModel):model_config = ConfigDict(extra="forbid")- enabled: bool+ enabled: bool | None = None+ # Also save each reply in the caller's mailbox's Drafts.+ mailbox_drafts: bool | None = Noneclass ReplyCardOut(BaseModel):@@ -315,12 +327,22 @@ class ReplyCardOut(BaseModel):can_allow: bool = False# Drafts in training: "Do it like this next time" is offered.learns_style: bool = False+ # Also in the caller's mailbox's Drafts; False: on this card alone.+ in_mailbox: bool = True+ # Which of their mailboxes it sends from: "Gmail" or "Outlook".+ mailbox: str = "Gmail"class RepliesOut(BaseModel):cards: list[ReplyCardOut]+class ReplyTextUpdate(BaseModel):+ model_config = ConfigDict(extra="forbid")++ text: str = Field(max_length=20_000)++class CardActionOut(BaseModel):index: int# invite, message or add_contact.@@ -472,6 +494,7 @@ def _inbox_out(person_id: int) -> InboxOut:watch_since=watch.watch_since,last_poll_at=watch.last_poll_at,checking=checking,+ mailbox_drafts=watch.mailbox_drafts,)@@ -698,16 +721,36 @@ _CHECKS: set[asyncio.Task[Any]] = set()async def update_delegation_inbox(request: Request, body: InboxUpdate) -> DelegationOut:person = _caller(request)person_id = _person_id(person)+ if body.enabled is None and body.mailbox_drafts is None:+ raise _refuse(422, "nothing_to_change", "Say what to change.")if body.enabled:if not is_enabled(person_id):raise _refuse(409, "act_as_me_off", "Turn Act as me on first.")status = await gmail_status(person.email)if status != "connected":raise _refuse(409, _BLOCKING_CODES.get(status, "gmail_error"), STATUS_MESSAGES[status])- _set_inbox(person_id, body.enabled)+ if body.mailbox_drafts is not None:+ _set_mailbox_drafts(person_id, body.mailbox_drafts)+ if body.enabled is not None:+ _set_inbox(person_id, body.enabled)return await _state(person)+def _set_mailbox_drafts(person_id: int, on: bool) -> None:+ """Whether replies are also saved in the caller's mailbox's Drafts. Cards+ already made keep where their reply is."""+ from openexecutive.delegation import inbox++ if inbox.get_watch(person_id).mailbox_drafts == on:+ return+ inbox.set_mailbox_drafts(person_id, on, updated_by=f"person:{person_id}")+ _audit(+ "delegation_inbox_changed",+ f"Also save replies in my Drafts turned {'on' if on else 'off'} by person {person_id}",+ {"person_id": person_id, "mailbox_drafts": on},+ )++@router.post("/delegation/inbox/check", status_code=202, response_model=InboxOut)async def check_delegation_inbox(request: Request) -> InboxOut:"""Check the caller's inbox now, in the background; ``GET /delegation``@@ -750,6 +793,34 @@ def get_delegation_replies(request: Request) -> RepliesOut:])[email protected]("/delegation/replies/{decision_id}/text", response_model=ReplyCardOut)+async def update_delegation_reply_text(request: Request, decision_id: int, body: ReplyTextUpdate) -> ReplyCardOut:+ """Change the words of one of the caller's reply cards before Send: on+ the card, and in their mailbox's Drafts when it is there too+ (``delegation.card_drafts.edit``). Their own cards only; sends nothing."""+ from openexecutive.delegation import card_drafts+ from openexecutive.delegation.inbox import DECISION_CLASS+ from openexecutive.delegation.replies import cards+ from openexecutive.delegation.reply_send import SendRefused+ from openexecutive.memory.decision_ledger import get_decision_instance++ person = _caller(request)+ person_id = _person_id(person)+ instance = get_decision_instance(decision_id)+ if instance is None or instance.decision_class != DECISION_CLASS or instance.approver_person_id != person_id:+ raise _refuse(404, "not_found", "That reply isn't waiting for you any more.")+ try:+ await card_drafts.edit(instance, caller=api_caller.caller(request), resolver=person_id, text=body.text)+ except SendRefused as refused:+ raise HTTPException(+ status_code=refused.status, detail={"code": refused.code, "message": refused.message, **refused.extra},+ ) from None+ card = next((c for c in cards(person) if c.decision_id == decision_id), None)+ if card is None:+ raise _refuse(404, "not_found", "That reply isn't waiting for you any more.")+ return ReplyCardOut(**{k: v for k, v in asdict(card).items() if k in ReplyCardOut.model_fields})++@router.get("/delegation/actions", response_model=ActionCardsOut)def get_delegation_actions(request: Request) -> ActionCardsOut:"""The action cards waiting for the caller to approve. Their own only:diff --git a/packages/core/openexecutive/architecture/architecture-facts.yaml b/packages/core/openexecutive/architecture/architecture-facts.yamlindex 6c3ce7f0..911e8fbe 100644--- a/packages/core/openexecutive/architecture/architecture-facts.yaml+++ b/packages/core/openexecutive/architecture/architecture-facts.yaml@@ -9813,12 +9813,19 @@ delegation:x-caller-email unless local login; turning it on needs gmail_statusconnected (409 gmail_not_connected / gmail_needs_reconnect /gmail_mismatch / no_email / shared_mailbox / gmail_error). Every change- writes a private audit row. PUT /delegation/inbox {enabled} (409+ writes a private audit row. PUT /delegation/inbox {enabled?,+ mailbox_drafts?} (mailbox_drafts: also save each reply in their Drafts,+ off by default, so a reply lives on its card alone until Send makes the+ draft from it: delegation.card_drafts; 409act_as_me_off or the Gmail codes; the same DelegationOut back, whoseinbox field is {enabled, status, message, watch_since, last_poll_at,checking}); POST /delegation/inbox/check (202 with the inbox state; 409inbox_off / in_progress); GET /delegation/replies ({cards: [...]}, see- reply_cards). Send is POST /decisions/{id}/approve (edits carry the+ reply_cards; each card says in_mailbox and mailbox); PUT+ /delegation/replies/{id}/text {text} changes a reply's words on its card+ and, when it is in their Drafts, there too, only while that draft is still+ the version the card last saw (409 draft_changed / draft_not_plain /+ caller_signing_required, 422 empty / too_long); it sends nothing. Send is POST /decisions/{id}/approve (edits carry thesecond yes; 409 confirm / caller_signing_required / draft_gone /you_replied / inbox_off / client_slot / the Gmail codes, 429rate_limited, 502 gmail_error / send_unconfirmed); Dismiss is POSTdiff --git a/packages/core/openexecutive/architecture/prebuilt/api.json b/packages/core/openexecutive/architecture/prebuilt/api.jsonindex 9edfc2a0..18008fa1 100644--- a/packages/core/openexecutive/architecture/prebuilt/api.json+++ b/packages/core/openexecutive/architecture/prebuilt/api.json@@ -1,7 +1,7 @@{"section_id": "api","title": "API Reference",- "markdown": "The FastAPI surface lives in `openexecutive.api.main`, which mounts one router per topic. A shared-secret middleware gates every request via an `x-api-key` header, except `/health` and the `/webhook/*` callbacks (which carry their own verification). With local login (`OE_LOCAL_LOGIN=1`, which only `make dev` sets, and only while neither Google nor SSO sign-in is set up) a second middleware answers 403 to any request whose raw `Host` is not `localhost`, `127.0.0.1` or `[::1]` (except a webhook that verifies its caller: Google Chat 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 configured UI origins. 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` | SSE stream of a live Executive turn. `POST /chat/add` hands the running turn a message the person typed while it works; the turn takes it at its next step and the stream names it in a `message_added` event, and a second `POST /chat` on the same conversation waits for the first to finish. The request body optionally carries `page_context` (route, page title, guide section id, and a form descriptor with current values) — sent only by the Ask OE side panel so the Executive can explain the current page or propose form values. When the Executive calls its `propose_form_values` tool, the stream emits a `form_patch` event (`{type, form_id, fields, rationale, iteration}`) that the panel applies into the on-screen form as highlighted suggestions; the user reviews and saves through the form's normal submit path. Each round of tool calls also emits an `activity` event (`{type, label, tool, iteration}`) naming what is running — progress only, forwarded verbatim and never persisted with the message, unlike an `action_taken` chip. A `session_id` in the body must be a chat the caller may use (the same ownership rule as `sessions`). If it isn't, the turn runs in a fresh chat instead, so nothing is written into someone else's session and the reply looks the same as for an unknown id. An unknown namespaced id (`slack:…`, `telegram:…` and so on) is ignored and a fresh chat is started, because those ids belong to the channel adapters and claiming one first would make the caller its owner. The client mints a `client_turn_id` and sends it with the turn; `POST /chat/stop` takes that id and halts the turn mid-flight, so the button is live from the moment Send is pressed rather than only once the first SSE byte arrives. A stopped turn emits a `stopped` event and then the usual `done` over the same still-open stream — never an `error` — and whatever streamed so far is persisted and flagged. The endpoint returns 404 both for an unknown id and for another caller's turn, so it cannot be used to probe which turns are live. An optional `memory_text` (1–2000 chars) is what peer memory records as the caller's words instead of `message` — the briefing handoffs send it because their seed quotes the Executive's own card; `POST /chat/upload` derives it from the typed text and filenames. Since it never reaches the transcript, the `chat_turn` audit row keeps it beside `message`. After the reply — a stopped or timed-out one too, before the `stopped` / `error` / `done` frames — a turn that looked at anything sends one `sources` event, `{type, session_id, sources: [{kind, title, url}], unavailable: [area]}`: `kind` is `company`, `knowledge`, `notion`, `research`, `document` or `web`, `url` is only ever an http(s) link or, for an earlier document, `/artifacts/<id>`, at most 12 sources (6 from the web, pages the reply cites first), and `unavailable` names parts of the analysis (\"finance\") whose specialist failed or said nothing every time it was asked. It is persisted with the reply as `chat_messages.sources`. A request that carries `x-caller-email` marks its turn signed in (`Session.web_caller_signed_in`), which Act as me needs on a deployment without local login. |\n| `sessions` | `GET /sessions`, `GET /sessions/{id}`, `GET /sessions/{id}/messages`, `DELETE /sessions/{id}`, `POST /sessions/{id}/messages/{message_id}/feedback`, `GET /sessions/{id}/followup` | List, read and delete saved chat sessions (assistant messages carry their row `id` and any `feedback`). The list is scoped to the caller. With `?q=` it is a search: the caller's own chats whose title or message text contains the words (case-insensitive, `LIKE` with wildcards escaped), each with `match_count` (messages that contain them; 0 for a title-only match) and `snippet` (the newest matching message, around the match, prefixed `You:` or `Executive:`). Scoped exactly like the list, so nobody else's conversation can match. The Chats page searches this way and opens a result with `?find=`, so the chat starts on that message and steps through the others. A chat-app conversation started with /new is left off the list until its first turn (`memory.conversations`). Every per-session route checks ownership, because session ids are guessable (`slack:dm:<user id>`, `telegram:<chat id>`): only the session's owner or the principal gets through, and a legacy row with no owner is the principal's alone. 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. |\n| `today` | `GET /today`, `GET /today/activity`, `GET /today/activity/daily`, `GET /today/brief-delivery`, `GET /today/top-three`, `GET /today/weekly-review` | Morning-brief aggregation, recent-action rail, and Pulse heartbeat heatmap (per-day activity counts). `GET /today` carries the viewer's cached \"What's going on\" `narrative` with `narrative_generated_at` (when it was written) and `narrative_stale` (a fresher one is being written — the page re-polls; see Today). A proposal backed by a roster request carries `roster_request` (the new sender's server-derived details and held-message previews; the principal's only) and is answered through the `people` routes below. `brief-delivery` returns the latest morning brief or end-of-day digest that didn't reach the owner, as `{brief, at, problem, fix, readable}` in plain language (`readable` is false when it couldn't be written, so there is nothing to read), or null — null while briefs go out, once the cause is fixed, while the scheduler is off, and for anyone but the owner (`chat._caller_is_principal_or_unclaimed`); it carries no address or channel id. `top-three` and `weekly-review` feed the solo Briefing's own cards and answer only in solo mode and only to the principal (`workflows._caller_is_the_principal`: a principal match or no caller header, never an unclaimed roster); anyone else, and team mode, get null. `top-three` returns `{items: [{key, kind, text, why, slot}]}` — the morning brief's top three from the same code (`build_top_three(principal_due_soon())`), `slot` a free block like `10:00–11:00`, `\"\"` when none is left, null when no calendar was read — and is kept off `GET /today` because its calendar read may take up to 4 s. `weekly-review` returns the latest completed `weekly_review` run as `{run_id, completed_at, period, top_three, excerpt}` (next week's top three as plain text; `excerpt` when that list is empty), or null when none has completed. |\n| `people` | `GET\\|POST\\|PATCH /people`, `POST /people/{id}/archive`, `GET /people/requests`, `GET /people/requests/{id}`, `POST /people/requests/{id}/approve`, `POST /people/requests/{id}/decline`, `GET\\|POST /people/{id}/open-loops`, `POST /open-loops/{loop_id}/close`, `GET /people/{id}/outreach`, `GET\\|PUT\\|DELETE /people/{id}/attunement` | Roster CRUD and scope lookups. Every `Person` carries `kind` (`team` / `contact`). `GET /people` lists team members only unless `?include_contacts=true` (the People page asks for both; the department-head and workflow pickers keep the default); `POST` / `PATCH` accept `kind`, and a principal contact is a 422 either way. They also take `email_aliases` (other addresses the person writes from, at most 10; on `PATCH` the full list replaces the current one, omitted leaves it): an alias matches their mail and may be emailed but never signs in; a malformed one is a 422, and an alias — or a new primary `email` — that is already someone else's address or alias is a 409. Every `POST` / `PATCH` then closes any pending roster request whose sender now matches someone and replays its held messages. Adding, editing and archiving (`POST`, `PATCH`, `/archive`) are the principal's only, or anyone's while no one is principal yet so a first setup can add its owner (`chat._caller_is_principal_or_unclaimed`, the check behind `PUT /workspace`; a request with no `x-caller-email`, such as the CLI or local login, counts as the principal). Anyone else, a person editing their own row included, gets 403 before the person lookup, so it can't probe which ids exist. Contacts are private to the principal (`caller_is_principal`: the signed-in email is the principal's, or no `x-caller-email`; stricter than the owner rule above, so while no one is principal nobody is): for anyone else `include_contacts` is ignored, a contact's id is a 404 on `GET /people/{id}` and open-loops (exactly as for a missing id; `PATCH` and archive are already a 403 for them), and creating a contact or turning someone into one is a 403, even on a first setup with no principal yet. `GET /people/me` returns `{person_id, is_principal}` so the UI offers contacts to the principal only. `GET /people/by-scope/{token}` never returns a contact. Archiving a person closes their open loops. The open-loop routes list what a person owes (soonest due first) and close one (`reason`: done / not_needed / cancelled) — both the principal's or the owner's only (403 otherwise, via `people.store.is_principal_or_self`). `POST /people/{id}/open-loops` `{task, due_date?}` assigns that person a task (201 with the loop; `due_date` is a local date, due 17:00 in the user's timezone, clamped to 60 days, default 2 days): any active team member may assign anyone on the team, 403 for anyone else; 409 for an archived person, a contact (as seen by the principal), a person at the open-loop cap, a duplicate or open loops turned off; 422 for an empty task. Nobody is messaged at assignment — the owner is chased once it is due. `/outreach` returns, per kind of proactive outreach over 30 days, `sent` / `replied` / `acted` / `ignored` / `pending` (voided DMs are excluded) — same access rule, checked before the person lookup so it can't probe which ids exist. `/attunement` reads, replaces (`rules`: up to 4 strings, or omitted to only set `locked`) or resets the person's working-style rules — same access rule, 404 for an archived person; `PUT` rejects a rule that is not purely about style with 422. Archiving a person also drops their working style and frees their aliases. The **roster-request** routes (declared before `/people/{person_id}`) are the principal's alone (`caller_is_principal`; anyone else gets 404, as for a missing id): `GET /people/requests?status=pending|approved|linked|declined|expired|superseded|all` lists up to 100 (`id`, `channel`, `channel_ref`, sanitised `display_name`, `profile_email`, `on_company_domain`, `suggested_kind`, `suggested_person_id` / `_name`, `status`, `resolved_person_id` / `_kind`, `message_count`, timestamps, `ack_sent`, and `previews` of the held messages while pending — shown to the principal, never to a model); `approve` takes either `link_person_id` (+ `replace_channel_id`) or `full_name` + `kind` (no default: 422 without both) + optional `role`; `decline` takes no body. An answered request is a 409, a chat id or address already on someone else is a 409; the held messages are replayed (or dropped) in the background. |\n| `departments` | `GET\\|POST\\|PATCH\\|DELETE /departments`, `.../goals` | Department state and per-department goals. `PATCH /departments/{slug}` also takes `watched_entities` (≤50 names, `[]` clears) — the entities the research watch policy may add watches for and route to this department. A `cadences` spec that does not parse is rejected with a 422 (empty means no cadence). 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}/ack`, `POST /alerts/bulk-ack`, `POST /alerts/{id}/reopen`, `POST /alerts/review` | Groom the briefing queue. `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), 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`, `GET /delegation/actions`, `PUT /delegation/handle-it`, `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}, team}`, where `team` is the owner's switch for the principal while `DELEGATION_TEAM_MEMBERS` allows it — `{enabled, members: [{person_id, name, enabled, inbox, drafts_30d, sent_30d}]}`, counts only — and `null` otherwise. `PUT /delegation/handle-it` takes `{enabled?, mode?}` (`mode` is `careful`, `balanced` or `bold`; anything else is a 422 `bad_mode`) from a caller the API knows is that person — 403 `not_yours`, 409 `caller_signing_required` with only the shared secret — and turning it on needs Act as me and Draft replies to my inbox on (409 `act_as_me_off` / `inbox_off`); `GET /delegation/handled` returns `{replies: [{decision_id, sent_at, to_name, to_email, subject, body, open_questions, gmail_link, source}]}`, the caller's replies and follow-ups (`source` `follow_up`) sent on its own in the last 7 days; a card on `GET /delegation/replies` carries `source` the same way, `can_allow` while Replies (Follow-ups, on a follow-up) is in training, and `learns_style` while Drafts is. `PUT /delegation/training` takes `{replies?, follow_ups?, actions?, drafts?}` (any other field is a 422) and returns the `GET /delegation` shape; putting Replies or Follow-ups in, or Suggested actions out, needs no signed sign-in, anything else does (409 `caller_signing_required`), and putting Replies or Follow-ups in turns Take the lead as you off (`PUT /delegation/take-the-lead` on answers 409 `in_training` while they are). `training.learned` is `[{id, label, setting, example, uses, created_at}]`, what the caller allowed or kept in training (`setting` `replies`, `follow_ups`, `actions` or `drafts`; the kept example, or \"\"); `DELETE /delegation/learned/{id}` removes one of the caller's own (404 for anyone else's). `PUT /delegation/team` takes `{enabled}` from the principal alone (403 `principal_only`; 409 `not_available` when the install doesn't allow it). The Gmail `status` is `connected`, `not_configured`, `needs_reconnect`, `mismatch`, `no_email`, `shared_mailbox` or `error`, checked live with Google on each call. `PUT` takes `{enabled}` (any other field is a 422); turning it on needs the caller's own Gmail connected, otherwise a 409 whose code says why (`gmail_not_connected`, `gmail_needs_reconnect`, `gmail_mismatch`, `no_email`, `shared_mailbox`, `gmail_error`). The voice routes show, learn (from the caller's sent mail, one pass at a time — a 409 `in_progress`, `locked`, `too_soon`, `not_enough_mail`, `no_profile` or `changed` when it was locked or edited while learning, or a Gmail code), write it from the caller's own description (`POST /delegation/voice/describe` with `{description}`: one model call applies their words to the profile they have and returns it with a short `sample_reply`, saving nothing, so they review it and save it with `PUT`; a 409 `empty`, `too_long`, `in_progress`, `too_many` past 10 an hour or `no_profile`; no mailbox needed), edit and lock, and reset \"How I write\": a typed field that fails validation is a 422 `invalid_voice` listing each `rejected` field, and `clear_exemplars` / `clear_signature` drop those. `POST /delegation/voice/signature` reads the signature from the caller's Gmail settings again and changes nothing else (a locked profile stays locked), with the same Gmail codes as learning: a 409 when their mailbox isn't connected, it refuses the sign-in or the check itself fails (`gmail_error`), and a 502 `gmail_error` when reading the signature fails. On an Outlook mailbox it is a 409 `signature_unavailable`, since Outlook gives apps no signature to read, and the stored one is left alone. A caller `can_delegate` refuses — anyone but the principal, for now — gets 403 `not_available_yet`, which hides the Settings card. A request with no `x-caller-email` is a 403 `sign_in_required` unless the API runs under local login — a header-less call is not a sign-in (the caller is read through `api/caller.py`, as on every principal-only route). `PUT /delegation/inbox` takes `{enabled}` and turns **Draft replies to my inbox** on or off, returning the same shape as `GET /delegation`: on needs Act as me on (409 `act_as_me_off`) and the mailbox connected (the Gmail codes above, which keep their names for an Outlook mailbox too), and turning Act as me off turns it off too. `POST /delegation/inbox/check` starts a scan now in the background and answers 202 with the `inbox` state (409 `inbox_off` or `in_progress`). `GET /delegation/replies` returns `{cards: [...]}`, the caller's open reply cards from the database alone (no Gmail call): the decision id, the sender's name, address, relation and whether it was verified, the subject, when it arrived, what they wrote, the draft's recipients, subject and body, `open_questions`, `flags` and a Gmail link built from a fixed prefix. **Send** is `POST /decisions/{id}/approve`: it sends the card's draft exactly as it is in Gmail, after checking again that the caller is its owner — which on a server needs signed callers (409 `caller_signing_required` otherwise) — that both switches are on (`inbox_off`), no client slot is active (`client_slot`), the Gmail is connected (the Gmail codes), the draft is still there and unanswered (`draft_gone`, `you_replied`) and its recipients are allowed (`no_recipients`, `too_many_recipients`, `executive_recipient`, `not_from_you`). Recipients that changed, or a newer message in the thread, answer 409 `{code: \"confirm\", message, reasons, recipients}`; approving again with `edits: {recipients: <the list shown>, thread_moved_on: true}` is the second yes. **Send + allow** adds `edits.allow: true`: 422 `cant_allow` unless Replies (Follow-ups, on a follow-up card) is in training, 409 `learned_full` when their list is full, both before anything is sent; `edits.example: true` keeps a draft edited in the mailbox as how they write to that person while Drafts is in training. A draft edited in Gmail between those checks and the send is not sent (`draft_changed`). A double tap sends once (`already_handled`); Gmail refusing answers 429 `rate_limited` or 502 `gmail_error` with nothing sent, and a send Gmail didn't confirm answers 502 `send_unconfirmed` and is settled by the next inbox scan. Dismiss is `POST /decisions/{id}/reject`. `GET /delegation/actions` returns `{cards: [...]}`, the caller's own approval cards (`delegation_actions`): the decision id, when it was made, a one-line `why`, and each action's `index`, `kind` (`invite`, `message`, `add_contact`), `summary` and `text` (a message as it will be sent, or a meeting's description). **Approve** is `POST /decisions/{id}/approve` with `edits: {only: [indexes]}` (and `allow: true` for Approve + allow while Suggested actions is in training: 422 `cant_allow` otherwise or when nothing on it can be allowed, 409 `learned_full`; a card carries `can_allow`); it needs the card's own person signed in (403 `not_yours`, 409 `caller_signing_required`), Act as me on (409 `act_as_me_off`) and a card under a week old (409 `expired`), runs once (409 `already_handled`), and returns the decision with `final_payload_json.results`: per action `done`, `waiting` (sent to whoever approves meetings), `failed` with why, or `skipped`. Every change writes a private audit row. |\n| `history` | `GET /memories/history` (`?q=`), `PUT /memories/history/settings`, `PATCH`/`DELETE /memories/history/{id}`, `POST /memories/history/{id}/forget-conversation` | Always in the loop: the **caller's own** notes and switches only, resolved as for Act as me (a signed-in person on the roster, or the principal under local login; otherwise 403 `sign_in_required` / `not_on_roster`). `GET` returns `{notes, reply_notes, retention_days, effective_retention_days, company_retention_days, retention_choices, can_keep_notes, can_note_replies, can_set_company_retention, share_work_style, can_share_work_style}` (`can_keep_notes`: a team member on the People list may turn notes on; `can_note_replies`: they can use Act as me, so email replies are noted too; `share_work_style`: their own \"Share my work style with the team\" switch, `can_share_work_style`: a team member in a team workspace). `PUT` turns notes on only for someone who may keep them, and `share_work_style` on only for someone who may share it (403 `not_available` for either; turning either off always works), takes a person's retention only when shorter than the company's (422 `invalid_setting`), and the company retention only from the principal (403 `principal_only`). `PATCH` pins or corrects a note; `DELETE` forgets it; `forget-conversation` is \"Don't remember this\". A note that isn't the caller's is 404. Every change is audited privately to its person. |\n| `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 list, its `total` and the usage totals leave them out, a private row's id is a 404, and a session shows only its other rows. |\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 (unauthenticated). |\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}]}`); `/documents/{drive\\|onedrive\\|notion}/{id}` returns the stored text (a OneDrive id is `<drive id>:<item id>`) for an id on record (the path comes from the state, never the caller). They are read-only — a synced file is removed where it lives. `POST …/sync` starts one tick of the same sync the scheduler runs as a background task (202); 409 when the source is not connected or a tick is already running (every sync holds a per-process run lock, so a manual run never overlaps the heartbeat; the route also keeps its own started task per source and re-checks just before starting one, so two simultaneous requests start one tick, not two), 429 with `Retry-After` within 60 s of the last successful run or of the end of the last tick in this process, failed ones included, so a failing or slow source can't be re-run back-to-back. The page's text view never loads images from synced content (a remote image would be a read beacon for whoever edits the shared folder). Upload is keyed on the filename, so re-uploading a document replaces its chunks rather than duplicating them, and `DELETE` removes the rows as well as the file. `domain` must be one of the nine specialist domains (including `sales`) or `general`; anything else is a 400 rather than a 200 that indexes where no specialist can retrieve. A scanned PDF is converted (`knowledge.pdf_reader`) before it is indexed and in the text view, as are scanned PDFs in `POST /chat/upload` and the client / onboarding intake uploads. The upload is streamed to disk 1 MB at a time and refused with a 413 once it passes 50 MB, and the file is parsed in a short-lived child process (see the RAG section), so a large document does not stay in the API process's memory. A Word or Excel file that cannot be parsed, or whose parse runs out of time, is a 422 with a readable reason. When every parser is busy, the response is a 503 with `Retry-After`. |\n| `executive` | `GET /executive/status`, `POST /executive/pause`, `POST /executive/resume` | Operator pause switch for all autonomous work (scheduler, Gmail poller, workflow resumer); inbound chat and DMs stay live. Status returns `{paused, paused_at, paused_by, reason, held_actions, can_resume}` — `held_actions` counts due `pending` rows that fire on resume. `pause` takes an optional `reason` (≤200 chars) and is idempotent (re-pausing keeps the original start and reason); `paused_by` is the UI proxy's `x-caller-email`, else `api`. Behind the shared-secret middleware — not `SCHEDULED_ADMIN_TOKEN`, which the UI cannot send. Any caller may pause; `resume` is principal-only (`is_principal_or_self`, 403 otherwise; open while no principal is rostered; a header-less caller resolves to the principal as in `chat`), and status carries `can_resume` for the viewer so the UI hides Resume from everyone else. |\n| `workspace` | `GET /workspace`, `PUT /workspace` | Solo/team mode, the user's time zone and the principal's role (`memory.workspace_settings`). Both return `{mode, timezone, effective_timezone, role_kind, role_title, reports_to, remit, measured_on, company_domains, company_domains_custom}` — `timezone` is what the user set (null when unset), `effective_timezone` the zone in effect (`timezone`, else `USER_TIMEZONE`, else UTC), and each role field is null until set. `PUT` is a partial update: only the fields sent change; `mode` is `solo` or `team` (not null), `timezone` an IANA zone, or null/blank to clear it; `role_kind` is `owner`, `in_house`, `independent` or `other`, and `role_title` / `reports_to` / `remit` / `measured_on` are free text (trimmed, at most 120 / 120 / 500 / 300 characters), each null or blank to clear it; an unknown zone, a bad mode or role kind, an over-long role field or an unknown field is a 422 and changes nothing. Switching to solo cancels every pending department check-in, switching to team re-schedules them, and a new zone re-times the pending briefs and reflection; a role change has no side effects (the next turn reads it). `company_domains` is the company's own email domains (a teammate matches by local part on them — see Org): `GET` returns the ones in effect (the stored list, or the domain of the principal's primary address, with `company_domains_custom` false) only to the same caller the role is shown to, `[]` for anyone else; `PUT` takes a list (at most 10 plain domain names, never a free-mail provider's — 422 otherwise, the value never quoted) or null / `[]` to go back to deriving them, and a change is audited with the new list. Each change writes a `workspace_settings_changed` audit row (a role change adds `details.role_fields_changed`, the names of the fields that changed — never their text). The role is the principal's: `GET` returns it only to a caller `PUT` would accept and reads it as nulls for anyone else. `PUT` is the principal's alone (`is_principal_or_self`, 403 otherwise; a header-less caller resolves to the principal as in `chat`) and open while no principal is rostered, so first-run setup can pick a mode. Both work before onboarding — unlike `company-profile`, nothing here needs a profile. |\n| `scheduled` | `GET\\|DELETE` scheduled actions (`?status=…&order=asc\\|desc`) | Pending and fired scheduled actions; `order` flips the `run_at` sort (asc=soonest-first for the upcoming queue, desc=most-recent-first for terminal-status history). `DELETE /scheduled/{id}` cancels a `pending` row (409 otherwise). Like pause it only stops work, so any signed-in user may — the UI proxy's `x-caller-email` is trusted when the request also carries the `BACKEND_SHARED_SECRET` `x-api-key` — as may a matching `X-Admin-Token` (`SCHEDULED_ADMIN_TOKEN`) or a loopback caller with no token set; otherwise 401 (token set) or 503. Audited as `scheduled_action_cancelled`. |\n| `watchlist` | `GET\\|POST\\|PATCH\\|DELETE /watchlist`, `POST /watchlist/{slug}/approve`, `POST /watchlist/{slug}/decline` | External-monitoring watchlist + signals. Rows carry `origin` (`manual` \\| `executive` \\| `research` \\| `research_proposed`); `approve` turns a research suggestion (`research_proposed`, `dry_run`) into a live watch, `decline` `{reason: not_relevant \\| too_noisy \\| wrong_source}` removes it and records the decline (or, for `too_noisy`, keeps it live at a high floor), both 409 unless the row is a pending suggestion; `DELETE ?reason=` on a research-origin row records the decline too. |\n| `workflows` | `GET /workflows`, `POST /workflows/{name}/runs`, `GET\\|POST\\|PUT\\|DELETE /workflows/custom`, `GET\\|DELETE /workflows/custom/{name}/targets`, `POST /workflows/runs/{run_id}/decision`, `GET /workflows/tools/search?q=`, `GET /workflows/tools/describe?names=` | Workflow catalog, run management, and user-created (dynamic) workflow CRUD. Custom definitions come back with a server-managed `owner_person_id` (the creator — the web caller on `POST`, set on insert only; a client-sent value is ignored), who is asked to approve a workflow's first write to a new target. `GET /workflows/custom/{name}/targets` lists the targets its tool steps may write to without asking and `DELETE …/targets?value=` forgets one. `POST /workflows/{name}/runs` is a 403 (\"Only the principal can run this workflow.\"), audited, before any run row exists, when the workflow is one only the principal may start in the workspace's mode (`weekly_review` always, `morning_brief` in solo) and the caller is not the principal. A request with no `x-caller-email` counts as the principal; with no principal on the roster, no signed-in caller does. This governs starting a run only. A run started by hand (this endpoint, or `run_workflow` / research in chat) records its starter as `owner_person_id` and is theirs alone: `GET /workflows/runs` lists the team's (scheduled, no owner) runs plus the caller's own and the ones waiting on them, and `GET` / `DELETE /workflows/runs/{run_id}` and `POST /workflows/runs/{run_id}/decision` are a 404 for anyone else's, the principal included. A signed-in email that is on nobody's People entry cannot start one (403), and a run whose starter can't be read is refused (503); its steps read and draft documents as the starter only. `POST /workflows/runs/{run_id}/decision` with `{decision: \"approve\"|\"reject\"}` answers a run awaiting a yes/no sign-off from the web app — 403 unless the caller is the person it waits on or the principal, 409 if it isn't awaiting or needs a written reply — through the same `apply_resolution` a chat reply uses. Custom create/update also rejects (422) any action-step tool that does not resolve, and so does `POST /workflows/custom/{name}/activate` when turning a workflow **on** — that click is the approval for a tool workflow chat saved switched off (turning off is never checked). Turning on a workflow with action steps requires the body `{is_active: true, definition}` carrying the definition the user reviewed; if the stored one differs (ignoring `is_active` and timestamps) it returns 409, and the switch itself is a compare-and-set on the validated revision (`dynamic_store.activate_if_unchanged`, keyed on `updated_at`), so a save that lands while the tool check awaits the gateway — even from another process — is a 409 too, so only what was shown gets switched on. `GET /workflows/custom` lists inactive definitions too; `GET /workflows/{name}` 404s for them. The two `tools` endpoints return `{tools: [{name, description, read_only, source}]}` for the advanced editor's tool picker and the review card; `read_only` is true only when the name says it reads (a label, not a control). The run stream adds a `progress` event (`step_id`, `summary`) while an action step uses tools. Each catalog entry (`WorkflowMeta`) carries `is_custom`, `background` (true for the system-run built-ins the UI files under “System”) and `quick` (true for a Quick workflow, one per playbook nothing else follows, named `quick_<playbook>`). The run endpoint streams SSE; its `awaiting_human` event carries `delivery` (`self` \\| `sent` \\| `suppressed` \\| `alerted` \\| `failed`) alongside `person_id` / `question` / `awaiting_until`, because the outbound guard or an unreachable approver means the question may never have been asked — a client must not render “waiting on them” for those. A paused run ends the stream with neither `done` nor `error`, so that `awaiting_human` frame carries `terminal: true` to say so explicitly, plus `resumable` — whether the run continues by itself once answered or stops at the gate. `GET /workflows/runs/{run_id}` returns the run row with the resume payload replaced by a small `resume_progress` summary (`gate_step_id`, `completed_step_ids`, or `null`): the payload holds every completed step's full text, and the run-detail page polls this endpoint while a run is unfinished. |\n| `knowledge` | `/knowledge/builtin`, `/external`, `/search` | MBA knowledge base and external sources. `/search` is the introspection parallel of `retriever.retrieve` and mirrors its filters — including the `general` catch-all on the company collection — so the panel cannot report a specialist seeing nothing that it does retrieve in chat. It accepts `general` in `domain_filter` for the same reason. `/search` applies the same review gate as `retrieve()` — withheld (pending or rejected) built-in, external and failure rows are dropped, so the panel never advertises knowledge the Executive cannot use; it degrades to unfiltered rather than failing if review state is unreadable. `POST /knowledge/builtin` refuses a name already held by shipped content, and `POST|DELETE /knowledge/failures` now register and deregister for review — without that a user-authored failure case study had no review row, so no SME decision could block it. |\n| `skills` | `/skills`, `/skills/search`, `/skills/{name}/restore` | Skill registry (the UI's **Playbooks**) CRUD and search. `PUT` on a built-in saves a company customization that shadows it; `DELETE` returns `{name, outcome}` — `deleted`, `reverted` (customization removed, built-in back) or `hidden` (built-in hidden for this company); `restore` un-hides; `GET /skills?include_hidden=true` lists hidden built-ins. List and detail carry `used_by` — `[{name, title, is_custom}]` of the workflows that follow the playbook (switched-off custom ones included) (`WorkflowMeta.playbooks` is the other direction). |\n| `evals` | `/evals/scenarios`, `/evals/runs` | Eval scenarios and run results. `POST /evals/runs` is a 403 when a workflow scenario names a workflow that only the principal may start in the mode it runs in (the weekly review; the morning brief in solo) and the caller is not the principal — the Jobs page's rule for starting a run; stored results are read under the existing `/evals/runs` rules. |\n| `memories` | `/memories/{decisions,initiatives,advice}`, `GET /memories/facts`, `POST /memories/facts/{fact_id}/{retire,approve,decline}`, `GET /memories/facts/approval`, `PUT /memories/facts/approval/{person_id}`, `GET /memories/people`, `GET /memories/people/{person_id}/conclusions` | Episodic-memory record management; the standing facts the Pulse Corrections tab reads (`{facts: [...], can_retire, retirable_ids, can_review}`; each fact carries `recorded_by_role` / `recorded_by_name`; `?include_inactive=` default true, honoured for the principal only; anyone else gets the active rows plus their own `proposed` ones, with the provenance (`session_id`, `turn_id`, `recorded_by_person_id`, `retired_reason`, and `source_quote` except on their own facts) blanked, never retired, replaced or declined text; `?limit=` 1–500) and their retire (the principal any fact, a teammate only one they recorded that the principal has not approved — else 403; the audit row names the teammate; 404 for an unknown or `profile` row, 409 when no longer active; writes a private `fact_retired` audit row); approve / decline a teammate's `proposed` fact (principal only, else 403; 409 when it is not proposed; private `fact_reviewed` row); and the per-teammate \"needs my approval\" switch (on by default; `GET` lists `[{person_id, full_name, needs_approval}]` for every active team member but the principal, `true` for anyone not yet set; `PUT` takes `{needs_approval}`, 404 for anyone else; both principal only; private `fact_approval_changed` row); plus the read-only peer-memory overview the Pulse People tab reads (`{status: ok|disabled|error, people: [...], conclusion_total}`; `?recent=` 1–50, default 5) and one person's full conclusion list, paged newest first (`{status, person_id, items, page, size, total, has_more}`; `?page=` ≥1, `?size=` 1–100, default 50; 404 when the person has no peer). Peer memory is each person's own: the overview holds only the caller's entry (none for a caller off the roster; `conclusion_total` counts only theirs), the principal included, and `/conclusions` for anyone but the caller is a 404. |\n| `review` | `/review/items`, `/review/stats`, `/review/trusted-defaults`, `POST /review/curate`, `POST /review/bulk-approve` | Knowledge review queue and annotations. Shipped knowledge registers as a trusted default (`approved` with a NULL `reviewed_at`), so the queue starts empty; `curate` (`{domain, action: start|stop}`, domain required) opts one domain in or out, and `trusted-defaults` returns domain → unreviewed count. `bulk-approve` takes a non-empty `domain`, `item_ids` (max 500) or `all_pending: true`, and 400s with no selector; it returns `{approved_count, item_ids}`. |\n| `onboarding` | `/onboard/interview/understand`, `/onboard/interview/start`, `/onboard/interview/message`, `/onboard/interview/draft`, `/onboard/interview/{id}`, `/onboard/interview/commit` | Conversational company setup. The `onboarding_interviewer` agent asks clarifying questions, then emits a draft profile + people + departments. **Nothing is persisted until `POST /onboard/interview/commit`** — the interview itself never writes. `start` is multipart (description + optional deck/one-pager uploads). `commit` answers 403 when the draft would make a different person the owner and the caller is not the current owner (setup demotes the old principal, and any signed-in user can open it). It also takes an optional `owner_email` — the principal's sign-in email, which the review screen pre-fills from the signed-in user — checked before anything is written (422 if it is malformed, already another person's, or would replace the principal's existing email — setup only fills in a missing one; 403 if the caller is not the owner and it is not the address they signed in with, since the roster is the sign-in allow-list) and saved on the principal's People row, so the owner's chats resolve to them from the first turn. |\n| `workflow_designer` | `POST /workflows/designer/start`, `POST /workflows/designer/edit`, `POST /workflows/designer/message`, `POST /workflows/designer/draft`, `GET /workflows/designer/{session_id}` | The conversational New workflow wizard, and editing a saved workflow by conversation. `/edit` (`{name}`) opens a session on a saved custom workflow with no model call: the stored definition is the starting draft, and every response then carries `editing` (its name) and `original` (the stored definition as the session opened on it); drafts keep that name and its on/off state whatever the model writes (404 for an unknown workflow). The UI saves one with `POST /workflows/custom/{name}/save-edit` (`{session_id, definition}`): the server saves the session's own draft, never a client-sent body, and only when it equals the `definition` the user reviewed (a later message is a 409, so the click saves only what was shown); it re-validates it, keeps the stored on/off state, and writes only if the stored workflow is still the version the conversation opened on — otherwise 409, as it is for a session about another workflow or one with nothing drafted yet. It sits under `/workflows/custom` so anything that limits writes to custom workflows covers it too. The `workflow_designer` agent asks clarifying questions (`phase: \"question\"`, with `hint` and up to four suggested `options`), then returns `phase: \"draft\"` with `draft.definition` (exactly the body `POST /workflows/custom` takes), `summary`, and `assumptions`; every response carries the `transcript`. **Nothing is persisted here** — sessions are in memory, and the UI saves through `POST /workflows/custom`. Errors are fixed strings (422 over the 8,000-char message cap or the transcript cap, 404 for an expired session, 409 while another turn on the same session is still running, 502/504 for model failure or timeout). Mounted ahead of the `workflows` router. |\n| `python_jobs` | `GET /python-jobs/{job_id}/{name}` | A result file a Python job (`run_python_job`) wrote, the principal's alone (403 otherwise), served as a download (`Content-Disposition: attachment`, `Content-Security-Policy: sandbox`, `nosniff`, `Cache-Control: no-store`); 404 for a bad id or name or a file past its 7 days. |\n| `saved_tools` | `GET /saved-tools`, `GET\\|PUT /saved-tools/{name}`, `POST /saved-tools/{name}/rollback` | The scripts the Executive saved as tools (Settings → Advanced → Saved tools), the owner's alone (403 otherwise). The list gives each tool's name, description, on/off, current version, `kind` (`script` or `python`, a kept Python job) and the tools it calls, plus whether `SAVED_TOOLS_ENABLED` is on; the detail adds the script, every version and the last 20 runs. `PUT {enabled?, workflows?, version?}` turns one on or off (off also turns it off for workflows, so turning it back on never re-arms unattended runs), and turns the named `version` — the one the owner looked at, never whatever is current by then — on for workflows (or workflows off); a Python tool never turns on for workflows (409) — turning workflows on lets more run unattended, so it needs a request tied to the owner (signed sign-ins or local login, as Take the lead's switches do; 409 otherwise); `rollback {version}` makes that version the one that runs. Both are audited as `saved_tool_changed`. The Executive saves tools itself through `run_script`; there is no create route. |\n| `onboarding` (fallback) | `/onboard/start`, `/onboard/answer`, `/onboard/status/{id}` | The original 12-step form wizard, kept as a fallback (UI at `/onboard?mode=form`) and used by the `openexecutive onboard` CLI. Its final answer saves the profile and adds people with their emails and a principal, so once there is an owner only they can send it (403, and the session rolls back so the owner can still finish it). `/onboard/start` reads the workspace mode once for the session: solo skips the Team Size, Team Members and Fractional Executives steps. Each status response's `current_step` / `total_steps` count only the steps that session asks, and `optional` says whether the current step can be skipped. |\n| `company-profile` | `GET\\|PATCH /company-profile` | Structured company profile. |\n| `alerts` (private cards) | `POST /alerts/{id}/ack`, `/reopen`, `/alerts/bulk-ack` | An alert tagged `private:principal` (see Today) is a 404 on ack and reopen for anyone but the principal, and their bulk sweep skips it. A roster-request card (source `roster_request`) is a 409 on `ack` even for the principal — it is answered at `/people/requests/{id}`, since acking would leave the sender waiting with nothing to show it — and, as an exempt source, `bulk-ack` and `reopen` skip it. |\n| `auth` | `GET /auth/allowed-emails` | Non-archived **team members** with an email, offered to the UI's sign-in gate — a contact is never on it, so adding a client to reach them by email no longer lets them sign in. The gate takes the **union** of this roster and its own `ALLOWED_EMAILS` env list, so env entries always work (and are checked first, short-circuiting the fetch) and roster entries are additive — a roster change can never revoke a configured operator. With local login (`make dev` with Google sign-in not set up — the UI then listens on 127.0.0.1 only) the UI signs in without an email, sends no `x-caller-email`, and the backend resolves the caller to the principal, as it does for the CLI. |\n| `fixtures` | `/fixtures`, `/fixtures/{name}/load` | Demo-company fixture load/reset/snapshot. `POST /fixtures/reset` leaves no departments, like a new install (`departments_seeded` is always 0). |\n| `clients` | `/clients`, `/clients/generate`, `/clients/cockpit`, `/clients/save`, `/clients/{slug}/activate` | Client-company slots — multi-client mode for fractional use; create from current/blank/AI-generated intake draft (pasted notes and/or file attachments, multipart on `/clients/generate`), save-back switching, engagement metadata (PATCH), cross-client cockpit, delete. See the Client Companies section. |\n| webhooks | `POST /webhook/telegram`, `POST /webhook/google-chat` | Inbound integration callbacks (self-verified). |\n| MCP server | `POST\\|GET /mcp` | Open Executive exposed as an MCP server (Streamable-HTTP). Not a router — a mounted FastMCP sub-app. Same shared-secret gate (`x-api-key`); exposes company context as resources and the specialist council as tools. See the MCP Server section. |\n\n**Take the lead** (`api/routes/take_the_lead.py`): `GET /take-the-lead` returns the As the Executive switch, its six Ask first switches (`{kind, label, hint, on}`, the hint a plain line on what each one catches), the company's rules, whether this server can tie a change to the owner (`available`), and whether the Executive is paused. `PUT /take-the-lead` takes `{enabled?, ask_first?}`, and `POST /take-the-lead/rules` / `DELETE /take-the-lead/rules/{id}` add or remove a company rule (`{kind: person|domain|words|amount, value}`, 422 on a bad one). All four are the principal's alone (403). Anything that lets more happen on its own (turning it on, turning an Ask first off, removing a rule) needs a caller the API can tie to them (`delegation.verified.caller_refusal`, else 409). `GET /today/activity` adds `took_the_lead` rows (what Take the lead did, named, not quoted) and, for the caller alone, `sent_as_you` rows for what Handle it for me sent as them. Under `/delegation`: `PUT /delegation/take-the-lead {enabled}` is Take the lead as you (the owner's only for now; turning it on turns Handle it for me on), and `GET|POST /delegation/take-the-lead/rules` and `DELETE …/rules/{id}` manage the caller's own rules. `HandleItOut` gains `lead` and `lead_available`. A `take_the_lead_action` decision is approved or rejected through the existing `/decisions/{id}/approve|reject`. Training: the response also carries `training` (In training: everything waits unless allowed), `learned` (`{id, label, feature, example, uses, created_at}`: what it was allowed, the edit kept as an example by field) and `suggested` (`{key, label, approvals}`); `PUT` takes `training?` too, and leaving training while on needs the same provable owner as turning it on. `POST /take-the-lead/learned {key}` allows a current suggestion (404 for anything else; provable owner), `DELETE /take-the-lead/learned/{id}` makes it ask first again. `learned` also lists the owner's own Act as me senders (`feature` `act_as_me`), never anyone else's, and Remove works on those too. On a `take_the_lead_action` card, `POST /decisions/{id}/approve` takes `edits.input` (the card's editable fields, 422 for any other; the principal's alone, 403 for an area approver) and `edits.allow: true` (a training card only, 422 otherwise; the principal from a provable request, 403 otherwise), finishing `approved_with_edit` when a field changed.",+ "markdown": "The FastAPI surface lives in `openexecutive.api.main`, which mounts one router per topic. A shared-secret middleware gates every request via an `x-api-key` header, except `/health` and the `/webhook/*` callbacks (which carry their own verification). With local login (`OE_LOCAL_LOGIN=1`, which only `make dev` sets, and only while neither Google nor SSO sign-in is set up) a second middleware answers 403 to any request whose raw `Host` is not `localhost`, `127.0.0.1` or `[::1]` (except a webhook that verifies its caller: Google Chat 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 configured UI origins. 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` | SSE stream of a live Executive turn. `POST /chat/add` hands the running turn a message the person typed while it works; the turn takes it at its next step and the stream names it in a `message_added` event, and a second `POST /chat` on the same conversation waits for the first to finish. The request body optionally carries `page_context` (route, page title, guide section id, and a form descriptor with current values) — sent only by the Ask OE side panel so the Executive can explain the current page or propose form values. When the Executive calls its `propose_form_values` tool, the stream emits a `form_patch` event (`{type, form_id, fields, rationale, iteration}`) that the panel applies into the on-screen form as highlighted suggestions; the user reviews and saves through the form's normal submit path. Each round of tool calls also emits an `activity` event (`{type, label, tool, iteration}`) naming what is running — progress only, forwarded verbatim and never persisted with the message, unlike an `action_taken` chip. A `session_id` in the body must be a chat the caller may use (the same ownership rule as `sessions`). If it isn't, the turn runs in a fresh chat instead, so nothing is written into someone else's session and the reply looks the same as for an unknown id. An unknown namespaced id (`slack:…`, `telegram:…` and so on) is ignored and a fresh chat is started, because those ids belong to the channel adapters and claiming one first would make the caller its owner. The client mints a `client_turn_id` and sends it with the turn; `POST /chat/stop` takes that id and halts the turn mid-flight, so the button is live from the moment Send is pressed rather than only once the first SSE byte arrives. A stopped turn emits a `stopped` event and then the usual `done` over the same still-open stream — never an `error` — and whatever streamed so far is persisted and flagged. The endpoint returns 404 both for an unknown id and for another caller's turn, so it cannot be used to probe which turns are live. An optional `memory_text` (1–2000 chars) is what peer memory records as the caller's words instead of `message` — the briefing handoffs send it because their seed quotes the Executive's own card; `POST /chat/upload` derives it from the typed text and filenames. Since it never reaches the transcript, the `chat_turn` audit row keeps it beside `message`. After the reply — a stopped or timed-out one too, before the `stopped` / `error` / `done` frames — a turn that looked at anything sends one `sources` event, `{type, session_id, sources: [{kind, title, url}], unavailable: [area]}`: `kind` is `company`, `knowledge`, `notion`, `research`, `document` or `web`, `url` is only ever an http(s) link or, for an earlier document, `/artifacts/<id>`, at most 12 sources (6 from the web, pages the reply cites first), and `unavailable` names parts of the analysis (\"finance\") whose specialist failed or said nothing every time it was asked. It is persisted with the reply as `chat_messages.sources`. A request that carries `x-caller-email` marks its turn signed in (`Session.web_caller_signed_in`), which Act as me needs on a deployment without local login. |\n| `sessions` | `GET /sessions`, `GET /sessions/{id}`, `GET /sessions/{id}/messages`, `DELETE /sessions/{id}`, `POST /sessions/{id}/messages/{message_id}/feedback`, `GET /sessions/{id}/followup` | List, read and delete saved chat sessions (assistant messages carry their row `id` and any `feedback`). The list is scoped to the caller. With `?q=` it is a search: the caller's own chats whose title or message text contains the words (case-insensitive, `LIKE` with wildcards escaped), each with `match_count` (messages that contain them; 0 for a title-only match) and `snippet` (the newest matching message, around the match, prefixed `You:` or `Executive:`). Scoped exactly like the list, so nobody else's conversation can match. The Chats page searches this way and opens a result with `?find=`, so the chat starts on that message and steps through the others. A chat-app conversation started with /new is left off the list until its first turn (`memory.conversations`). Every per-session route checks ownership, because session ids are guessable (`slack:dm:<user id>`, `telegram:<chat id>`): only the session's owner or the principal gets through, and a legacy row with no owner is the principal's alone. 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. |\n| `today` | `GET /today`, `GET /today/activity`, `GET /today/activity/daily`, `GET /today/brief-delivery`, `GET /today/top-three`, `GET /today/weekly-review` | Morning-brief aggregation, recent-action rail, and Pulse heartbeat heatmap (per-day activity counts). `GET /today` carries the viewer's cached \"What's going on\" `narrative` with `narrative_generated_at` (when it was written) and `narrative_stale` (a fresher one is being written — the page re-polls; see Today). A proposal backed by a roster request carries `roster_request` (the new sender's server-derived details and held-message previews; the principal's only) and is answered through the `people` routes below. `brief-delivery` returns the latest morning brief or end-of-day digest that didn't reach the owner, as `{brief, at, problem, fix, readable}` in plain language (`readable` is false when it couldn't be written, so there is nothing to read), or null — null while briefs go out, once the cause is fixed, while the scheduler is off, and for anyone but the owner (`chat._caller_is_principal_or_unclaimed`); it carries no address or channel id. `top-three` and `weekly-review` feed the solo Briefing's own cards and answer only in solo mode and only to the principal (`workflows._caller_is_the_principal`: a principal match or no caller header, never an unclaimed roster); anyone else, and team mode, get null. `top-three` returns `{items: [{key, kind, text, why, slot}]}` — the morning brief's top three from the same code (`build_top_three(principal_due_soon())`), `slot` a free block like `10:00–11:00`, `\"\"` when none is left, null when no calendar was read — and is kept off `GET /today` because its calendar read may take up to 4 s. `weekly-review` returns the latest completed `weekly_review` run as `{run_id, completed_at, period, top_three, excerpt}` (next week's top three as plain text; `excerpt` when that list is empty), or null when none has completed. |\n| `people` | `GET\\|POST\\|PATCH /people`, `POST /people/{id}/archive`, `GET /people/requests`, `GET /people/requests/{id}`, `POST /people/requests/{id}/approve`, `POST /people/requests/{id}/decline`, `GET\\|POST /people/{id}/open-loops`, `POST /open-loops/{loop_id}/close`, `GET /people/{id}/outreach`, `GET\\|PUT\\|DELETE /people/{id}/attunement` | Roster CRUD and scope lookups. Every `Person` carries `kind` (`team` / `contact`). `GET /people` lists team members only unless `?include_contacts=true` (the People page asks for both; the department-head and workflow pickers keep the default); `POST` / `PATCH` accept `kind`, and a principal contact is a 422 either way. They also take `email_aliases` (other addresses the person writes from, at most 10; on `PATCH` the full list replaces the current one, omitted leaves it): an alias matches their mail and may be emailed but never signs in; a malformed one is a 422, and an alias — or a new primary `email` — that is already someone else's address or alias is a 409. Every `POST` / `PATCH` then closes any pending roster request whose sender now matches someone and replays its held messages. Adding, editing and archiving (`POST`, `PATCH`, `/archive`) are the principal's only, or anyone's while no one is principal yet so a first setup can add its owner (`chat._caller_is_principal_or_unclaimed`, the check behind `PUT /workspace`; a request with no `x-caller-email`, such as the CLI or local login, counts as the principal). Anyone else, a person editing their own row included, gets 403 before the person lookup, so it can't probe which ids exist. Contacts are private to the principal (`caller_is_principal`: the signed-in email is the principal's, or no `x-caller-email`; stricter than the owner rule above, so while no one is principal nobody is): for anyone else `include_contacts` is ignored, a contact's id is a 404 on `GET /people/{id}` and open-loops (exactly as for a missing id; `PATCH` and archive are already a 403 for them), and creating a contact or turning someone into one is a 403, even on a first setup with no principal yet. `GET /people/me` returns `{person_id, is_principal}` so the UI offers contacts to the principal only. `GET /people/by-scope/{token}` never returns a contact. Archiving a person closes their open loops. The open-loop routes list what a person owes (soonest due first) and close one (`reason`: done / not_needed / cancelled) — both the principal's or the owner's only (403 otherwise, via `people.store.is_principal_or_self`). `POST /people/{id}/open-loops` `{task, due_date?}` assigns that person a task (201 with the loop; `due_date` is a local date, due 17:00 in the user's timezone, clamped to 60 days, default 2 days): any active team member may assign anyone on the team, 403 for anyone else; 409 for an archived person, a contact (as seen by the principal), a person at the open-loop cap, a duplicate or open loops turned off; 422 for an empty task. Nobody is messaged at assignment — the owner is chased once it is due. `/outreach` returns, per kind of proactive outreach over 30 days, `sent` / `replied` / `acted` / `ignored` / `pending` (voided DMs are excluded) — same access rule, checked before the person lookup so it can't probe which ids exist. `/attunement` reads, replaces (`rules`: up to 4 strings, or omitted to only set `locked`) or resets the person's working-style rules — same access rule, 404 for an archived person; `PUT` rejects a rule that is not purely about style with 422. Archiving a person also drops their working style and frees their aliases. The **roster-request** routes (declared before `/people/{person_id}`) are the principal's alone (`caller_is_principal`; anyone else gets 404, as for a missing id): `GET /people/requests?status=pending|approved|linked|declined|expired|superseded|all` lists up to 100 (`id`, `channel`, `channel_ref`, sanitised `display_name`, `profile_email`, `on_company_domain`, `suggested_kind`, `suggested_person_id` / `_name`, `status`, `resolved_person_id` / `_kind`, `message_count`, timestamps, `ack_sent`, and `previews` of the held messages while pending — shown to the principal, never to a model); `approve` takes either `link_person_id` (+ `replace_channel_id`) or `full_name` + `kind` (no default: 422 without both) + optional `role`; `decline` takes no body. An answered request is a 409, a chat id or address already on someone else is a 409; the held messages are replayed (or dropped) in the background. |\n| `departments` | `GET\\|POST\\|PATCH\\|DELETE /departments`, `.../goals` | Department state and per-department goals. `PATCH /departments/{slug}` also takes `watched_entities` (≤50 names, `[]` clears) — the entities the research watch policy may add watches for and route to this department. A `cadences` spec that does not parse is rejected with a 422 (empty means no cadence). 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}/ack`, `POST /alerts/bulk-ack`, `POST /alerts/{id}/reopen`, `POST /alerts/review` | Groom the briefing queue. `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), and an instance of a class with no spec gets 409 instead of being carried out as another. Only the principal, or the person the decision went to for approval (`approver_person_id`), may approve, reject or cancel it. Anyone else gets 403, and a decision nobody was asked about, or one private to the principal, is the principal's alone. The resolver is recorded as `resolver_person_id`, and a reject that loses the race to another answer is a 409. `GET /audit/reliability` is the principal's alone (403 otherwise), because it counts private decisions too. A proposed booking is surfaced on the briefing as a companion alert; approve/reject/cancel here also clear that alert. An approval whose caller resolves to the principal runs the booking inside `grant_contact_egress()`, so a meeting the principal proposed with a contact can be created. Such a booking's payload is marked `private`: it is proposed to the principal, left out of anyone else's `GET /decisions`, and a 404 for them on `GET /decisions/{id}` and every action route. Reviewed in the briefing — there is no separate proposals page. The class routes read and set how meetings are handled: both return `{decision_class: \"meeting_scheduling\", mode: \"propose\" \\| \"auto_execute\"}` (default `propose`); the `PUT` body is `{mode}`, principal-only (403 otherwise, open before a principal exists — but then only `propose` can be set: `auto_execute` is a 409 until a non-archived principal is on the roster), 422 on any other mode, and a change writes a `decision_class_mode_changed` audit row. In solo mode the class mode decides a booking, and `auto_execute` applies only to a turn the principal started on a verified surface — any other turn gets a proposal. |\n| `delegation` | `GET`/`PUT /delegation`, `GET`/`PUT`/`DELETE /delegation/voice`, `POST /delegation/voice/learn`, `POST /delegation/voice/describe`, `POST /delegation/voice/signature`, `PUT /delegation/inbox`, `POST /delegation/inbox/check`, `GET /delegation/replies`, `PUT /delegation/replies/{id}/text`, `GET /delegation/actions`, `PUT /delegation/handle-it`, `PUT /delegation/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}, team}`, where `team` is the owner's switch for the principal while `DELEGATION_TEAM_MEMBERS` allows it — `{enabled, members: [{person_id, name, enabled, inbox, drafts_30d, sent_30d}]}`, counts only — and `null` otherwise. `PUT /delegation/handle-it` takes `{enabled?, mode?}` (`mode` is `careful`, `balanced` or `bold`; anything else is a 422 `bad_mode`) from a caller the API knows is that person — 403 `not_yours`, 409 `caller_signing_required` with only the shared secret — and turning it on needs Act as me and Draft replies to my inbox on (409 `act_as_me_off` / `inbox_off`); `GET /delegation/handled` returns `{replies: [{decision_id, sent_at, to_name, to_email, subject, body, open_questions, gmail_link, source}]}`, the caller's replies and follow-ups (`source` `follow_up`) sent on its own in the last 7 days; a card on `GET /delegation/replies` carries `source` the same way, `can_allow` while Replies (Follow-ups, on a follow-up) is in training, and `learns_style` while Drafts is. `PUT /delegation/training` takes `{replies?, follow_ups?, actions?, drafts?}` (any other field is a 422) and returns the `GET /delegation` shape; putting Replies or Follow-ups in, or Suggested actions out, needs no signed sign-in, anything else does (409 `caller_signing_required`), and putting Replies or Follow-ups in turns Take the lead as you off (`PUT /delegation/take-the-lead` on answers 409 `in_training` while they are). `training.learned` is `[{id, label, setting, example, uses, created_at}]`, what the caller allowed or kept in training (`setting` `replies`, `follow_ups`, `actions` or `drafts`; the kept example, or \"\"); `DELETE /delegation/learned/{id}` removes one of the caller's own (404 for anyone else's). `PUT /delegation/team` takes `{enabled}` from the principal alone (403 `principal_only`; 409 `not_available` when the install doesn't allow it). The Gmail `status` is `connected`, `not_configured`, `needs_reconnect`, `mismatch`, `no_email`, `shared_mailbox` or `error`, checked live with Google on each call. `PUT` takes `{enabled}` (any other field is a 422); turning it on needs the caller's own Gmail connected, otherwise a 409 whose code says why (`gmail_not_connected`, `gmail_needs_reconnect`, `gmail_mismatch`, `no_email`, `shared_mailbox`, `gmail_error`). The voice routes show, learn (from the caller's sent mail, one pass at a time — a 409 `in_progress`, `locked`, `too_soon`, `not_enough_mail`, `no_profile` or `changed` when it was locked or edited while learning, or a Gmail code), write it from the caller's own description (`POST /delegation/voice/describe` with `{description}`: one model call applies their words to the profile they have and returns it with a short `sample_reply`, saving nothing, so they review it and save it with `PUT`; a 409 `empty`, `too_long`, `in_progress`, `too_many` past 10 an hour or `no_profile`; no mailbox needed), edit and lock, and reset \"How I write\": a typed field that fails validation is a 422 `invalid_voice` listing each `rejected` field, and `clear_exemplars` / `clear_signature` drop those. `POST /delegation/voice/signature` reads the signature from the caller's Gmail settings again and changes nothing else (a locked profile stays locked), with the same Gmail codes as learning: a 409 when their mailbox isn't connected, it refuses the sign-in or the check itself fails (`gmail_error`), and a 502 `gmail_error` when reading the signature fails. On an Outlook mailbox it is a 409 `signature_unavailable`, since Outlook gives apps no signature to read, and the stored one is left alone. A caller `can_delegate` refuses — anyone but the principal, for now — gets 403 `not_available_yet`, which hides the Settings card. A request with no `x-caller-email` is a 403 `sign_in_required` unless the API runs under local login — a header-less call is not a sign-in (the caller is read through `api/caller.py`, as on every principal-only route). `PUT /delegation/inbox` takes `{enabled}` and turns **Draft replies to my inbox** on or off, returning the same shape as `GET /delegation`: on needs Act as me on (409 `act_as_me_off`) and the mailbox connected (the Gmail codes above, which keep their names for an Outlook mailbox too), and turning Act as me off turns it off too. `POST /delegation/inbox/check` starts a scan now in the background and answers 202 with the `inbox` state (409 `inbox_off` or `in_progress`). `GET /delegation/replies` returns `{cards: [...]}`, the caller's open reply cards from the database alone (no Gmail call): the decision id, the sender's name, address, relation and whether it was verified, the subject, when it arrived, what they wrote, the draft's recipients, subject and body, `open_questions`, `flags` and a Gmail link built from a fixed prefix. **Send** is `POST /decisions/{id}/approve`: it sends the card's draft exactly as it is in Gmail, after checking again that the caller is its owner — which on a server needs signed callers (409 `caller_signing_required` otherwise) — that both switches are on (`inbox_off`), no client slot is active (`client_slot`), the Gmail is connected (the Gmail codes), the draft is still there and unanswered (`draft_gone`, `you_replied`) and its recipients are allowed (`no_recipients`, `too_many_recipients`, `executive_recipient`, `not_from_you`). Recipients that changed, or a newer message in the thread, answer 409 `{code: \"confirm\", message, reasons, recipients}`; approving again with `edits: {recipients: <the list shown>, thread_moved_on: true}` is the second yes. **Send + allow** adds `edits.allow: true`: 422 `cant_allow` unless Replies (Follow-ups, on a follow-up card) is in training, 409 `learned_full` when their list is full, both before anything is sent; `edits.example: true` keeps a draft edited in the mailbox as how they write to that person while Drafts is in training. A draft edited in Gmail between those checks and the send is not sent (`draft_changed`). A double tap sends once (`already_handled`); Gmail refusing answers 429 `rate_limited` or 502 `gmail_error` with nothing sent, and a send Gmail didn't confirm answers 502 `send_unconfirmed` and is settled by the next inbox scan. Dismiss is `POST /decisions/{id}/reject`. `GET /delegation/actions` returns `{cards: [...]}`, the caller's own approval cards (`delegation_actions`): the decision id, when it was made, a one-line `why`, and each action's `index`, `kind` (`invite`, `message`, `add_contact`), `summary` and `text` (a message as it will be sent, or a meeting's description). **Approve** is `POST /decisions/{id}/approve` with `edits: {only: [indexes]}` (and `allow: true` for Approve + allow while Suggested actions is in training: 422 `cant_allow` otherwise or when nothing on it can be allowed, 409 `learned_full`; a card carries `can_allow`); it needs the card's own person signed in (403 `not_yours`, 409 `caller_signing_required`), Act as me on (409 `act_as_me_off`) and a card under a week old (409 `expired`), runs once (409 `already_handled`), and returns the decision with `final_payload_json.results`: per action `done`, `waiting` (sent to whoever approves meetings), `failed` with why, or `skipped`. Every change writes a private audit row. |\n| `history` | `GET /memories/history` (`?q=`), `PUT /memories/history/settings`, `PATCH`/`DELETE /memories/history/{id}`, `POST /memories/history/{id}/forget-conversation` | Always in the loop: the **caller's own** notes and switches only, resolved as for Act as me (a signed-in person on the roster, or the principal under local login; otherwise 403 `sign_in_required` / `not_on_roster`). `GET` returns `{notes, reply_notes, retention_days, effective_retention_days, company_retention_days, retention_choices, can_keep_notes, can_note_replies, can_set_company_retention, share_work_style, can_share_work_style}` (`can_keep_notes`: a team member on the People list may turn notes on; `can_note_replies`: they can use Act as me, so email replies are noted too; `share_work_style`: their own \"Share my work style with the team\" switch, `can_share_work_style`: a team member in a team workspace). `PUT` turns notes on only for someone who may keep them, and `share_work_style` on only for someone who may share it (403 `not_available` for either; turning either off always works), takes a person's retention only when shorter than the company's (422 `invalid_setting`), and the company retention only from the principal (403 `principal_only`). `PATCH` pins or corrects a note; `DELETE` forgets it; `forget-conversation` is \"Don't remember this\". A note that isn't the caller's is 404. Every change is audited privately to its person. |\n| `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 list, its `total` and the usage totals leave them out, a private row's id is a 404, and a session shows only its other rows. |\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 (unauthenticated). |\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}]}`); `/documents/{drive\\|onedrive\\|notion}/{id}` returns the stored text (a OneDrive id is `<drive id>:<item id>`) for an id on record (the path comes from the state, never the caller). They are read-only — a synced file is removed where it lives. `POST …/sync` starts one tick of the same sync the scheduler runs as a background task (202); 409 when the source is not connected or a tick is already running (every sync holds a per-process run lock, so a manual run never overlaps the heartbeat; the route also keeps its own started task per source and re-checks just before starting one, so two simultaneous requests start one tick, not two), 429 with `Retry-After` within 60 s of the last successful run or of the end of the last tick in this process, failed ones included, so a failing or slow source can't be re-run back-to-back. The page's text view never loads images from synced content (a remote image would be a read beacon for whoever edits the shared folder). Upload is keyed on the filename, so re-uploading a document replaces its chunks rather than duplicating them, and `DELETE` removes the rows as well as the file. `domain` must be one of the nine specialist domains (including `sales`) or `general`; anything else is a 400 rather than a 200 that indexes where no specialist can retrieve. A scanned PDF is converted (`knowledge.pdf_reader`) before it is indexed and in the text view, as are scanned PDFs in `POST /chat/upload` and the client / onboarding intake uploads. The upload is streamed to disk 1 MB at a time and refused with a 413 once it passes 50 MB, and the file is parsed in a short-lived child process (see the RAG section), so a large document does not stay in the API process's memory. A Word or Excel file that cannot be parsed, or whose parse runs out of time, is a 422 with a readable reason. When every parser is busy, the response is a 503 with `Retry-After`. |\n| `executive` | `GET /executive/status`, `POST /executive/pause`, `POST /executive/resume` | Operator pause switch for all autonomous work (scheduler, Gmail poller, workflow resumer); inbound chat and DMs stay live. Status returns `{paused, paused_at, paused_by, reason, held_actions, can_resume}` — `held_actions` counts due `pending` rows that fire on resume. `pause` takes an optional `reason` (≤200 chars) and is idempotent (re-pausing keeps the original start and reason); `paused_by` is the UI proxy's `x-caller-email`, else `api`. Behind the shared-secret middleware — not `SCHEDULED_ADMIN_TOKEN`, which the UI cannot send. Any caller may pause; `resume` is principal-only (`is_principal_or_self`, 403 otherwise; open while no principal is rostered; a header-less caller resolves to the principal as in `chat`), and status carries `can_resume` for the viewer so the UI hides Resume from everyone else. |\n| `workspace` | `GET /workspace`, `PUT /workspace` | Solo/team mode, the user's time zone and the principal's role (`memory.workspace_settings`). Both return `{mode, timezone, effective_timezone, role_kind, role_title, reports_to, remit, measured_on, company_domains, company_domains_custom}` — `timezone` is what the user set (null when unset), `effective_timezone` the zone in effect (`timezone`, else `USER_TIMEZONE`, else UTC), and each role field is null until set. `PUT` is a partial update: only the fields sent change; `mode` is `solo` or `team` (not null), `timezone` an IANA zone, or null/blank to clear it; `role_kind` is `owner`, `in_house`, `independent` or `other`, and `role_title` / `reports_to` / `remit` / `measured_on` are free text (trimmed, at most 120 / 120 / 500 / 300 characters), each null or blank to clear it; an unknown zone, a bad mode or role kind, an over-long role field or an unknown field is a 422 and changes nothing. Switching to solo cancels every pending department check-in, switching to team re-schedules them, and a new zone re-times the pending briefs and reflection; a role change has no side effects (the next turn reads it). `company_domains` is the company's own email domains (a teammate matches by local part on them — see Org): `GET` returns the ones in effect (the stored list, or the domain of the principal's primary address, with `company_domains_custom` false) only to the same caller the role is shown to, `[]` for anyone else; `PUT` takes a list (at most 10 plain domain names, never a free-mail provider's — 422 otherwise, the value never quoted) or null / `[]` to go back to deriving them, and a change is audited with the new list. Each change writes a `workspace_settings_changed` audit row (a role change adds `details.role_fields_changed`, the names of the fields that changed — never their text). The role is the principal's: `GET` returns it only to a caller `PUT` would accept and reads it as nulls for anyone else. `PUT` is the principal's alone (`is_principal_or_self`, 403 otherwise; a header-less caller resolves to the principal as in `chat`) and open while no principal is rostered, so first-run setup can pick a mode. Both work before onboarding — unlike `company-profile`, nothing here needs a profile. |\n| `scheduled` | `GET\\|DELETE` scheduled actions (`?status=…&order=asc\\|desc`) | Pending and fired scheduled actions; `order` flips the `run_at` sort (asc=soonest-first for the upcoming queue, desc=most-recent-first for terminal-status history). `DELETE /scheduled/{id}` cancels a `pending` row (409 otherwise). Like pause it only stops work, so any signed-in user may — the UI proxy's `x-caller-email` is trusted when the request also carries the `BACKEND_SHARED_SECRET` `x-api-key` — as may a matching `X-Admin-Token` (`SCHEDULED_ADMIN_TOKEN`) or a loopback caller with no token set; otherwise 401 (token set) or 503. Audited as `scheduled_action_cancelled`. |\n| `watchlist` | `GET\\|POST\\|PATCH\\|DELETE /watchlist`, `POST /watchlist/{slug}/approve`, `POST /watchlist/{slug}/decline` | External-monitoring watchlist + signals. Rows carry `origin` (`manual` \\| `executive` \\| `research` \\| `research_proposed`); `approve` turns a research suggestion (`research_proposed`, `dry_run`) into a live watch, `decline` `{reason: not_relevant \\| too_noisy \\| wrong_source}` removes it and records the decline (or, for `too_noisy`, keeps it live at a high floor), both 409 unless the row is a pending suggestion; `DELETE ?reason=` on a research-origin row records the decline too. |\n| `workflows` | `GET /workflows`, `POST /workflows/{name}/runs`, `GET\\|POST\\|PUT\\|DELETE /workflows/custom`, `GET\\|DELETE /workflows/custom/{name}/targets`, `POST /workflows/runs/{run_id}/decision`, `GET /workflows/tools/search?q=`, `GET /workflows/tools/describe?names=` | Workflow catalog, run management, and user-created (dynamic) workflow CRUD. Custom definitions come back with a server-managed `owner_person_id` (the creator — the web caller on `POST`, set on insert only; a client-sent value is ignored), who is asked to approve a workflow's first write to a new target. `GET /workflows/custom/{name}/targets` lists the targets its tool steps may write to without asking and `DELETE …/targets?value=` forgets one. `POST /workflows/{name}/runs` is a 403 (\"Only the principal can run this workflow.\"), audited, before any run row exists, when the workflow is one only the principal may start in the workspace's mode (`weekly_review` always, `morning_brief` in solo) and the caller is not the principal. A request with no `x-caller-email` counts as the principal; with no principal on the roster, no signed-in caller does. This governs starting a run only. A run started by hand (this endpoint, or `run_workflow` / research in chat) records its starter as `owner_person_id` and is theirs alone: `GET /workflows/runs` lists the team's (scheduled, no owner) runs plus the caller's own and the ones waiting on them, and `GET` / `DELETE /workflows/runs/{run_id}` and `POST /workflows/runs/{run_id}/decision` are a 404 for anyone else's, the principal included. A signed-in email that is on nobody's People entry cannot start one (403), and a run whose starter can't be read is refused (503); its steps read and draft documents as the starter only. `POST /workflows/runs/{run_id}/decision` with `{decision: \"approve\"|\"reject\"}` answers a run awaiting a yes/no sign-off from the web app — 403 unless the caller is the person it waits on or the principal, 409 if it isn't awaiting or needs a written reply — through the same `apply_resolution` a chat reply uses. Custom create/update also rejects (422) any action-step tool that does not resolve, and so does `POST /workflows/custom/{name}/activate` when turning a workflow **on** — that click is the approval for a tool workflow chat saved switched off (turning off is never checked). Turning on a workflow with action steps requires the body `{is_active: true, definition}` carrying the definition the user reviewed; if the stored one differs (ignoring `is_active` and timestamps) it returns 409, and the switch itself is a compare-and-set on the validated revision (`dynamic_store.activate_if_unchanged`, keyed on `updated_at`), so a save that lands while the tool check awaits the gateway — even from another process — is a 409 too, so only what was shown gets switched on. `GET /workflows/custom` lists inactive definitions too; `GET /workflows/{name}` 404s for them. The two `tools` endpoints return `{tools: [{name, description, read_only, source}]}` for the advanced editor's tool picker and the review card; `read_only` is true only when the name says it reads (a label, not a control). The run stream adds a `progress` event (`step_id`, `summary`) while an action step uses tools. Each catalog entry (`WorkflowMeta`) carries `is_custom`, `background` (true for the system-run built-ins the UI files under “System”) and `quick` (true for a Quick workflow, one per playbook nothing else follows, named `quick_<playbook>`). The run endpoint streams SSE; its `awaiting_human` event carries `delivery` (`self` \\| `sent` \\| `suppressed` \\| `alerted` \\| `failed`) alongside `person_id` / `question` / `awaiting_until`, because the outbound guard or an unreachable approver means the question may never have been asked — a client must not render “waiting on them” for those. A paused run ends the stream with neither `done` nor `error`, so that `awaiting_human` frame carries `terminal: true` to say so explicitly, plus `resumable` — whether the run continues by itself once answered or stops at the gate. `GET /workflows/runs/{run_id}` returns the run row with the resume payload replaced by a small `resume_progress` summary (`gate_step_id`, `completed_step_ids`, or `null`): the payload holds every completed step's full text, and the run-detail page polls this endpoint while a run is unfinished. |\n| `knowledge` | `/knowledge/builtin`, `/external`, `/search` | MBA knowledge base and external sources. `/search` is the introspection parallel of `retriever.retrieve` and mirrors its filters — including the `general` catch-all on the company collection — so the panel cannot report a specialist seeing nothing that it does retrieve in chat. It accepts `general` in `domain_filter` for the same reason. `/search` applies the same review gate as `retrieve()` — withheld (pending or rejected) built-in, external and failure rows are dropped, so the panel never advertises knowledge the Executive cannot use; it degrades to unfiltered rather than failing if review state is unreadable. `POST /knowledge/builtin` refuses a name already held by shipped content, and `POST|DELETE /knowledge/failures` now register and deregister for review — without that a user-authored failure case study had no review row, so no SME decision could block it. |\n| `skills` | `/skills`, `/skills/search`, `/skills/{name}/restore` | Skill registry (the UI's **Playbooks**) CRUD and search. `PUT` on a built-in saves a company customization that shadows it; `DELETE` returns `{name, outcome}` — `deleted`, `reverted` (customization removed, built-in back) or `hidden` (built-in hidden for this company); `restore` un-hides; `GET /skills?include_hidden=true` lists hidden built-ins. List and detail carry `used_by` — `[{name, title, is_custom}]` of the workflows that follow the playbook (switched-off custom ones included) (`WorkflowMeta.playbooks` is the other direction). |\n| `evals` | `/evals/scenarios`, `/evals/runs` | Eval scenarios and run results. `POST /evals/runs` is a 403 when a workflow scenario names a workflow that only the principal may start in the mode it runs in (the weekly review; the morning brief in solo) and the caller is not the principal — the Jobs page's rule for starting a run; stored results are read under the existing `/evals/runs` rules. |\n| `memories` | `/memories/{decisions,initiatives,advice}`, `GET /memories/facts`, `POST /memories/facts/{fact_id}/{retire,approve,decline}`, `GET /memories/facts/approval`, `PUT /memories/facts/approval/{person_id}`, `GET /memories/people`, `GET /memories/people/{person_id}/conclusions` | Episodic-memory record management; the standing facts the Pulse Corrections tab reads (`{facts: [...], can_retire, retirable_ids, can_review}`; each fact carries `recorded_by_role` / `recorded_by_name`; `?include_inactive=` default true, honoured for the principal only; anyone else gets the active rows plus their own `proposed` ones, with the provenance (`session_id`, `turn_id`, `recorded_by_person_id`, `retired_reason`, and `source_quote` except on their own facts) blanked, never retired, replaced or declined text; `?limit=` 1–500) and their retire (the principal any fact, a teammate only one they recorded that the principal has not approved — else 403; the audit row names the teammate; 404 for an unknown or `profile` row, 409 when no longer active; writes a private `fact_retired` audit row); approve / decline a teammate's `proposed` fact (principal only, else 403; 409 when it is not proposed; private `fact_reviewed` row); and the per-teammate \"needs my approval\" switch (on by default; `GET` lists `[{person_id, full_name, needs_approval}]` for every active team member but the principal, `true` for anyone not yet set; `PUT` takes `{needs_approval}`, 404 for anyone else; both principal only; private `fact_approval_changed` row); plus the read-only peer-memory overview the Pulse People tab reads (`{status: ok|disabled|error, people: [...], conclusion_total}`; `?recent=` 1–50, default 5) and one person's full conclusion list, paged newest first (`{status, person_id, items, page, size, total, has_more}`; `?page=` ≥1, `?size=` 1–100, default 50; 404 when the person has no peer). Peer memory is each person's own: the overview holds only the caller's entry (none for a caller off the roster; `conclusion_total` counts only theirs), the principal included, and `/conclusions` for anyone but the caller is a 404. |\n| `review` | `/review/items`, `/review/stats`, `/review/trusted-defaults`, `POST /review/curate`, `POST /review/bulk-approve` | Knowledge review queue and annotations. Shipped knowledge registers as a trusted default (`approved` with a NULL `reviewed_at`), so the queue starts empty; `curate` (`{domain, action: start|stop}`, domain required) opts one domain in or out, and `trusted-defaults` returns domain → unreviewed count. `bulk-approve` takes a non-empty `domain`, `item_ids` (max 500) or `all_pending: true`, and 400s with no selector; it returns `{approved_count, item_ids}`. |\n| `onboarding` | `/onboard/interview/understand`, `/onboard/interview/start`, `/onboard/interview/message`, `/onboard/interview/draft`, `/onboard/interview/{id}`, `/onboard/interview/commit` | Conversational company setup. The `onboarding_interviewer` agent asks clarifying questions, then emits a draft profile + people + departments. **Nothing is persisted until `POST /onboard/interview/commit`** — the interview itself never writes. `start` is multipart (description + optional deck/one-pager uploads). `commit` answers 403 when the draft would make a different person the owner and the caller is not the current owner (setup demotes the old principal, and any signed-in user can open it). It also takes an optional `owner_email` — the principal's sign-in email, which the review screen pre-fills from the signed-in user — checked before anything is written (422 if it is malformed, already another person's, or would replace the principal's existing email — setup only fills in a missing one; 403 if the caller is not the owner and it is not the address they signed in with, since the roster is the sign-in allow-list) and saved on the principal's People row, so the owner's chats resolve to them from the first turn. |\n| `workflow_designer` | `POST /workflows/designer/start`, `POST /workflows/designer/edit`, `POST /workflows/designer/message`, `POST /workflows/designer/draft`, `GET /workflows/designer/{session_id}` | The conversational New workflow wizard, and editing a saved workflow by conversation. `/edit` (`{name}`) opens a session on a saved custom workflow with no model call: the stored definition is the starting draft, and every response then carries `editing` (its name) and `original` (the stored definition as the session opened on it); drafts keep that name and its on/off state whatever the model writes (404 for an unknown workflow). The UI saves one with `POST /workflows/custom/{name}/save-edit` (`{session_id, definition}`): the server saves the session's own draft, never a client-sent body, and only when it equals the `definition` the user reviewed (a later message is a 409, so the click saves only what was shown); it re-validates it, keeps the stored on/off state, and writes only if the stored workflow is still the version the conversation opened on — otherwise 409, as it is for a session about another workflow or one with nothing drafted yet. It sits under `/workflows/custom` so anything that limits writes to custom workflows covers it too. The `workflow_designer` agent asks clarifying questions (`phase: \"question\"`, with `hint` and up to four suggested `options`), then returns `phase: \"draft\"` with `draft.definition` (exactly the body `POST /workflows/custom` takes), `summary`, and `assumptions`; every response carries the `transcript`. **Nothing is persisted here** — sessions are in memory, and the UI saves through `POST /workflows/custom`. Errors are fixed strings (422 over the 8,000-char message cap or the transcript cap, 404 for an expired session, 409 while another turn on the same session is still running, 502/504 for model failure or timeout). Mounted ahead of the `workflows` router. |\n| `python_jobs` | `GET /python-jobs/{job_id}/{name}` | A result file a Python job (`run_python_job`) wrote, the principal's alone (403 otherwise), served as a download (`Content-Disposition: attachment`, `Content-Security-Policy: sandbox`, `nosniff`, `Cache-Control: no-store`); 404 for a bad id or name or a file past its 7 days. |\n| `saved_tools` | `GET /saved-tools`, `GET\\|PUT /saved-tools/{name}`, `POST /saved-tools/{name}/rollback` | The scripts the Executive saved as tools (Settings → Advanced → Saved tools), the owner's alone (403 otherwise). The list gives each tool's name, description, on/off, current version, `kind` (`script` or `python`, a kept Python job) and the tools it calls, plus whether `SAVED_TOOLS_ENABLED` is on; the detail adds the script, every version and the last 20 runs. `PUT {enabled?, workflows?, version?}` turns one on or off (off also turns it off for workflows, so turning it back on never re-arms unattended runs), and turns the named `version` — the one the owner looked at, never whatever is current by then — on for workflows (or workflows off); a Python tool never turns on for workflows (409) — turning workflows on lets more run unattended, so it needs a request tied to the owner (signed sign-ins or local login, as Take the lead's switches do; 409 otherwise); `rollback {version}` makes that version the one that runs. Both are audited as `saved_tool_changed`. The Executive saves tools itself through `run_script`; there is no create route. |\n| `onboarding` (fallback) | `/onboard/start`, `/onboard/answer`, `/onboard/status/{id}` | The original 12-step form wizard, kept as a fallback (UI at `/onboard?mode=form`) and used by the `openexecutive onboard` CLI. Its final answer saves the profile and adds people with their emails and a principal, so once there is an owner only they can send it (403, and the session rolls back so the owner can still finish it). `/onboard/start` reads the workspace mode once for the session: solo skips the Team Size, Team Members and Fractional Executives steps. Each status response's `current_step` / `total_steps` count only the steps that session asks, and `optional` says whether the current step can be skipped. |\n| `company-profile` | `GET\\|PATCH /company-profile` | Structured company profile. |\n| `alerts` (private cards) | `POST /alerts/{id}/ack`, `/reopen`, `/alerts/bulk-ack` | An alert tagged `private:principal` (see Today) is a 404 on ack and reopen for anyone but the principal, and their bulk sweep skips it. A roster-request card (source `roster_request`) is a 409 on `ack` even for the principal — it is answered at `/people/requests/{id}`, since acking would leave the sender waiting with nothing to show it — and, as an exempt source, `bulk-ack` and `reopen` skip it. |\n| `auth` | `GET /auth/allowed-emails` | Non-archived **team members** with an email, offered to the UI's sign-in gate — a contact is never on it, so adding a client to reach them by email no longer lets them sign in. The gate takes the **union** of this roster and its own `ALLOWED_EMAILS` env list, so env entries always work (and are checked first, short-circuiting the fetch) and roster entries are additive — a roster change can never revoke a configured operator. With local login (`make dev` with Google sign-in not set up — the UI then listens on 127.0.0.1 only) the UI signs in without an email, sends no `x-caller-email`, and the backend resolves the caller to the principal, as it does for the CLI. |\n| `fixtures` | `/fixtures`, `/fixtures/{name}/load` | Demo-company fixture load/reset/snapshot. `POST /fixtures/reset` leaves no departments, like a new install (`departments_seeded` is always 0). |\n| `clients` | `/clients`, `/clients/generate`, `/clients/cockpit`, `/clients/save`, `/clients/{slug}/activate` | Client-company slots — multi-client mode for fractional use; create from current/blank/AI-generated intake draft (pasted notes and/or file attachments, multipart on `/clients/generate`), save-back switching, engagement metadata (PATCH), cross-client cockpit, delete. See the Client Companies section. |\n| webhooks | `POST /webhook/telegram`, `POST /webhook/google-chat` | Inbound integration callbacks (self-verified). |\n| MCP server | `POST\\|GET /mcp` | Open Executive exposed as an MCP server (Streamable-HTTP). Not a router — a mounted FastMCP sub-app. Same shared-secret gate (`x-api-key`); exposes company context as resources and the specialist council as tools. See the MCP Server section. |\n\n**Take the lead** (`api/routes/take_the_lead.py`): `GET /take-the-lead` returns the As the Executive switch, its six Ask first switches (`{kind, label, hint, on}`, the hint a plain line on what each one catches), the company's rules, whether this server can tie a change to the owner (`available`), and whether the Executive is paused. `PUT /take-the-lead` takes `{enabled?, ask_first?}`, and `POST /take-the-lead/rules` / `DELETE /take-the-lead/rules/{id}` add or remove a company rule (`{kind: person|domain|words|amount, value}`, 422 on a bad one). All four are the principal's alone (403). Anything that lets more happen on its own (turning it on, turning an Ask first off, removing a rule) needs a caller the API can tie to them (`delegation.verified.caller_refusal`, else 409). `GET /today/activity` adds `took_the_lead` rows (what Take the lead did, named, not quoted) and, for the caller alone, `sent_as_you` rows for what Handle it for me sent as them. Under `/delegation`: `PUT /delegation/take-the-lead {enabled}` is Take the lead as you (the owner's only for now; turning it on turns Handle it for me on), and `GET|POST /delegation/take-the-lead/rules` and `DELETE …/rules/{id}` manage the caller's own rules. `HandleItOut` gains `lead` and `lead_available`. A `take_the_lead_action` decision is approved or rejected through the existing `/decisions/{id}/approve|reject`. Training: the response also carries `training` (In training: everything waits unless allowed), `learned` (`{id, label, feature, example, uses, created_at}`: what it was allowed, the edit kept as an example by field) and `suggested` (`{key, label, approvals}`); `PUT` takes `training?` too, and leaving training while on needs the same provable owner as turning it on. `POST /take-the-lead/learned {key}` allows a current suggestion (404 for anything else; provable owner), `DELETE /take-the-lead/learned/{id}` makes it ask first again. `learned` also lists the owner's own Act as me senders (`feature` `act_as_me`), never anyone else's, and Remove works on those too. On a `take_the_lead_action` card, `POST /decisions/{id}/approve` takes `edits.input` (the card's editable fields, 422 for any other; the principal's alone, 403 for an area approver) and `edits.allow: true` (a training card only, 422 otherwise; the principal from a provable request, 403 otherwise), finishing `approved_with_edit` when a field changed.","mermaid": null,"generated_at": "2026-10-10T16:08:33Z"}diff --git a/packages/core/openexecutive/architecture/prebuilt/delegation.json b/packages/core/openexecutive/architecture/prebuilt/delegation.jsonindex 4edc9bd4..3a0afb77 100644--- a/packages/core/openexecutive/architecture/prebuilt/delegation.json+++ b/packages/core/openexecutive/architecture/prebuilt/delegation.json@@ -1,7 +1,7 @@{"section_id": "delegation","title": "Act as Me (Delegation)",- "markdown": "The **delegation** module (`openexecutive.delegation`) is **Act as me**: the one place the Executive writes *as* a person instead of as itself. Everywhere else it has its own Google account and bots and signs as itself. Here — when the person asks, or, with a second switch, for mail in their inbox that needs them — it writes an email in their voice and saves it as a **draft in their own mailbox** — Gmail or Outlook — for them to review and send. The one thing it ever sends is one of those inbox drafts, exactly as it is in their mailbox: when the person taps **Send** on its card, or, with a third switch, **Handle it for me**, on its own when plain-code rules allow it (below); chat never sends. The principal can turn it on for themselves, and so can each team member once the owner lets them. It is off by default, and off changes nothing: the prompts, tool lists and prompt caches are byte-identical to an install without it.\n\n## Who can have it, and when it is offered\n\n`delegation.settings.can_delegate(person)` is the single rule for who may turn it on: the principal (a non-archived team member flagged `is_principal`), and any other non-archived team member — never a contact — once team members may have it (`team_members_enabled`). That takes two things: the install allows it (`DELEGATION_TEAM_MEMBERS`, default off, which offers the owner the switch) and the owner turned on **Let team members use it** (`PUT /delegation/team`, principal only, one row in `delegation_team`). Turning the owner's switch off takes it away from every team member from their next message, and their inbox watchers stop at their next check; their own switches, drafts and cards are kept. Everything is keyed by `person_id`. A person turns it on for themselves (`PUT /delegation`); nobody turns it on for anyone else. The setting is one row per person in `delegation_settings`, and a missing, unreadable or zero row all mean off.\n\nAt the start of every chat turn (`Executive.stream_chat` and the committee path) `pin_turn_delegation(session, speaker_text)` runs next to the workspace-mode pin and records a `TurnDelegation` on the session. `ghostwrite_email` is **offered** only when all of these hold:\n\n- the speaker may have it and turned it on — read fresh every turn, so turning it off applies from the next message;\n- the speaker is on a surface that verified it is them — the principal through `people_tools.is_principal_on_verified_surface`, a team member through `teammate_on_verified_surface` (the web app signed in, their own Slack or Discord, never an email turn) — and a web turn also carried a signed-in caller (`Session.web_caller_signed_in`, set from `x-caller-email`) or runs under local login — a request with no caller header is not a sign-in and never gets it (whoever holds the shared secret is trusted as the UI proxy that stamps that header, as on every principal-only route);\n- the conversation is private to the speaker: the web chat, a Slack or Discord DM, or a verified private Telegram chat — never a shared channel or thread, where the draft's preview or the matching threads would be posted for everyone and other people's messages sit in the model's context;\n- the turn is neither unattended (the scheduler's proactive run) nor private to the principal (the email poller's turns), so inbound text can never reach it. The MCP server, workflows, reflection and research never carry it at all.\n\nThe mailbox connection is deliberately **not** part of the offer: the handler checks it on every call and says how to fix it, so the cached tool prefix never flips when a token lapses. The pin lives in a context variable for the turn's task as well as on the session, so two turns running at once on one session (a second browser tab) each read their own. It also carries the speaker's own words for the turn (a new email may go to an address they just typed — the turn's message joins the history only once the turn ends), a per-turn draft count, and `touched_mail` (see Privacy). `own_words` reads those words back for every own-words check (addresses here, facts and task assignments elsewhere): it first removes the hydrated `<outbound_reply_context>` backstory by its exact, anchored shape, so a look-alike closing tag quoted inside it cannot pass the rest off as the speaker's, then drops other adapter tag blocks, and returns nothing for a message carrying an attachment.\n\n## The tool: `ghostwrite_email`\n\nIt lives in its own registry (`orchestrator.delegation_tools.DELEGATION_TOOLS` / `DELEGATION_TOOL_HANDLERS`), **never** `_ALL_SKILL_TOOLS`, so no other toolkit can carry it. On a turn it is offered to, the agent loop adds it to the pool *before* the sort and builds that turn's handler map from both registries; on any other turn a call to it is an unknown tool. The handler re-checks the pin and the surface anyway, then:\n\n1. **Caps** — at most 5 drafts per turn, and `DELEGATION_MAX_DRAFTS_PER_DAY` (default 50, at most 1000) per person per UTC day, shared with the inbox watcher (`delegation.caps`). It is counted from `delegation_drafts`, one row of ids per draft saved from either place, with a count kept in the process as a floor in case a row was lost. Each slot is taken before the first await — a round's tool calls run concurrently, so otherwise every call in it would pass the caps before any counted — and handed back if nothing was drafted. If the rows can't be read it refuses rather than guess.\n2. **Marks the turn** — sets `TurnDelegation.touched_mail` *before* its first read of the mailbox.\n3. **Checks the mailbox** — `gmail_status` asks Google or Microsoft whose mailbox the credential opens and compares it with the person's People email, on every call: a roster email can change, and a client slot swaps the roster.\n4. **Finds the thread** — by `thread_id` (checked against the mailbox's own id shape), or a Gmail-style search (`find`; on Outlook, words, `from:`, `to:`, `cc:`, `subject:` and `newer_than:` are kept and other Gmail operators dropped). Several matches return `{status: \"choose\", candidates}` (subject, sender and date — no message text) and draft nothing; none returns `not_found`.\n5. **Sets the recipients in code**, never from the model. A reply goes to the last inbound message's `From` — never its `Reply-To` (a different one is flagged `reply_to_ignored`) — with the thread's other recipients only on `reply_all`. A new email 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 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## Forwarding and reminders\n\n`ghostwrite_email` also forwards: with `forward` (a thread id) and `to`, it drafts a forward of the thread's latest message, `intent` becoming the short note above it (the ghostwriter writes only the note; the forwarded email's subject, someone else's words, is never put in the intent). Recipients follow the new-email rule (`_new_recipients`: the roster, or addresses the speaker typed this turn). Gmail's draft quotes a forward header and the original's own words under the note and attaches the original's files, up to 10 and 20 MB (`FORWARD_MAX_FILES`, `FORWARD_MAX_BYTES`; any left off are flagged `attachments_left_off`); Outlook uses Graph's `createForward`, which keeps the original and its files, with the note as its comment and the body never patched. It is still only a draft.\n\n`remind_me(text, when)` (`orchestrator.reminder_tools`) rides with the same tools and checks, but opens no mailbox, so it never marks or locks a turn (`MAILBOX_TOOL_NAMES` are the ones that do). It stores the text once cleaned — one line, anything a chat app could turn into a link (a URL of any scheme, an address, a domain-like word, a host and port, an IP address) replaced with \"[link]\", at most 300 characters — with its time (stored in UTC) in `delegation_reminders` (5 a turn, 25 waiting, a year ahead, refused when the person has no channel). When it is due the scheduler sends that text to the person alone, as \"Reminder you set on <date>: …\", running nothing (see Scheduler); the Slack and Discord DMs it may go by turn link previews off. The chat chip shows the text as it will be sent. A reminder that comes due in the person's quiet hours or leave (when `OUTBOUND_RESPECT_QUIET_HOURS` is on) waits unclaimed and goes once they end, rather than being suppressed and lost. It is allowed after mail is read and in later turns of that conversation: it reaches only the speaker, as plain text. `schedule_followup`, which runs a turn with tools and is listed to everyone, stays refused there.\n\n## 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) and `add_contact` (a new contact; the principal's cards only, since contacts are theirs). 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 Approve + allow, and a card of actions all allowed is carried out on its own (see In training above).\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;\n- up to 3 short exemplars, each checked to be verbatim from a sample, with addresses and phone numbers masked — and none while a client slot is active, so one client's mail never lands in another's state.\n\nThe signature comes from Gmail's `sendAs` settings, not the model (Outlook gives apps no way to read one, so a learn keeps the stored signature and `POST /delegation/voice/signature` answers 409 `signature_unavailable` rather than clearing it), as plain text with its lines kept (`gmail.html_to_text`: a `<br>` always ends a line, and a block tag, opening or closing, ends one when it has text, so Gmail's layout of a first line followed by one `<div>` per line comes out line by line). `POST /delegation/voice/signature` reads it again without relearning: nothing else changes and a locked profile stays locked, so it picks up a changed Gmail signature and undoes **Don't add my signature**. A person can also describe their style in their own words: `POST /delegation/voice/describe` applies the description to the profile they have through the same forced tool (a separate system prompt, no exemplars) and the same validation, keeps their signature and writing examples, and returns the result with a short sample reply for them to review. It saves nothing and needs no mailbox; Save stores it as an ordinary edit. The person can edit the profile, lock it (a locked profile is never relearned) and reset it, and every change is kept in `delegation_voice_history`. One learn runs at a time per person, and a lock or an edit made while it runs wins: the learned profile is dropped (`changed`).\n\n## Draft replies to my inbox\n\nA second switch under Act as me, **Draft replies to my inbox** (`delegation.inbox`), has the Executive watch the person's own inbox and write a first reply to mail that needs them. The reply goes into their Drafts and waits on a private card on Today; nothing is sent until they tap **Send** (below). The switch is one row per person in `delegation_inbox_watch`. Turning it on needs Act as me on and their mailbox connected, and sets `watch_since` to now every time, so it never drafts for mail that arrived before; turning Act as me off turns it off too. Off means no mailbox call and no row written, with one exception: a send the person started that the mailbox never confirmed is still followed through until it is settled.\n\n### When it looks\n\nA throttled hook in the scheduler tick (`_maybe_scan_inbox`, after the pause, company-profile and rotation gates) checks each person whose switch is on every `DELEGATION_INBOX_POLL_MINUTES` (default 5). It is not a scheduled action, because those are listed on `/scheduled` for everyone and anyone may cancel them. One scan task runs at a time, one scan per person, and none while a client slot is active. **Check now** on the Settings card runs the same scan. Every row a scan writes is private and the person's own (`audit.rows_for_person`: a team member's rows are hidden from the principal too, see Privacy), and the process log carries counts and codes, never an address or a line of mail. The scan never marks mail read or changes a label.\n\n### What it drafts for\n\nA scan first settles the open cards (below), and stops with `backlog_full` once 25 are waiting, counting the ones it makes. It then lists the inbox since `watch_since` (`inbox_message_ids`) — not chats, not mail from the person, and not the promotions, social, updates or forums tabs (on Outlook: the Focused inbox only) — up to 100 messages, and takes the newest message of each thread that still needs a look, at most 10: settled threads and threads with an open card are passed over first, so a burst of mail, or a pause for a limit or a back-off, never hides older threads for good. `delegation_inbox_messages` is its durable cursor: one row per message (`UNIQUE(person_id, message_id)`) with what happened to it, the reason, how many tries it took, and the draft and card ids. It stores a hash of the sender's address, never the address. A message is skipped, with the reason recorded, when:\n\n- it came before `watch_since`, or more than three days ago;\n- it is from the person or one of their send-as addresses, from the Executive, or one of this module's own drafts;\n- it is automatic — `Auto-Submitted`, a bulk or auto-reply `Precedence`, a bounce, a calendar invite or a no-reply sender — or from a mailing list, or in a Gmail tab, spam or trash;\n- the person is not in To or Cc, or it has more than 10 recipients;\n- the person replied last, or a draft already sits in the thread.\n\nThree kinds are left unrecorded, so a later scan looks again: mail under 10 minutes old (mail the person answers straight away never gets a card), mail in a thread whose card is still open, and mail a daily limit holds back.\n\n### Deciding, then writing\n\nTwo model calls, and code decides between them. The classifier (`delegation.inbox_classifier`) is one forced-tool call, `classify_email`, returning whether the email needs a personal reply, what kind it is and how sure it is. It sees a few one-lined header lines and the sender's own new words (at most 3000 characters, every line scrubbed) inside one `<email>` block marked as data, and it has no other tools, context or memory, so an email can ask for anything and there is nothing to do it with. A reply is drafted only for a question, a request, scheduling, an introduction or a follow-up, and only when the confidence clears a bar that rises the less the sender is known: 0.6 for their team or a contact (the principal's contacts count only for the principal: a team member's mail is weighed by the team and their own sent mail), 0.7 for someone they have written to before (`has_written_to`, a search of their sent mail), 0.85 for a stranger. Pitches, notes of thanks, FYIs, notifications, newsletters and phishing get nothing, and so does any failure. An email that also went to other people is drafted for only when the person is in To and it asks them themselves: the classifier is told their name, whether they are in To or Cc and how many others it went to, and lists the names the email greets or asks by name (`asked_names`). Code matches those against the person's name, whole name parts only (\"Alexis\" never counts for \"Alex\", and a nickname misses, which means no draft), so mail that greets someone else (\"Good morning, Brennan, could you sign ...\") is never theirs, whatever the model makes of it as a whole. When it names nobody, the model's `asked_of_them` decides, false for a question to the group at large. One that only copies them is never drafted for. Either is recorded `not_needed` with the reason `asks_someone_else`. It runs on `DELEGATION_CLASSIFIER_MODEL`, else the routing model. A sender whose address Gmail couldn't authenticate is handled as a stranger whatever the roster says — anyone can put a colleague's or a client's address in From — so they get the stranger's bar, a holding reply and the stranger limits; the card still says who they claim to be, and that the address isn't verified.\n\nThe reply is written by the same ghostwriter, in the person's voice, but from a fixed intent the module builds rather than words the person typed. Because the intent lets it restate the person's own earlier words, which words are theirs is never written inside the thread, where a sender could imitate any marker with a look-alike: every message there is labelled alike, and the person's own words come in a separate `<writer_said>` block after the thread, taken only from mail their own mailbox sent. Nothing inside the thread can close the thread block or open another. The intent: acknowledge the sender; say again only what the person's *own* earlier messages in the thread already said; commit to nothing new — no yes or no, date, time, price, fact or promise — and say they will get back to them; and put every question it could not answer from their words in **open questions**. A stranger always gets a short holding reply. The lint still strips any link or address that isn't the person's own. The reply goes to the sender (never `Reply-To`) and, on a group email, to everyone else it went to as Cc (reply to all, never the person's own addresses or the Executive); a stranger's holding reply goes to the sender alone. The card says when others were on the email, and its `draft_to` lists everyone, which Send checks.\n\nThe order: record the message, classify, reserve a slot in the shared daily limit, write, save the draft in Gmail (from the alias the mail went to, when it went to one) and store its id, then create the card (idempotent on the message) and mark it drafted. Nothing that fails along the way loses the message. A failure that may pass — the classifier or the writer failing, Gmail refusing the draft, a card that couldn't be made (its draft is deleted first, so no draft is left without a card), any other error with that one message — leaves it for a later scan (`retry`), and it is given up on only after three tries; one message's trouble never holds up the rest. A daily limit reached while it was being read leaves it for later without counting as a try.\n\n### The reply cards\n\nA card is a `delegation_reply` decision whose class is **its approver's alone** (`DecisionClassSpec.approver_only`): only the person it was drafted for sees or resolves it on any decisions route — a team member's card answers 404 to the principal too — and it is never an alert: alerts feed chat turns, which would put other people's mail into memory. It carries the sender with who they are to the person and whether Gmail could verify the address (SPF/DKIM/DMARC, through `fact_confirmation.headers_authenticated`), the subject, what they wrote, the draft, the open questions and its warnings. `GET /delegation/replies` lists the open ones from the database alone, so Today never waits on Google.\n\n- **Send** approves the card, which sends its draft exactly as it is in their mailbox (see *Send on your tap*). **Edit in Gmail** (or **Edit in Outlook**) opens it there, to change the draft first or send it from there.\n- **Dismiss** rejects the card; the class's after-reject step then deletes the draft if nobody edited it — its message id is still the one it was saved with, since Gmail gives an edited draft a new one, and the Outlook client makes a draft's message id `<id>.<changeKey>` so an edit there changes it too — and keeps it otherwise. What happened is recorded even when Gmail fails.\n- Each scan first **settles** what Gmail already settled: a draft sent from Gmail, a draft deleted there, a reply the person wrote themselves, a thread that is gone, or a card left for 7 days (its draft stays in Gmail). Each is a compare-and-set close with the reason. A newer message from someone else flags the card instead. A card being sent at that moment is left alone.\n\n### Send on your tap\n\n`delegation.reply_send` is the only thing in Act as me that sends, and all it can send is the draft on a card, by its id: `DelegateGmail.send_draft` posts `{\"id\": …}` to Gmail's `drafts.send`, and `DelegateOutlook.send_draft` posts an empty body to that draft's Graph `send`, and nothing else, so no text, recipient or header is ever passed. It has two doors: `send_approved_reply`, reached only from `POST /decisions/{id}/approve` — a class only the card's own person may resolve — and `send_on_its_own`, reached only from the inbox watcher under Handle it for me (below). AST tests pin both call sites, so no model, chat turn, workflow, scheduled job or MCP call can. A tap is checked like this: At send time it checks everything again:\n\n1. **Who is asking.** The caller is the card's person and the API knows it: signed callers are on and the request carries that person's signed assertion (or the operator's, under local login), or the API runs for local login and answers this computer only. Anything else is a 409 `caller_signing_required` — with only the shared secret, whoever holds it could send as the owner — so on a server Send needs signed sign-ins.\n2. **The switches.** Act as me and Draft replies to my inbox are on, and no client slot is active.\n3. **The mailbox.** Their mailbox is connected.\n4. **The draft.** It still exists, in the same thread, and they haven't replied there themselves since; otherwise the card closes.\n5. **Who it goes to.** To, Cc and Bcc hold between 1 and 10 addresses, never the Executive's own, and it is from one of their own addresses.\n6. **What changed.** Recipients that differ from the card's, or a newer message from someone else, need a second yes: the first tap gets a 409 `confirm` naming the recipients and the reason, and the person approves again with what they were shown.\n\nThen it claims the card (`claim_for_execution`, proposed → executing, a compare-and-set, so a double tap sends once) and reads the draft once more: `drafts.send` sends whatever the draft is when Gmail gets the request, so if it was edited since the checks read it — in another tab, by a delegate — nothing is sent and the card comes back (`draft_changed`). Then it sends, and records the result: `approved_with_edit` when the draft was edited in Gmail, the sent message's id, the draft row's `sent_message_id`, and a private `delegation_reply_sent` row. A refusal that proves nothing went — a 4xx, a lapsed sign-in, a rate limit, a draft already gone — hands the card back. A failure that leaves it unclear — a timeout, a 5xx — leaves it `executing` and says to check the Sent folder, and the next scans ask Gmail: their message in the thread means it was sent; anything else is judged on the second scan that sees it: the draft still there and nothing sent means it was not (Gmail deletes a draft it sends), and the card comes back, flagged; the draft gone and nothing sent means it was deleted. Nothing is ever retried on its own. Sending is the person's own act, so it works while the Executive is paused.\n\n### Limits and failures\n\nAt most 5 drafts a scan; `DELEGATION_INBOX_MAX_DRAFTS_PER_DAY` (default 20) a day, inside the shared `DELEGATION_MAX_DRAFTS_PER_DAY` it shares with chat; 200 classifications, 2 drafts per sender (1 for a stranger) and 10 for strangers in all per day; and never more than 25 open cards. A lapsed Gmail sign-in sets the status and is looked at again every 30 minutes; a rate limit, an error reaching Gmail or a crash backs off from 5 minutes, doubling up to 2 hours. Neither turns the switch off: the Settings card shows the status in plain words.\n\n## Handle it for me\n\nA third switch under Act as me, **Handle it for me** (`delegation.handle_it`), lets the inbox watcher send some of its replies itself instead of leaving them on a card. It is one row per person in `delegation_handle_it` (`enabled`, `mode`); no row means off. One setting says how much goes without them, the way quality does on the Agent Council (`handle_it.RULES`): **Easy ones** (`careful`) sends only replies to people they know (someone on their team, a contact or someone they have written to) of at most 400 characters when the classifier is at least 0.9 sure; **People I know** (`balanced`), where it starts, sends replies to people they know up to 1200 characters at 0.8; **Most mail** (`bold`) also answers strangers, up to 2000 characters, and lets a link or an amount through when the classifier is at least 0.9 sure. Everything else waits on a card as before, so turning it on never drafts less. A table from before the setting gets the `mode` column on its next open (`schema._add_handle_it_mode`): someone who had strangers set to send keeps that as Bold, everyone else gets Balanced. Only the person turns it on (`PUT /delegation/handle-it`), from a session the API knows is theirs: the same rule Send uses (`delegation.verified.caller_refusal`), so with only the shared secret it answers 409 `caller_signing_required`. Turning it on needs Act as me and Draft replies to my inbox on, and turning the inbox watcher off (or Act as me, which turns it off) turns it off too.\n\n**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 is Replies in training, with a *Train follow-ups too* box for Follow-ups), and **Suggested actions** picks Always ask / In training; one *What it's learned* list sits at the bottom, 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 + allow and Approve + allow 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 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 Settings card shows it under the switch with how many went today.\n\n### Take the lead as you\n\nOn Settings → Act as me, Handle it for me is one dial: **Off**, **Easy ones**, **People I know**, **Most mail** and, for the owner, **Everything**, which uses **Take the lead** (`PUT /delegation/take-the-lead`, one row `person:<id>` in `take_the_lead`; turning it on turns Handle it for me on). While it is on, `handle_it.refusal` drops the setting's limits: strangers, the classifier's confidence, amounts, and the length up to a 4000-character ceiling. A reply with a link still waits for a tap (refusal `link`). In their place it checks the company's and the person's own added rules (`take_the_lead.reply_hit`, refusal `lead_rule`). Everything Handle it always keeps still holds: signed sign-ins, an authenticated sender, a reply kind, exactly the thread's people, the topics that always wait, draft flags, never twice in a row, one a thread a day and the daily limit. Follow-ups under it may go to anyone the person wrote to, with the same sensitive, amount, link and length checks plus the added rules. `reply_send.send_on_its_own` accepts the card while both switches are on. Each person adds and removes their own rules (`/delegation/take-the-lead/rules`). Removing one needs a caller the API can tie to them.\n\n## The mailbox client\n\n`delegation.gmail.DelegateGmail` talks to the Gmail REST API directly and is **never registered with the MCP gateway**, so the model reaches the mailbox only through the typed handler. The credential is one file per person in `DELEGATION_GOOGLE_CREDENTIALS_DIR`, named from a hash of the address (0600 in a 0700 directory), minted by `scripts/connect-own-gmail.py` on the Executive's own OAuth client with the scopes `gmail.readonly` and `gmail.compose`. It never lives in `WORKSPACE_MCP_CREDENTIALS_DIR`, where workspace-mcp picks a credential by address. Besides reading threads and saving drafts it lists the inbox and checks whether they have written to an address, reads one message or draft, lists the person's send-as addresses and deletes a draft. Its **one send method**, `send_draft`, sends an existing draft by its id and nothing else — never `messages.send`, which sends any text it is given — and unit tests pin the method set, the endpoint, the request body and its single caller. A failed request says whether it may have been carried out anyway (a timeout after connecting, a 5xx), which is what the send path needs to know. A parsed message carries when it arrived, whether it is bulk, a bounce or a calendar invite, and whether Gmail's authentication results vouch for its sender.\n\n`gmail_status` answers `connected`, `not_configured`, `needs_reconnect` (Google refused the saved sign-in — an app in Testing mode has its tokens expire after 7 days; a rate limit, though Gmail may send it as a 403, is an `error` to retry, not a reconnect), `mismatch`, `no_email`, `shared_mailbox` or `error`. `shared_mailbox` means the person's address *is* the Executive's; it is refused before asking Google, because then everything the Executive writes would look like theirs. The gateway closes the other door: every `google_workspace__*` call must act as the Executive's own account, and a `user_google_email` naming anyone else is refused and audited (see Integrations).\n\n### Outlook\n\nA person may connect an Outlook mailbox instead (work, school or personal), with `scripts/connect-own-outlook.py`: a device-code sign-in on the Executive's own Entra app (`MS365_MCP_CLIENT_ID`, tenant `MS365_MCP_TENANT_ID` or `common`) asking for `User.Read`, `Mail.ReadWrite`, `Mail.Send` and `offline_access`. It writes the same per-person file with `\"provider\": \"microsoft\"`, so a person has one mailbox for Act as me, and `gmail_for` hands back `delegation.outlook.DelegateOutlook`, which keeps `DelegateGmail`'s methods, return types and errors, so every caller above runs unchanged. It talks to Microsoft Graph directly, never through the Microsoft 365 MCP server the Executive's own Outlook uses, and is never registered with the gateway. Microsoft rotates the refresh token on use; the new one is written back into the file (atomically, keeping every other key, and only if the file still holds the old one). Graph is asked for immutable ids, so a sent draft keeps its id; a thread is Outlook's `conversationId`. Gmail's labels are mapped onto what the callers read: `SENT` only for mail in their Sent Items folder (a From line set to their address by someone else never counts), `DRAFT`, `INBOX`, and Focused Inbox's Other read as a tab. A sender counts as authenticated only when the topmost `Authentication-Results` — the one Exchange wrote, above anything the sender added — holds exactly one DMARC verdict, a pass for From's own domain, and Exchange Online Protection's own `compauth=` verdict, so a header the sender wrote on mail EOP never stamped doesn't count. `delete_draft` refuses anything that isn't a draft, and deletes with the draft's etag (`If-Match`), so a draft sent in between — it keeps its id — is left alone. No client secret is ever written into a person's file, and Graph has no signature setting to read.\n\n## Privacy\n\nWhat a person's mailbox touches is theirs. For the principal that means private to the principal, as every private row is. For a team member it means theirs alone, the principal included: an audit row carries `private_to_person` (set by `audit.rows_for_person` around the inbox watcher, a card's Send and Dismiss and their settings changes, and by `people_tools.audit_row_owner` on a turn that read their mail) and is left out of every audit read — the log, a session's timeline, a row by id, the brief — with only the usage totals counting it; their reply cards are theirs alone (above); and the owner's view of their use is counts only (drafts and sends in 30 days, and whether their inbox watcher is on). The conversation itself becomes its owner's alone before the mailbox is first read: `ghostwrite_email` marks the session `mail_private` (`session_store.mark_mail_private`, creating a channel adapter's row early, with its owner) and refuses to read the mailbox if that can't be stored or the conversation already belongs to someone else (which it then leaves unmarked); from then on only its owner may open it (`chat._session_access`), and working-style learning skips it. Every later turn there starts private (`settings.pin_turn_delegation` reads the flag and fails closed, setting `touched_mail`), so a follow-up answered from history alone is still private to its owner and teaches no memory, and the web chat's rows before the turn (the inbound message and the knowledge lookup) are theirs too. It does not start locked down: the lockdown is `read_mail`, set only by a turn that reads the mailbox or notes itself, 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. 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## Surfaces\n\n- **Settings → Act as me** (`ActAsMeCard`, hidden unless `GET /delegation` answers, so a team member sees it once the owner lets them): the mailbox connection (`provider` says which) with both connect commands (Gmail and Outlook) and **Check again**, the **Write drafts as me** switch, the **Draft replies to my inbox** switch with its status in plain words, when it last checked and **Check now**, and **How I write**: length and tone, a greeting per audience (`{first}` is their first name), the sign-off, habits and never-rules in fields that grow to show every line, the signature with **Refresh from Gmail** and **Don't add my signature** (or **Add my Gmail signature** when none is added; on Outlook only **Don't add my signature**, with why), and each example quoted with **Remove examples**. The owner also gets **Let team members use it** where the install allows it, with each team member who has it on listed by name and counts only.\n- **Today → Replies waiting** (`RepliesWaiting`, the top of the left column; hidden unless `GET /delegation/replies` answers with cards): each card shows who wrote and who they are to you, whether their address was verified, the subject, **They wrote** as plain text, your draft, **Decide before sending** (the open questions) and its warnings, with **Send** (a confirm naming who it goes to, and a second one when that or the thread changed), **Edit in Gmail** or **Edit in Outlook**, and **Dismiss**.\n- **Setup status**: a **Your own mailbox (Act as me)** light (`your_gmail`), amber while the inbox watcher can't reach the mailbox, is being rate-limited or has 25 replies waiting.\n- **Settings → Your Executive** (`app/settings/executive`, where `/settings/on-its-own` lands): the pause, **Take the lead** and **Book meetings without asking** (as the Executive). **Handle it for me** (the Off / Easy ones / People I know / Most mail / Everything dial, what each sends, how many went today and what it sent this week, as you) sits under the mailbox card on **Settings → Act as me**.\n- **API**: `GET`/`PUT /delegation`, `GET`/`PUT`/`DELETE /delegation/voice`, `POST /delegation/voice/learn`, `POST /delegation/voice/describe`, `POST /delegation/voice/signature`, `PUT /delegation/inbox`, `POST /delegation/inbox/check`, `GET /delegation/replies`, `PUT /delegation/handle-it`, `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). Send is `POST /decisions/{id}/approve`; Dismiss is `POST /decisions/{id}/reject`.\n- **Evals**: a scenario's `delegation:` block runs the turn against an in-memory mailbox (`evals.mailbox.ScenarioMailbox`) and hands the saved drafts to the judge (`delegation_001`–`003`). A `type: inbox` scenario runs the watcher's two model calls on one thread: whether it drafts must match the scenario, and a draft is judged on saying nothing the person hadn't, copying no link or address, and listing every open question (`delegation_inbox_001`–`007`; the last checks a draft never claims anything was sent).\n\nActing within rules the person sets and standing in for them are later, separate changes, each behind its own switch, off by default.",+ "markdown": "The **delegation** module (`openexecutive.delegation`) is **Act as me**: the one place the Executive writes *as* a person instead of as itself. Everywhere else it has its own Google account and bots and signs as itself. Here — when the person asks, or, with a second switch, for mail in their inbox that needs them — it writes an email in their voice and saves it as a **draft in their own mailbox** — Gmail or Outlook — for them to review and send. The one thing it ever sends is one of those inbox drafts, exactly as it is in their mailbox: when the person taps **Send** on its card, or, with a third switch, **Handle it for me**, on its own when plain-code rules allow it (below); chat never sends. The principal can turn it on for themselves, and so can each team member once the owner lets them. It is off by default, and off changes nothing: the prompts, tool lists and prompt caches are byte-identical to an install without it.\n\n## Who can have it, and when it is offered\n\n`delegation.settings.can_delegate(person)` is the single rule for who may turn it on: the principal (a non-archived team member flagged `is_principal`), and any other non-archived team member — never a contact — once team members may have it (`team_members_enabled`). That takes two things: the install allows it (`DELEGATION_TEAM_MEMBERS`, default off, which offers the owner the switch) and the owner turned on **Let team members use it** (`PUT /delegation/team`, principal only, one row in `delegation_team`). Turning the owner's switch off takes it away from every team member from their next message, and their inbox watchers stop at their next check; their own switches, drafts and cards are kept. Everything is keyed by `person_id`. A person turns it on for themselves (`PUT /delegation`); nobody turns it on for anyone else. The setting is one row per person in `delegation_settings`, and a missing, unreadable or zero row all mean off.\n\nAt the start of every chat turn (`Executive.stream_chat` and the committee path) `pin_turn_delegation(session, speaker_text)` runs next to the workspace-mode pin and records a `TurnDelegation` on the session. `ghostwrite_email` is **offered** only when all of these hold:\n\n- the speaker may have it and turned it on — read fresh every turn, so turning it off applies from the next message;\n- the speaker is on a surface that verified it is them — the principal through `people_tools.is_principal_on_verified_surface`, a team member through `teammate_on_verified_surface` (the web app signed in, their own Slack or Discord, never an email turn) — and a web turn also carried a signed-in caller (`Session.web_caller_signed_in`, set from `x-caller-email`) or runs under local login — a request with no caller header is not a sign-in and never gets it (whoever holds the shared secret is trusted as the UI proxy that stamps that header, as on every principal-only route);\n- the conversation is private to the speaker: the web chat, a Slack or Discord DM, or a verified private Telegram chat — never a shared channel or thread, where the draft's preview or the matching threads would be posted for everyone and other people's messages sit in the model's context;\n- the turn is neither unattended (the scheduler's proactive run) nor private to the principal (the email poller's turns), so inbound text can never reach it. The MCP server, workflows, reflection and research never carry it at all.\n\nThe mailbox connection is deliberately **not** part of the offer: the handler checks it on every call and says how to fix it, so the cached tool prefix never flips when a token lapses. The pin lives in a context variable for the turn's task as well as on the session, so two turns running at once on one session (a second browser tab) each read their own. It also carries the speaker's own words for the turn (a new email may go to an address they just typed — the turn's message joins the history only once the turn ends), a per-turn draft count, and `touched_mail` (see Privacy). `own_words` reads those words back for every own-words check (addresses here, facts and task assignments elsewhere): it first removes the hydrated `<outbound_reply_context>` backstory by its exact, anchored shape, so a look-alike closing tag quoted inside it cannot pass the rest off as the speaker's, then drops other adapter tag blocks, and returns nothing for a message carrying an attachment.\n\n## The tool: `ghostwrite_email`\n\nIt lives in its own registry (`orchestrator.delegation_tools.DELEGATION_TOOLS` / `DELEGATION_TOOL_HANDLERS`), **never** `_ALL_SKILL_TOOLS`, so no other toolkit can carry it. On a turn it is offered to, the agent loop adds it to the pool *before* the sort and builds that turn's handler map from both registries; on any other turn a call to it is an unknown tool. The handler re-checks the pin and the surface anyway, then:\n\n1. **Caps** — at most 5 drafts per turn, and `DELEGATION_MAX_DRAFTS_PER_DAY` (default 50, at most 1000) per person per UTC day, shared with the inbox watcher (`delegation.caps`). It is counted from `delegation_drafts`, one row of ids per draft saved from either place, with a count kept in the process as a floor in case a row was lost. Each slot is taken before the first await — a round's tool calls run concurrently, so otherwise every call in it would pass the caps before any counted — and handed back if nothing was drafted. If the rows can't be read it refuses rather than guess.\n2. **Marks the turn** — sets `TurnDelegation.touched_mail` *before* its first read of the mailbox.\n3. **Checks the mailbox** — `gmail_status` asks Google or Microsoft whose mailbox the credential opens and compares it with the person's People email, on every call: a roster email can change, and a client slot swaps the roster.\n4. **Finds the thread** — by `thread_id` (checked against the mailbox's own id shape), or a Gmail-style search (`find`; on Outlook, words, `from:`, `to:`, `cc:`, `subject:` and `newer_than:` are kept and other Gmail operators dropped). Several matches return `{status: \"choose\", candidates}` (subject, sender and date — no message text) and draft nothing; none returns `not_found`.\n5. **Sets the recipients in code**, never from the model. A reply goes to the last inbound message's `From` — never its `Reply-To` (a different one is flagged `reply_to_ignored`) — with the thread's other recipients only on `reply_all`. A new email 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 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## Forwarding and reminders\n\n`ghostwrite_email` also forwards: with `forward` (a thread id) and `to`, it drafts a forward of the thread's latest message, `intent` becoming the short note above it (the ghostwriter writes only the note; the forwarded email's subject, someone else's words, is never put in the intent). Recipients follow the new-email rule (`_new_recipients`: the roster, or addresses the speaker typed this turn). Gmail's draft quotes a forward header and the original's own words under the note and attaches the original's files, up to 10 and 20 MB (`FORWARD_MAX_FILES`, `FORWARD_MAX_BYTES`; any left off are flagged `attachments_left_off`); Outlook uses Graph's `createForward`, which keeps the original and its files, with the note as its comment and the body never patched. It is still only a draft.\n\n`remind_me(text, when)` (`orchestrator.reminder_tools`) rides with the same tools and checks, but opens no mailbox, so it never marks or locks a turn (`MAILBOX_TOOL_NAMES` are the ones that do). It stores the text once cleaned — one line, anything a chat app could turn into a link (a URL of any scheme, an address, a domain-like word, a host and port, an IP address) replaced with \"[link]\", at most 300 characters — with its time (stored in UTC) in `delegation_reminders` (5 a turn, 25 waiting, a year ahead, refused when the person has no channel). When it is due the scheduler sends that text to the person alone, as \"Reminder you set on <date>: …\", running nothing (see Scheduler); the Slack and Discord DMs it may go by turn link previews off. The chat chip shows the text as it will be sent. A reminder that comes due in the person's quiet hours or leave (when `OUTBOUND_RESPECT_QUIET_HOURS` is on) waits unclaimed and goes once they end, rather than being suppressed and lost. It is allowed after mail is read and in later turns of that conversation: it reaches only the speaker, as plain text. `schedule_followup`, which runs a turn with tools and is listed to everyone, stays refused there.\n\n## 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) and `add_contact` (a new contact; the principal's cards only, since contacts are theirs). 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 Approve + allow, and a card of actions all allowed is carried out on its own (see In training above).\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;\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;\n- the person is not in To or Cc, or it has more than 10 recipients;\n- the person replied last, or a draft already sits in the thread.\n\nThree kinds are left unrecorded, so a later scan looks again: mail under 10 minutes old (mail the person answers straight away never gets a card), mail in a thread whose card is still open, and mail a daily limit holds back.\n\n### Deciding, then writing\n\nTwo model calls, and code decides between them. The classifier (`delegation.inbox_classifier`) is one forced-tool call, `classify_email`, returning whether the email needs a personal reply, what kind it is and how sure it is. It sees a few one-lined header lines and the sender's own new words (at most 3000 characters, every line scrubbed) inside one `<email>` block marked as data, and it has no other tools, context or memory, so an email can ask for anything and there is nothing to do it with. A reply is drafted only for a question, a request, scheduling, an introduction or a follow-up, and only when the confidence clears a bar that rises the less the sender is known: 0.6 for their team or a contact (the principal's contacts count only for the principal: a team member's mail is weighed by the team and their own sent mail), 0.7 for someone they have written to before (`has_written_to`, a search of their sent mail), 0.85 for a stranger. Pitches, notes of thanks, FYIs, notifications, newsletters and phishing get nothing, and so does any failure. An email that also went to other people is drafted for only when the person is in To and it asks them themselves: the classifier is told their name, whether they are in To or Cc and how many others it went to, and lists the names the email greets or asks by name (`asked_names`). Code matches those against the person's name, whole name parts only (\"Alexis\" never counts for \"Alex\", and a nickname misses, which means no draft), so mail that greets someone else (\"Good morning, Brennan, could you sign ...\") is never theirs, whatever the model makes of it as a whole. When it names nobody, the model's `asked_of_them` decides, false for a question to the group at large. One that only copies them is never drafted for. Either is recorded `not_needed` with the reason `asks_someone_else`. It runs on `DELEGATION_CLASSIFIER_MODEL`, else the routing model. A sender whose address Gmail couldn't authenticate is handled as a stranger whatever the roster says — anyone can put a colleague's or a client's address in From — so they get the stranger's bar, a holding reply and the stranger limits; the card still says who they claim to be, and that the address isn't verified.\n\nThe reply is written by the same ghostwriter, in the person's voice, but from a fixed intent the module builds rather than words the person typed. Because the intent lets it restate the person's own earlier words, which words are theirs is never written inside the thread, where a sender could imitate any marker with a look-alike: every message there is labelled alike, and the person's own words come in a separate `<writer_said>` block after the thread, taken only from mail their own mailbox sent. Nothing inside the thread can close the thread block or open another. The intent: acknowledge the sender; say again only what the person's *own* earlier messages in the thread already said; commit to nothing new — no yes or no, date, time, price, fact or promise — and say they will get back to them; and put every question it could not answer from their words in **open questions**. A stranger always gets a short holding reply. The lint still strips any link or address that isn't the person's own. The reply goes to the sender (never `Reply-To`) and, on a group email, to everyone else it went to as Cc (reply to all, never the person's own addresses or the Executive); a stranger's holding reply goes to the sender alone. The card says when others were on the email, and its `draft_to` lists everyone, which Send checks.\n\nThe order: record the message, classify, reserve a slot in the shared daily limit, write, save the draft in Gmail (from the alias the mail went to, when it went to one) and store its id, then create the card (idempotent on the message) and mark it drafted. Nothing that fails along the way loses the message. A failure that may pass — the classifier or the writer failing, Gmail refusing the draft, a card that couldn't be made (its draft is deleted first, so no draft is left without a card), any other error with that one message — leaves it for a later scan (`retry`), and it is given up on only after three tries; one message's trouble never holds up the rest. A daily limit reached while it was being read leaves it for later without counting as a try.\n\n### The reply cards\n\nA card is a `delegation_reply` decision whose class is **its approver's alone** (`DecisionClassSpec.approver_only`): only the person it was drafted for sees or resolves it on any decisions route — a team member's card answers 404 to the principal too — and it is never an alert: alerts feed chat turns, which would put other people's mail into memory. It carries the sender with who they are to the person and whether Gmail could verify the address (SPF/DKIM/DMARC, through `fact_confirmation.headers_authenticated`), the subject, what they wrote, the draft, the open questions and its warnings. `GET /delegation/replies` lists the open ones from the database alone, so Today never waits on Google.\n\n- **Send** approves the card, which sends its draft exactly as it is in their mailbox (see *Send on your tap*). **Edit** 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). **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 is Replies in training, with a *Train follow-ups too* box for Follow-ups), and **Suggested actions** picks Always ask / In training; one *What it's learned* list sits at the bottom, 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 + allow and Approve + allow 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 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 Settings card shows it under the switch with how many went today.\n\n### Take the lead as you\n\nOn Settings → Act as me, Handle it for me is one dial: **Off**, **Easy ones**, **People I know**, **Most mail** and, for the owner, **Everything**, which uses **Take the lead** (`PUT /delegation/take-the-lead`, one row `person:<id>` in `take_the_lead`; turning it on turns Handle it for me on). While it is on, `handle_it.refusal` drops the setting's limits: strangers, the classifier's confidence, amounts, and the length up to a 4000-character ceiling. A reply with a link still waits for a tap (refusal `link`). In their place it checks the company's and the person's own added rules (`take_the_lead.reply_hit`, refusal `lead_rule`). Everything Handle it always keeps still holds: signed sign-ins, an authenticated sender, a reply kind, exactly the thread's people, the topics that always wait, draft flags, never twice in a row, one a thread a day and the daily limit. Follow-ups under it may go to anyone the person wrote to, with the same sensitive, amount, link and length checks plus the added rules. `reply_send.send_on_its_own` accepts the card while both switches are on. Each person adds and removes their own rules (`/delegation/take-the-lead/rules`). Removing one needs a caller the API can tie to them.\n\n## The mailbox client\n\n`delegation.gmail.DelegateGmail` talks to the Gmail REST API directly and is **never registered with the MCP gateway**, so the model reaches the mailbox only through the typed handler. The credential is one file per person in `DELEGATION_GOOGLE_CREDENTIALS_DIR`, named from a hash of the address (0600 in a 0700 directory), minted by `scripts/connect-own-gmail.py` on the Executive's own OAuth client with the scopes `gmail.readonly` and `gmail.compose`. It never lives in `WORKSPACE_MCP_CREDENTIALS_DIR`, where workspace-mcp picks a credential by address. Besides reading threads and saving drafts it lists the inbox and checks whether they have written to an address, reads one message or draft, lists the person's send-as addresses and deletes a draft. Its **one send method**, `send_draft`, sends an existing draft by its id and nothing else — never `messages.send`, which sends any text it is given — and unit tests pin the method set, the endpoint, the request body and its single caller. A failed request says whether it may have been carried out anyway (a timeout after connecting, a 5xx), which is what the send path needs to know. A parsed message carries when it arrived, whether it is bulk, a bounce or a calendar invite, and whether Gmail's authentication results vouch for its sender.\n\n`gmail_status` answers `connected`, `not_configured`, `needs_reconnect` (Google refused the saved sign-in — an app in Testing mode has its tokens expire after 7 days; a rate limit, though Gmail may send it as a 403, is an `error` to retry, not a reconnect), `mismatch`, `no_email`, `shared_mailbox` or `error`. `shared_mailbox` means the person's address *is* the Executive's; it is refused before asking Google, because then everything the Executive writes would look like theirs. The gateway closes the other door: every `google_workspace__*` call must act as the Executive's own account, and a `user_google_email` naming anyone else is refused and audited (see Integrations).\n\n### Outlook\n\nA person may connect an Outlook mailbox instead (work, school or personal), with `scripts/connect-own-outlook.py`: a device-code sign-in on the Executive's own Entra app (`MS365_MCP_CLIENT_ID`, tenant `MS365_MCP_TENANT_ID` or `common`) asking for `User.Read`, `Mail.ReadWrite`, `Mail.Send` and `offline_access`. It writes the same per-person file with `\"provider\": \"microsoft\"`, so a person has one mailbox for Act as me, and `gmail_for` hands back `delegation.outlook.DelegateOutlook`, which keeps `DelegateGmail`'s methods, return types and errors, so every caller above runs unchanged. It talks to Microsoft Graph directly, never through the Microsoft 365 MCP server the Executive's own Outlook uses, and is never registered with the gateway. Microsoft rotates the refresh token on use; the new one is written back into the file (atomically, keeping every other key, and only if the file still holds the old one). Graph is asked for immutable ids, so a sent draft keeps its id; a thread is Outlook's `conversationId`. Gmail's labels are mapped onto what the callers read: `SENT` only for mail in their Sent Items folder (a From line set to their address by someone else never counts), `DRAFT`, `INBOX`, and Focused Inbox's Other read as a tab. A sender counts as authenticated only when the topmost `Authentication-Results` — the one Exchange wrote, above anything the sender added — holds exactly one DMARC verdict, a pass for From's own domain, and Exchange Online Protection's own `compauth=` verdict, so a header the sender wrote on mail EOP never stamped doesn't count. `delete_draft` refuses anything that isn't a draft, and deletes with the draft's etag (`If-Match`), so a draft sent in between — it keeps its id — is left alone. No client secret is ever written into a person's file, and Graph has no signature setting to read.\n\n## Privacy\n\nWhat a person's mailbox touches is theirs. For the principal that means private to the principal, as every private row is. For a team member it means theirs alone, the principal included: an audit row carries `private_to_person` (set by `audit.rows_for_person` around the inbox watcher, a card's Send and Dismiss and their settings changes, and by `people_tools.audit_row_owner` on a turn that read their mail) and is left out of every audit read — the log, a session's timeline, a row by id, the brief — with only the usage totals counting it; their reply cards are theirs alone (above); and the owner's view of their use is counts only (drafts and sends in 30 days, and whether their inbox watcher is on). The conversation itself becomes its owner's alone before the mailbox is first read: `ghostwrite_email` marks the session `mail_private` (`session_store.mark_mail_private`, creating a channel adapter's row early, with its owner) and refuses to read the mailbox if that can't be stored or the conversation already belongs to someone else (which it then leaves unmarked); from then on only its owner may open it (`chat._session_access`), and working-style learning skips it. Every later turn there starts private (`settings.pin_turn_delegation` reads the flag and fails closed, setting `touched_mail`), so a follow-up answered from history alone is still private to its owner and teaches no memory, and the web chat's rows before the turn (the inbound message and the knowledge lookup) are theirs too. It does not start locked down: the lockdown is `read_mail`, set only by a turn that reads the mailbox or notes itself, 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. 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## Surfaces\n\n- **Settings → Act as me** (`ActAsMeCard`, hidden unless `GET /delegation` answers, so a team member sees it once the owner lets them): the mailbox connection (`provider` says which) with both connect commands (Gmail and Outlook) and **Check again**, the **Write drafts as me** switch, the **Draft replies to my inbox** switch with its status in plain words, when it last checked and **Check now**, and **How I write**: length and tone, a greeting per audience (`{first}` is their first name), the sign-off, habits and never-rules in fields that grow to show every line, the signature with **Refresh from Gmail** and **Don't add my signature** (or **Add my Gmail signature** when none is added; on Outlook only **Don't add my signature**, with why), and each example quoted with **Remove examples**. The owner also gets **Let team members use it** where the install allows it, with each team member who has it on listed by name and counts only.\n- **Today → Replies waiting** (`RepliesWaiting`, the top of the left column; hidden unless `GET /delegation/replies` answers with cards): each card shows who wrote and who they are to you, whether their address was verified, the subject, **They wrote** as plain text, your draft, **Decide before sending** (the open questions) and its warnings, with **Send** (a confirm naming who it goes to, and a second one when that or the thread changed), **Edit** (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- **Setup status**: a **Your own mailbox (Act as me)** light (`your_gmail`), amber while the inbox watcher can't reach the mailbox, is being rate-limited or has 25 replies waiting.\n- **Settings → Your Executive** (`app/settings/executive`, where `/settings/on-its-own` lands): the pause, **Take the lead** and **Book meetings without asking** (as the Executive). **Handle it for me** (the Off / Easy ones / People I know / Most mail / Everything dial, what each sends, how many went today and what it sent this week, as you) sits under the mailbox card on **Settings → Act as me**.\n- **API**: `GET`/`PUT /delegation`, `GET`/`PUT`/`DELETE /delegation/voice`, `POST /delegation/voice/learn`, `POST /delegation/voice/describe`, `POST /delegation/voice/signature`, `PUT /delegation/inbox` (`{enabled?, mailbox_drafts?}`), `POST /delegation/inbox/check`, `GET /delegation/replies`, `PUT /delegation/replies/{id}/text`, `PUT /delegation/handle-it`, `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). Send is `POST /decisions/{id}/approve`; Dismiss is `POST /decisions/{id}/reject`.\n- **Evals**: a scenario's `delegation:` block runs the turn against an in-memory mailbox (`evals.mailbox.ScenarioMailbox`) and hands the saved drafts to the judge (`delegation_001`–`003`). A `type: inbox` scenario runs the watcher's two model calls on one thread: whether it drafts must match the scenario, and a draft is judged on saying nothing the person hadn't, copying no link or address, and listing every open question (`delegation_inbox_001`–`007`; the last checks a draft never claims anything was sent).\n\nActing within rules the person sets and standing in for them are later, separate changes, each behind its own switch, off by default.","mermaid": "flowchart TD\n Ask[\"Principal or team member, verified<br/>'reply to Dana as me: yes'\"] --> Pin[\"pin_turn_delegation<br/>may have it? on? verified? private? attended?\"]\n Pin -->|\"offered\"| Loop[\"Executive tool loop<br/>with ghostwrite_email\"]\n Pin -->|\"not offered\"| Self[\"writes as itself<br/>(unknown tool this turn)\"]\n Loop --> Tool[\"ghostwrite_email handler<br/>caps, mailbox check, recipients in code\"]\n Tool -->|\"touched_mail\"| Private[\"turn's rows and conversation<br/>theirs alone, no memory\"]\n Tool --> Client[\"DelegateGmail or DelegateOutlook<br/>REST, outside the MCP gateway\"]\n Tick[\"Scheduler tick or Check now<br/>Draft replies to my inbox on\"] --> Scan[\"inbox scan, rows theirs alone<br/>skip rules, limits, ledger\"]\n Scan --> Client\n Client --> Box[(\"The person's own Gmail or Outlook\")]\n Scan --> Classify[\"classifier, no tools<br/>needs a reply? kind, confidence\"]\n Classify -->|\"worth a draft\"| Gw\n Voice[(\"delegation_voice<br/>How I write\")] --> Gw[\"ghostwriter<br/>no tools: voice + intent + thread\"]\n Tool --> Gw\n Gw --> Lint[\"lint: links and addresses<br/>only the person's own\"]\n Lint --> Draft[\"create_draft, threaded\"]\n Draft --> Box\n Draft --> Chip[\"chat chip: open the draft<br/>chat never sends\"]\n Draft --> Card[\"Today: Replies waiting<br/>their own card\"]\n Card -->|\"Send, confirmed\"| SendPath[\"reply_send: checks again,<br/>claim, send the draft by id\"]\n SendPath --> Box\n class Ask entry\n class Pin compute\n class Loop compute\n class Self compute\n class Tool compute\n class Private compute\n class Client compute\n class Tick entry\n class Scan compute\n class Classify compute\n class Box external\n class Voice storage\n class Gw compute\n class Lint compute\n class Draft hot\n class Chip entry\n class Card entry\n class SendPath hot",- "generated_at": "2026-10-09T18:00:00Z"+ "generated_at": "2026-10-10T16:26:53Z"}diff --git a/packages/core/openexecutive/architecture/prebuilt/memory.json b/packages/core/openexecutive/architecture/prebuilt/memory.jsonindex 4b08bcde..57b48159 100644--- a/packages/core/openexecutive/architecture/prebuilt/memory.json+++ b/packages/core/openexecutive/architecture/prebuilt/memory.json@@ -1,7 +1,7 @@{"section_id": "memory","title": "Memory System",- "markdown": "The Executive's durable memory is an episodic SQLite store at `./episodic_memory.db`, managed by `openexecutive.memory.episodic`. It holds four tables:\n\n- `decisions` — choices made, with `domain`, `summary`, `rationale`, `outcome`, and `tags`. `outcome` is filled in when the principal says how a decision turned out — the `record_decision_outcome` chat tool (principal on a verified surface only) or the Memories page. The weekly review reads this table twice: the week's decisions (`decisions_since`) and up to three older than 30 days with no outcome yet (`decisions_awaiting_outcome`), which it asks about.\n- `initiatives` — tracked efforts with a `status` and `summary` (idempotent upserts).\n- `advice_given` — query/advice pairs per domain.\n- `scheduled_actions` — a dispatch queue, treated separately from recall memory. `cancel_scheduled_action` guards its UPDATE on `status = 'pending'`, so a cancel never overwrites a row the scheduler claimed a moment earlier.\n\n### What gets extracted, and when\n\n`episodic.extract_and_store` runs after a turn and asks a utility-fast model for decisions, initiatives and advice. Every candidate must carry a `user_commitment_quote` that appears verbatim in the principal's own message (`_is_valid_user_commitment`) — the turn's speaker text (`memory_text` when the entry point supplies one, else the prompt), so a quoted Executive email or a briefing card's body inside the prompt cannot satisfy it — the model has repeatedly tried to log the Executive's *recommendations* as the user's commitments, and that quote is the hard gate against it.\n\nA turn reaches the extractor if `should_extract(speaker_text, session=...)` is true, which means only that the principal said something on a surface that proved it was them — there is deliberately **no length floor**. There used to be one, on the combined user+assistant length, and on a live tenant it selected almost exactly the wrong turns: 9 of 16 exchanges were blocked, and the 9 held every instruction the principal gave, while the 7 admitted were long analytical exchanges with no commitment in them. The extractor ran 13 times and stored nothing.\n\nMoving that floor to the user's side would relocate the bug, not fix it. The canonical executive decision is a long analysis answered with \"Approve option B.\" (17 chars) or \"Do B.\" (5), and any floor high enough to skip \"Done\" (4) also skips those — \"Do B.\" and \"Done\" differ by one character and mean opposite things. Length cannot separate a decision from an acknowledgement; the verbatim-quote check can, so `_is_valid_user_commitment` is the gate that decides. The price is one utility-fast call on turns that propose nothing.\n\nThat quote check is only meaningful when `user_message` holds the **principal's** words, and on a chat channel it does not — `Executive.chat()` is reached from Slack, Discord, Telegram, Google Chat and the email poller. A teammate's line would be written to `decisions` with no speaker attached, indistinguishable from the principal's own; an inbound email body is text the sender chose, so a self-quote is free. Removing the length floor is what makes this bite — short channel traffic used to fall under it incidentally — so `should_extract` asks the untrusted-content policy (`orchestrator.content_trust.principal_speaking`) whether the principal is speaking. It names the principal's surfaces rather than inferring them: the web chat (signed in as the principal — or, on an install with no principal on the People page yet, a request that carried no sign-in; a signed-in email on nobody's entry, such as an archived teammate still allowed to sign in, is not the principal), the CLI (`Session.from_cli`), the principal's own Slack or Discord or a private Telegram chat with a valid webhook secret (`people_tools.is_principal_on_verified_surface`), and email from the principal's primary address that Gmail's own `Authentication-Results` marks `dmarc=pass` (`Session.email_authenticated`). Everything else fails closed: a teammate (on the web too), an unrostered sender, the principal's address on mail Gmail did not authenticate, Google Chat, the MCP server (its caller names themselves), unattended runs, and an unreadable roster. The rule used to be \"no `origin_channel` means the principal's own surface\", and the email poller left `origin_channel` empty, so every stranger's email ran through the extractor with its body — headers, quoted chain and all — as the principal's words, and whatever it stored rendered on every later turn. The poller now tags its sessions `origin_channel=\"email\"`, and the gate no longer reads an empty channel as trust.\n\nThe extractor also reads only the words **outside** every `<untrusted_content>` block (`schedule_extraction` runs `content_trust.strip_untrusted` first): an attached document's text is inlined in that block, so a sentence the principal did not type can never be quoted back as their commitment, and a turn that is nothing but an attachment is not extracted at all.\n\nEach pass writes a `memory_extraction` audit row — in a `finally`, so a pass that crashed is recorded too, with the exception type as its `failure` reason: how many items the model proposed, how many were stored, a `malformed` count so a pass where the model returned only garbage does not read as one that found nothing, and a `{kind, reason}` record per drop — `bad_quote` and `missing_field` for an item the model proposed, `not_a_list`, `item_not_a_dict` and `payload_not_a_dict` for a shape that was never a usable item. Every proposed item is either stored or dropped, so `proposed == stored + item drops` is the arithmetic that says whether anything was lost silently. The tool payload is not schema-checked anywhere, so a malformed shape is counted as a drop rather than raised — it used to abort the whole pass, discarding the other two kinds with it and suppressing the row, which read exactly like \"extraction never ran\". Without it, \"the model found nothing\" and \"the model found things and every one was rejected\" are indistinguishable from outside the database — which is why the failure above survived undetected and took a SQLite session on the tenant to find. A `proposed>0, stored=0` streak is the signal to watch.\n\nThe validator rejects a paraphrase, and the model paraphrases: on one install two of three real commitments were lost that way, the quote beginning \"SVN's engagement covers only …\" where the person had typed something else. So a `bad_quote` drop earns exactly one corrective call. The model is shown the rejected items and the quotes it gave, told to copy the span character-for-character (typos and casing included) or return empty arrays, and the tool is forced where the provider supports tool choice. Every retry item is validated first; a still-invalid one adds no second drop and is counted `still_invalid`. A valid item is then classified in order: its label matches a pending drop record → a recovery, stored and the record released; else its quote (terminal punctuation ignored) already supports a stored item of that kind → a re-send, ignored and counted `repeated`, so a model that re-sends everything cannot double-count `stored`; else a new proposal, stored and counted — a reworded label cannot be told from a different item, and crediting it would erase the very `bad_quote` census the row exists to show, so its original drop stands. Recovery is checked before re-send because two commitments can rest on one sentence. Malformed shapes at any level — a kind that is not a list, an item or payload that is not a dict, a response with no tool call — are counted `malformed`, so a retry that returned garbage does not read like one that obediently returned nothing. The row's `retry` block (`rejected`, `recovered`, `repeated`, `still_invalid`, `malformed`, `failure`) is always present, zeros when nothing was rejected; `rejected` is set from the complete drop list when the row is written, so neither a store failure before the retry nor a cancellation during it can zero it. The arithmetic above still holds after the retry. An exception on the retry is recorded as the retry's own `failure` and leaves the first pass's results untouched; the cost is one utility-model call, only on turns that dropped something. `memory_extraction` is a declared event type, so the audit page's filter can select it.\n\n### Standing facts (corrections that persist everywhere)\n\nA fifth table, `facts` (`openexecutive.memory.facts`, created on first write), holds facts and corrections the principal stated and asked to keep — \"Maple House is 48 units, not 52\". Before it, a chat correction's only durable home was Honcho peer memory: optional, best-effort (its prefetch times out or errors under load), re-injected only into that person's later chat turns, and never read by the briefs, the scheduled runs or the alert review. The episodic extractor cannot hold one either: it stores only decisions backed by a commitment quote, and a fact is not a commitment.\n\n- **Written from chat, by the principal or an attributed teammate.** `remember_fact` stores one (subject, statement, optional wrong value) and `forget_fact` retires one. The principal on a verified surface may do both. A teammate on the People list (a `team` row, not archived, not a contact) on a verified surface (the web app signed in, their own Slack or Discord; `fact_tools._teammate_speaker`) may call `remember_fact` only; email, Google Chat and unrostered senders are refused. Both tools are withheld from every unattended run and every turn private to the principal. Every call, `forget_fact` included (retiring a fact changes what later prompts treat as true just as writing one does), also needs `source_quote`: at least two words and eight characters, found in what the speaker typed this turn (`delegation.settings.own_words` over the pinned `TurnDelegation.speaker_text`). The `<outbound_reply_context>` backstory a Slack or Discord reply is hydrated with is stripped first, and a message with an attachment is refused outright. The quote alone only proves the principal asked, so everything `remember_fact` stores and renders (the statement, the subject shown as `[fact N] subject:`, and a previous value shown as `(corrects: …)`) is tied to their words too. An omitted previous value falls back to the replaced fact's own statement. Every figure must be a number they wrote, compared at its magnitude: `$180k` matches `180,000`, but `180m` never lets `$180k` through. Every name must also appear in what they typed: a capitalised word, or any word holding a non-ASCII letter, other than the statement's very first word (a statement is one fact, so splitting a document's names into one-word sentences exempts nothing). So must every month, weekday or quarter. A name the model writes in lower case is not caught: the gate narrows what a real quote can carry in; it does not prove a paraphrase. A real quote therefore cannot carry a document's figure, name or date in with it (\"Cedar Court's lease expires in March\" after \"remember what the lease doc says\"), while a paraphrase of what they said still passes. So the model cannot store its own inference, a document's figure or text quoted back at the principal as something they said. Every audit row the tools write, and the chat loop's `skill:` dispatch row for them (whose input quotes the principal verbatim), is private to the principal (`executive._private_tool_row`). Those rows tie a fact to the principal's session and turn, which `GET /memories/facts` hides from teammates, and a teammate can read any non-private audit row. The handlers run in a worker thread (`asyncio.to_thread`, which carries the turn's context), and the chat and committee paths, the alert review, the morning brief's synthesis and the end-of-day, weekly-review and reflection workflows read the block the same way, so SQLite, the profile file and its lock never block the event loop the SSE streams share. The principal's own email may ask too: the change is checked the same way, then held until they confirm it by replying to a one-time token sent to their own address (see Integrations → Standing facts by email).\n- **Provenance and attribution.** Each row keeps the quote, the channel (`web` or the adapter), `session_id`, `turn_id`, the recording person and the time, plus `recorded_by_role` (`principal` or `teammate`) and, for a teammate, `recorded_by_name` as the People list had it. Rows written before these columns existed read as the principal's (`_migrate` adds the columns on the first write; the read-only render tolerates a DB that has none).\n- **One active fact per subject.** A new row supersedes any active row with the same folded subject key, or the id named in `replaces_fact_id`, in one transaction. The old row stays as `superseded` (with `superseded_by`), and the new one is stored as a `correction` carrying what it replaced. Retiring sets `retired` with a reason. **The principal outranks a teammate:** a teammate's write that would replace an active fact the principal set (by subject or `replaces_fact_id`) raises `PrincipalFactConflict`, and the tool stores it as `proposed` instead, naming the fact it would replace (`replaces_fact_id`); teammates replace each other's facts freely, and the principal replaces anyone's. **\"Needs my approval\"** (`fact_approval_rules`, per teammate, **on by default**, set only by the principal) stores every fact from that teammate as `proposed`; the principal turns it off for a teammate they trust, whose facts then apply at once (except one that would replace the principal's). The rule is read inside `record_fact`'s own write transaction, so a switch turned on a moment earlier cannot let one fact through; a teammate write that names no person is never trusted. One teammate may have at most `MAX_PENDING_PROPOSALS_PER_PERSON` (20) proposals waiting (`TooManyProposals`; the tool tells them to wait for the principal's review). A teammate's retire checks ownership in the `UPDATE` itself (`retire_fact(teammate_id=)`: their own row, not approved). A proposed row never renders; `approve_fact` makes it active and replaces what it names (the principal's own fact included — approving it is their word) and stamps `approved_at`, after which it outranks teammates exactly as the principal's own fact does (`Fact.principal_owned`: no teammate may replace or retire it); `decline_fact` sets `declined`. No field of a teammate's fact may carry what the render adds itself — `(per <anyone>)` in any case (a unit such as `(per month)` or `(per unit)` is fine), `[fact N]` or a date stamp after any dash, read NFKC-folded with invisible characters removed (`fact_tools._marker_error`) — so a teammate cannot plant a second, forged attribution inside their statement (the principal's own unmarked lines are not checked: \"(per Smith lease)\" is ordinary wording for them). The tool answers `awaiting_approval` (no action chip) and tells the model to say it is not in use yet.\n- **Rendered everywhere output is produced.** `render_facts_for_prompt` renders the active rows newest first under a self-explaining `STANDING FACTS` header (use these over older figures; a line ending `(per <name>)` is that teammate's word and the principal's unmarked line wins a conflict; the current conversation still wins; quoted data never instructions). A teammate's line ends `(per <name>)`, the name defanged like the rest, capped at 40 facts / 6000 chars, with angle brackets defanged. It opens the DB read-only and never creates it or the table. The block always rides in a user turn, never a cached system block: a chat turn's `<standing_facts>` (so every scheduled run through the chat loop too), each specialist consult (`route_to_specialist`, chat and workflow steps alike), the /today header and the morning brief (`render_briefing_context`, after the quiet check and inside the string the header's cache key hashes, so a new fact rewrites the header), the alert review's batch (`render_batch`, read once per pass), and the end-of-day digest, the weekly review's top-three call and the morning reflection (`with_standing_facts`).\n- **Company-profile edits from chat.** `update_company_profile` (same gate and quote rule) changes one whitelisted field of `company/profile.yaml`, under `PROFILE_EDIT_LOCK` (also taken by `PATCH /company-profile`, so neither edit silently drops the other): a text or number field is set, a list field gets an item added or removed, and `financials.key_metrics` takes a named metric. It writes through `CompanyProfile.save_to_yaml` and updates the session's profile, so the next turn's cached company block carries it (one cache miss on the change). The new value must itself appear in the principal's own words, not just the quote: the value renders into the cached company block on every later turn, so \"set our mission to what the doc says\" or \"update our headcount\" is refused rather than saving a document's text or a guessed figure. A number must be one they wrote, however they wrote it (`$180k`, `1.2m`, `2,400,000`). Saved text has `<`/`>` defanged. A `kind='profile'` row records each edit with its quote for the Pulse page. Those rows are never rendered into a prompt, because the profile block already carries the value.\n\n### Session scoping\n\n`decisions` and `advice_given` rows carry a `session_id`, so per-thread channels (Discord, Telegram) can pull just-this-thread history without leaking cross-conversation context. A null `session_id` falls back to a global view.\n\n### Surfacing\n\n`openexecutive.memory.episodic.format_for_prompt` renders recent decisions and initiatives into a compact `<past_decisions>` block injected into the user turn — alongside `<retrieved_context>` and peer memory — never into a cached system block. Each decision names where it was recorded when that was a channel — `- 2026-09-01 [finance] (via email): …`, from the prefix of its `session_id` (`email:`, `slack:`, `discord:`, `telegram:`, `google_chat:`); a web or CLI decision has no tag. Rows extracted from mail before the untrusted-content policy, when any sender's body could be stored, therefore read as mail rather than as the principal's own word.\n\nScoped to a session, decisions and advice cover every conversation of a chat app's stream (`memory.conversation_ids.family_clause`): a Telegram chat or a DM is cut into conversations after two quiet hours or a /new (`memory.conversations`), and what an earlier conversation decided still renders in the next.\n\nThe chat route also injects a `<briefing>` block into the same user turn: a compact digest of the current open (unread) alerts, built by `openexecutive.briefing.context.format_open_alerts_for_prompt` (company-wide, `status=\"unread\"`, mirroring `/today`). This is what lets the Executive discuss a briefing item the principal clicked or named on `/today` (e.g. \"Gulf Coast Port Cyberattack\"). It is resolved in parallel with the other context fetches, omitted when there are no open alerts, and never placed in a cached system block.\n\nOn the Pulse page the Memory section shows the three lists as Decisions, Initiatives and Advice tabs, then a **Corrections** tab (`GET /memories/facts`: active standing facts and profile edits with their quote, channel and — for a teammate's — their name; proposals first under \"Waiting for your approval\" with **Approve** / **Decline** for the principal; the replaced, retired and declined history folded away; **Retire** on any fact for the principal and on their own not-yet-approved one for a teammate; and, for the principal, a per-teammate \"needs my approval\" switch), and a **History** tab for the person's own Always in the loop notes (see below). The header's Memories tile counts the three lists. What peer memory has learned about the signed-in person is theirs alone, so it is not on Pulse: it is on **Settings → About you** (see the peer memory section).\n\nThe same user turn carries a `<drive_memory>` block when the conversation has touched Google Drive (`openexecutive.memory.drive_reads`). Drive is reached only as live Google Workspace calls inside a turn and history keeps only prose, so without it a file found one turn was gone the next. `MCPGateway.call_tool` hands each `search_drive_files` and `get_drive_file_content` result to `record_drive_result`, which keeps, per session, every file found or opened (file id, name, type, link, and for an opened file its first 600 characters) and every search that matched nothing, with its query. `format_drive_memory` lists the 20 most recent files, so \"the file you found earlier\" resolves to a file id the Executive reopens rather than searching again, and the queries that found nothing (dropped once the same query later finds something). Rows are keyed on the session *and* the speaker, and shown only to that speaker in that session, because one session can span several people (an email thread, a Slack or Discord thread). Nothing is recorded or shown without a bound `current_session` and a rostered speaker, on a turn private to the principal, or on one that touched the speaker's own mailbox (Act as me). workspace-mcp writes file names into its output unescaped, so a name containing a newline can forge a result line. Only a Drive-shaped file id, type and `docs`/`drive.google.com` link are therefore kept; any other line is dropped, and the name is always quoted as the file's own content, not instructions. Each speaker keeps at most 100 files and 100 searches per session, older rows are pruned on write, and `session_store.delete_session` drops them all.\n\nA conversation can also become its owner's alone. When Act as me first reads the speaker's own mailbox in it, `session_store.mark_mail_private` sets `sessions.mail_private` (creating the row with its owner when a channel adapter hasn't written it yet), and from then on only the session's owner may open, continue or delete it — the principal included, when it is a team member's (`chat._session_access`). It is never cleared. Beside it `sessions.mail_read_at` keeps how many history messages the conversation held before the last turn that read the mail (`session_store.mail_read_at`; NULL on rows marked before the column): Act as me's hold on links and scripts in later turns lasts only while that turn is still in the history window (see Act as me). A search that matched nothing also gains a note in its tool result: say the exact query and that it found nothing, never that the file does not exist. This is a first step: Drive is still not indexed into the company collection.\n\n### System of record\n\nSQL is the system of record; the peer-memory service is a recall layer mirrored from it, not a replacement. When `store_decision` / `store_initiative` / `store_advice` insert a row whose `department` is non-empty and not `\"general\"`, the row is mirrored as a kind-tagged note into that department's peer via `append_department_note`. The mirror fires only after a successful INSERT, is fire-and-forget, and never rolls back the SQL row on peer-memory failure. `scheduled_actions` is never mirrored — it is a queue, not memory.\n\nThe episodic extractor still learns only from the principal's own words. Commitments and asks from everyone else on the roster are tracked as **open loops** (see Attunement) — `scheduled_actions` rows with `kind='open_loop'`, opened and closed by a separate quote-gated pass after each attributed turn. That pass depends on `chat_messages.sender_person_id`, which records who actually wrote each persisted user message. An open loop counts toward `list_awaiting_replies_by_person` only once it is due, and `list_scheduled_actions(exclude_internal=True)` filters `__internal__` rows in SQL so readers that want real sends are not starved by them. `mark_outbound_context_consumed` also resolves the Attunement outcome row for that DM as `replied` — a matched reply is the clearest sign proactive outreach landed — and a real change to an existing initiative (`store_initiative` / `update_initiative`, new status or summary) marks the updater's own check-in nudges `acted` — an update with no known updater, such as `PATCH /memories/initiatives/{id}`, credits nobody.\n\n### Workspace settings\n\nThe same database holds one row of settings that are not memory: `workspace_settings` (`openexecutive.memory.workspace_settings`) — the install's mode (`team` by default, or `solo` for one person using Open Executive just for themselves), the user's IANA time zone, the principal's role (`PrincipalRole`: `role_kind`, `role_title`, `reports_to`, `remit`, `measured_on`, all nullable; only solo mode reads it), and the company's own email domains (`company_domains`, a JSON list, or NULL to derive them from the principal's primary address — `people.identity` matches a teammate by local part on them; `validate_company_domains` lowercases, dedupes and sorts, allows at most 10 plain DNS names and refuses a free-mail provider's, and a stored value that no longer validates reads as NULL). It is a table of its own rather than a company-profile field because onboarding rebuilds the profile from scratch. Every read is fresh and read-only (a missing file or table reads as the defaults; a table from before the role or `company_domains` columns reads them as unset and is migrated additively by the next init or write). A read error (a locked database, say) also reads as the defaults, so `get_workspace` then says team; `read_stored_mode` is the strict read of the mode alone — None when the row cannot be read or holds no valid mode — for the scheduler's weekly-review check, which must not take a failed read for team. A session may carry an explicit `workspace_mode` override; otherwise the mode is read fresh at the start of each turn and pinned on the session for that turn only (`Session.turn_workspace_mode`, via `pin_turn_workspace_mode`), so every tool handler in the turn sees the mode its persona and tools were built in. `effective_workspace_mode` reads override, then the pin, then the setting; `effective_principal_role` reads a session's `principal_role` override, then the role pinned for the turn (`Session.turn_principal_role`, via `pin_turn_principal_role`), then the stored role. See Org for what solo changes and Scheduler for the time zone.\n\n### Act as me\n\n`initialize_db` also creates Act as me's per-person tables (`delegation.schema.ensure_schema`): `delegation_settings`, `delegation_voice` and `delegation_voice_history`. They hold a setting and a writing profile rather than memory, and nothing in them is mirrored to peer memory. A turn that touched the speaker's own mailbox teaches no memory: the episodic, open-loop and working-style passes are skipped along with the Honcho peer and department syncs, since its reply quotes a draft built from other people's mail. See **Act as Me (Delegation)**.\n\n### Always in the loop (notes of what you said)\n\nA person can keep private, dated notes of what they said, in chat with the Executive and in email replies it drafted for them: what they promised, agreed, declined, answered, asked for or shared. The switch is per person (\"Keep track of what happens\", `history_person_settings.reply_notes`, off by default, one switch for every channel). Any team member on the People list may turn it on (`history.can_keep_notes`: kind `team`, not archived, the principal included); Act as me isn't needed, though notes from email replies only come through it.\n\n- **Where notes come from: chat.** After each chat turn, on both the single-voice and the committee path, the Executive's post-turn block calls `memory.history_chat.schedule_chat_notes` next to the open-loop and style passes, except on a turn that touched the speaker's mailbox. It reads only what the speaker typed this turn (`delegation.settings.own_words`: no backstory an adapter added, nothing when a file came with it), never the reply and never anyone else's message: every channel calls the Executive with the one speaker's message, and what other people say to each other is never read. It runs only for a speaker the turn verified (`history_chat.verified_speaker`): the turn's `caller_person_id` is them, nobody started it by email or runs it unattended or for them, and the surface proved who they are (the web chat signed in or a local install, the principal or a team member on their own Slack or Discord, a private Telegram chat behind a valid webhook secret, or a channel whose adapter verified the sender itself and set `Session.speaker_verified`). A shared Slack or Discord thread counts: the notes stay private and are read back only where nobody else can see them. A message under 40 characters is skipped, and each person gets at most 40 passes a day, counted in `history_chat_passes` so the cap holds across workers and restarts. The pass uses a constant `CHAT_PROMPT` (requests to the assistant, questions and small talk are not notes), the same `record_notes` tool and the same `check_note` gate with the message as both body and allowed words; the note's channel is the inbound channel or `web`, its conversation the session id, and it names no counterpart.\n- **Where notes come from: email.** After `delegation.reply_send` sends a reply, it starts `memory.history_notes.note_sent_reply` in the background. The note-taker reads only the words the person sent (`email_poller.sender_new_text` strips quoted mail) and the recipients' names, cut to four words of name characters (`history_notes.short_name`): never the mail being answered, nor the subject, which others in the thread write too, so nothing another person wrote can become a note. One forced `record_notes` call with a constant prompt and no other tools returns at most three notes. Code then drops any note that says more than they did: the `quote` must appear word for word in what they sent, every figure in the summary must be in the quote, every name or date word must be in what they sent or the recipients' names, at least half its other content words must be theirs, the summary carries no link or address, and a `due_date` is kept only for something promised or agreed. Notes record events, never instructions, and carry `trust = high` because they rest on the person's own words.\n- **Whose they are.** Every note is private to its person (`visibility = private`). Nobody else reads it, the principal included; there is no shared note.\n- **How long they last.** The company default is 90 days (`history_settings.retention_days`, the principal's choice of 30, 90, 365 or until forgotten). A person may only choose a shorter time; shortening the company time clamps everyone's choice and re-dates live notes. A pinned note never expires; unpinning restarts its clock, and a later retention change counts from there. Reads skip expired notes and the scheduler's alert sweep deletes them (`history.sweep_expired`).\n- **What a person controls.** Through `/memories/history` they read, search, pin, correct and forget their own notes. On the Pulse page this is the **History** tab, last in the Memory section and shown only to someone with notes to see (signed in and on the People list): each note shows its kind, who it was with, the date, the person's own words, any due date and when it will be forgotten, and its menu holds **Correct** (a side panel; \"Use the original\" clears a correction), **Pin**, **Don't remember this** and **Forget**. \"Don't remember this\" forgets every note from that conversation and adds it to `history_excluded`, so it is never noted again. Settings → **Memory** holds the switch (\"Keep track of what happens\") and a shorter time for their own notes, and the company time, which the principal changes and everyone else reads. A chat note shows the channel alone (\"Slack\", \"Web chat\").\n- **Recall.** `recall_history` (`orchestrator.history_tools`) is offered only on a turn where the speaker may read their notes: verified as above, a team member who may keep notes, in a conversation private to them (`history_chat.private_chat`: the web chat, a Slack or Discord DM, a Telegram chat, or one its adapter marked `Session.private_chat`), with their switch on. Before any note is read the turn is set `touched_mail`, for the principal too, so its rows are private to the speaker, it teaches no memory and the mail lockdown holds from that round on. The conversation is also marked theirs alone (`session_store.mark_mail_private`), so every later turn in it is private the same way (the lockdown is that turn's alone) and, for a team member, the principal can't open it; recall refuses if that can't be stored. Notes come back in a `<history_notes>` block as history to cite: the date, the person's own words first, then how they were noted. With `due: true` it lists only notes with a due date, from a week overdue to two weeks ahead, soonest first (\"what's due today?\").\n- **In the owner's briefs.** The morning brief adds a FROM YOUR NOTES — DUE SOON block (`memory.history_brief.due_soon_block`: what the owner promised, agreed or asked of someone, from a week overdue to a week ahead, in the workspace's local dates) and the end-of-day digest a FROM YOUR NOTES — TODAY block (`noted_today_block`: what they promised, agreed, asked or declined since the last digest, then what is due tomorrow). Both only on the scheduler's delivery to the owner alone (`morning_brief.PRINCIPAL_DELIVERY`), never a run started from chat, whose tool result lands in the turn's shared audit row and peer memory; only when the owner may keep notes and has the switch on (`history_brief.owner_keeping_notes`), and only the owner's own notes. A run that used any is marked `private_to_principal`, so the shared run history keeps `PRIVATE_RUN_ARTIFACT` instead of its text, and the note ids with their state (overdue, today, soon) enter the brief's fingerprint, so one falling due un-suppresses an unchanged brief. Teammates get no brief, so their notes reach them only through recall and reminders.\n- **In Act as me drafts.** The ghostwriter gets a `<writer_noted>` block (`memory.history_drafts.notes_for_draft`): the writer's own notes from earlier Act as me replies that every recipient of the new draft was on, with their switch on. It keeps the draft consistent with them and turns a contradiction into an open question on the card; it never adds anything from them (see Act as me).\n- **Due-today reminders.** `memory.history_reminders.maybe_remind`, called from the scheduler tick every 15 minutes between 09:00 and 18:00 local time, sends each person with the switch on one message on a day something they promised or agreed to by email (`source = approved_reply`) falls due. Chat promises are left to open loops, which the nudge engine already chases. The message says only how many things are due, never what or to whom, and the channel senders' audit rows for it are private to the person (`audit.context.rows_for_person`; the owner's `private_rows`), which also keeps the send off the shared activity rail (`_record_send_to_activity` skips a send whose rows are private). The person asks \"what's due today?\" in a private conversation and `recall_history` answers. It goes to their own Slack or Discord DM, a private Telegram chat (`delivery_order` skips a negative group id, for the owner's briefs too) or their own email (`scheduler.runner.deliver_to_person`), never a shared channel. `history_reminders` holds one row per person per day, claimed before sending and never released, so two workers never both send and a half-failed send is never repeated; a failed one waits for the next due day.\n- **Not peer memory.** Notes never reach Honcho, episodic extraction, standing facts or another person's turn. The tables (`history_notes`, `history_settings`, `history_person_settings`, `history_excluded`, `history_chat_passes`, `history_reminders`, created by `history_schema.ensure_schema` from `initialize_db`) swap with a client slot and are cleared by a factory reset.\n\n## Decision ledger\n\n`openexecutive.memory.decision_ledger` keeps one `decision_instances` row per gated action — a meeting the Executive proposes to book, an Act as me reply card — with how it was resolved, so each class has a reliability record. Every status change is a compare-and-set. A tap with an outside effect (sending an email) claims the row first (`claim_for_execution`, proposed → executing), so of two taps only one acts, and finishes it as `approved_unchanged`, `approved_with_edit` or `failed`, or hands it back (`release_claim`). A row whose class acted on its own with nobody tapping — `gate_mode` `auto_execute`, as Act as me's **Handle it for me** replies are — finishes as `executed` instead, with no resolver, so a reliability read never counts it as an approval. A send whose result is unclear stays `executing` for a reconciler and is never retried.",+ "markdown": "The Executive's durable memory is an episodic SQLite store at `./episodic_memory.db`, managed by `openexecutive.memory.episodic`. It holds four tables:\n\n- `decisions` — choices made, with `domain`, `summary`, `rationale`, `outcome`, and `tags`. `outcome` is filled in when the principal says how a decision turned out — the `record_decision_outcome` chat tool (principal on a verified surface only) or the Memories page. The weekly review reads this table twice: the week's decisions (`decisions_since`) and up to three older than 30 days with no outcome yet (`decisions_awaiting_outcome`), which it asks about.\n- `initiatives` — tracked efforts with a `status` and `summary` (idempotent upserts).\n- `advice_given` — query/advice pairs per domain.\n- `scheduled_actions` — a dispatch queue, treated separately from recall memory. `cancel_scheduled_action` guards its UPDATE on `status = 'pending'`, so a cancel never overwrites a row the scheduler claimed a moment earlier.\n\n### What gets extracted, and when\n\n`episodic.extract_and_store` runs after a turn and asks a utility-fast model for decisions, initiatives and advice. Every candidate must carry a `user_commitment_quote` that appears verbatim in the principal's own message (`_is_valid_user_commitment`) — the turn's speaker text (`memory_text` when the entry point supplies one, else the prompt), so a quoted Executive email or a briefing card's body inside the prompt cannot satisfy it — the model has repeatedly tried to log the Executive's *recommendations* as the user's commitments, and that quote is the hard gate against it.\n\nA turn reaches the extractor if `should_extract(speaker_text, session=...)` is true, which means only that the principal said something on a surface that proved it was them — there is deliberately **no length floor**. There used to be one, on the combined user+assistant length, and on a live tenant it selected almost exactly the wrong turns: 9 of 16 exchanges were blocked, and the 9 held every instruction the principal gave, while the 7 admitted were long analytical exchanges with no commitment in them. The extractor ran 13 times and stored nothing.\n\nMoving that floor to the user's side would relocate the bug, not fix it. The canonical executive decision is a long analysis answered with \"Approve option B.\" (17 chars) or \"Do B.\" (5), and any floor high enough to skip \"Done\" (4) also skips those — \"Do B.\" and \"Done\" differ by one character and mean opposite things. Length cannot separate a decision from an acknowledgement; the verbatim-quote check can, so `_is_valid_user_commitment` is the gate that decides. The price is one utility-fast call on turns that propose nothing.\n\nThat quote check is only meaningful when `user_message` holds the **principal's** words, and on a chat channel it does not — `Executive.chat()` is reached from Slack, Discord, Telegram, Google Chat and the email poller. A teammate's line would be written to `decisions` with no speaker attached, indistinguishable from the principal's own; an inbound email body is text the sender chose, so a self-quote is free. Removing the length floor is what makes this bite — short channel traffic used to fall under it incidentally — so `should_extract` asks the untrusted-content policy (`orchestrator.content_trust.principal_speaking`) whether the principal is speaking. It names the principal's surfaces rather than inferring them: the web chat (signed in as the principal — or, on an install with no principal on the People page yet, a request that carried no sign-in; a signed-in email on nobody's entry, such as an archived teammate still allowed to sign in, is not the principal), the CLI (`Session.from_cli`), the principal's own Slack or Discord or a private Telegram chat with a valid webhook secret (`people_tools.is_principal_on_verified_surface`), and email from the principal's primary address that Gmail's own `Authentication-Results` marks `dmarc=pass` (`Session.email_authenticated`). Everything else fails closed: a teammate (on the web too), an unrostered sender, the principal's address on mail Gmail did not authenticate, Google Chat, the MCP server (its caller names themselves), unattended runs, and an unreadable roster. The rule used to be \"no `origin_channel` means the principal's own surface\", and the email poller left `origin_channel` empty, so every stranger's email ran through the extractor with its body — headers, quoted chain and all — as the principal's words, and whatever it stored rendered on every later turn. The poller now tags its sessions `origin_channel=\"email\"`, and the gate no longer reads an empty channel as trust.\n\nThe extractor also reads only the words **outside** every `<untrusted_content>` block (`schedule_extraction` runs `content_trust.strip_untrusted` first): an attached document's text is inlined in that block, so a sentence the principal did not type can never be quoted back as their commitment, and a turn that is nothing but an attachment is not extracted at all.\n\nEach pass writes a `memory_extraction` audit row — in a `finally`, so a pass that crashed is recorded too, with the exception type as its `failure` reason: how many items the model proposed, how many were stored, a `malformed` count so a pass where the model returned only garbage does not read as one that found nothing, and a `{kind, reason}` record per drop — `bad_quote` and `missing_field` for an item the model proposed, `not_a_list`, `item_not_a_dict` and `payload_not_a_dict` for a shape that was never a usable item. Every proposed item is either stored or dropped, so `proposed == stored + item drops` is the arithmetic that says whether anything was lost silently. The tool payload is not schema-checked anywhere, so a malformed shape is counted as a drop rather than raised — it used to abort the whole pass, discarding the other two kinds with it and suppressing the row, which read exactly like \"extraction never ran\". Without it, \"the model found nothing\" and \"the model found things and every one was rejected\" are indistinguishable from outside the database — which is why the failure above survived undetected and took a SQLite session on the tenant to find. A `proposed>0, stored=0` streak is the signal to watch.\n\nThe validator rejects a paraphrase, and the model paraphrases: on one install two of three real commitments were lost that way, the quote beginning \"SVN's engagement covers only …\" where the person had typed something else. So a `bad_quote` drop earns exactly one corrective call. The model is shown the rejected items and the quotes it gave, told to copy the span character-for-character (typos and casing included) or return empty arrays, and the tool is forced where the provider supports tool choice. Every retry item is validated first; a still-invalid one adds no second drop and is counted `still_invalid`. A valid item is then classified in order: its label matches a pending drop record → a recovery, stored and the record released; else its quote (terminal punctuation ignored) already supports a stored item of that kind → a re-send, ignored and counted `repeated`, so a model that re-sends everything cannot double-count `stored`; else a new proposal, stored and counted — a reworded label cannot be told from a different item, and crediting it would erase the very `bad_quote` census the row exists to show, so its original drop stands. Recovery is checked before re-send because two commitments can rest on one sentence. Malformed shapes at any level — a kind that is not a list, an item or payload that is not a dict, a response with no tool call — are counted `malformed`, so a retry that returned garbage does not read like one that obediently returned nothing. The row's `retry` block (`rejected`, `recovered`, `repeated`, `still_invalid`, `malformed`, `failure`) is always present, zeros when nothing was rejected; `rejected` is set from the complete drop list when the row is written, so neither a store failure before the retry nor a cancellation during it can zero it. The arithmetic above still holds after the retry. An exception on the retry is recorded as the retry's own `failure` and leaves the first pass's results untouched; the cost is one utility-model call, only on turns that dropped something. `memory_extraction` is a declared event type, so the audit page's filter can select it.\n\n### Standing facts (corrections that persist everywhere)\n\nA fifth table, `facts` (`openexecutive.memory.facts`, created on first write), holds facts and corrections the principal stated and asked to keep — \"Maple House is 48 units, not 52\". Before it, a chat correction's only durable home was Honcho peer memory: optional, best-effort (its prefetch times out or errors under load), re-injected only into that person's later chat turns, and never read by the briefs, the scheduled runs or the alert review. The episodic extractor cannot hold one either: it stores only decisions backed by a commitment quote, and a fact is not a commitment.\n\n- **Written from chat, by the principal or an attributed teammate.** `remember_fact` stores one (subject, statement, optional wrong value) and `forget_fact` retires one. The principal on a verified surface may do both. A teammate on the People list (a `team` row, not archived, not a contact) on a verified surface (the web app signed in, their own Slack or Discord; `fact_tools._teammate_speaker`) may call `remember_fact` only; email, Google Chat and unrostered senders are refused. Both tools are withheld from every unattended run and every turn private to the principal. Every call, `forget_fact` included (retiring a fact changes what later prompts treat as true just as writing one does), also needs `source_quote`: at least two words and eight characters, found in what the speaker typed this turn (`delegation.settings.own_words` over the pinned `TurnDelegation.speaker_text`). The `<outbound_reply_context>` backstory a Slack or Discord reply is hydrated with is stripped first, and a message with an attachment is refused outright. The quote alone only proves the principal asked, so everything `remember_fact` stores and renders (the statement, the subject shown as `[fact N] subject:`, and a previous value shown as `(corrects: …)`) is tied to their words too. An omitted previous value falls back to the replaced fact's own statement. Every figure must be a number they wrote, compared at its magnitude: `$180k` matches `180,000`, but `180m` never lets `$180k` through. Every name must also appear in what they typed: a capitalised word, or any word holding a non-ASCII letter, other than the statement's very first word (a statement is one fact, so splitting a document's names into one-word sentences exempts nothing). So must every month, weekday or quarter. A name the model writes in lower case is not caught: the gate narrows what a real quote can carry in; it does not prove a paraphrase. A real quote therefore cannot carry a document's figure, name or date in with it (\"Cedar Court's lease expires in March\" after \"remember what the lease doc says\"), while a paraphrase of what they said still passes. So the model cannot store its own inference, a document's figure or text quoted back at the principal as something they said. Every audit row the tools write, and the chat loop's `skill:` dispatch row for them (whose input quotes the principal verbatim), is private to the principal (`executive._private_tool_row`). Those rows tie a fact to the principal's session and turn, which `GET /memories/facts` hides from teammates, and a teammate can read any non-private audit row. The handlers run in a worker thread (`asyncio.to_thread`, which carries the turn's context), and the chat and committee paths, the alert review, the morning brief's synthesis and the end-of-day, weekly-review and reflection workflows read the block the same way, so SQLite, the profile file and its lock never block the event loop the SSE streams share. The principal's own email may ask too: the change is checked the same way, then held until they confirm it by replying to a one-time token sent to their own address (see Integrations → Standing facts by email).\n- **Provenance and attribution.** Each row keeps the quote, the channel (`web` or the adapter), `session_id`, `turn_id`, the recording person and the time, plus `recorded_by_role` (`principal` or `teammate`) and, for a teammate, `recorded_by_name` as the People list had it. Rows written before these columns existed read as the principal's (`_migrate` adds the columns on the first write; the read-only render tolerates a DB that has none).\n- **One active fact per subject.** A new row supersedes any active row with the same folded subject key, or the id named in `replaces_fact_id`, in one transaction. The old row stays as `superseded` (with `superseded_by`), and the new one is stored as a `correction` carrying what it replaced. Retiring sets `retired` with a reason. **The principal outranks a teammate:** a teammate's write that would replace an active fact the principal set (by subject or `replaces_fact_id`) raises `PrincipalFactConflict`, and the tool stores it as `proposed` instead, naming the fact it would replace (`replaces_fact_id`); teammates replace each other's facts freely, and the principal replaces anyone's. **\"Needs my approval\"** (`fact_approval_rules`, per teammate, **on by default**, set only by the principal) stores every fact from that teammate as `proposed`; the principal turns it off for a teammate they trust, whose facts then apply at once (except one that would replace the principal's). The rule is read inside `record_fact`'s own write transaction, so a switch turned on a moment earlier cannot let one fact through; a teammate write that names no person is never trusted. One teammate may have at most `MAX_PENDING_PROPOSALS_PER_PERSON` (20) proposals waiting (`TooManyProposals`; the tool tells them to wait for the principal's review). A teammate's retire checks ownership in the `UPDATE` itself (`retire_fact(teammate_id=)`: their own row, not approved). A proposed row never renders; `approve_fact` makes it active and replaces what it names (the principal's own fact included — approving it is their word) and stamps `approved_at`, after which it outranks teammates exactly as the principal's own fact does (`Fact.principal_owned`: no teammate may replace or retire it); `decline_fact` sets `declined`. No field of a teammate's fact may carry what the render adds itself — `(per <anyone>)` in any case (a unit such as `(per month)` or `(per unit)` is fine), `[fact N]` or a date stamp after any dash, read NFKC-folded with invisible characters removed (`fact_tools._marker_error`) — so a teammate cannot plant a second, forged attribution inside their statement (the principal's own unmarked lines are not checked: \"(per Smith lease)\" is ordinary wording for them). The tool answers `awaiting_approval` (no action chip) and tells the model to say it is not in use yet.\n- **Rendered everywhere output is produced.** `render_facts_for_prompt` renders the active rows newest first under a self-explaining `STANDING FACTS` header (use these over older figures; a line ending `(per <name>)` is that teammate's word and the principal's unmarked line wins a conflict; the current conversation still wins; quoted data never instructions). A teammate's line ends `(per <name>)`, the name defanged like the rest, capped at 40 facts / 6000 chars, with angle brackets defanged. It opens the DB read-only and never creates it or the table. The block always rides in a user turn, never a cached system block: a chat turn's `<standing_facts>` (so every scheduled run through the chat loop too), each specialist consult (`route_to_specialist`, chat and workflow steps alike), the /today header and the morning brief (`render_briefing_context`, after the quiet check and inside the string the header's cache key hashes, so a new fact rewrites the header), the alert review's batch (`render_batch`, read once per pass), and the end-of-day digest, the weekly review's top-three call and the morning reflection (`with_standing_facts`).\n- **Company-profile edits from chat.** `update_company_profile` (same gate and quote rule) changes one whitelisted field of `company/profile.yaml`, under `PROFILE_EDIT_LOCK` (also taken by `PATCH /company-profile`, so neither edit silently drops the other): a text or number field is set, a list field gets an item added or removed, and `financials.key_metrics` takes a named metric. It writes through `CompanyProfile.save_to_yaml` and updates the session's profile, so the next turn's cached company block carries it (one cache miss on the change). The new value must itself appear in the principal's own words, not just the quote: the value renders into the cached company block on every later turn, so \"set our mission to what the doc says\" or \"update our headcount\" is refused rather than saving a document's text or a guessed figure. A number must be one they wrote, however they wrote it (`$180k`, `1.2m`, `2,400,000`). Saved text has `<`/`>` defanged. A `kind='profile'` row records each edit with its quote for the Pulse page. Those rows are never rendered into a prompt, because the profile block already carries the value.\n\n### Session scoping\n\n`decisions` and `advice_given` rows carry a `session_id`, so per-thread channels (Discord, Telegram) can pull just-this-thread history without leaking cross-conversation context. A null `session_id` falls back to a global view.\n\n### Surfacing\n\n`openexecutive.memory.episodic.format_for_prompt` renders recent decisions and initiatives into a compact `<past_decisions>` block injected into the user turn — alongside `<retrieved_context>` and peer memory — never into a cached system block. Each decision names where it was recorded when that was a channel — `- 2026-09-01 [finance] (via email): …`, from the prefix of its `session_id` (`email:`, `slack:`, `discord:`, `telegram:`, `google_chat:`); a web or CLI decision has no tag. Rows extracted from mail before the untrusted-content policy, when any sender's body could be stored, therefore read as mail rather than as the principal's own word.\n\nScoped to a session, decisions and advice cover every conversation of a chat app's stream (`memory.conversation_ids.family_clause`): a Telegram chat or a DM is cut into conversations after two quiet hours or a /new (`memory.conversations`), and what an earlier conversation decided still renders in the next.\n\nThe chat route also injects a `<briefing>` block into the same user turn: a compact digest of the current open (unread) alerts, built by `openexecutive.briefing.context.format_open_alerts_for_prompt` (company-wide, `status=\"unread\"`, mirroring `/today`). This is what lets the Executive discuss a briefing item the principal clicked or named on `/today` (e.g. \"Gulf Coast Port Cyberattack\"). It is resolved in parallel with the other context fetches, omitted when there are no open alerts, and never placed in a cached system block.\n\nOn the Pulse page the Memory section shows the three lists as Decisions, Initiatives and Advice tabs, then a **Corrections** tab (`GET /memories/facts`: active standing facts and profile edits with their quote, channel and — for a teammate's — their name; proposals first under \"Waiting for your approval\" with **Approve** / **Decline** for the principal; the replaced, retired and declined history folded away; **Retire** on any fact for the principal and on their own not-yet-approved one for a teammate; and, for the principal, a per-teammate \"needs my approval\" switch), and a **History** tab for the person's own Always in the loop notes (see below). The header's Memories tile counts the three lists. What peer memory has learned about the signed-in person is theirs alone, so it is not on Pulse: it is on **Settings → About you** (see the peer memory section).\n\nThe same user turn carries a `<drive_memory>` block when the conversation has touched Google Drive (`openexecutive.memory.drive_reads`). Drive is reached only as live Google Workspace calls inside a turn and history keeps only prose, so without it a file found one turn was gone the next. `MCPGateway.call_tool` hands each `search_drive_files` and `get_drive_file_content` result to `record_drive_result`, which keeps, per session, every file found or opened (file id, name, type, link, and for an opened file its first 600 characters) and every search that matched nothing, with its query. `format_drive_memory` lists the 20 most recent files, so \"the file you found earlier\" resolves to a file id the Executive reopens rather than searching again, and the queries that found nothing (dropped once the same query later finds something). Rows are keyed on the session *and* the speaker, and shown only to that speaker in that session, because one session can span several people (an email thread, a Slack or Discord thread). Nothing is recorded or shown without a bound `current_session` and a rostered speaker, on a turn private to the principal, or on one that touched the speaker's own mailbox (Act as me). workspace-mcp writes file names into its output unescaped, so a name containing a newline can forge a result line. Only a Drive-shaped file id, type and `docs`/`drive.google.com` link are therefore kept; any other line is dropped, and the name is always quoted as the file's own content, not instructions. Each speaker keeps at most 100 files and 100 searches per session, older rows are pruned on write, and `session_store.delete_session` drops them all.\n\nA conversation can also become its owner's alone. When Act as me first reads the speaker's own mailbox in it, `session_store.mark_mail_private` sets `sessions.mail_private` (creating the row with its owner when a channel adapter hasn't written it yet), and from then on only the session's owner may open, continue or delete it — the principal included, when it is a team member's (`chat._session_access`). It is never cleared. Beside it `sessions.mail_read_at` keeps how many history messages the conversation held before the last turn that read the mail (`session_store.mail_read_at`; NULL on rows marked before the column): Act as me's hold on links and scripts in later turns lasts only while that turn is still in the history window (see Act as me). A search that matched nothing also gains a note in its tool result: say the exact query and that it found nothing, never that the file does not exist. This is a first step: Drive is still not indexed into the company collection.\n\n### System of record\n\nSQL is the system of record; the peer-memory service is a recall layer mirrored from it, not a replacement. When `store_decision` / `store_initiative` / `store_advice` insert a row whose `department` is non-empty and not `\"general\"`, the row is mirrored as a kind-tagged note into that department's peer via `append_department_note`. The mirror fires only after a successful INSERT, is fire-and-forget, and never rolls back the SQL row on peer-memory failure. `scheduled_actions` is never mirrored — it is a queue, not memory.\n\nThe episodic extractor still learns only from the principal's own words. Commitments and asks from everyone else on the roster are tracked as **open loops** (see Attunement) — `scheduled_actions` rows with `kind='open_loop'`, opened and closed by a separate quote-gated pass after each attributed turn. That pass depends on `chat_messages.sender_person_id`, which records who actually wrote each persisted user message. An open loop counts toward `list_awaiting_replies_by_person` only once it is due, and `list_scheduled_actions(exclude_internal=True)` filters `__internal__` rows in SQL so readers that want real sends are not starved by them. `mark_outbound_context_consumed` also resolves the Attunement outcome row for that DM as `replied` — a matched reply is the clearest sign proactive outreach landed — and a real change to an existing initiative (`store_initiative` / `update_initiative`, new status or summary) marks the updater's own check-in nudges `acted` — an update with no known updater, such as `PATCH /memories/initiatives/{id}`, credits nobody.\n\n### Workspace settings\n\nThe same database holds one row of settings that are not memory: `workspace_settings` (`openexecutive.memory.workspace_settings`) — the install's mode (`team` by default, or `solo` for one person using Open Executive just for themselves), the user's IANA time zone, the principal's role (`PrincipalRole`: `role_kind`, `role_title`, `reports_to`, `remit`, `measured_on`, all nullable; only solo mode reads it), and the company's own email domains (`company_domains`, a JSON list, or NULL to derive them from the principal's primary address — `people.identity` matches a teammate by local part on them; `validate_company_domains` lowercases, dedupes and sorts, allows at most 10 plain DNS names and refuses a free-mail provider's, and a stored value that no longer validates reads as NULL). It is a table of its own rather than a company-profile field because onboarding rebuilds the profile from scratch. Every read is fresh and read-only (a missing file or table reads as the defaults; a table from before the role or `company_domains` columns reads them as unset and is migrated additively by the next init or write). A read error (a locked database, say) also reads as the defaults, so `get_workspace` then says team; `read_stored_mode` is the strict read of the mode alone — None when the row cannot be read or holds no valid mode — for the scheduler's weekly-review check, which must not take a failed read for team. A session may carry an explicit `workspace_mode` override; otherwise the mode is read fresh at the start of each turn and pinned on the session for that turn only (`Session.turn_workspace_mode`, via `pin_turn_workspace_mode`), so every tool handler in the turn sees the mode its persona and tools were built in. `effective_workspace_mode` reads override, then the pin, then the setting; `effective_principal_role` reads a session's `principal_role` override, then the role pinned for the turn (`Session.turn_principal_role`, via `pin_turn_principal_role`), then the stored role. See Org for what solo changes and Scheduler for the time zone.\n\n### Act as me\n\n`initialize_db` also creates Act as me's per-person tables (`delegation.schema.ensure_schema`): `delegation_settings`, `delegation_voice` and `delegation_voice_history`. They hold a setting and a writing profile rather than memory, and nothing in them is mirrored to peer memory. A turn that touched the speaker's own mailbox teaches no memory: the episodic, open-loop and working-style passes are skipped along with the Honcho peer and department syncs, since its reply quotes a draft built from other people's mail. See **Act as Me (Delegation)**.\n\n### Always in the loop (notes of what you said)\n\nA person can keep private, dated notes of what they said, in chat with the Executive and in email replies it drafted for them: what they promised, agreed, declined, answered, asked for or shared. The switch is per person (\"Keep track of what happens\", `history_person_settings.reply_notes`, off by default, one switch for every channel). Any team member on the People list may turn it on (`history.can_keep_notes`: kind `team`, not archived, the principal included); Act as me isn't needed, though notes from email replies only come through it.\n\n- **Where notes come from: chat.** After each chat turn, on both the single-voice and the committee path, the Executive's post-turn block calls `memory.history_chat.schedule_chat_notes` next to the open-loop and style passes, except on a turn that touched the speaker's mailbox. It reads only what the speaker typed this turn (`delegation.settings.own_words`: no backstory an adapter added, nothing when a file came with it), never the reply and never anyone else's message: every channel calls the Executive with the one speaker's message, and what other people say to each other is never read. It runs only for a speaker the turn verified (`history_chat.verified_speaker`): the turn's `caller_person_id` is them, nobody started it by email or runs it unattended or for them, and the surface proved who they are (the web chat signed in or a local install, the principal or a team member on their own Slack or Discord, a private Telegram chat behind a valid webhook secret, or a channel whose adapter verified the sender itself and set `Session.speaker_verified`). A shared Slack or Discord thread counts: the notes stay private and are read back only where nobody else can see them. A message under 40 characters is skipped, and each person gets at most 40 passes a day, counted in `history_chat_passes` so the cap holds across workers and restarts. The pass uses a constant `CHAT_PROMPT` (requests to the assistant, questions and small talk are not notes), the same `record_notes` tool and the same `check_note` gate with the message as both body and allowed words; the note's channel is the inbound channel or `web`, its conversation the session id, and it names no counterpart.\n- **Where notes come from: email.** After `delegation.reply_send` sends a reply, it starts `memory.history_notes.note_sent_reply` in the background. The note-taker reads only the words the person sent (`email_poller.sender_new_text` strips quoted mail) and the recipients' names, cut to four words of name characters (`history_notes.short_name`): never the mail being answered, nor the subject, which others in the thread write too, so nothing another person wrote can become a note. One forced `record_notes` call with a constant prompt and no other tools returns at most three notes. Code then drops any note that says more than they did: the `quote` must appear word for word in what they sent, every figure in the summary must be in the quote, every name or date word must be in what they sent or the recipients' names, at least half its other content words must be theirs, the summary carries no link or address, and a `due_date` is kept only for something promised or agreed. Notes record events, never instructions, and carry `trust = high` because they rest on the person's own words.\n- **Whose they are.** Every note is private to its person (`visibility = private`). Nobody else reads it, the principal included; there is no shared note.\n- **How long they last.** The company default is 90 days (`history_settings.retention_days`, the principal's choice of 30, 90, 365 or until forgotten). A person may only choose a shorter time; shortening the company time clamps everyone's choice and re-dates live notes. A pinned note never expires; unpinning restarts its clock, and a later retention change counts from there. Reads skip expired notes and the scheduler's alert sweep deletes them (`history.sweep_expired`).\n- **What a person controls.** Through `/memories/history` they read, search, pin, correct and forget their own notes. On the Pulse page this is the **History** tab, last in the Memory section and shown only to someone with notes to see (signed in and on the People list): each note shows its kind, who it was with, the date, the person's own words, any due date and when it will be forgotten, and its menu holds **Correct** (a side panel; \"Use the original\" clears a correction), **Pin**, **Don't remember this** and **Forget**. \"Don't remember this\" forgets every note from that conversation and adds it to `history_excluded`, so it is never noted again. Settings → **Memory** holds the switch (\"Keep track of what happens\") and a shorter time for their own notes, and the company time, which the principal changes and everyone else reads. A chat note shows the channel alone (\"Slack\", \"Web chat\").\n- **Recall.** `recall_history` (`orchestrator.history_tools`) is offered only on a turn where the speaker may read their notes: verified as above, a team member who may keep notes, in a conversation private to them (`history_chat.private_chat`: the web chat, a Slack or Discord DM, a Telegram chat, or one its adapter marked `Session.private_chat`), with their switch on. Before any note is read the turn is set `touched_mail`, for the principal too, so its rows are private to the speaker, it teaches no memory and the mail lockdown holds from that round on. The conversation is also marked theirs alone (`session_store.mark_mail_private`), so every later turn in it is private the same way (the lockdown is that turn's alone) and, for a team member, the principal can't open it; recall refuses if that can't be stored. Notes come back in a `<history_notes>` block as history to cite: the date, the person's own words first, then how they were noted. With `due: true` it lists only notes with a due date, from a week overdue to two weeks ahead, soonest first (\"what's due today?\").\n- **In the owner's briefs.** The morning brief adds a FROM YOUR NOTES — DUE SOON block (`memory.history_brief.due_soon_block`: what the owner promised, agreed or asked of someone, from a week overdue to a week ahead, in the workspace's local dates) and the end-of-day digest a FROM YOUR NOTES — TODAY block (`noted_today_block`: what they promised, agreed, asked or declined since the last digest, then what is due tomorrow). Both only on the scheduler's delivery to the owner alone (`morning_brief.PRINCIPAL_DELIVERY`), never a run started from chat, whose tool result lands in the turn's shared audit row and peer memory; only when the owner may keep notes and has the switch on (`history_brief.owner_keeping_notes`), and only the owner's own notes. A run that used any is marked `private_to_principal`, so the shared run history keeps `PRIVATE_RUN_ARTIFACT` instead of its text, and the note ids with their state (overdue, today, soon) enter the brief's fingerprint, so one falling due un-suppresses an unchanged brief. Teammates get no brief, so their notes reach them only through recall and reminders.\n- **In Act as me drafts.** The ghostwriter gets a `<writer_noted>` block (`memory.history_drafts.notes_for_draft`): the writer's own notes from earlier Act as me replies that every recipient of the new draft was on, with their switch on. It keeps the draft consistent with them and turns a contradiction into an open question on the card; it never adds anything from them (see Act as me).\n- **Due-today reminders.** `memory.history_reminders.maybe_remind`, called from the scheduler tick every 15 minutes between 09:00 and 18:00 local time, sends each person with the switch on one message on a day something they promised or agreed to by email (`source = approved_reply`) falls due. Chat promises are left to open loops, which the nudge engine already chases. The message says only how many things are due, never what or to whom, and the channel senders' audit rows for it are private to the person (`audit.context.rows_for_person`; the owner's `private_rows`), which also keeps the send off the shared activity rail (`_record_send_to_activity` skips a send whose rows are private). The person asks \"what's due today?\" in a private conversation and `recall_history` answers. It goes to their own Slack or Discord DM, a private Telegram chat (`delivery_order` skips a negative group id, for the owner's briefs too) or their own email (`scheduler.runner.deliver_to_person`), never a shared channel. `history_reminders` holds one row per person per day, claimed before sending and never released, so two workers never both send and a half-failed send is never repeated; a failed one waits for the next due day.\n- **Not peer memory.** Notes never reach Honcho, episodic extraction, standing facts or another person's turn. The tables (`history_notes`, `history_settings`, `history_person_settings`, `history_excluded`, `history_chat_passes`, `history_reminders`, created by `history_schema.ensure_schema` from `initialize_db`) swap with a client slot and are cleared by a factory reset.\n\n## Decision ledger\n\n`openexecutive.memory.decision_ledger` keeps one `decision_instances` row per gated action — a meeting the Executive proposes to book, an Act as me reply card — with how it was resolved, so each class has a reliability record. Every status change is a compare-and-set. A tap with an outside effect (sending an email) claims the row first (`claim_for_execution`, proposed → executing), so of two taps only one acts, and finishes it as `approved_unchanged`, `approved_with_edit` or `failed`, or hands it back (`release_claim`). A row whose class acted on its own with nobody tapping — `gate_mode` `auto_execute`, as Act as me's **Handle it for me** replies are — finishes as `executed` instead, with no resolver, so a reliability read never counts it as an approval. A send whose result is unclear stays `executing` for a reconciler and is never retried. A row still waiting can have its payload changed only by compare-and-set (`update_open_payload`, on `proposed` and, when given, on the payload as it was read): that is how an Act as me reply card takes the person's edit, or records the draft made for it at Send.","mermaid": "flowchart TD\n Store[\"store_decision / store_initiative / store_advice\"]\n DB[\"episodic_memory.db<br/>decisions / initiatives<br/>advice_given / scheduled_actions\"]\n Fmt[\"format_for_prompt\"]\n Turn[\"User turn<br/>past_decisions block\"]\n Mirror[\"append_department_note\"]\n Peer[\"Department peer<br/>(Honcho)\"]\n Store --> DB\n DB --> Fmt\n Fmt --> Turn\n Store -->|\"dept set & not general\"| Mirror\n Mirror -->|\"fire-and-forget\"| Peer\n Tool[\"remember_fact / update_company_profile<br/>(principal, verified, quoted)\"]\n Facts[\"facts table<br/>active / superseded / retired\"]\n Every[\"STANDING FACTS block<br/>chat, specialists, briefs,<br/>alert review, workflows\"]\n Tool --> Facts\n Facts -->|\"render_facts_for_prompt\"| Every\n class Store entry\n class DB storage\n class Fmt compute\n class Turn hot\n class Peer external\n\n class Tool entry\n class Facts storage\n class Every hot",- "generated_at": "2026-10-09T18:00:00Z"+ "generated_at": "2026-10-10T16:30:36Z"}diff --git a/packages/core/openexecutive/architecture/prebuilt/schemas.json b/packages/core/openexecutive/architecture/prebuilt/schemas.jsonindex 914ccae8..7b7bbee3 100644--- a/packages/core/openexecutive/architecture/prebuilt/schemas.json+++ b/packages/core/openexecutive/architecture/prebuilt/schemas.json@@ -1,7 +1,7 @@{"section_id": "schemas","title": "Data Schemas",- "markdown": "The shapes below are the load-bearing data structures: episodic SQLite tables (in `episodic_memory.db`) and the Pydantic models for departments and people.\n\n### Episodic tables\n\n| Table | Key columns |\n|---|---|\n| `decisions` | `id`, `timestamp`, `domain`, `summary`, `rationale`, `outcome`, `tags`, `department`, `session_id` |\n| `initiatives` | `id`, `title`, `status`, `created_at`, `updated_at`, `summary`, `department` |\n| `advice_given` | `id`, `timestamp`, `domain`, `query_summary`, `advice_summary`, `department`, `session_id` |\n| `facts` | `id`, `kind` (fact / correction / profile), `subject`, `subject_key`, `statement`, `previous_statement`, `source_quote`, `source_channel`, `session_id`, `turn_id`, `recorded_by_person_id`, `created_at`, `status` (active / superseded / retired), `superseded_by`, `retired_at`, `retired_reason` |\n| `scheduled_actions` | `id`, `created_at`, `run_at`, `channel`, `channel_ref`, `intent_text`, `status`, `attempts`, `kind`, `department`, `assigned_to_person_id`, `awaiting_response_since`, `scope_key`, `required_scope` |\n| `outbound_context` | `id`, `created_at`, `channel`, `channel_ref`, `recipient_person_id`, `outbound_text`, `originating_session_id`, `outbound_message_id`, `consumed_at`, `status` |\n| `history_reminders` | (`person_id`, `day`) PK, `sent_at` — the days a person was reminded of notes due (`memory.history_reminders`), older days pruned on write |\n| `session_drive_files` | (`session_id`, `person_id`, `file_id`) PK, `name`, `mime_type`, `link`, `summary` (first 600 chars of an opened file), `opened`, `found_by` (the search query), `first_seen_at`, `last_seen_at` — Drive files a conversation found or opened (`memory.drive_reads`) |\n| `session_drive_searches` | `id`, `session_id`, `person_id`, `query`, `result_count`, `searched_at` — every Drive search a conversation ran |\n| `saved_tools` | `name` (PK), `description`, `enabled`, `current_version`, `workflow_version` (the version workflows may run, NULL until the owner turns it on; never set for a Python tool), `kind` (`script` for `run_script`, `python` for a kept `run_python_job`; added with default `script`), `created_at`, `updated_at` — scripts and Python jobs the Executive saved to run again (`workflows.saved_tools`) |\n| `saved_tool_versions` | (`name`, `version`) PK, `description`, `script`, `tools` (JSON: the tools the script called when saved), `origin` (`chat` or `workflow:<name>/<step>`), `created_at` |\n| `saved_tool_runs` | `id`, `name`, `version`, `ok`, `calls`, `duration_ms`, `origin`, `at` — the newest 200 runs per tool |\n| `chat_messages` | `id`, `session_id`, `role`, `content`, `created_at`, `action_chips`, `stopped`, `sender_person_id`, `feedback`, `feedback_note`, `feedback_by_person_id`, `sources` (JSON `{sources: [{kind, title, url}], unavailable: [area]}` — what an assistant reply looked at and which areas it left out; NULL on older rows) |\n| `attunement_usage` | `day` (PK, UTC date), `calls` — the per-day ceiling on open-loop extraction model calls |\n| `attunement_profiles` | `person_id` (PK), `rules` (JSON: up to 4 `{text, basis, evidence}`), `locked`, `updated_at`, `updated_by`, `last_pass_at`, `pass_day`, `passes_today`, `last_message_id` — per-person working style plus pass pacing |\n| `attunement_profile_history` | `id`, `person_id`, `created_at`, `rules`, `locked`, `updated_by` — every change to a working style |\n| `proactive_outcomes` | `id`, `created_at`, `person_id`, `source`, `ref`, `channel`, `channel_ref`, `outbound_context_id`, `outcome` (`replied` / `acted` / `ignored` / `void`, NULL while open), `resolved_at` — one row per proactive DM (Attunement outcome ledger) |\n| `delegation_settings` | `person_id` (PK), `enabled` (default 0), `updated_at`, `updated_by` — Act as me, per person; no row means off |\n| `history_notes` | `id`, `person_id`, `visibility` (`private`), `source` (`approved_reply`), `channel` (`email`), `conversation_key` (a hash of the channel and thread, never the thread id), `counterpart`, `subject`, `kind` (`promised` / `agreed` / `declined` / `answered` / `asked` / `shared`), `summary`, `quote` (the person's own words), `due_date`, `trust`, `occurred_at`, `created_at`, `expires_at` (NULL: until forgotten), `pinned`, `correction`, `corrected_at`, `kept_from` (when the retention clock started: NULL means `occurred_at`; an unpin restarts it) — Always in the loop, one row per note |\n| `history_settings` | `id` (1), `retention_days` (NULL: until forgotten; no row means 90), `updated_at`, `updated_by` — the company retention |\n| `history_person_settings` | `person_id` (PK), `reply_notes` (default 0), `retention_days` (NULL: the company's), `updated_at`, `updated_by` |\n| `history_excluded` | `person_id`, `conversation_key` (PK together), `created_at` — conversations a person asked not to remember |\n| `history_chat_passes` | `person_id`, `day` (PK together, UTC `YYYY-MM-DD`), `passes` — note passes run on a person's chat messages that day, against the daily cap; older days pruned on write |\n| `delegation_voice` | `person_id` (PK), `profile` (JSON: `greetings` per audience, `sign_off`, `signature`, `length`, `formality`, up to 8 `habits`, up to 6 `avoid`, up to 3 `exemplars`), `locked`, `learned_at`, `sample_count`, `updated_at`, `updated_by` — \"How I write\" |\n| `delegation_voice_history` | `id`, `person_id`, `created_at`, `profile`, `locked`, `updated_by` — every change to a writing profile |\n| `delegation_drafts` | `id`, `person_id`, `source` (`chat` \\| `inbox`), `thread_id`, `draft_id`, `message_id`, `sent_message_id`, `created_at` — one row of ids per draft Act as me saved in someone's Gmail (no address, subject or text): the daily limit counts it, and \"How I write\" skips a chat draft's thread and a sent draft's message |\n| `delegation_inbox_watch` | `person_id` (PK), `enabled`, `watch_since` (reset on every off→on), `last_poll_at`, `status`, `backoff_until`, `failures`, `updated_at`, `updated_by` — **Draft replies to my inbox**, per person; no row means off |\n| `delegation_inbox_messages` | `id`, `person_id`, `message_id`, `thread_id`, `received_at`, `sender_key` (a hash of the address, never the address), `relation`, `outcome` (`processing`, `retry` — left for a later scan, `skipped`, `not_needed`, `deferred`, `failed`, `drafted`, `sent`, `dismissed`, `closed`, `expired`), `reason`, `classified`, `attempts`, `draft_id`, `decision_id`, `flags` (JSON), `created_at`, `updated_at`; `UNIQUE(person_id, message_id)` — the inbox watcher's cursor: what happened to each message it looked at |\n| `delegation_handle_it` | `person_id` (PK), `enabled`, `mode` (`careful`, `balanced` or `bold`), `levels` (the per-kind setting `mode` replaced, kept for older rows), `updated_at`, `updated_by` — **Handle it for me**, per person; no row means off. A `training` mode from before per-setting training moves to `balanced` with Replies and Follow-ups in training |\n| `delegation_training` | `person_id`, `setting` (`replies`, `follow_ups`, `actions` or `drafts`), `enabled`, `updated_at`, `updated_by`; primary key `(person_id, setting)` — Act as me settings in training, per person; no row means not in training |\n| `delegation_handled` | `id`, `person_id`, `thread_id`, `decision_id`, `sent_message_id`, `sent_at`; index on `(person_id, sent_at)` — one row per reply or follow-up Handle it for me sent on its own, read for its one-per-thread-a-day and daily limits |\n\n| `dynamic_workflows` | `name` (PK), `definition` (JSON of `DynamicWorkflowDef`), `is_active`, `created_at`, `updated_at`, `owner_person_id` (creator; set on insert only, kept out of the definition JSON) |\n| `workflow_approved_targets` | (`workflow_name`, `value`) PK, `key`, `approved_at`, `run_id` — targets a workflow's tool steps may write to without asking again; cleared when the workflow is deleted |\n| `executive_control` | `id` (PK, always 1), `paused`, `paused_at`, `paused_by`, `reason`, `updated_at` — the operator pause switch (`scheduler.pause`); operator-level, so client-slot switches carry it across |\n| `app_migrations` | `name` (PK), `applied_at` — one-shot data migrations (sweeps that must run exactly once per DB); schema DDL stays idempotent and is not recorded here |\n\n`department` and `session_id` are additive columns (default `''`); `session_id` scopes per-thread recall. `scheduled_actions.status` ∈ pending / running / done / failed / cancelled, and `scheduled_actions.kind` includes `dynamic_workflow` (a cadence-fired user-created workflow run) and `open_loop` (an Attunement open loop: `assigned_to_person_id` is the owner, `awaiting_response_since` the due time — cleared when the loop closes — and `scope_key` `loop:{owner}:{hash}`, unique among open loops via the partial index `idx_scheduled_open_loop_scope`). `chat_messages.sender_person_id` is the resolved rostered sender of a user message (never the session owner's principal fallback; NULL on legacy rows and for unrostered senders); `feedback` is `up` / `down` on an assistant reply. `dynamic_workflows` stores user-created (dynamic) workflow definitions interpreted by the generic `DynamicWorkflow` engine; the JSON `definition` holds free-text input fields and an ordered step list (specialist / approval_gate / synthesis) plus an optional cadence.\n\n### Legacy tables (talent / staff onboarding)\n\nThe talent (executive-search) and staff-onboarding features were removed. Their tables —\n`engagements`, `candidates`, `offers`, `onboarding_templates`, `onboarding_plans`,\n`onboarding_tasks` — are **not dropped**: no code creates, reads or writes them any more,\nbut rows survive on upgraded installs. `clients.slots` still wipes them when a blank client\nslot is activated (existence-guarded, a no-op on fresh installs) so a slot can never inherit\na previous client's candidate data.\n\n### Department / Goal / ChecklistItem\n\n| Model | Fields |\n|---|---|\n| `DepartmentConfig` | `slug`, `title`, `specialist_key`, `charter`, `authority_level`, `head_person_id`, `head_persona_slug`, `cadences`, `slack_channel_id`, `discord_channel_id`, `telegram_chat_id` |\n| `Goal` | `id`, `department_slug`, `period_type`, `period_value`, `key_result`, `target`, `current`, `status`, `created_at`, `updated_at`, `last_reviewed_at` |\n| `DepartmentState` | `config`, `goals`, `headcount`, `budget_usd`, `member_person_ids`, `updated_at` |\n\n`authority_level` ∈ `auto_execute` / `propose_only` / `escalate`; `Goal.status` ∈ `on_track` / `at_risk` / `off_track`.\n\n### Person\n\n| Field group | Fields |\n|---|---|\n| Identity | `id`, `full_name`, `role`, `is_principal`, `kind`, `department_slugs` |\n| Contact | `email`, `email_aliases`, `slack_user_id`, `telegram_chat_id`, `discord_user_id`, `preferred_channel` |\n| Routing | `availability`, `authority_scope`, `response_sla_hours`, `on_leave_until`, `reports_to_person_id` |\n| Lifecycle | `archived`, `created_at`, `updated_at` |\n\nExactly one `Person` should have `is_principal=True` — the fallback approver when no delegated person matches.\n\n`kind` is `team` (the default) or `contact` — someone outside the team, such as a client or contractor. It is an additive column, `kind TEXT NOT NULL DEFAULT 'team'`, added by the same `PRAGMA table_info`-guarded migration as `discord_user_id`, so every existing row is a team member. The principal is always `team`: the store refuses to write a principal contact (`PrincipalContactError`), and `initialize_db` repairs a hand-edited one on boot. A stored value the code does not know reads as `contact`. Every roster read in `people.store` and `people.registry` returns team members only unless it passes `include_contacts=True` (see Org).\n\n`email` is the one address a person signs in with; `email_aliases` (read from the `person_emails` table, up to 10) are other addresses they write from — they match inbound mail and may be emailed, but never sign in (see Org).\n\n### People-side tables\n\nThese live next to `people` (created by `people.store.initialize_db`, which also runs `people.roster_requests.initialize_tables`):\n\n| Table | Key columns |\n|---|---|\n| `person_emails` | `id`, `person_id` (FK → `people`, `ON DELETE CASCADE`), `email`, `email_norm` (trimmed + lowercased, **UNIQUE** across the roster), `source` (`manual` / `chat_tool` / `roster_request`), `roster_request_id`, `created_at` — a person's aliases; deleted when they are archived |\n| `roster_requests` | `id`, `channel` (`email` / `slack` / `discord` / `telegram`), `channel_ref` (the address or chat id), `display_name` (sanitised, unverified), `profile_email`, `on_company_domain`, `suggested_kind`, `suggested_person_id`, `status` (`pending` / `resolving` / `approved` / `linked` / `declined` / `expired` / `superseded`), `resolved_person_id`, `resolved_kind`, `resolved_via` (`web` / `slack` / `discord` / `telegram` / `email` / `people_page`), `resolved_at`, `token_hash` (the email answer token, hashed; cleared on resolve), `confirm_message_id`, `notified_at`, `notified_channel`, `ack_sent_at`, `alert_id`, `message_count`, `first_seen_at`, `last_seen_at`, `expires_at` — one pending row per `(channel, channel_ref)` (partial unique index) |\n| `roster_request_messages` | `id`, `request_id` (FK, cascade), `external_id` (unique per request, so a redelivery is held once), `payload_json` (what the adapter needs to replay it), `preview`, `received_at`, `replay_status` (`held` / `replaying` / `replayed` / `dropped` / `failed` / `unavailable`), `replayed_at` — at most 10 per request; `payload_json` and `preview` are blanked once a message is replayed or dropped |\n| `roster_ack_log` | `id`, `channel`, `channel_ref`, `sent_at` — one row per acknowledgement sent to a new sender, for the per-sender window and the daily cap |\n\n**Take the lead tables** (`orchestrator.take_the_lead`, created on first use, per company in `clients.slots` and `reset_all_state`): `take_the_lead` (`scope` PK: `executive` or `person:<id>`, `enabled`, `training` (added in place on older databases), `updated_at`, `updated_by`; each kind's Ask first is a `decision_class_state` row for `take_the_lead_action:<kind>`); `take_the_lead_rules` (`id`, `scope`: `company` or `person:<id>`, `kind` person|domain|words|amount, `value`, `created_by`, `created_at`); `take_the_lead_log` (`id`, `at`, `scope`, `source` reflection|research|scheduled, `tool`, `summary`, `status` done|waiting|approved|declined|failed, `why`, `decision_id`). A held action is a `decision_instances` row of class `take_the_lead_action` whose payload carries the tool, its input, whether it is an MCP tool, the gate kind or rule, the reason and the summary. `take_the_lead_allowed` (`id`, `key` unique: `<feature>|<action>|<who>`, `label`, `feature`, `example` (JSON of the edited fields, or empty), `uses`, `last_used_at`, `created_by`, `created_at`, `decision_id`, `removed_at`: set by Remove, so only approvals after it count toward a new suggestion, `person_id`: whose it is for a feature that learns per person, Act as me's `act_as_me|person:<id>|<reply|follow_up|message|invite|style>|<who>`, NULL for Take the lead; added in place on older databases): what it may do on its own in training, at most `ALLOWED_MAX` (200) per feature and person.",+ "markdown": "The shapes below are the load-bearing data structures: episodic SQLite tables (in `episodic_memory.db`) and the Pydantic models for departments and people.\n\n### Episodic tables\n\n| Table | Key columns |\n|---|---|\n| `decisions` | `id`, `timestamp`, `domain`, `summary`, `rationale`, `outcome`, `tags`, `department`, `session_id` |\n| `initiatives` | `id`, `title`, `status`, `created_at`, `updated_at`, `summary`, `department` |\n| `advice_given` | `id`, `timestamp`, `domain`, `query_summary`, `advice_summary`, `department`, `session_id` |\n| `facts` | `id`, `kind` (fact / correction / profile), `subject`, `subject_key`, `statement`, `previous_statement`, `source_quote`, `source_channel`, `session_id`, `turn_id`, `recorded_by_person_id`, `created_at`, `status` (active / superseded / retired), `superseded_by`, `retired_at`, `retired_reason` |\n| `scheduled_actions` | `id`, `created_at`, `run_at`, `channel`, `channel_ref`, `intent_text`, `status`, `attempts`, `kind`, `department`, `assigned_to_person_id`, `awaiting_response_since`, `scope_key`, `required_scope` |\n| `outbound_context` | `id`, `created_at`, `channel`, `channel_ref`, `recipient_person_id`, `outbound_text`, `originating_session_id`, `outbound_message_id`, `consumed_at`, `status` |\n| `history_reminders` | (`person_id`, `day`) PK, `sent_at` — the days a person was reminded of notes due (`memory.history_reminders`), older days pruned on write |\n| `session_drive_files` | (`session_id`, `person_id`, `file_id`) PK, `name`, `mime_type`, `link`, `summary` (first 600 chars of an opened file), `opened`, `found_by` (the search query), `first_seen_at`, `last_seen_at` — Drive files a conversation found or opened (`memory.drive_reads`) |\n| `session_drive_searches` | `id`, `session_id`, `person_id`, `query`, `result_count`, `searched_at` — every Drive search a conversation ran |\n| `saved_tools` | `name` (PK), `description`, `enabled`, `current_version`, `workflow_version` (the version workflows may run, NULL until the owner turns it on; never set for a Python tool), `kind` (`script` for `run_script`, `python` for a kept `run_python_job`; added with default `script`), `created_at`, `updated_at` — scripts and Python jobs the Executive saved to run again (`workflows.saved_tools`) |\n| `saved_tool_versions` | (`name`, `version`) PK, `description`, `script`, `tools` (JSON: the tools the script called when saved), `origin` (`chat` or `workflow:<name>/<step>`), `created_at` |\n| `saved_tool_runs` | `id`, `name`, `version`, `ok`, `calls`, `duration_ms`, `origin`, `at` — the newest 200 runs per tool |\n| `chat_messages` | `id`, `session_id`, `role`, `content`, `created_at`, `action_chips`, `stopped`, `sender_person_id`, `feedback`, `feedback_note`, `feedback_by_person_id`, `sources` (JSON `{sources: [{kind, title, url}], unavailable: [area]}` — what an assistant reply looked at and which areas it left out; NULL on older rows) |\n| `attunement_usage` | `day` (PK, UTC date), `calls` — the per-day ceiling on open-loop extraction model calls |\n| `attunement_profiles` | `person_id` (PK), `rules` (JSON: up to 4 `{text, basis, evidence}`), `locked`, `updated_at`, `updated_by`, `last_pass_at`, `pass_day`, `passes_today`, `last_message_id` — per-person working style plus pass pacing |\n| `attunement_profile_history` | `id`, `person_id`, `created_at`, `rules`, `locked`, `updated_by` — every change to a working style |\n| `proactive_outcomes` | `id`, `created_at`, `person_id`, `source`, `ref`, `channel`, `channel_ref`, `outbound_context_id`, `outcome` (`replied` / `acted` / `ignored` / `void`, NULL while open), `resolved_at` — one row per proactive DM (Attunement outcome ledger) |\n| `delegation_settings` | `person_id` (PK), `enabled` (default 0), `updated_at`, `updated_by` — Act as me, per person; no row means off |\n| `history_notes` | `id`, `person_id`, `visibility` (`private`), `source` (`approved_reply`), `channel` (`email`), `conversation_key` (a hash of the channel and thread, never the thread id), `counterpart`, `subject`, `kind` (`promised` / `agreed` / `declined` / `answered` / `asked` / `shared`), `summary`, `quote` (the person's own words), `due_date`, `trust`, `occurred_at`, `created_at`, `expires_at` (NULL: until forgotten), `pinned`, `correction`, `corrected_at`, `kept_from` (when the retention clock started: NULL means `occurred_at`; an unpin restarts it) — Always in the loop, one row per note |\n| `history_settings` | `id` (1), `retention_days` (NULL: until forgotten; no row means 90), `updated_at`, `updated_by` — the company retention |\n| `history_person_settings` | `person_id` (PK), `reply_notes` (default 0), `retention_days` (NULL: the company's), `updated_at`, `updated_by` |\n| `history_excluded` | `person_id`, `conversation_key` (PK together), `created_at` — conversations a person asked not to remember |\n| `history_chat_passes` | `person_id`, `day` (PK together, UTC `YYYY-MM-DD`), `passes` — note passes run on a person's chat messages that day, against the daily cap; older days pruned on write |\n| `delegation_voice` | `person_id` (PK), `profile` (JSON: `greetings` per audience, `sign_off`, `signature`, `length`, `formality`, up to 8 `habits`, up to 6 `avoid`, up to 3 `exemplars`), `locked`, `learned_at`, `sample_count`, `updated_at`, `updated_by` — \"How I write\" |\n| `delegation_voice_history` | `id`, `person_id`, `created_at`, `profile`, `locked`, `updated_by` — every change to a writing profile |\n| `delegation_drafts` | `id`, `person_id`, `source` (`chat` \\| `inbox`), `thread_id`, `draft_id`, `message_id`, `sent_message_id`, `created_at` — one row of ids per draft Act as me saved in someone's Gmail (no address, subject or text): the daily limit counts it, and \"How I write\" skips a chat draft's thread and a sent draft's message |\n| `delegation_inbox_watch` | `person_id` (PK), `enabled`, `watch_since` (reset on every off→on), `last_poll_at`, `status`, `backoff_until`, `failures`, `mailbox_drafts` (also save each reply in their Drafts; default 0, the reply lives on its card alone), `updated_at`, `updated_by` — **Draft replies to my inbox**, per person; no row means off |\n| `delegation_inbox_messages` | `id`, `person_id`, `message_id`, `thread_id`, `received_at`, `sender_key` (a hash of the address, never the address), `relation`, `outcome` (`processing`, `retry` — left for a later scan, `skipped`, `not_needed`, `deferred`, `failed`, `drafted`, `sent`, `dismissed`, `closed`, `expired`), `reason`, `classified`, `attempts`, `draft_id`, `decision_id`, `flags` (JSON), `created_at`, `updated_at`; `UNIQUE(person_id, message_id)` — the inbox watcher's cursor: what happened to each message it looked at |\n| `delegation_handle_it` | `person_id` (PK), `enabled`, `mode` (`careful`, `balanced` or `bold`), `levels` (the per-kind setting `mode` replaced, kept for older rows), `updated_at`, `updated_by` — **Handle it for me**, per person; no row means off. A `training` mode from before per-setting training moves to `balanced` with Replies and Follow-ups in training |\n| `delegation_training` | `person_id`, `setting` (`replies`, `follow_ups`, `actions` or `drafts`), `enabled`, `updated_at`, `updated_by`; primary key `(person_id, setting)` — Act as me settings in training, per person; no row means not in training |\n| `delegation_handled` | `id`, `person_id`, `thread_id`, `decision_id`, `sent_message_id`, `sent_at`; index on `(person_id, sent_at)` — one row per reply or follow-up Handle it for me sent on its own, read for its one-per-thread-a-day and daily limits |\n\n| `dynamic_workflows` | `name` (PK), `definition` (JSON of `DynamicWorkflowDef`), `is_active`, `created_at`, `updated_at`, `owner_person_id` (creator; set on insert only, kept out of the definition JSON) |\n| `workflow_approved_targets` | (`workflow_name`, `value`) PK, `key`, `approved_at`, `run_id` — targets a workflow's tool steps may write to without asking again; cleared when the workflow is deleted |\n| `executive_control` | `id` (PK, always 1), `paused`, `paused_at`, `paused_by`, `reason`, `updated_at` — the operator pause switch (`scheduler.pause`); operator-level, so client-slot switches carry it across |\n| `app_migrations` | `name` (PK), `applied_at` — one-shot data migrations (sweeps that must run exactly once per DB); schema DDL stays idempotent and is not recorded here |\n\n`department` and `session_id` are additive columns (default `''`); `session_id` scopes per-thread recall. `scheduled_actions.status` ∈ pending / running / done / failed / cancelled, and `scheduled_actions.kind` includes `dynamic_workflow` (a cadence-fired user-created workflow run) and `open_loop` (an Attunement open loop: `assigned_to_person_id` is the owner, `awaiting_response_since` the due time — cleared when the loop closes — and `scope_key` `loop:{owner}:{hash}`, unique among open loops via the partial index `idx_scheduled_open_loop_scope`). `chat_messages.sender_person_id` is the resolved rostered sender of a user message (never the session owner's principal fallback; NULL on legacy rows and for unrostered senders); `feedback` is `up` / `down` on an assistant reply. `dynamic_workflows` stores user-created (dynamic) workflow definitions interpreted by the generic `DynamicWorkflow` engine; the JSON `definition` holds free-text input fields and an ordered step list (specialist / approval_gate / synthesis) plus an optional cadence.\n\n### Legacy tables (talent / staff onboarding)\n\nThe talent (executive-search) and staff-onboarding features were removed. Their tables —\n`engagements`, `candidates`, `offers`, `onboarding_templates`, `onboarding_plans`,\n`onboarding_tasks` — are **not dropped**: no code creates, reads or writes them any more,\nbut rows survive on upgraded installs. `clients.slots` still wipes them when a blank client\nslot is activated (existence-guarded, a no-op on fresh installs) so a slot can never inherit\na previous client's candidate data.\n\n### Department / Goal / ChecklistItem\n\n| Model | Fields |\n|---|---|\n| `DepartmentConfig` | `slug`, `title`, `specialist_key`, `charter`, `authority_level`, `head_person_id`, `head_persona_slug`, `cadences`, `slack_channel_id`, `discord_channel_id`, `telegram_chat_id` |\n| `Goal` | `id`, `department_slug`, `period_type`, `period_value`, `key_result`, `target`, `current`, `status`, `created_at`, `updated_at`, `last_reviewed_at` |\n| `DepartmentState` | `config`, `goals`, `headcount`, `budget_usd`, `member_person_ids`, `updated_at` |\n\n`authority_level` ∈ `auto_execute` / `propose_only` / `escalate`; `Goal.status` ∈ `on_track` / `at_risk` / `off_track`.\n\n### Person\n\n| Field group | Fields |\n|---|---|\n| Identity | `id`, `full_name`, `role`, `is_principal`, `kind`, `department_slugs` |\n| Contact | `email`, `email_aliases`, `slack_user_id`, `telegram_chat_id`, `discord_user_id`, `preferred_channel` |\n| Routing | `availability`, `authority_scope`, `response_sla_hours`, `on_leave_until`, `reports_to_person_id` |\n| Lifecycle | `archived`, `created_at`, `updated_at` |\n\nExactly one `Person` should have `is_principal=True` — the fallback approver when no delegated person matches.\n\n`kind` is `team` (the default) or `contact` — someone outside the team, such as a client or contractor. It is an additive column, `kind TEXT NOT NULL DEFAULT 'team'`, added by the same `PRAGMA table_info`-guarded migration as `discord_user_id`, so every existing row is a team member. The principal is always `team`: the store refuses to write a principal contact (`PrincipalContactError`), and `initialize_db` repairs a hand-edited one on boot. A stored value the code does not know reads as `contact`. Every roster read in `people.store` and `people.registry` returns team members only unless it passes `include_contacts=True` (see Org).\n\n`email` is the one address a person signs in with; `email_aliases` (read from the `person_emails` table, up to 10) are other addresses they write from — they match inbound mail and may be emailed, but never sign in (see Org).\n\n### People-side tables\n\nThese live next to `people` (created by `people.store.initialize_db`, which also runs `people.roster_requests.initialize_tables`):\n\n| Table | Key columns |\n|---|---|\n| `person_emails` | `id`, `person_id` (FK → `people`, `ON DELETE CASCADE`), `email`, `email_norm` (trimmed + lowercased, **UNIQUE** across the roster), `source` (`manual` / `chat_tool` / `roster_request`), `roster_request_id`, `created_at` — a person's aliases; deleted when they are archived |\n| `roster_requests` | `id`, `channel` (`email` / `slack` / `discord` / `telegram`), `channel_ref` (the address or chat id), `display_name` (sanitised, unverified), `profile_email`, `on_company_domain`, `suggested_kind`, `suggested_person_id`, `status` (`pending` / `resolving` / `approved` / `linked` / `declined` / `expired` / `superseded`), `resolved_person_id`, `resolved_kind`, `resolved_via` (`web` / `slack` / `discord` / `telegram` / `email` / `people_page`), `resolved_at`, `token_hash` (the email answer token, hashed; cleared on resolve), `confirm_message_id`, `notified_at`, `notified_channel`, `ack_sent_at`, `alert_id`, `message_count`, `first_seen_at`, `last_seen_at`, `expires_at` — one pending row per `(channel, channel_ref)` (partial unique index) |\n| `roster_request_messages` | `id`, `request_id` (FK, cascade), `external_id` (unique per request, so a redelivery is held once), `payload_json` (what the adapter needs to replay it), `preview`, `received_at`, `replay_status` (`held` / `replaying` / `replayed` / `dropped` / `failed` / `unavailable`), `replayed_at` — at most 10 per request; `payload_json` and `preview` are blanked once a message is replayed or dropped |\n| `roster_ack_log` | `id`, `channel`, `channel_ref`, `sent_at` — one row per acknowledgement sent to a new sender, for the per-sender window and the daily cap |\n\n**Take the lead tables** (`orchestrator.take_the_lead`, created on first use, per company in `clients.slots` and `reset_all_state`): `take_the_lead` (`scope` PK: `executive` or `person:<id>`, `enabled`, `training` (added in place on older databases), `updated_at`, `updated_by`; each kind's Ask first is a `decision_class_state` row for `take_the_lead_action:<kind>`); `take_the_lead_rules` (`id`, `scope`: `company` or `person:<id>`, `kind` person|domain|words|amount, `value`, `created_by`, `created_at`); `take_the_lead_log` (`id`, `at`, `scope`, `source` reflection|research|scheduled, `tool`, `summary`, `status` done|waiting|approved|declined|failed, `why`, `decision_id`). A held action is a `decision_instances` row of class `take_the_lead_action` whose payload carries the tool, its input, whether it is an MCP tool, the gate kind or rule, the reason and the summary. `take_the_lead_allowed` (`id`, `key` unique: `<feature>|<action>|<who>`, `label`, `feature`, `example` (JSON of the edited fields, or empty), `uses`, `last_used_at`, `created_by`, `created_at`, `decision_id`, `removed_at`: set by Remove, so only approvals after it count toward a new suggestion, `person_id`: whose it is for a feature that learns per person, Act as me's `act_as_me|person:<id>|<reply|follow_up|message|invite|style>|<who>`, NULL for Take the lead; added in place on older databases): what it may do on its own in training, at most `ALLOWED_MAX` (200) per feature and person.","mermaid": null,- "generated_at": "2026-10-09T12:32:24Z"+ "generated_at": "2026-10-10T16:26:53Z"}diff --git a/packages/core/openexecutive/delegation/card_drafts.py b/packages/core/openexecutive/delegation/card_drafts.pynew file mode 100644index 00000000..ebc1404c--- /dev/null+++ b/packages/core/openexecutive/delegation/card_drafts.py@@ -0,0 +1,293 @@+"""Act as me: where a reply the inbox watcher wrote lives, and changing it+from its card.++Two places, by the person's own choice on the Draft replies to my inbox+card (``InboxWatch.mailbox_drafts``):++- On the card alone (the default). Nothing is saved in their mailbox, so+ their Drafts folder doesn't fill up with replies they may never send. The+ card keeps what a draft would hold (``draft_spec``: who it goes to, the+ subject, the thread headers) and the words (``draft_body``). Send makes+ the draft from exactly that, at that moment, and sends it through the same+ checked path as any other (``reply_send``); a refusal before it went takes+ the draft back out of their mailbox.+- Also in their mailbox's Drafts, as before: they can open it there, and+ Send sends it exactly as it is there.++Either way the words can be changed on the card (``edit``) before Send. A+reply in their mailbox is rewritten there too (``update_draft_text``), and+only while it is still the version the card last saw: an edit made in the+mailbox meanwhile is never overwritten. Only the card's own person, from a+request the API can tie to them, can change it, and never while it is being+sent on its own. Nothing here sends anything.+"""+from __future__ import annotations++import logging+from typing import Any++logger = logging.getLogger(__name__)++# The longest reply that can be typed on a card.+MAX_TEXT_CHARS = 20_000++# Card payload keys for a reply kept on its card alone.+CARD_ONLY = "card_only"+DRAFT_SPEC = "draft_spec"+DRAFT_KEY = "draft_key"+# Set once the person changed the words on the card.+EDITED_ON_CARD = "edited_on_card"+# A reply in their mailbox: its version after the last edit on the card.+EDITED_VERSION = "edited_version"++# Cards whose draft is being made right now in this process, so two taps+# never make two.+_MAKING: set[int] = set()+# Cards whose words are being changed right now in this process: one edit at+# a time, so a second can't rewrite the mailbox draft and then lose the card.+_EDITING: set[int] = set()+++def in_mailbox(person_id: int) -> bool:+ """Whether ``person_id``'s replies are also saved in their mailbox's+ Drafts. Unreadable is no: nothing lands in their mailbox unasked."""+ from openexecutive.delegation.inbox import get_watch++ return get_watch(person_id).mailbox_drafts+++async def save(person_id: int, client: Any, spec: Any) -> Any:+ """Save ``spec`` in ``person_id``'s Drafts when they keep replies there;+ otherwise nothing is saved and the returned draft has no id (the card+ keeps the reply, ``card_fields``)."""+ from openexecutive.delegation.gmail import CreatedDraft++ if in_mailbox(person_id):+ return await client.create_draft(spec)+ return CreatedDraft(draft_id="", message_id="", thread_id=spec.thread_id or "")+++def card_key(message_id: str) -> str:+ """The ``delegation_drafts`` row id of a reply kept on its card, until it+ becomes a real draft (``drafts.rename``)."""+ return f"card-{message_id}"+++def card_fields(spec: Any, key: str) -> dict[str, Any]:+ """What a card needs to make the draft itself when it is sent."""+ return {+ CARD_ONLY: True,+ DRAFT_KEY: key,+ DRAFT_SPEC: {+ "to": list(spec.to),+ "cc": list(spec.cc),+ "subject": spec.subject,+ "thread_id": spec.thread_id,+ "in_reply_to": spec.in_reply_to,+ "references": spec.references,+ "from_name": spec.from_name,+ "from_addr": spec.from_addr,+ },+ }+++def is_card_only(payload: dict[str, Any]) -> bool:+ """A reply kept on its card that hasn't become a draft yet."""+ return payload.get(CARD_ONLY) is True and not payload.get("draft_id")+++def _spec(payload: dict[str, Any]) -> Any:+ from openexecutive.delegation.gmail import DraftSpec++ stored = payload.get(DRAFT_SPEC)+ stored = stored if isinstance(stored, dict) else {}++ def text(key: str) -> str | None:+ value = stored.get(key)+ return value if isinstance(value, str) and value else None++ def addresses(key: str) -> list[str]:+ value = stored.get(key)+ return [a for a in value if isinstance(a, str) and a] if isinstance(value, list) else []++ return DraftSpec(+ to=addresses("to"),+ cc=addresses("cc"),+ subject=text("subject") or str(payload.get("draft_subject") or ""),+ body=str(payload.get("draft_body") or ""),+ thread_id=text("thread_id") or str(payload.get("thread_id") or "") or None,+ in_reply_to=text("in_reply_to"),+ references=text("references"),+ from_name=text("from_name") or "",+ from_addr=text("from_addr"),+ )+++async def make_draft(instance: Any, person_id: int, client: Any) -> dict[str, Any]:+ """Send, for a reply kept on its card: save it in the person's Drafts+ exactly as the card shows it, and record that on the card, so the send+ path checks and sends it like any other (and the reconciler can settle+ it). Returns the card's payload as it now is. Raises ``SendRefused``."""+ from openexecutive.delegation import drafts+ from openexecutive.delegation.gmail import GmailError+ from openexecutive.delegation.inbox import card_payload+ from openexecutive.delegation.reply_send import SendRefused+ from openexecutive.memory.decision_ledger import get_decision_instance, update_open_payload++ if instance.id in _MAKING or instance.id in _EDITING:+ raise SendRefused(409, "busy", "Your change to this reply is still being saved. Try again in a moment.")+ _MAKING.add(instance.id)+ try:+ current = get_decision_instance(instance.id)+ payload = card_payload(current) if current is not None else {}+ if current is None or not is_card_only(payload):+ # Made meanwhile (another tap) or no longer waiting.+ raise SendRefused(409, "already_handled", "This reply was already sent or dismissed.")+ spec = _spec(payload)+ if not spec.to or not spec.body.strip():+ raise SendRefused(409, "no_recipients", "This reply isn't addressed to anyone, so it wasn't sent.")+ try:+ created = await client.create_draft(spec)+ except GmailError as exc:+ raise SendRefused(+ 502, "gmail_error", "Couldn't reach your mailbox to send it. Nothing was sent; try again in a moment.",+ ) from exc+ made = {**payload, "draft_id": created.draft_id, "draft_message_id": created.message_id}+ if not update_open_payload(instance.id, made, expected_json=current.proposed_payload_json):+ await _delete_quietly(client, created.draft_id)+ raise SendRefused(409, "already_handled", "This reply was already sent or dismissed.")+ try:+ drafts.rename(person_id, str(payload.get(DRAFT_KEY) or ""), created.draft_id, created.message_id)+ except Exception:+ logger.warning("delegation.card_drafts: couldn't record the draft", exc_info=True)+ return made+ finally:+ _MAKING.discard(instance.id)+++async def take_back(instance: Any, person_id: int, payload: dict[str, Any], client: Any) -> None:+ """A send refused after ``make_draft``: take the draft back out of the+ person's mailbox and keep the reply on its card again. Best-effort; a+ card that closed meanwhile only loses the draft."""+ from openexecutive.delegation import drafts+ from openexecutive.delegation.inbox import card_payload+ from openexecutive.memory.decision_ledger import get_decision_instance, update_open_payload++ draft_id = str(payload.get("draft_id") or "")+ if not draft_id:+ return+ await _delete_quietly(client, draft_id)+ current = get_decision_instance(instance.id)+ if current is None:+ return+ now = card_payload(current)+ if now.get("draft_id") != draft_id:+ return+ back = {**now, "draft_id": "", "draft_message_id": ""}+ if update_open_payload(instance.id, back, expected_json=current.proposed_payload_json):+ try:+ drafts.rename(person_id, draft_id, str(payload.get(DRAFT_KEY) or ""), "")+ except Exception:+ logger.warning("delegation.card_drafts: couldn't record the draft taken back", exc_info=True)+++async def _delete_quietly(client: Any, draft_id: str) -> None:+ try:+ await client.delete_draft(draft_id)+ except Exception:+ logger.warning("delegation.card_drafts: couldn't take a draft back out of the mailbox", exc_info=True)+++async def edit(instance: Any, *, caller: Any, resolver: int | None, text: str, gmail: Any = None) -> dict[str, Any]:+ """Change the words of the reply on ``instance`` to ``text``, on the+ person's tap. Returns the card's payload as it now is; raises+ ``SendRefused``. Sends nothing."""+ from openexecutive.audit import rows_for_person+ from openexecutive.delegation.gmail import normalize_email+ from openexecutive.delegation.inbox import SENDING, card_payload+ from openexecutive.delegation.reply_send import _NOT_YOURS, SendRefused, _check_caller+ from openexecutive.delegation.settings import can_delegate, is_enabled+ from openexecutive.memory.decision_ledger import STATUS_PROPOSED+ from openexecutive.people.store import get_person++ payload = card_payload(instance)+ person = get_person(int(payload.get("person_id") or 0))+ if (+ person is None or person.id is None or not person.email or not can_delegate(person)+ or instance.approver_person_id != person.id or resolver != person.id+ ):+ raise SendRefused(403, "not_yours", _NOT_YOURS)+ with rows_for_person(person.id):+ _check_caller(caller, normalize_email(person.email))+ if instance.status != STATUS_PROPOSED or instance.id in SENDING:+ raise SendRefused(409, "already_handled", "This reply was already sent or dismissed.")+ if getattr(instance, "gate_mode", "") == "auto_execute":+ raise SendRefused(409, "already_handled", "This reply is being sent on its own right now.")+ if not is_enabled(person.id):+ raise SendRefused(409, "inbox_off", "Turn on Act as me to change this reply here.")+ words = text.rstrip()+ if not words.strip():+ raise SendRefused(422, "empty", "Write something before you save it.")+ if len(words) > MAX_TEXT_CHARS:+ raise SendRefused(422, "too_long", f"That's too long to send from here (at most {MAX_TEXT_CHARS:,} characters).")+ if instance.id in _EDITING or instance.id in _MAKING:+ raise SendRefused(409, "busy", "This reply is being saved or sent right now. Try again in a moment.")+ _EDITING.add(instance.id)+ try:+ return await _edit(instance, person, payload, words, gmail)+ finally:+ _EDITING.discard(instance.id)+++async def _edit(instance: Any, person: Any, payload: dict[str, Any], words: str, gmail: Any) -> dict[str, Any]:+ """``edit`` once its checks passed, one at a time per card."""+ from openexecutive.delegation.gmail import (+ BLOCKING_CODES,+ STATUS_MESSAGES,+ DraftChanged,+ GmailError,+ GmailNotFound,+ gmail_for,+ gmail_status,+ normalize_email,+ )+ from openexecutive.delegation.inbox import CLOSED, _audit, _close_card+ from openexecutive.delegation.reply_send import SendRefused+ from openexecutive.memory.decision_ledger import update_open_payload++ changed = {**payload, "draft_body": words, EDITED_ON_CARD: True}+ draft_id = str(payload.get("draft_id") or "")+ if draft_id:+ email = normalize_email(person.email)+ client = gmail if gmail is not None else gmail_for(email)+ status = await gmail_status(email, gmail=client)+ if status != "connected":+ raise SendRefused(409, BLOCKING_CODES.get(status, "gmail_error"), STATUS_MESSAGES[status])+ seen = str(payload.get(EDITED_VERSION) or payload.get("draft_message_id") or "")+ try:+ version = await client.update_draft_text(draft_id, seen, words)+ except GmailNotFound:+ _close_card(person.id, instance.id, str(payload.get("message_id") or ""), "draft_gone", CLOSED)+ raise SendRefused(+ 409, "draft_gone", "That draft isn't in your mailbox any more: it was sent or deleted there.",+ ) from None+ except DraftChanged as exc:+ if exc.reason == "not_plain":+ raise SendRefused(+ 409, "draft_not_plain", "This draft has files or formatting, so change it in your mailbox.",+ ) from None+ raise SendRefused(+ 409, "draft_changed",+ "This draft was changed in your mailbox, so it wasn't changed here. Change it there, or dismiss it.",+ ) from None+ except GmailError as exc:+ raise SendRefused(+ 502, "gmail_error", "Couldn't save your change in your mailbox. Try again in a moment.",+ ) from exc+ changed[EDITED_VERSION] = version+ if not update_open_payload(instance.id, changed, expected_json=instance.proposed_payload_json):+ raise SendRefused(409, "already_handled", "This reply changed or was sent meanwhile. Look at it again.")+ _audit("delegation_reply_edited", f"Person {person.id} changed a reply on its card", {+ "person_id": person.id, "decision_id": instance.id, "in_mailbox": bool(draft_id),+ })+ return changeddiff --git a/packages/core/openexecutive/delegation/drafts.py b/packages/core/openexecutive/delegation/drafts.pyindex 2b1c8522..aab5c1f8 100644--- a/packages/core/openexecutive/delegation/drafts.py+++ b/packages/core/openexecutive/delegation/drafts.py@@ -101,6 +101,25 @@ def mark_sent(conn.close()+def rename(+ person_id: int, old_draft_id: str, draft_id: str, message_id: str, *, db_path: Path | None = None+) -> bool:+ """A reply kept on its card alone (``card_drafts``) became a real draft+ when it was sent: its row takes the draft's ids, so it is still counted+ once and ``mark_sent`` finds it."""+ conn = _connect(db_path)+ try:+ cur = conn.execute(+ f"UPDATE {DRAFTS_TABLE} SET draft_id = ?, message_id = ? " # noqa: S608 — constant table name+ "WHERE person_id = ? AND draft_id = ?",+ (draft_id, message_id, person_id, old_draft_id),+ )+ conn.commit()+ return cur.rowcount > 0+ finally:+ conn.close()++def chat_thread_ids(person_id: int, *, db_path: Path | None = None) -> set[str]:"""The threads chat drafted into as ``person_id``."""conn = _connect(db_path)diff --git a/packages/core/openexecutive/delegation/follow_ups.py b/packages/core/openexecutive/delegation/follow_ups.pyindex 67f2da4f..5b0e3ec6 100644--- a/packages/core/openexecutive/delegation/follow_ups.py+++ b/packages/core/openexecutive/delegation/follow_ups.py@@ -129,7 +129,7 @@ async def _follow_up("""Draft one follow-up and leave its card, or send it. True when a draftwas made."""from openexecutive.config import get_settings- from openexecutive.delegation import caps, drafts, handle_it, inbox+ from openexecutive.delegation import caps, card_drafts, drafts, handle_it, inboxfrom openexecutive.delegation.ghostwriter import ComposeError, Recipient, composefrom openexecutive.delegation.gmail import DraftSpec, references_headerfrom openexecutive.delegation.inbox_classifier import Verdict@@ -184,16 +184,19 @@ async def _follow_up(held = handle_it.follow_up_refusal(person.id, sent, reply, relation=relation, own=own, exec_address=exec_address, now=now,)- draft = await client.create_draft(DraftSpec(+ spec = DraftSpec(to=reply.to, cc=reply.cc, subject=reply.subject, body=reply.body, thread_id=thread.id,in_reply_to=reply.in_reply_to, references=reply.references,from_name=" ".join(names), from_addr=None if sent.from_addr == email else sent.from_addr,- ))+ )+ # In their Drafts too, or on the card alone (card_drafts).+ draft = await card_drafts.save(person.id, client, spec)saved = True+ key = draft.draft_id or card_drafts.card_key(sent.id)try:drafts.record(person.id, source=drafts.SOURCE_INBOX, thread_id=thread.id,- draft_id=draft.draft_id, message_id=draft.message_id, now=now,+ draft_id=key, message_id=draft.message_id, now=now,)except Exception:logger.warning("delegation.follow_ups: couldn't record the draft", exc_info=True)@@ -204,10 +207,12 @@ async def _follow_up(person, sent, thread, reply, draft, relation=relation, handled_as=relation,verdict=Verdict(needs_reply=True, kind="follow_up", confidence=1.0),on_its_own=held is None, handle_it_reason=held, source=inbox.FOLLOW_UP_SOURCE,+ kept=None if draft.draft_id else card_drafts.card_fields(spec, key),)except Exception:# No card, so no draft either: a draft with no card would wait unseen.- await client.delete_draft(draft.draft_id)+ if draft.draft_id:+ await client.delete_draft(draft.draft_id)raiseinbox._set_outcome(person.id, sent.id, inbox.DRAFTED, decision_id=decision_id)result.drafted += 1diff --git a/packages/core/openexecutive/delegation/gmail.py b/packages/core/openexecutive/delegation/gmail.pyindex de17bb27..a03f6af5 100644--- a/packages/core/openexecutive/delegation/gmail.py+++ b/packages/core/openexecutive/delegation/gmail.py@@ -155,6 +155,16 @@ class GmailNotFound(GmailError):"""No such message, thread or draft (404). For a draft: sent or deleted."""+class DraftChanged(GmailError):+ """A draft can't be rewritten from the card: it changed in the mailbox+ since it was last read (``reason`` "changed"), or it holds more than plain+ text, such as files ("not_plain")."""++ def __init__(self, reason: str) -> None:+ super().__init__(f"draft {reason}")+ self.reason = reason++class GmailAuthError(GmailError):"""Google refused the credential: revoked, expired, or missing a scope."""@@ -1041,6 +1051,46 @@ class DelegateGmail:return Falsereturn True+ async def update_draft_text(self, draft_id: str, expected_version: str, text: str) -> str:+ """Replace the words of the draft ``draft_id`` with ``text``, keeping+ every header (who it goes to, the subject, the thread), when it is+ still the version ``expected_version``. Returns its new version (the+ message id Gmail gives the edited draft). Raises ``GmailNotFound``+ when it is gone and ``DraftChanged`` when it changed meanwhile or is+ more than plain text. Nothing is sent."""+ if not valid_id(draft_id):+ raise GmailError("invalid draft id")+ async with self._client() as client:+ data = await self._get(client, f"/drafts/{draft_id}", {"format": "raw"})+ current = data.get("message")+ current = current if isinstance(current, dict) else {}+ if str(current.get("id") or "") != expected_version:+ raise DraftChanged("changed")+ raw = current.get("raw")+ if not isinstance(raw, str):+ raise GmailError("gmail returned no draft")+ try:+ from email import message_from_bytes, policy++ msg = message_from_bytes(_b64decode(raw), policy=policy.default)+ except (ValueError, TypeError) as exc:+ raise GmailError("gmail returned an unreadable draft") from exc+ if not isinstance(msg, EmailMessage) or msg.is_multipart() or msg.get_content_type() != "text/plain":+ raise DraftChanged("not_plain")+ msg.set_content(text)+ message: dict[str, Any] = {"raw": base64.urlsafe_b64encode(msg.as_bytes()).decode("ascii")}+ thread_id = current.get("threadId")+ if isinstance(thread_id, str) and valid_id(thread_id):+ message["threadId"] = thread_id+ updated = await self._request(+ client, "PUT", f"/drafts/{draft_id}", json_body={"id": draft_id, "message": message},+ )+ saved = updated.get("message")+ version = str(saved.get("id") or "") if isinstance(saved, dict) else ""+ if not version:+ raise GmailError("gmail returned no edited draft", maybe_done=True)+ return version+async def send_draft(self, draft_id: str) -> SentMessage:"""Send the draft ``draft_id`` exactly as it is in Gmail now: therequest body is its id and nothing else, so nothing here can changediff --git a/packages/core/openexecutive/delegation/inbox.py b/packages/core/openexecutive/delegation/inbox.pyindex f62680f7..3fdb31a8 100644--- a/packages/core/openexecutive/delegation/inbox.py+++ b/packages/core/openexecutive/delegation/inbox.py@@ -163,6 +163,9 @@ class InboxWatch:status: str = "off"backoff_until: str | None = Nonefailures: int = 0+ # Also save each reply in their mailbox's Drafts. Off (the default), a+ # reply lives on its card alone until they send it (delegation.card_drafts).+ mailbox_drafts: bool = False@dataclass@@ -255,6 +258,7 @@ def get_watch(person_id: int, *, db_path: Path | None = None) -> InboxWatch:status=row["status"] or ("waiting" if row["enabled"] else "off"),backoff_until=row["backoff_until"],failures=int(row["failures"] or 0),+ mailbox_drafts=bool(row["mailbox_drafts"]),)@@ -289,6 +293,27 @@ def set_watch(return get_watch(person_id, db_path=db_path)+def set_mailbox_drafts(+ person_id: int, on: bool, *, updated_by: str, now: datetime | None = None, db_path: Path | None = None+) -> InboxWatch:+ """Whether replies are also saved in the person's mailbox's Drafts+ (callers authorize first). Kept while the switch is off, for when it is+ turned on again. Cards already made keep where their reply is."""+ moment = (now or datetime.now(UTC)).isoformat()+ conn = _connect(db_path)+ try:+ conn.execute(+ f"INSERT INTO {INBOX_WATCH_TABLE} (person_id, enabled, mailbox_drafts, updated_at, updated_by) " # noqa: S608+ "VALUES (?, 0, ?, ?, ?) ON CONFLICT(person_id) DO UPDATE SET mailbox_drafts = excluded.mailbox_drafts, "+ "updated_at = excluded.updated_at, updated_by = excluded.updated_by",+ (person_id, int(on), moment, updated_by),+ )+ conn.commit()+ finally:+ conn.close()+ return get_watch(person_id, db_path=db_path)++def _update_watch(person_id: int, db_path: Path | None = None, **fields: Any) -> None:if not fields:return@@ -1069,7 +1094,7 @@ async def _consider(Once claimed, a message is finished or left for a later scan(``_retry_later``); a Gmail failure is raised for the scan to back off."""from openexecutive.config import get_settings- from openexecutive.delegation import caps, drafts, handle_it+ from openexecutive.delegation import caps, card_drafts, drafts, handle_itfrom openexecutive.delegation.ghostwriter import ComposeErrorfrom openexecutive.delegation.gmail import DraftSpec, GmailErrorfrom openexecutive.delegation.inbox_classifier import addressing, classify, wants_draft@@ -1146,27 +1171,30 @@ async def _consider(# addresses rather than the primary when only that one was used.addressed = [*message.to, *message.cc]alias = None if email in addressed else next((a for a in addressed if a in own), None)+ spec = DraftSpec(+ to=reply.to,+ cc=reply.cc,+ subject=reply.subject,+ body=reply.body,+ thread_id=thread.id,+ in_reply_to=reply.in_reply_to,+ references=reply.references,+ from_name=" ".join(names),+ from_addr=alias,+ )try:- draft = await client.create_draft(DraftSpec(- to=reply.to,- cc=reply.cc,- subject=reply.subject,- body=reply.body,- thread_id=thread.id,- in_reply_to=reply.in_reply_to,- references=reply.references,- from_name=" ".join(names),- from_addr=alias,- ))+ # In their Drafts too, or on the card alone (card_drafts).+ draft = await card_drafts.save(person.id, client, spec)except GmailError:_retry_later(person.id, message.id, "draft_failed")raisesaved = True- _set_outcome(person.id, message.id, PROCESSING, draft_id=draft.draft_id)+ key = draft.draft_id or card_drafts.card_key(message.id)+ _set_outcome(person.id, message.id, PROCESSING, draft_id=key)try:drafts.record(person.id, source=drafts.SOURCE_INBOX, thread_id=thread.id,- draft_id=draft.draft_id, message_id=draft.message_id, now=now,+ draft_id=key, message_id=draft.message_id, now=now,)except Exception:logger.warning("delegation.inbox: couldn't record the draft", exc_info=True)@@ -1176,13 +1204,14 @@ async def _consider(decision_id = _create_card(person, message, thread, reply, draft, relation=known_as, handled_as=relation, verdict=verdict,on_its_own=held is None, handle_it_reason=held if handling.enabled else None,+ kept=None if draft.draft_id else card_drafts.card_fields(spec, key),)except Exception as exc:logger.warning("delegation.inbox: couldn't make the card (%s)", type(exc).__name__)# Take the draft back, so a later scan starts over rather than# leaving a draft with no card (which would also mute its thread).try:- taken_back = await client.delete_draft(draft.draft_id)+ taken_back = await client.delete_draft(draft.draft_id) if draft.draft_id else Trueexcept GmailError:taken_back = Falseif taken_back:@@ -1197,6 +1226,7 @@ async def _consider("person_id": person.id,"thread_id": thread.id,"draft_id": draft.draft_id,+ "in_mailbox": bool(draft.draft_id),"decision_id": decision_id,"relation": relation,"kind": verdict.kind,@@ -1250,6 +1280,7 @@ def _hand_back(card: Any, reason: str | None) -> None:def _create_card(person: Any, message: Any, thread: Any, reply: Reply, draft: Any, *, relation: str, handled_as: str,verdict: Any, on_its_own: bool = False, handle_it_reason: str | None = None, source: str | None = None,+ kept: dict[str, Any] | None = None,) -> int | None:"""The card for this reply, made once per message (its idempotency key):a second call for the same message finds the one the first made. A card@@ -1265,7 +1296,7 @@ def _create_card(proposed_payload=_card_payload(person, message, thread, reply, draft, relation=relation, handled_as=handled_as, verdict=verdict,handle_it_reason=handle_it_reason, source=source,- ),+ ) | (kept or {}),idempotency_key=key,gate_mode="auto_execute" if on_its_own else "propose",approver_person_id=person.id,@@ -1350,7 +1381,7 @@ async def reconcile(person: Any, client: Any, *, now: datetime, own: set[str]) -async def _reconcile_card(person: Any, client: Any, card: Any, *, now: datetime, own: set[str]) -> int:"""Settle one open card against Gmail; 1 when it closed."""- from openexecutive.delegation import drafts+ from openexecutive.delegation import card_drafts, draftsfrom openexecutive.delegation.gmail import GmailNotFoundfrom openexecutive.memory.decision_ledger import STATUS_EXECUTING, STATUS_PROPOSED@@ -1363,14 +1394,16 @@ async def _reconcile_card(person: Any, client: Any, card: Any, *, now: datetime,created = _parse(card.created_at)if created is not None and now - created > CARD_TTL:return int(_close_card(person.id, card.id, message_id, "expired", EXPIRED))- draft = await client.get_draft(str(payload.get("draft_id") or ""))+ # A reply kept on its card alone has no draft to look for.+ card_only = card_drafts.is_card_only(payload)+ draft = None if card_only else await client.get_draft(str(payload.get("draft_id") or ""))try:thread = await client.get_thread(str(payload.get("thread_id") or ""))except GmailNotFound:return int(_close_card(person.id, card.id, message_id, "thread_gone", CLOSED))later = later_messages(thread, payload, now=now)sent_by_them = [m for m in later if "SENT" in m.labels and m.from_addr in own]- if draft is None:+ if draft is None and not card_only:if not sent_by_them:return int(_close_card(person.id, card.id, message_id, "draft_deleted", CLOSED))if not _close_card(person.id, card.id, message_id, "sent_in_gmail", SENT):@@ -1383,7 +1416,7 @@ async def _reconcile_card(person: Any, client: Any, card: Any, *, now: datetime,if payload.get("source") == FOLLOW_UP_SOURCE:# They answered: the follow-up isn't needed any more.closed = _close_card(person.id, card.id, message_id, "answered", CLOSED)- if closed and draft.message.id == payload.get("draft_message_id"):+ if closed and draft is not None and draft.message.id == payload.get("draft_message_id"):# Nobody touched the draft: take it out of their Drafts too.try:await client.delete_draft(draft.draft_id)@@ -1417,6 +1450,8 @@ async def _settle_unconfirmed_send(message_id = str(payload.get("message_id") or "")draft_id = str(payload.get("draft_id") or "")+ if not draft_id:+ return 0 # never sent: a card is claimed only once its draft existsdraft = await client.get_draft(draft_id)try:thread = await client.get_thread(str(payload.get("thread_id") or ""))diff --git a/packages/core/openexecutive/delegation/outlook.py b/packages/core/openexecutive/delegation/outlook.pyindex a10d80ba..9776f3fb 100644--- a/packages/core/openexecutive/delegation/outlook.py+++ b/packages/core/openexecutive/delegation/outlook.py@@ -64,6 +64,7 @@ from openexecutive.delegation.gmail import (_BULK_PRECEDENCE,_REPORT_SENDERS,CreatedDraft,+ DraftChanged,DraftInfo,DraftSpec,GmailAuthError,@@ -778,6 +779,42 @@ class DelegateOutlook:return Falsereturn True+ async def update_draft_text(self, draft_id: str, expected_version: str, text: str) -> str:+ """Replace the words of the draft ``draft_id`` with ``text``, keeping+ who it goes to, the subject and the conversation, when it is still the+ version ``expected_version`` (``draft_version``; If-Match holds it to+ that version on Microsoft's side too). Returns its new version.+ Raises ``GmailNotFound`` when it is gone and ``DraftChanged`` when it+ changed meanwhile or is more than plain text. Nothing is sent."""+ if not valid_id(draft_id):+ raise GmailError("invalid draft id")+ path = f"/messages/{quote(draft_id, safe='')}"+ async with self._client() as client:+ data = await self._get(client, path, {"$select": "id,isDraft,changeKey,body,hasAttachments"})+ if data.get("isDraft") is not True:+ raise GmailNotFound("not a draft")+ change_key = str(data.get("changeKey") or "")+ if draft_version(draft_id, change_key) != expected_version or not change_key:+ raise DraftChanged("changed")+ body = data.get("body")+ if data.get("hasAttachments") is True or not (+ isinstance(body, dict) and str(body.get("contentType") or "").lower() == "text"+ ):+ raise DraftChanged("not_plain")+ etag = str(data.get("@odata.etag") or f'W/"{change_key}"')+ try:+ updated = await self._request(+ client, "PATCH", path, json_body={"body": {"contentType": "text", "content": text}},+ if_match=etag,+ )+ except GmailNotFound as exc:+ # 412: it changed between the read and the write.+ raise DraftChanged("changed") from exc+ new_key = str(updated.get("changeKey") or "")+ if not new_key:+ raise GmailError("graph returned no edited draft", maybe_done=True)+ return draft_version(draft_id, new_key)+async def send_draft(self, draft_id: str) -> SentMessage:"""Send the draft ``draft_id`` exactly as it is in Outlook now: Graph's``send`` with no body, so nothing here can change what goes, or todiff --git a/packages/core/openexecutive/delegation/replies.py b/packages/core/openexecutive/delegation/replies.pyindex aa6ac418..c4181fe6 100644--- a/packages/core/openexecutive/delegation/replies.py+++ b/packages/core/openexecutive/delegation/replies.py@@ -47,6 +47,11 @@ class ReplyCard:# Drafts is in training: "Do it like this next time" keeps a draft they# changed as how they write to this person.learns_style: bool = False+ # Also saved in their mailbox's Drafts; False when it lives on this card+ # alone until Send (delegation.card_drafts).+ in_mailbox: bool = True+ # Which of their mailboxes it sends from: "Gmail" or "Outlook".+ mailbox: str = "Gmail"def _strings(value: Any) -> list[str]:@@ -56,7 +61,7 @@ def _strings(value: Any) -> list[str]:def cards(person: Any) -> list[ReplyCard]:"""``person``'s open reply cards, newest first."""from openexecutive.delegation import training- from openexecutive.delegation.gmail import mailbox_link+ from openexecutive.delegation.gmail import credential_provider, mailbox_linkfrom openexecutive.delegation.handle_it import REASONSfrom openexecutive.delegation.inbox import card_payload, ledger_flags, open_cards@@ -65,6 +70,7 @@ def cards(person: Any) -> list[ReplyCard]:added = ledger_flags(person.id, [str(p.get("message_id") or "") for _, p in payloads])email = (person.email or "").strip().lower()trained = training.get(person.id)+ mailbox = "Outlook" if email and credential_provider(email) == "microsoft" else "Gmail"out: list[ReplyCard] = []for card, payload in payloads:thread_id = str(payload.get("thread_id") or "")@@ -90,11 +96,15 @@ def cards(person: Any) -> list[ReplyCard]:draft_body=str(payload.get("draft_body") or ""),open_questions=_strings(payload.get("open_questions")),flags=flags,- gmail_link=mailbox_link(email, thread_id=thread_id, draft_id=draft_id) if email and thread_id else "",+ gmail_link=(+ mailbox_link(email, thread_id=thread_id, draft_id=draft_id) if email and thread_id and draft_id else ""+ ),waited_because=REASONS.get(str(payload.get("handle_it_reason") or ""), ""),source="follow_up" if payload.get("source") == "follow_up" else "",can_allow=_can_allow(person.id, payload, trained),learns_style=trained.drafts,+ in_mailbox=bool(draft_id),+ mailbox=mailbox,))return out@@ -112,7 +122,7 @@ def _can_allow(person_id: int, payload: dict[str, Any], trained: Any) -> bool:async def dismiss(instance: Any, *, gmail: Any = None) -> str:"""After a card was rejected: delete its draft when nobody edited it.Returns what happened (``deleted``, ``kept_edited``, ``already_gone``,- ``not_connected``, ``gmail_error``). Gmail errors propagate after the+ ``card_only``, ``not_connected``, ``gmail_error``). Gmail errors propagate after theoutcome is recorded; the reject already stands."""from openexecutive.delegation.gmail import gmail_for, gmail_statusfrom openexecutive.delegation.inbox import DISMISSED, _audit, _set_outcome, card_payload@@ -128,13 +138,19 @@ async def dismiss(instance: Any, *, gmail: Any = None) -> str:# card as still drafted.outcome = "gmail_error"try:- if await gmail_status(email, gmail=client) != "connected":+ if not payload.get("draft_id"):+ # Kept on its card alone: nothing in their mailbox to remove.+ outcome = "card_only"+ elif await gmail_status(email, gmail=client) != "connected":outcome = "not_connected"else:draft = await client.get_draft(str(payload.get("draft_id") or ""))+ # Changed on its card is theirs to dismiss there; changed in the+ # mailbox stays there.+ seen = {payload.get("draft_message_id"), payload.get("edited_version")} - {None, ""}if draft is None:outcome = "already_gone"- elif draft.message.id != payload.get("draft_message_id"):+ elif draft.message.id not in seen:outcome = "kept_edited"else:outcome = "deleted" if await client.delete_draft(draft.draft_id) else "already_gone"diff --git a/packages/core/openexecutive/delegation/reply_send.py b/packages/core/openexecutive/delegation/reply_send.pyindex 952f1cd8..1199e2b3 100644--- a/packages/core/openexecutive/delegation/reply_send.py+++ b/packages/core/openexecutive/delegation/reply_send.py@@ -46,8 +46,12 @@ is refused before anything is sent unless Replies (or, on a follow-up card,Follow-ups) is in training and their list has room; once the reply went,replies to that sender (follow-ups to those people) may go on their own."Do it like this next time" (``example``, with Drafts in training) keeps what-they sent, when they changed the draft in their mailbox first, as how they-write to that person.+they sent, when they changed the draft first (on the card or in their+mailbox), as how they write to that person.++A reply kept on its card alone (``card_drafts``, the default) has no draft+until Send: it is made from exactly what the card shows just before the+checks below, and taken back out of the mailbox when they refuse it.Then it claims the card (``claim_for_execution``, proposed → executing, acompare-and-set: a double tap sends once), reads the draft once more and sends@@ -158,9 +162,30 @@ def _addresses(value: Any) -> list[str] | None:async def _send(instance: Any, *, caller: Any, resolver: int | None, confirm: dict[str, Any], gmail: Any, now: datetime,on_its_own: bool = False, allow: bool = False, example: bool = False,+) -> str:+ """``_send_checked``, and for a reply kept on its card alone+ (``card_drafts``): the draft it made is taken back out of the mailbox+ when the send is refused before anything went."""+ from openexecutive.delegation import card_drafts++ made: dict[str, Any] = {}+ try:+ return await _send_checked(+ instance, caller=caller, resolver=resolver, confirm=confirm, gmail=gmail, now=now,+ on_its_own=on_its_own, allow=allow, example=example, made=made,+ )+ except SendRefused as refused:+ if made and refused.code != "send_unconfirmed":+ await card_drafts.take_back(instance, made["person_id"], made["payload"], made["client"])+ raise+++async def _send_checked(+ instance: Any, *, caller: Any, resolver: int | None, confirm: dict[str, Any], gmail: Any, now: datetime,+ on_its_own: bool = False, allow: bool = False, example: bool = False, made: dict[str, Any],) -> str:from openexecutive.config import get_settings- from openexecutive.delegation import drafts, handle_it, training+ from openexecutive.delegation import card_drafts, drafts, handle_it, trainingfrom openexecutive.delegation.gmail import (BLOCKING_CODES,STATUS_MESSAGES,@@ -270,6 +295,11 @@ async def _send(if status != "connected":raise SendRefused(409, BLOCKING_CODES.get(status, "gmail_error"), STATUS_MESSAGES[status])+ if card_drafts.is_card_only(payload):+ # Kept on its card alone: make the draft from exactly what the card+ # shows, then check and send it like any other.+ payload = await card_drafts.make_draft(instance, person.id, client)+ made.update(person_id=person.id, payload=payload, client=client)message_id = str(payload.get("message_id") or "")thread_id = str(payload.get("thread_id") or "")unreadable = "Couldn't read the draft in your mailbox. Try again in a moment."@@ -322,7 +352,11 @@ async def _send(reasons=reasons, recipients=recipients,)- edited = draft.message.id != str(payload.get("draft_message_id") or "")+ # Changed in the mailbox, or on the card (``card_drafts.edit``).+ edited = (+ draft.message.id != str(payload.get("draft_message_id") or "")+ or payload.get(card_drafts.EDITED_ON_CARD) is True+ )if on_its_own and edited:# Someone changed it in the mailbox since it was written: that# version was never checked, so the person sends it, not this path.diff --git a/packages/core/openexecutive/delegation/schema.py b/packages/core/openexecutive/delegation/schema.pyindex 26ff2669..f39defd2 100644--- a/packages/core/openexecutive/delegation/schema.py+++ b/packages/core/openexecutive/delegation/schema.py@@ -87,6 +87,8 @@ _DDL: tuple[str, ...] = (f"ON {DRAFTS_TABLE}(person_id, created_at)",# The inbox watcher's switch and health, one row per person (absent: off).# watch_since resets on every off → on, so it never drafts for old mail.+ # mailbox_drafts: also save each reply in their mailbox's Drafts (off: the+ # reply lives on its card alone until they send it).f"CREATE TABLE IF NOT EXISTS {INBOX_WATCH_TABLE} ("" person_id INTEGER PRIMARY KEY,"" enabled INTEGER NOT NULL DEFAULT 0,"@@ -95,6 +97,7 @@ _DDL: tuple[str, ...] = (" status TEXT NOT NULL DEFAULT 'off',"" backoff_until TEXT,"" failures INTEGER NOT NULL DEFAULT 0,"+ " mailbox_drafts INTEGER NOT NULL DEFAULT 0,"" updated_at TEXT,"" updated_by TEXT"")",@@ -240,9 +243,19 @@ def _move_training_off_the_dial(conn: sqlite3.Connection) -> None:conn.commit()+def _add_mailbox_drafts(conn: sqlite3.Connection) -> None:+ """Give a watch table made before ``mailbox_drafts`` existed the column,+ off: replies wait on their cards and no longer fill the person's Drafts."""+ columns = {row[1] for row in conn.execute(f"PRAGMA table_info({INBOX_WATCH_TABLE})")}+ if "mailbox_drafts" not in columns:+ conn.execute(f"ALTER TABLE {INBOX_WATCH_TABLE} ADD COLUMN mailbox_drafts INTEGER NOT NULL DEFAULT 0")+ conn.commit()++def ensure_schema(conn: sqlite3.Connection) -> None:"""Create the tables if missing. Idempotent."""for statement in _DDL:conn.execute(statement)_add_handle_it_mode(conn)+ _add_mailbox_drafts(conn)_move_training_off_the_dial(conn)diff --git a/packages/core/openexecutive/memory/decision_ledger.py b/packages/core/openexecutive/memory/decision_ledger.pyindex c8ab813b..dae3f7b7 100644--- a/packages/core/openexecutive/memory/decision_ledger.py+++ b/packages/core/openexecutive/memory/decision_ledger.py@@ -307,6 +307,28 @@ def hand_back(instance_id: int, proposed_payload: dict[str, Any], db_path: Pathreturn result.rowcount == 1+def update_open_payload(+ instance_id: int,+ proposed_payload: dict[str, Any],+ *,+ expected_json: str | None = None,+ db_path: Path | None = None,+) -> bool:+ """Replace the payload of a row still waiting on someone (proposed),+ compare-and-set: a row claimed, acted on or closed meanwhile is left+ alone. With ``expected_json`` (the row's ``proposed_payload_json`` as it+ was read), only while it is still that, so two writers never overwrite+ each other's change."""+ sql = "UPDATE decision_instances SET proposed_payload_json = ? WHERE id = ? AND status = ?"+ params: tuple[Any, ...] = (json.dumps(proposed_payload), instance_id, STATUS_PROPOSED)+ if expected_json is not None:+ sql += " AND proposed_payload_json = ?"+ params = (*params, expected_json)+ with _get_conn(db_path or _db_path()) as conn:+ result = conn.execute(sql, params)+ return result.rowcount == 1++def close_externally(instance_id: int,*,diff --git a/packages/core/tests/unit/test_delegation_card_drafts.py b/packages/core/tests/unit/test_delegation_card_drafts.pynew file mode 100644index 00000000..9ddf1493--- /dev/null+++ b/packages/core/tests/unit/test_delegation_card_drafts.py@@ -0,0 +1,209 @@+"""Replies kept on their card alone, and changing a reply's words on its card+(delegation/card_drafts.py)."""+from __future__ import annotations++import asyncio+from datetime import timedelta+from pathlib import Path+from typing import Any++import pytest++from openexecutive.api.caller import Caller+from openexecutive.delegation import card_drafts, drafts, inbox, replies+from openexecutive.delegation.reply_send import SendRefused, send_approved_reply+from openexecutive.memory import decision_ledger as ledger++from . import test_delegation_inbox as _inbox_tests+from .test_delegation_inbox import DANA, NOW, OWNER, FakeInbox, _msg, _scan++db = _inbox_tests.db+models = _inbox_tests.models++LOCAL = Caller("open", "")++[email protected](autouse=True)+def local_login(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setenv("OE_LOCAL_LOGIN", "1")+ monkeypatch.delenv("OE_PUBLIC_DEPLOYMENT", raising=False)+ monkeypatch.delenv("CALLER_ASSERTION_PUBLIC_KEYS", raising=False)+++def owner() -> Any:+ """The owner with both switches on and the default: replies on their card alone."""+ from openexecutive.delegation.settings import set_enabled+ from openexecutive.people import registry as people_registry+ from openexecutive.people import store as people_store++ pid = people_store.upsert_person(full_name="Olivia Owner", is_principal=True, email=OWNER)+ people_store.upsert_person(full_name="Dana Park", email=DANA, kind="contact")+ people_registry.invalidate()+ set_enabled(pid, True, updated_by="test")+ inbox.set_watch(pid, True, updated_by="test", now=NOW - timedelta(days=1))+ return people_store.get_person(pid)+++def _card(owner: Any) -> tuple[FakeInbox, Any]:+ mailbox = FakeInbox()+ mailbox.add(_msg("m1", "t1"))+ _scan(owner, mailbox)+ return mailbox, inbox.open_cards(owner.id)[0]+++def _fresh(card: Any) -> Any:+ row = ledger.get_decision_instance(card.id)+ assert row is not None+ return row+++def _send(card: Any, mailbox: FakeInbox, owner: Any, **confirm: Any) -> str:+ return asyncio.run(send_approved_reply(+ _fresh(card), caller=LOCAL, resolver=owner.id, confirm=confirm or None, gmail=mailbox,+ now=NOW + timedelta(minutes=30),+ ))+++def _edit(card: Any, mailbox: FakeInbox, owner: Any, text: str, *, resolver: int | None = -1,+ caller: Caller = LOCAL) -> dict[str, Any]:+ return asyncio.run(card_drafts.edit(+ _fresh(card), caller=caller, resolver=owner.id if resolver == -1 else resolver, text=text, gmail=mailbox,+ ))+++def test_off_by_default_the_reply_waits_on_its_card_alone(db: Path, owner: Any, models: dict[str, Any]) -> None:+ assert inbox.get_watch(owner.id).mailbox_drafts is False+ mailbox, card = _card(owner)+ # Nothing saved in their mailbox.+ assert mailbox.specs == [] and mailbox.drafts == {}+ payload = inbox.card_payload(card)+ assert payload["draft_id"] == "" and payload["card_only"] is True+ assert payload["draft_spec"]["to"] == [DANA] and payload["draft_spec"]["in_reply_to"] == "<[email protected]>"+ # Still counted against the day's limit.+ assert drafts.count_since(owner.id, NOW - timedelta(hours=1)) == 1+ shown = replies.cards(owner)[0]+ assert shown.in_mailbox is False and shown.gmail_link == ""+ # The reconciler has no draft to miss: the card stays.+ assert asyncio.run(inbox.reconcile(owner, mailbox, now=NOW + timedelta(minutes=5), own={OWNER})) == 0+ assert _fresh(card).status == "proposed"+++def test_send_makes_the_draft_from_the_card_and_sends_it(db: Path, owner: Any, models: dict[str, Any]) -> None:+ mailbox, card = _card(owner)+ assert _send(card, mailbox, owner) == "sent-d1"+ spec = mailbox.specs[0]+ assert spec.to == [DANA] and spec.thread_id == "t1" and spec.in_reply_to == "<[email protected]>"+ assert "get back to you shortly" in spec.body+ assert mailbox.sent == ["d1"] and _fresh(card).status == "approved_unchanged"+ # The day's row became that draft, and knows what it was sent as.+ import sqlite3++ with sqlite3.connect(db) as conn:+ rows = conn.execute("SELECT draft_id, sent_message_id FROM delegation_drafts").fetchall()+ assert rows == [("d1", "sent-d1")]+++def test_an_edit_on_the_card_is_what_goes(db: Path, owner: Any, models: dict[str, Any]) -> None:+ mailbox, card = _card(owner)+ before = list(mailbox.calls)+ changed = _edit(card, mailbox, owner, "Hi Dana,\n\nFriday at 10 works. I'll send a new invite.\n\nOlivia\n\n")+ assert changed["draft_body"].endswith("Olivia") and changed["edited_on_card"] is True+ assert replies.cards(owner)[0].draft_body.startswith("Hi Dana,\n\nFriday at 10 works.")+ assert mailbox.calls == before # on the card alone: no mailbox call+ assert _send(card, mailbox, owner) == "sent-d1"+ assert "Friday at 10 works" in mailbox.specs[0].body+ assert _fresh(card).status == "approved_with_edit"+++def test_a_refused_send_takes_the_draft_back(db: Path, owner: Any, models: dict[str, Any]) -> None:+ mailbox, card = _card(owner)+ mailbox.add(_msg("m2", "t1", minutes_ago=10, text="Actually, Monday is better."))+ with pytest.raises(SendRefused) as err:+ _send(card, mailbox, owner)+ assert err.value.code == "confirm"+ # The draft it made for that tap is gone again; the card still holds the reply.+ assert mailbox.deleted == ["d1"] and mailbox.drafts == {}+ assert card_drafts.is_card_only(inbox.card_payload(_fresh(card)))+ # The second yes makes it again and sends it.+ assert _send(card, mailbox, owner, thread_moved_on=True) == "sent-d2"+ assert _fresh(card).status == "approved_unchanged"+++def test_dismiss_has_nothing_to_delete(db: Path, owner: Any, models: dict[str, Any]) -> None:+ mailbox, card = _card(owner)+ assert asyncio.run(replies.dismiss(_fresh(card), gmail=mailbox)) == "card_only"+ assert mailbox.deleted == []+++def test_their_own_reply_closes_a_card_only_reply(db: Path, owner: Any, models: dict[str, Any]) -> None:+ mailbox, card = _card(owner)+ mailbox.add(_msg("s1", "t1", sender=OWNER, to=[DANA], labels=("SENT",), minutes_ago=5))+ assert asyncio.run(inbox.reconcile(owner, mailbox, now=NOW + timedelta(minutes=5), own={OWNER})) == 1+ assert _fresh(card).status == "closed_externally"+++def test_only_its_person_and_only_while_it_waits(db: Path, owner: Any, models: dict[str, Any]) -> None:+ mailbox, card = _card(owner)+ with pytest.raises(SendRefused) as err:+ _edit(card, mailbox, owner, "Hi", resolver=owner.id + 1)+ assert err.value.code == "not_yours"+ with pytest.raises(SendRefused) as err:+ _edit(card, mailbox, owner, "Hi", caller=Caller("user", "[email protected]"))+ assert err.value.code == "not_yours"+ with pytest.raises(SendRefused) as err:+ _edit(card, mailbox, owner, " \n")+ assert err.value.code == "empty"+ _send(card, mailbox, owner)+ with pytest.raises(SendRefused) as err:+ _edit(card, mailbox, owner, "Too late")+ assert err.value.code == "already_handled"+++def test_in_the_mailbox_an_edit_rewrites_the_draft_there(db: Path, owner: Any, models: dict[str, Any]) -> None:+ inbox.set_mailbox_drafts(owner.id, True, updated_by="test")+ mailbox, card = _card(owner)+ assert list(mailbox.drafts) == ["d1"] and replies.cards(owner)[0].in_mailbox is True+ _edit(card, mailbox, owner, "Friday works.")+ assert mailbox.drafts["d1"].message.text == "Friday works."+ # A second edit starts from the version the first one left.+ _edit(card, mailbox, owner, "Friday at 10 works.")+ assert mailbox.drafts["d1"].message.text == "Friday at 10 works."+ # Changed in the mailbox since: never overwritten from the card.+ mailbox.edit("d1")+ with pytest.raises(SendRefused) as err:+ _edit(card, mailbox, owner, "Monday works.")+ assert err.value.code == "draft_changed"+ assert mailbox.drafts["d1"].message.text == "Friday at 10 works."+++def test_an_edited_mailbox_draft_dismissed_on_its_card_is_deleted(+ db: Path, owner: Any, models: dict[str, Any]+) -> None:+ inbox.set_mailbox_drafts(owner.id, True, updated_by="test")+ mailbox, card = _card(owner)+ _edit(card, mailbox, owner, "Friday works.")+ assert asyncio.run(replies.dismiss(_fresh(card), gmail=mailbox)) == "deleted"+++def test_the_setting_is_kept_while_the_switch_is_off(db: Path, owner: Any) -> None:+ inbox.set_mailbox_drafts(owner.id, True, updated_by="test")+ inbox.set_watch(owner.id, False, updated_by="test")+ inbox.set_watch(owner.id, True, updated_by="test")+ assert inbox.get_watch(owner.id).mailbox_drafts is True+++def test_one_change_at_a_time(db: Path, owner: Any, models: dict[str, Any]) -> None:+ """A second save while the first is still being written is refused before+ it touches the mailbox, so the card and the draft never disagree."""+ inbox.set_mailbox_drafts(owner.id, True, updated_by="test")+ mailbox, card = _card(owner)+ card_drafts._EDITING.add(card.id)+ try:+ with pytest.raises(SendRefused) as err:+ _edit(card, mailbox, owner, "Friday works.")+ assert err.value.code == "busy" and "update:d1" not in mailbox.calls+ finally:+ card_drafts._EDITING.discard(card.id)+ _edit(card, mailbox, owner, "Friday works.")+ assert card.id not in card_drafts._EDITINGdiff --git a/packages/core/tests/unit/test_delegation_gmail.py b/packages/core/tests/unit/test_delegation_gmail.pyindex 5c8161d4..2d4607e2 100644--- a/packages/core/tests/unit/test_delegation_gmail.py+++ b/packages/core/tests/unit/test_delegation_gmail.py@@ -336,6 +336,8 @@ def test_the_only_send_is_an_existing_draft_by_its_id() -> None:# The inbox watcher: reads, and deleting a draft it wrote."list_message_ids", "inbox_message_ids", "has_written_to", "get_message", "send_as_addresses","get_draft", "delete_draft",+ # Changing a reply's words from its card (delegation.card_drafts); sends nothing.+ "update_draft_text",# Chat's reads of their own mailbox (orchestrator.mail_read_tools)."list_attachments", "attachment_bytes",# Send on the person's tap (delegation.reply_send).@@ -368,6 +370,42 @@ def test_send_draft_sends_the_draft_by_its_id_and_nothing_else() -> None:asyncio.run(client.send_draft("d1/../../messages"))+def test_update_draft_text_keeps_every_header_and_only_the_version_it_saw() -> None:+ from email import message_from_bytes, policy++ from openexecutive.delegation.gmail import DraftChanged, build_raw++ raw = build_raw(EMAIL, DraftSpec(+ to=["[email protected]"], cc=["[email protected]"], subject="Re: Pilot", body="Yes.",+ thread_id="t1", in_reply_to="<[email protected]>", references="<[email protected]> <[email protected]>",+ ))+ google = FakeGoogle()+ puts: list[dict[str, Any]] = []++ def handler(request: httpx.Request) -> httpx.Response:+ if request.url.path.endswith("/drafts/d1") and request.method == "GET":+ assert request.url.params["format"] == "raw"+ return httpx.Response(200, json={"id": "d1", "message": {"id": "m9", "threadId": "t1", "raw": raw}})+ if request.url.path.endswith("/drafts/d1") and request.method == "PUT":+ puts.append(json.loads(request.content))+ return httpx.Response(200, json={"id": "d1", "message": {"id": "m10", "threadId": "t1"}})+ return FakeGoogle.handler(google, request)++ client = DelegateGmail(EMAIL, credential=_cred(), transport=httpx.MockTransport(handler))+ assert asyncio.run(client.update_draft_text("d1", "m9", "Yes, Thursday works.")) == "m10"+ sent = puts[0]+ assert sent["id"] == "d1" and sent["message"]["threadId"] == "t1"+ msg = message_from_bytes(base64.urlsafe_b64decode(sent["message"]["raw"]), policy=policy.default)+ assert msg["To"] == "[email protected]" and msg["Cc"] == "[email protected]"+ assert msg["Subject"] == "Re: Pilot" and msg["In-Reply-To"] == "<[email protected]>"+ assert msg["References"] == "<[email protected]> <[email protected]>"+ assert msg.get_content().strip() == "Yes, Thursday works."+ # Changed in Gmail since the card saw it: never overwritten.+ with pytest.raises(DraftChanged) as err:+ asyncio.run(client.update_draft_text("d1", "m8", "No."))+ assert err.value.reason == "changed" and len(puts) == 1++@pytest.mark.parametrize(("response", "maybe_done"), [(httpx.Response(500, json={}), True),(httpx.Response(503, json={}), True),diff --git a/packages/core/tests/unit/test_delegation_inbox.py b/packages/core/tests/unit/test_delegation_inbox.pyindex a4ed6edc..f47ddd36 100644--- a/packages/core/tests/unit/test_delegation_inbox.py+++ b/packages/core/tests/unit/test_delegation_inbox.py@@ -151,6 +151,19 @@ class FakeInbox:self.drafts[f"d{n}"] = DraftInfo(draft_id=f"d{n}", message=draft_message)return CreatedDraft(draft_id=f"d{n}", message_id=f"dm{n}", thread_id=draft_message.thread_id)+ async def update_draft_text(self, draft_id: str, expected_version: str, text: str) -> str:+ from openexecutive.delegation.gmail import DraftChanged++ self.calls.append(f"update:{draft_id}")+ info = self.drafts.get(draft_id)+ if info is None:+ raise GmailNotFound("404")+ if info.message.id != expected_version:+ raise DraftChanged("changed")+ info.message.id = info.message.id + "-card"+ info.message.text = text+ return info.message.id+# What the owner does in Gmail itself.def edit(self, draft_id: str, *, cc: list[str] | None = None, bcc: list[str] | None = None,to: list[str] | None = None) -> None:@@ -219,6 +232,9 @@ def owner() -> Any:people_registry.invalidate()set_enabled(pid, True, updated_by="test")inbox.set_watch(pid, True, updated_by="test", now=NOW - timedelta(days=1))+ # These tests follow replies saved in the mailbox's Drafts too; replies+ # kept on their card alone (the default) are test_delegation_card_drafts.py's.+ inbox.set_mailbox_drafts(pid, True, updated_by="test")return people_store.get_person(pid)diff --git a/packages/core/tests/unit/test_delegation_inbox_routes.py b/packages/core/tests/unit/test_delegation_inbox_routes.pyindex 33ba0a32..ae97c3fd 100644--- a/packages/core/tests/unit/test_delegation_inbox_routes.py+++ b/packages/core/tests/unit/test_delegation_inbox_routes.py@@ -127,6 +127,7 @@ def _card(owner_id: int, monkeypatch: pytest.MonkeyPatch) -> tuple[FakeInbox, inmonkeypatch.setattr(gw, "_call_model", composer)set_enabled(owner_id, True, updated_by="t")inbox.set_watch(owner_id, True, updated_by="t", now=datetime(2026, 9, 29, tzinfo=UTC))+ inbox.set_mailbox_drafts(owner_id, True, updated_by="t")mailbox = FakeInbox()mailbox.add(_msg("m1", "t1"))person = people_store.get_person(owner_id)@@ -225,3 +226,35 @@ def test_send_and_allow_through_decisions(assert resp.status_code == 200 and mailbox.sent == ["d1"]assert training.example_for(ids["principal"], "[email protected]") == "Dana, Friday is great."assert training.allowed_sender(ids["principal"], "[email protected]") is not None+++def test_keeping_replies_in_the_mailbox_is_the_callers_own_choice_and_off_by_default(+ client: TestClient, ids: dict[str, int]+) -> None:+ set_enabled(ids["principal"], True, updated_by="t")+ body = client.put("/delegation/inbox", json={"enabled": True}, headers=OWNER).json()+ assert body["inbox"]["mailbox_drafts"] is False+ body = client.put("/delegation/inbox", json={"mailbox_drafts": True}, headers=OWNER).json()+ assert body["inbox"]["mailbox_drafts"] is True and body["inbox"]["enabled"] is True+ assert client.put("/delegation/inbox", json={}, headers=OWNER).status_code == 422+ assert client.put("/delegation/inbox", json={"mailbox_drafts": True}, headers=TEAMMATE).status_code == 403+ assert inbox.get_watch(ids["teammate"]).mailbox_drafts is False+++def test_changing_a_replys_words_on_its_card(+ client: TestClient, ids: dict[str, int], monkeypatch: pytest.MonkeyPatch+) -> None:+ mailbox, card_id = _card(ids["principal"], monkeypatch)+ monkeypatch.setattr("openexecutive.delegation.gmail.gmail_for", lambda email: mailbox)+ url = f"/delegation/replies/{card_id}/text"+ # Like Send: only a caller the API can tie to the person.+ resp = client.put(url, json={"text": "Friday at 10 works."}, headers=OWNER)+ assert resp.status_code == 409 and resp.json()["detail"]["code"] == "caller_signing_required"+ monkeypatch.setenv("OE_LOCAL_LOGIN", "1")+ assert client.put(url, json={"text": "Friday at 10 works."}, headers=TEAMMATE).status_code == 403+ resp = client.put(url, json={"text": "Friday at 10 works."}, headers=OWNER)+ assert resp.status_code == 200 and resp.json()["draft_body"] == "Friday at 10 works."+ # It was in their Drafts too (this test's setting): changed there as well.+ assert mailbox.drafts["d1"].message.text == "Friday at 10 works."+ assert client.put(url, json={"text": "x" * 20_001}, headers=OWNER).status_code == 422+ assert client.put("/delegation/replies/9999/text", json={"text": "Hi"}, headers=OWNER).status_code == 404diff --git a/packages/core/tests/unit/test_delegation_outlook.py b/packages/core/tests/unit/test_delegation_outlook.pyindex 549935e1..034349df 100644--- a/packages/core/tests/unit/test_delegation_outlook.py+++ b/packages/core/tests/unit/test_delegation_outlook.py@@ -600,6 +600,52 @@ def test_a_draft_sent_while_it_is_being_deleted_is_left_alone() -> None:assert "d1" in graph.messages+def test_update_draft_text_changes_only_the_version_it_saw() -> None:+ from openexecutive.delegation.gmail import DraftChanged++ graph = FakeGraph()+ graph.messages["d1"] = _msg("d1", isDraft=True)+ client = graph.client()+ seen = ol.draft_version("d1", "ck1")+ version = asyncio.run(client.update_draft_text("d1", seen, "Friday at 10 works."))+ assert version == ol.draft_version("d1", "ck1x")+ patch = next(r for r in graph.graph_calls() if r.method == "PATCH")+ assert json.loads(patch.content) == {"body": {"contentType": "text", "content": "Friday at 10 works."}}+ assert patch.headers["If-Match"] == 'W/"ck1"'+ # Changed in Outlook since the card saw it: never overwritten.+ with pytest.raises(DraftChanged) as err:+ asyncio.run(client.update_draft_text("d1", seen, "Monday."))+ assert err.value.reason == "changed"+ assert graph.messages["d1"]["body"]["content"] == "Friday at 10 works."++[email protected]("fields", [+ {"hasAttachments": True},+ {"body": {"contentType": "html", "content": "<p>Hi</p>"}},+])+def test_update_draft_text_leaves_a_draft_with_files_or_formatting(fields: dict[str, Any]) -> None:+ from openexecutive.delegation.gmail import DraftChanged++ graph = FakeGraph()+ graph.messages["d1"] = _msg("d1", isDraft=True, **fields)+ with pytest.raises(DraftChanged) as err:+ asyncio.run(graph.client().update_draft_text("d1", ol.draft_version("d1", "ck1"), "Hi"))+ assert err.value.reason == "not_plain"+ assert not any(r.method == "PATCH" for r in graph.graph_calls())+++def test_update_draft_text_changed_between_read_and_write_is_refused() -> None:+ """A 412 on the PATCH (If-Match) means someone changed it meanwhile."""+ from openexecutive.delegation.gmail import DraftChanged++ graph = FakeGraph()+ graph.messages["d1"] = _msg("d1", isDraft=True)+ graph.fail["PATCH /messages/d1"] = 412+ with pytest.raises(DraftChanged) as err:+ asyncio.run(graph.client().update_draft_text("d1", ol.draft_version("d1", "ck1"), "Hi"))+ assert err.value.reason == "changed"++def test_send_draft_sends_the_draft_by_its_id_and_nothing_else() -> None:graph = FakeGraph()graph.messages["d1"] = _msg("d1", isDraft=True)diff --git a/packages/core/tests/unit/test_delegation_reply_send.py b/packages/core/tests/unit/test_delegation_reply_send.pyindex 7ffc5625..477c3927 100644--- a/packages/core/tests/unit/test_delegation_reply_send.py+++ b/packages/core/tests/unit/test_delegation_reply_send.py@@ -418,14 +418,21 @@ def test_only_the_send_path_sends_and_only_the_approve_route_and_the_watcher_reaassert _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 _importers("openexecutive.delegation.reply_send") == {"api/routes/decisions.py", "delegation/inbox.py"}+ # card_drafts and the edit route 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",+ }def test_only_dismiss_deletes_a_draft() -> None:"""Dismiss deletes an unedited draft; the watcher takes back only one ithas just made, when that draft's card couldn't be made (a follow-up's- too), or an unedited follow-up nobody needs once the thread is answered."""- assert _uses("delete_draft") == {"delegation/replies.py", "delegation/inbox.py", "delegation/follow_ups.py"}+ too), or an unedited follow-up nobody needs once the thread is answered,+ and a reply kept on its card takes back the draft it made for a send that+ was refused before anything went."""+ assert _uses("delete_draft") == {+ "delegation/replies.py", "delegation/inbox.py", "delegation/follow_ups.py", "delegation/card_drafts.py",+ }assert _importers("openexecutive.delegation.replies") == {"api/routes/decisions.py", "api/routes/delegation.py"}diff --git a/packages/ui/scripts/replyCards.test.mjs b/packages/ui/scripts/replyCards.test.mjsindex ab0eda7f..4e32b005 100644--- a/packages/ui/scripts/replyCards.test.mjs+++ b/packages/ui/scripts/replyCards.test.mjs@@ -78,6 +78,11 @@ test("sendQuestion names who the reply goes to", () => {"Send this reply to [email protected], [email protected] from your Gmail, exactly as the draft is there?",);assert.match(sendQuestion([]), /to the sender/);+ // Kept on its card alone: it goes as the card shows it.+ assert.equal(+ sendQuestion(["[email protected]"], "Outlook", false),+ "Send this reply to [email protected] from your Outlook, as shown above?",+ );});test("a failed send says whether the card is gone", () => {diff --git a/packages/ui/src/components/Briefing.tsx b/packages/ui/src/components/Briefing.tsxindex fc9b22e7..da78b2ba 100644--- a/packages/ui/src/components/Briefing.tsx+++ b/packages/ui/src/components/Briefing.tsx@@ -545,7 +545,13 @@ export default function Briefing({ onContinue, showHeader = false, firstName, ba...replies.cards.map((card) => ({key: `reply-${card.decision_id}`,render: (emphasized: boolean) => (- <ReplyCardItem card={card} onGone={replies.gone} onRefresh={replies.refresh} emphasized={emphasized} />+ <ReplyCardItem+ card={card}+ onGone={replies.gone}+ onRefresh={replies.refresh}+ onChanged={replies.replace}+ emphasized={emphasized}+ />),})),...actionCards.cards.map((card) => ({diff --git a/packages/ui/src/components/RepliesWaiting.tsx b/packages/ui/src/components/RepliesWaiting.tsxindex b823a766..fe29c7e0 100644--- a/packages/ui/src/components/RepliesWaiting.tsx+++ b/packages/ui/src/components/RepliesWaiting.tsx@@ -5,6 +5,7 @@ import { useCallback, useEffect, useState } from "react";import Button, { buttonClass } from "@/components/ui/Button";import {dismissReplyCard,+ editReplyText,getReplyCards,ReplySendError,sendReplyCard,@@ -24,15 +25,17 @@ import {} from "@/lib/replyCards";import FeatureName from "@/components/FeatureName";-// Home: the replies the Executive drafted in your own Gmail for mail that-// needs you (Delegate → Act as me → Draft replies to my inbox), shown as-// cards in "Needs you". Each card shows who wrote, what they wrote, the-// draft, what it leaves you to decide and anything to check. Send (the-// card's primary) sends that draft from your Gmail exactly as it is there,-// after you confirm who it goes to; Edit in Gmail and Dismiss (deletes it-// unless you edited it) are their own buttons beside it. GET /delegation/replies answers-// only the owner, so nothing shows for everyone else, on a backend without-// it, and when nothing is waiting.+// Home: the replies the Executive wrote as you for mail that needs you+// (Delegate → Act as me → Draft replies to my inbox), shown as cards in+// "Needs you". Each card shows who wrote, what they wrote, the draft, what it+// leaves you to decide and anything to check. The reply waits on the card+// alone unless you chose to keep replies in your Drafts too. Edit changes its+// words right on the card (and in your Drafts when it's there:+// PUT /delegation/replies/{id}/text). Send (the card's primary) sends it from+// your own mailbox after you confirm who it goes to; Open in Gmail (when it's+// in your Drafts) and Dismiss are their own buttons beside it.+// GET /delegation/replies answers only the owner, so nothing shows for+// everyone else, on a backend without it, and when nothing is waiting.// While a send Gmail hasn't confirmed is being settled (the card is// "executing"), how often the cards are read again.@@ -74,15 +77,20 @@ export function useReplyCards() {setNotice(note ?? null);}, []);- return { cards: cards ?? [], notice, gone, refresh };+ // A card changed in place (its words edited).+ const replace = useCallback((card: ReplyCard) => {+ setCards((prev) => (prev ?? []).map((c) => (c.decision_id === card.decision_id ? card : c)));+ }, []);++ return { cards: cards ?? [], notice, gone, refresh, replace };}// What the Replies-waiting cards are, for the Needs you header's tip.export const REPLIES_WAITING_TIP =- "Mail that needs you, with a first reply the Executive wrote in your voice. Each " +- "draft is in your own Drafts, and nothing is sent until you tap Send: it sends that " +- "draft exactly as it is in your mailbox, so edit it there first if you want to change it. " +- "Dismiss deletes the draft, unless you've edited it there. Only you see these.";+ "Mail that needs you, with a first reply the Executive wrote in your voice. Tap Edit to " ++ "change or add to it right here. Nothing is sent until you tap Send. If you keep replies " ++ "in your Drafts too, Dismiss deletes that draft unless you changed it in your mailbox. " ++ "Only you see these.";// What the row is doing: idle, asking before sending (first or second// time), or waiting on the backend.@@ -98,16 +106,20 @@ export function ReplyCardItem({card,onGone,onRefresh,+ onChanged,emphasized = false,}: {card: ReplyCard;emphasized?: boolean;onGone: (id: number, note?: string) => void;onRefresh: () => Promise<void>;+ onChanged?: (card: ReplyCard) => void;}) {const [step, setStep] = useState<Step>({ kind: "idle" });const [error, setError] = useState<string | null>(null);const [fullDraft, setFullDraft] = useState(false);+ // Edit: the draft's words in a box on the card, until Save or Cancel.+ const [editing, setEditing] = useState<string | null>(null);// Drafts in training: keep what you sent as an example when you changed it first.const [keepExample, setKeepExample] = useState(true);const learnsStyle = Boolean(card.learns_style);@@ -118,7 +130,9 @@ export function ReplyCardItem({const warnings = replyFlagLines(card.flags);const received = formatRelativeTime(card.received_at);const gmailLink = safeGmailLink(card.gmail_link);- const mailbox = mailboxName(card.gmail_link);+ const mailbox = card.mailbox || mailboxName(card.gmail_link);+ // Kept in their Drafts too, or on this card alone until Send.+ const inMailbox = card.in_mailbox !== false;const who = card.from_name.trim() || card.from_email;const followUp = card.source === "follow_up";@@ -134,6 +148,21 @@ export function ReplyCardItem({}};+ const saveEdit = async () => {+ if (editing === null) return;+ setStep({ kind: "busy", label: "Saving…" });+ setError(null);+ try {+ const updated = await editReplyText(card.decision_id, editing);+ onChanged?.(updated);+ setEditing(null);+ } catch (err) {+ setError(err instanceof Error ? err.message : "Couldn't save your change.");+ } finally {+ setStep({ kind: "idle" });+ }+ };+const send = async (confirm: { recipients: string[]; thread_moved_on?: boolean }, allow: boolean) => {setStep({ kind: "busy", label: "Sending…" });setError(null);@@ -227,6 +256,33 @@ export function ReplyCardItem({<div className="mt-3"><div className={label}>Your draft</div>+ {editing !== null ? (+ <div className="mt-1.5">+ <div className="px-1 text-xs text-fg-subtle break-words">To: {card.draft_to.join(", ")}</div>+ <textarea+ aria-label="Your draft"+ rows={9}+ value={editing}+ disabled={busy}+ autoFocus+ onChange={(e) => setEditing(e.target.value)}+ className="mt-1 w-full resize-y whitespace-pre-wrap rounded-xl border border-line-strong bg-surface p-3 text-[15px] leading-relaxed text-fg focus:outline-none focus:ring-2 focus:ring-accent/40 disabled:opacity-50"+ />+ <p className="mt-1 px-1 text-xs text-fg-subtle">+ {inMailbox+ ? `Saving changes the draft in your ${mailbox} too. Nothing is sent until you tap Send.`+ : "Nothing is sent until you tap Send."}+ </p>+ <div className="mt-2 flex flex-wrap items-center gap-2">+ <Button variant="primary" onClick={() => void saveEdit()} disabled={busy || !editing.trim()}>+ {busy ? step.label : "Save"}+ </Button>+ <Button variant="ghost" onClick={() => setEditing(null)} disabled={busy}>+ Cancel+ </Button>+ </div>+ </div>+ ) : (<div className="mt-1.5 rounded-xl border border-line bg-surface px-3 py-2"><div className="text-xs text-fg-subtle break-words">To: {card.draft_to.join(", ")}</div><p@@ -247,6 +303,7 @@ export function ReplyCardItem({</button>)}</div>+ )}</div>{card.waited_because && (@@ -282,7 +339,7 @@ export function ReplyCardItem({{step.kind === "confirm" && (<p className="text-sm text-amber-700 dark:text-amber-300">{step.message}</p>)}- <p className="text-sm text-fg">{sendQuestion(step.recipients, mailbox)}</p>+ <p className="text-sm text-fg">{sendQuestion(step.recipients, mailbox, inMailbox)}</p>{step.allow && (<p className="mt-2 text-sm text-fg">From now on, {followUp ? "follow-ups" : "replies"} to {who} go on their own while Handle it for me is@@ -297,7 +354,7 @@ export function ReplyCardItem({onChange={(e) => setKeepExample(e.target.checked)}className="h-4 w-4 accent-accent"/>- Do it like this next time (if you changed it in {mailbox})+ Do it like this next time (if you changed it)</label>)}<div className="mt-3 flex flex-wrap items-center gap-2">@@ -319,7 +376,7 @@ export function ReplyCardItem({</Button></div></div>- ) : (+ ) : editing !== null ? null : (<div className="mt-4 flex flex-wrap items-center gap-2"><Buttonvariant="primary"@@ -337,14 +394,24 @@ export function ReplyCardItem({Send + allow</Button>)}+ <Button+ variant="secondary"+ onClick={() => {+ setError(null);+ setEditing(card.draft_body);+ }}+ disabled={busy}+ >+ Edit+ </Button>{gmailLink && (<ahref={gmailLink}target="_blank"rel="noopener noreferrer"- className={buttonClass("secondary")}+ className={buttonClass("ghost")}>- Edit in {mailbox}+ Open in {mailbox}</a>)}{/* Dismiss is its own button, set apart on the right, so it's neverdiff --git a/packages/ui/src/components/settings/ActAsMeCard.tsx b/packages/ui/src/components/settings/ActAsMeCard.tsxindex a9a35ce5..40e441c7 100644--- a/packages/ui/src/components/settings/ActAsMeCard.tsx+++ b/packages/ui/src/components/settings/ActAsMeCard.tsx@@ -279,6 +279,7 @@ export default function ActAsMeCard({inbox={stoppedWaiting ? { ...settings.inbox, checking: false } : settings.inbox}actAsMeOn={on}handleItOn={!!settings.handle_it?.enabled}+ mailbox={settings.gmail?.provider === "microsoft" ? "Outlook" : "Gmail"}onSettings={setSettings}onInbox={(inbox) => {setStoppedWaiting(false);@@ -367,12 +368,14 @@ function InboxSection({inbox,actAsMeOn,handleItOn,+ mailbox,onSettings,onInbox,}: {inbox: InboxWatch;actAsMeOn: boolean;handleItOn: boolean;+ mailbox: string;onSettings: (next: DelegationSettings) => void;onInbox: (next: InboxWatch) => void;}) {@@ -384,7 +387,21 @@ function InboxSection({setBusy(true);setError(null);try {- onSettings(await setInboxWatch(!on));+ onSettings(await setInboxWatch({ enabled: !on }));+ } catch (err) {+ setError(err instanceof Error ? err.message : "Could not save the setting.");+ } finally {+ setBusy(false);+ }+ };++ // Also keep each reply in their mailbox's Drafts (off: on its card alone).+ const inDrafts = !!inbox.mailbox_drafts;+ const keepInDrafts = async (next: boolean) => {+ setBusy(true);+ setError(null);+ try {+ onSettings(await setInboxWatch({ mailbox_drafts: next }));} catch (err) {setError(err instanceof Error ? err.message : "Could not save the setting.");} finally {@@ -412,8 +429,8 @@ function InboxSection({description={on? handleItOn- ? "When mail comes in that needs you, it writes a first reply in your Drafts. Handle it for me, on the next tab, sends the simple ones; the rest wait on Today, where you send, edit or dismiss them."- : "When mail comes in that needs you, it writes a first reply in your Drafts and puts it on Today, where you send it, edit it in your mailbox or dismiss it. Nothing is sent until you tap Send."+ ? "When mail comes in that needs you, it writes a first reply. Handle it for me, on the next tab, sends the simple ones; the rest wait on Today, where you send, edit or dismiss them."+ : "When mail comes in that needs you, it writes a first reply and puts it on Today, where you can edit it, send it or dismiss it. Nothing is sent until you tap Send.": actAsMeOn? "Off: it only drafts when you ask it to in chat.": "Turn on Write drafts as me first."@@ -438,6 +455,25 @@ function InboxSection({</Button></div>)}+ {on && (+ <label className="mt-4 flex cursor-pointer items-start gap-3 border-t border-line pt-4">+ <input+ type="checkbox"+ checked={inDrafts}+ disabled={busy}+ onChange={(e) => void keepInDrafts(e.target.checked)}+ className="mt-0.5 h-5 w-5 flex-shrink-0 accent-indigo-500"+ />+ <span>+ <span className="block text-[15px] font-semibold text-fg">Also save replies in my {mailbox} Drafts</span>+ <span className="mt-0.5 block text-sm text-fg-muted leading-snug">+ {inDrafts+ ? `Each reply is in your ${mailbox} Drafts too, so you can open it there.`+ : `Off: replies wait on their cards only, so your ${mailbox} Drafts stay clear.`}+ </span>+ </span>+ </label>+ )}{error && <p className="mt-2 text-sm text-red-500">{error}</p>}</SettingsCard>);diff --git a/packages/ui/src/lib/api.ts b/packages/ui/src/lib/api.tsindex fcc388ba..7e21d29a 100644--- a/packages/ui/src/lib/api.ts+++ b/packages/ui/src/lib/api.ts@@ -1568,6 +1568,8 @@ export interface InboxWatch {watch_since: string | null;last_poll_at: string | null;checking: boolean;+ // Also save each reply in your mailbox's Drafts (off: on its card alone).+ mailbox_drafts?: boolean;}// Handle it for me: the inbox watcher sends some replies on its own,@@ -1662,6 +1664,11 @@ export interface ReplyCard {can_allow?: boolean;// Drafts in training: "Do it like this next time" keeps your changed draft.learns_style?: boolean;+ // Also saved in your mailbox's Drafts; false when it waits on this card+ // alone until you send it.+ in_mailbox?: boolean;+ // Which of your mailboxes it sends from: "Gmail" or "Outlook".+ mailbox?: string;}// "How I write": learned from your own sent mail; you can edit and lock it.@@ -1806,16 +1813,30 @@ export async function setDelegationTeam(enabled: boolean): Promise<DelegationSetreturn res.json();}-export async function setInboxWatch(enabled: boolean): Promise<DelegationSettings> {+export async function setInboxWatch(+ update: { enabled?: boolean; mailbox_drafts?: boolean },+): Promise<DelegationSettings> {const res = await fetch(`${API_BASE}/delegation/inbox`, {method: "PUT",headers: { "Content-Type": "application/json" },- body: JSON.stringify({ enabled }),+ body: JSON.stringify(update),});if (!res.ok) throw await delegationError(res, "Couldn't change Draft replies to my inbox.");return res.json();}+// Change a waiting reply's words before Send: on its card, and in your+// mailbox's Drafts when it's there too. Sends nothing.+export async function editReplyText(id: number, text: string): Promise<ReplyCard> {+ const res = await fetch(`${API_BASE}/delegation/replies/${id}/text`, {+ method: "PUT",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ text }),+ });+ if (!res.ok) throw await delegationError(res, "Couldn't save your change.");+ return (await res.json()) as ReplyCard;+}+// Forget one thing it learned in training: it asks again from now on.export async function removeTrainingLearned(id: number): Promise<DelegationSettings> {const res = await fetch(`${API_BASE}/delegation/learned/${id}`, { method: "DELETE" });diff --git a/packages/ui/src/lib/replyCards.ts b/packages/ui/src/lib/replyCards.tsindex 52c1e6ed..899bdd8f 100644--- a/packages/ui/src/lib/replyCards.ts+++ b/packages/ui/src/lib/replyCards.ts@@ -89,10 +89,14 @@ export function mailboxName(link: string): string {return link.startsWith("https://outlook.") ? "Outlook" : "Gmail";}-/** The first Send's question: who it goes to, from where. */-export function sendQuestion(recipients: readonly string[], mailbox = "Gmail"): string {+/** The first Send's question: who it goes to, from where. A reply saved in+ * their mailbox goes exactly as the draft is there; one kept on its card+ * alone goes as the card shows it. */+export function sendQuestion(recipients: readonly string[], mailbox = "Gmail", inMailbox = true): string {const to = recipients.length ? recipients.join(", ") : "the sender";- return `Send this reply to ${to} from your ${mailbox}, exactly as the draft is there?`;+ return inMailbox+ ? `Send this reply to ${to} from your ${mailbox}, exactly as the draft is there?`+ : `Send this reply to ${to} from your ${mailbox}, as shown above?`;}// Send refusals after which the card is gone for good: its draft was sent or