AI-powered virtual executive team — a single coherent executive persona backed by 8 specialist agents (FastAPI + Next.js).
fix(delegation): stop drafting inbox replies to group emails that ask someone else (#343)
Rufus5da0b29821e5
diff --git a/packages/core/openexecutive/architecture/architecture-facts.yaml b/packages/core/openexecutive/architecture/architecture-facts.yamlindex 66d72131..cc1d882e 100644--- a/packages/core/openexecutive/architecture/architecture-facts.yaml+++ b/packages/core/openexecutive/architecture/architecture-facts.yaml@@ -8795,6 +8795,12 @@ delegation:be (payload relation) beside handled_as.fyi, thanks, pitch, notification, newsletter, phishing and other neverget one, and any failure or malformed answer means none.+ A group email (anyone else in To or Cc besides the sender and the+ Executive) is drafted for only when the person is in To and the+ classifier's asked_of_them is true: it names or greets them, not someone+ else by name or the group at large. The classifier is told the person's+ name, To or Cc, and how many others; a Cc-only person never gets a+ draft. Recorded not_needed / asks_someone_else.inbox_drafting: |delegation.inbox.compose_reply — ghostwriter.compose and the person'svoice block unchanged, with a constant intent in place of a person's.@@ -8813,8 +8819,11 @@ delegation:can't answer from their words goes in open_questions), orINBOX_HOLDING_INTENT for a stranger (a short thank-you-I'll-get-backholding reply, answering nothing). lint still strips any link or- address that is not the person's own. The reply goes to the sender only- (threads.plan_reply with reply_all off, Reply-To ignored); the card is+ address that is not the person's own. The reply goes to the sender and, on+ a group email, Cc to everyone else it went to (threads.plan_reply with+ reply_all on, minus the person's own addresses and the Executive; a+ stranger's holding reply has reply_all off; Reply-To ignored; draft_to+ lists everyone and Send checks it); the card isflagged others_on_thread when anyone else was addressed,executive_on_thread when the Executive was, and sender_unverified whenGmail's SPF/DKIM/DMARC results don't vouch for the From addressdiff --git a/packages/core/openexecutive/architecture/prebuilt/delegation.json b/packages/core/openexecutive/architecture/prebuilt/delegation.jsonindex 4a438201..f0eea658 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; chat never sends. The principal can turn it on for themselves, and so can each team member once the owner lets them. It is off by default, and off changes nothing: the prompts, tool lists and prompt caches are byte-identical to an install without it.\n\n## Who can have it, and when it is offered\n\n`delegation.settings.can_delegate(person)` is the single rule for who may turn it on: the principal (a non-archived team member flagged `is_principal`), and any other non-archived team member — never a contact — once team members may have it (`team_members_enabled`). That takes two things: the install allows it (`DELEGATION_TEAM_MEMBERS`, default off, which offers the owner the switch) and the owner turned on **Let team members use it** (`PUT /delegation/team`, principal only, one row in `delegation_team`). Turning the owner's switch off takes it away from every team member from their next message, and their inbox watchers stop at their next check; their own switches, drafts and cards are kept. Everything is keyed by `person_id`. A person turns it on for themselves (`PUT /delegation`); nobody turns it on for anyone else. The setting is one row per person in `delegation_settings`, and a missing, unreadable or zero row all mean off.\n\nAt the start of every chat turn (`Executive.stream_chat` and the committee path) `pin_turn_delegation(session, speaker_text)` runs next to the workspace-mode pin and records a `TurnDelegation` on the session. `ghostwrite_email` is **offered** only when all of these hold:\n\n- the speaker may have it and turned it on — read fresh every turn, so turning it off applies from the next message;\n- the speaker is on a surface that verified it is them — the principal through `people_tools.is_principal_on_verified_surface`, a team member through `teammate_on_verified_surface` (the web app signed in, their own Slack or Discord, never an email turn) — and a web turn also carried a signed-in caller (`Session.web_caller_signed_in`, set from `x-caller-email`) or runs under local login — a request with no caller header is not a sign-in and never gets it (whoever holds the shared secret is trusted as the UI proxy that stamps that header, as on every principal-only route);\n- the conversation is private to the speaker: the web chat, a Slack or Discord DM, or a verified private Telegram chat — never a shared channel or thread, where the draft's preview or the matching threads would be posted for everyone and other people's messages sit in the model's context;\n- the turn is neither unattended (the scheduler's proactive run) nor private to the principal (the email poller's turns), so inbound text can never reach it. The MCP server, workflows, reflection and research never carry it at all.\n\nThe mailbox connection is deliberately **not** part of the offer: the handler checks it on every call and says how to fix it, so the cached tool prefix never flips when a token lapses. The pin lives in a context variable for the turn's task as well as on the session, so two turns running at once on one session (a second browser tab) each read their own. It also carries the speaker's own words for the turn (a new email may go to an address they just typed — the turn's message joins the history only once the turn ends), a per-turn draft count, and `touched_mail` (see Privacy). `own_words` reads those words back for every own-words check (addresses here, facts and task assignments elsewhere): it first removes the hydrated `<outbound_reply_context>` backstory by its exact, anchored shape, so a look-alike closing tag quoted inside it cannot pass the rest off as the speaker's, then drops other adapter tag blocks, and returns nothing for a message carrying an attachment.\n\n## The tool: `ghostwrite_email`\n\nIt lives in its own registry (`orchestrator.delegation_tools.DELEGATION_TOOLS` / `DELEGATION_TOOL_HANDLERS`), **never** `_ALL_SKILL_TOOLS`, so no other toolkit can carry it. On a turn it is offered to, the agent loop adds it to the pool *before* the sort and builds that turn's handler map from both registries; on any other turn a call to it is an unknown tool. The handler re-checks the pin and the surface anyway, then:\n\n1. **Caps** — at most 5 drafts per turn, and `DELEGATION_MAX_DRAFTS_PER_DAY` (default 50, at most 1000) per person per UTC day, shared with the inbox watcher (`delegation.caps`). It is counted from `delegation_drafts`, one row of ids per draft saved from either place, with a count kept in the process as a floor in case a row was lost. Each slot is taken before the first await — a round's tool calls run concurrently, so otherwise every call in it would pass the caps before any counted — and handed back if nothing was drafted. If the rows can't be read it refuses rather than guess.\n2. **Marks the turn** — sets `TurnDelegation.touched_mail` *before* its first read of the mailbox.\n3. **Checks the mailbox** — `gmail_status` asks Google or Microsoft whose mailbox the credential opens and compares it with the person's People email, on every call: a roster email can change, and a client slot swaps the roster.\n4. **Finds the thread** — by `thread_id` (checked against the mailbox's own id shape), or a Gmail-style search (`find`; on Outlook, words, `from:`, `to:`, `cc:`, `subject:` and `newer_than:` are kept and other Gmail operators dropped). Several matches return `{status: \"choose\", candidates}` (subject, sender and date — no message text) and draft nothing; none returns `not_found`.\n5. **Sets the recipients in code**, never from the model. A reply goes to the last inbound message's `From` — never its `Reply-To` (a different one is flagged `reply_to_ignored`) — with the thread's other recipients only on `reply_all`. A new email goes only to someone on the roster (contacts only when `contacts_reachable_now()`), or to an address the speaker typed this turn. Mailing-list mail, a thread they replied to last and a reply-all trimmed to 10 recipients are flagged. An address inside a block an adapter added to their message (the backstory hydrated into a DM) is not one they typed, and when the message carries an attachment — a document's inlined text, or a note naming the file — none of its addresses count: neither has an end mark, and a filename is chosen by whoever sent the file. They give the address in a message of its own.\n6. **Writes it** (the ghostwriter, below) and saves it with the mailbox client's `create_draft` (Gmail: threaded with `In-Reply-To`, `References` (whole message ids: when the chain is too long for one header the oldest after the thread's first go, never the parent) and `threadId`, and stamped `X-OE-Ghostwritten`; Outlook: Graph's `createReply` on the message it answers, then the text and recipients, and a named property marking it).\n\nThe result is `{status: \"drafted\", draft_id, gmail_link, to, cc, subject, preview, flags, open_questions, note}`. The link (`gmail.mailbox_link`) is built server-side from a fixed prefix — the thread in Gmail, the draft itself in Outlook on the web — and the note tells the model the preview is the person's draft, to be treated as data. The chat shows an action chip — \"Drafted an email as you to … — in your Drafts\" — that opens it, and only a link under `MAILBOX_LINK_PREFIXES` is ever linked. A sincere \"are you an AI?\" in the thread comes back as an open question for the person to answer themselves.\n\n## 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- **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**. 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. 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 only (never `Reply-To`); if anyone else was on the email, the card says so.\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.send_approved_reply` 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. Only `POST /decisions/{id}/approve` reaches it — a class only the card's own person may resolve — and AST tests pin both call sites, so no model, chat turn, workflow, scheduled job or MCP call can. 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## 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 as if it had read the mail (`settings.pin_turn_delegation` reads the flag and fails closed), so a follow-up answered from history alone is still private to its owner, teaches no memory and stays under the lockdown, and the web chat's rows before the turn (the inbound message and the knowledge lookup) are theirs too. A channel adapter's own pre-turn rows are written as before. Anyone else speaking in it is not offered Act as me.\n\nOnce `touched_mail` is set, every audit row the turn writes is private (`people_tools.audit_row_private_to_principal`), and a team member's is theirs alone: the tool row (its input and result redacted, since `ghostwrite` is a sensitive tool name), the reply's `chat_turn` row that carries the preview, the model-call rows, and the background passes, which run under `private_rows`. The Honcho peer and department syncs are skipped, because peer memory is read on other people's turns. No memory is learned from the turn at all: the episodic, open-loop and working-style passes are skipped too, since its reply quotes a draft built from other people's mail. The `delegation_*` audit events are always private and carry metadata only — ids, counts and flags, never the draft or the thread. The inbox watcher is private the same way: every row a scan or a card action writes is its person's alone, and it starts no chat turn, alert, scheduled action or workflow run and teaches no memory.\n\nThe turn also stops reaching anyone else (`delegation.lockdown`). From the round that calls `ghostwrite_email` — a round's tools run together — until the turn ends, the dispatch guard refuses every tool that sends, posts, invites, queues or starts work, fetches an outside address, or writes state that others or later turns read: the DMs and `message_person`, broadcasts, calendar bookings and cancellations, follow-ups, workflows and research, `read_document` and the watchlist, `load_mcp_server`, roster, goal, skill and alert changes, open loops, decisions and standing facts. Through MCP `call_tool`, only the six Google Workspace reads remain. Every tool is classified as allowed or withheld, a test fails on a new unclassified one, and an unknown name is withheld. A refused call gets a private `tool_invocation` row (`refused: mail_touched`) and tells the model to offer it in a new message. The offered tool list never changes mid-turn, so the cached prefix holds. The send paths check again on their own (`_guard_outbound`, the broadcast, calendar, workflow, research and follow-up handlers, the gateway's `call_tool` and `load_mcp_server`). The server-side web search stays, as on a turn private to the principal. The lockdown lasts for that turn only.\n\n## Always in the loop\n\nA sent reply can leave a note. Once the reply went, `reply_send` starts `memory.history_notes.note_sent_reply` for the person who sent it, in the background, when their \"Keep track of what happens\" switch is on and the conversation isn't one they asked not to remember. The note-taker sees only the words they sent, so other people's mail never becomes a note, and a failure never touches the send. Recall is `recall_history`, offered on the same verified, private surfaces as `ghostwrite_email` and also allowed under the mail lockdown, since it only reads the speaker's own notes. Calling it locks the turn like `ghostwrite_email` does, from its own round on. 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 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- **API**: `GET`/`PUT /delegation`, `GET`/`PUT`/`DELETE /delegation/voice`, `POST /delegation/voice/learn`, `POST /delegation/voice/signature`, `PUT /delegation/inbox`, `POST /delegation/inbox/check` and `GET /delegation/replies` — 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; chat never sends. The principal can turn it on for themselves, and so can each team member once the owner lets them. It is off by default, and off changes nothing: the prompts, tool lists and prompt caches are byte-identical to an install without it.\n\n## Who can have it, and when it is offered\n\n`delegation.settings.can_delegate(person)` is the single rule for who may turn it on: the principal (a non-archived team member flagged `is_principal`), and any other non-archived team member — never a contact — once team members may have it (`team_members_enabled`). That takes two things: the install allows it (`DELEGATION_TEAM_MEMBERS`, default off, which offers the owner the switch) and the owner turned on **Let team members use it** (`PUT /delegation/team`, principal only, one row in `delegation_team`). Turning the owner's switch off takes it away from every team member from their next message, and their inbox watchers stop at their next check; their own switches, drafts and cards are kept. Everything is keyed by `person_id`. A person turns it on for themselves (`PUT /delegation`); nobody turns it on for anyone else. The setting is one row per person in `delegation_settings`, and a missing, unreadable or zero row all mean off.\n\nAt the start of every chat turn (`Executive.stream_chat` and the committee path) `pin_turn_delegation(session, speaker_text)` runs next to the workspace-mode pin and records a `TurnDelegation` on the session. `ghostwrite_email` is **offered** only when all of these hold:\n\n- the speaker may have it and turned it on — read fresh every turn, so turning it off applies from the next message;\n- the speaker is on a surface that verified it is them — the principal through `people_tools.is_principal_on_verified_surface`, a team member through `teammate_on_verified_surface` (the web app signed in, their own Slack or Discord, never an email turn) — and a web turn also carried a signed-in caller (`Session.web_caller_signed_in`, set from `x-caller-email`) or runs under local login — a request with no caller header is not a sign-in and never gets it (whoever holds the shared secret is trusted as the UI proxy that stamps that header, as on every principal-only route);\n- the conversation is private to the speaker: the web chat, a Slack or Discord DM, or a verified private Telegram chat — never a shared channel or thread, where the draft's preview or the matching threads would be posted for everyone and other people's messages sit in the model's context;\n- the turn is neither unattended (the scheduler's proactive run) nor private to the principal (the email poller's turns), so inbound text can never reach it. The MCP server, workflows, reflection and research never carry it at all.\n\nThe mailbox connection is deliberately **not** part of the offer: the handler checks it on every call and says how to fix it, so the cached tool prefix never flips when a token lapses. The pin lives in a context variable for the turn's task as well as on the session, so two turns running at once on one session (a second browser tab) each read their own. It also carries the speaker's own words for the turn (a new email may go to an address they just typed — the turn's message joins the history only once the turn ends), a per-turn draft count, and `touched_mail` (see Privacy). `own_words` reads those words back for every own-words check (addresses here, facts and task assignments elsewhere): it first removes the hydrated `<outbound_reply_context>` backstory by its exact, anchored shape, so a look-alike closing tag quoted inside it cannot pass the rest off as the speaker's, then drops other adapter tag blocks, and returns nothing for a message carrying an attachment.\n\n## The tool: `ghostwrite_email`\n\nIt lives in its own registry (`orchestrator.delegation_tools.DELEGATION_TOOLS` / `DELEGATION_TOOL_HANDLERS`), **never** `_ALL_SKILL_TOOLS`, so no other toolkit can carry it. On a turn it is offered to, the agent loop adds it to the pool *before* the sort and builds that turn's handler map from both registries; on any other turn a call to it is an unknown tool. The handler re-checks the pin and the surface anyway, then:\n\n1. **Caps** — at most 5 drafts per turn, and `DELEGATION_MAX_DRAFTS_PER_DAY` (default 50, at most 1000) per person per UTC day, shared with the inbox watcher (`delegation.caps`). It is counted from `delegation_drafts`, one row of ids per draft saved from either place, with a count kept in the process as a floor in case a row was lost. Each slot is taken before the first await — a round's tool calls run concurrently, so otherwise every call in it would pass the caps before any counted — and handed back if nothing was drafted. If the rows can't be read it refuses rather than guess.\n2. **Marks the turn** — sets `TurnDelegation.touched_mail` *before* its first read of the mailbox.\n3. **Checks the mailbox** — `gmail_status` asks Google or Microsoft whose mailbox the credential opens and compares it with the person's People email, on every call: a roster email can change, and a client slot swaps the roster.\n4. **Finds the thread** — by `thread_id` (checked against the mailbox's own id shape), or a Gmail-style search (`find`; on Outlook, words, `from:`, `to:`, `cc:`, `subject:` and `newer_than:` are kept and other Gmail operators dropped). Several matches return `{status: \"choose\", candidates}` (subject, sender and date — no message text) and draft nothing; none returns `not_found`.\n5. **Sets the recipients in code**, never from the model. A reply goes to the last inbound message's `From` — never its `Reply-To` (a different one is flagged `reply_to_ignored`) — with the thread's other recipients only on `reply_all`. A new email goes only to someone on the roster (contacts only when `contacts_reachable_now()`), or to an address the speaker typed this turn. Mailing-list mail, a thread they replied to last and a reply-all trimmed to 10 recipients are flagged. An address inside a block an adapter added to their message (the backstory hydrated into a DM) is not one they typed, and when the message carries an attachment — a document's inlined text, or a note naming the file — none of its addresses count: neither has an end mark, and a filename is chosen by whoever sent the file. They give the address in a message of its own.\n6. **Writes it** (the ghostwriter, below) and saves it with the mailbox client's `create_draft` (Gmail: threaded with `In-Reply-To`, `References` (whole message ids: when the chain is too long for one header the oldest after the thread's first go, never the parent) and `threadId`, and stamped `X-OE-Ghostwritten`; Outlook: Graph's `createReply` on the message it answers, then the text and recipients, and a named property marking it).\n\nThe result is `{status: \"drafted\", draft_id, gmail_link, to, cc, subject, preview, flags, open_questions, note}`. The link (`gmail.mailbox_link`) is built server-side from a fixed prefix — the thread in Gmail, the draft itself in Outlook on the web — and the note tells the model the preview is the person's draft, to be treated as data. The chat shows an action chip — \"Drafted an email as you to … — in your Drafts\" — that opens it, and only a link under `MAILBOX_LINK_PREFIXES` is ever linked. A sincere \"are you an AI?\" in the thread comes back as an open question for the person to answer themselves.\n\n## 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- **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**. 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 answers `asked_of_them`, false when the email greets someone else by name (\"Brennan: ...\") or asks 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.send_approved_reply` 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. Only `POST /decisions/{id}/approve` reaches it — a class only the card's own person may resolve — and AST tests pin both call sites, so no model, chat turn, workflow, scheduled job or MCP call can. 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## 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 as if it had read the mail (`settings.pin_turn_delegation` reads the flag and fails closed), so a follow-up answered from history alone is still private to its owner, teaches no memory and stays under the lockdown, and the web chat's rows before the turn (the inbound message and the knowledge lookup) are theirs too. A channel adapter's own pre-turn rows are written as before. Anyone else speaking in it is not offered Act as me.\n\nOnce `touched_mail` is set, every audit row the turn writes is private (`people_tools.audit_row_private_to_principal`), and a team member's is theirs alone: the tool row (its input and result redacted, since `ghostwrite` is a sensitive tool name), the reply's `chat_turn` row that carries the preview, the model-call rows, and the background passes, which run under `private_rows`. The Honcho peer and department syncs are skipped, because peer memory is read on other people's turns. No memory is learned from the turn at all: the episodic, open-loop and working-style passes are skipped too, since its reply quotes a draft built from other people's mail. The `delegation_*` audit events are always private and carry metadata only — ids, counts and flags, never the draft or the thread. The inbox watcher is private the same way: every row a scan or a card action writes is its person's alone, and it starts no chat turn, alert, scheduled action or workflow run and teaches no memory.\n\nThe turn also stops reaching anyone else (`delegation.lockdown`). From the round that calls `ghostwrite_email` — a round's tools run together — until the turn ends, the dispatch guard refuses every tool that sends, posts, invites, queues or starts work, fetches an outside address, or writes state that others or later turns read: the DMs and `message_person`, broadcasts, calendar bookings and cancellations, follow-ups, workflows and research, `read_document` and the watchlist, `load_mcp_server`, roster, goal, skill and alert changes, open loops, decisions and standing facts. Through MCP `call_tool`, only the six Google Workspace reads remain. Every tool is classified as allowed or withheld, a test fails on a new unclassified one, and an unknown name is withheld. A refused call gets a private `tool_invocation` row (`refused: mail_touched`) and tells the model to offer it in a new message. The offered tool list never changes mid-turn, so the cached prefix holds. The send paths check again on their own (`_guard_outbound`, the broadcast, calendar, workflow, research and follow-up handlers, the gateway's `call_tool` and `load_mcp_server`). The server-side web search stays, as on a turn private to the principal. The lockdown lasts for that turn only.\n\n## Always in the loop\n\nA sent reply can leave a note. Once the reply went, `reply_send` starts `memory.history_notes.note_sent_reply` for the person who sent it, in the background, when their \"Keep track of what happens\" switch is on and the conversation isn't one they asked not to remember. The note-taker sees only the words they sent, so other people's mail never becomes a note, and a failure never touches the send. Recall is `recall_history`, offered on the same verified, private surfaces as `ghostwrite_email` and also allowed under the mail lockdown, since it only reads the speaker's own notes. Calling it locks the turn like `ghostwrite_email` does, from its own round on. 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 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- **API**: `GET`/`PUT /delegation`, `GET`/`PUT`/`DELETE /delegation/voice`, `POST /delegation/voice/learn`, `POST /delegation/voice/signature`, `PUT /delegation/inbox`, `POST /delegation/inbox/check` and `GET /delegation/replies` — 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-03T12:00:00Z"+ "generated_at": "2026-10-03T12:40:00Z"}diff --git a/packages/core/openexecutive/delegation/inbox.py b/packages/core/openexecutive/delegation/inbox.pyindex c716e474..3f46713c 100644--- a/packages/core/openexecutive/delegation/inbox.py+++ b/packages/core/openexecutive/delegation/inbox.py@@ -42,9 +42,13 @@ couldn't authenticate is handled as a stranger (``handling_relation``). The ghoswrites the reply in the person's voice, from a fixed intent this modulebuilds: acknowledge, restate only what the person themselves already said inthe thread, promise nothing new, and put every unanswered ask in-``open_questions``. A stranger always gets a short holding reply. The reply-goes to the sender only; others on the thread are named on the card-(``others_on_thread``).+``open_questions``. A stranger always gets a short holding reply. An email that+also went to others is drafted for only when the person is in To and it asks+them themselves, not someone else by name or the group at large+(``inbox_classifier.wants_draft``). The reply goes to everyone the email went to+(reply to all, never the person's own addresses or the Executive); a+stranger's holding reply goes to the sender alone. The card flags+``others_on_thread``.**Limits.** Per scan 5 drafts; per day ``DELEGATION_INBOX_MAX_DRAFTS_PER_DAY``within the shared daily limit (``delegation.caps``), 200 classifications, 2@@ -77,7 +81,7 @@ import jsonimport loggingimport reimport sqlite3-from dataclasses import asdict, dataclass+from dataclasses import asdict, dataclass, fieldfrom datetime import UTC, datetime, timedeltafrom pathlib import Pathfrom typing import Any@@ -685,6 +689,8 @@ class Reply:flags: list[str]in_reply_to: str | Nonereferences: str | None+ # Everyone else the email went to, on a group email (reply to all).+ cc: list[str] = field(default_factory=list)async def compose_reply(person: Any, message: Any, thread: Any, *, relation: str, own: set[str]) -> Reply | str:@@ -696,6 +702,8 @@ async def compose_reply(person: Any, message: Any, thread: Any, *, relation: strfrom openexecutive.delegation.voice import composer_model, get_voice, render_voice_blockemail = (person.email or "").strip().lower()+ # A group email is answered to everyone on it, as the person would; a+ # stranger's holding reply goes to the stranger alone.plan = plan_reply(thread, email, False)if isinstance(plan, str) or plan["to"] != [message.from_addr]:return "no_reply_target"@@ -704,6 +712,18 @@ async def compose_reply(person: Any, message: Any, thread: Any, *, relation: strstored = get_voice(person.id)names = (person.full_name or "").split()exec_address = (get_settings().exec_email_address or "").strip().lower()+ # Everyone else the email went to, never the person's own addresses or+ # the Executive (Send refuses a draft addressed to it), filtered before+ # trimming so the room goes to real recipients.+ cc: list[str] = []+ if relation != "stranger":+ cc = [+ a for a in dict.fromkeys([*message.to, *message.cc])+ if a not in own and a != exec_address and a != message.from_addr+ ]+ if len(cc) > MAX_RECIPIENTS - 1:+ cc = cc[: MAX_RECIPIENTS - 1]+ plan["flags"].append("cc_trimmed")relation_text = {"team": "on their team","contact": "one of their contacts",@@ -717,7 +737,10 @@ async def compose_reply(person: Any, message: Any, thread: Any, *, relation: strwriter_said=writer_said(thread, email),reply_subject=plan["subject"],intent=INBOX_HOLDING_INTENT if relation == "stranger" else INBOX_REPLY_INTENT,- recipients=[Recipient(email=message.from_addr, name=message.from_name, relation=relation_text)],+ recipients=[+ Recipient(email=message.from_addr, name=message.from_name, relation=relation_text),+ *(Recipient(email=a, relation="also on the email") for a in cc),+ ],signature=stored.profile.signature,exec_name=get_settings().exec_display_name,model=composer_model(),@@ -730,6 +753,7 @@ async def compose_reply(person: Any, message: Any, thread: Any, *, relation: strquestions.append("They asked whether they're talking to an AI — answer that yourself.")return Reply(to=plan["to"],+ cc=cc,subject=composed.subject,body=composed.body,open_questions=questions,@@ -739,6 +763,16 @@ async def compose_reply(person: Any, message: Any, thread: Any, *, relation: str)+def addressed_for(person: Any, message: Any, own: set[str]) -> Any:+ """Who ``message`` went to, from ``person``'s side, counted as the scan+ counts it (the Executive copied is nobody else)."""+ from openexecutive.config import get_settings+ from openexecutive.delegation.inbox_classifier import addressing++ exec_address = (get_settings().exec_email_address or "").strip().lower()+ return addressing(message, name=person.full_name or "", own=own, exec_address=exec_address)++async def reply_for(person: Any, message: Any, thread: Any, *, relation: str, own: set[str]) -> tuple[Any, Reply | str | None]:@@ -750,8 +784,9 @@ async def reply_for(from openexecutive.delegation.inbox_classifier import classify, wants_draftrelation = handling_relation(relation, message)- verdict = await classify(message, relation=relation)- if verdict is None or not wants_draft(verdict, relation):+ addressed = addressed_for(person, message, own)+ verdict = await classify(message, relation=relation, addressed=addressed)+ if verdict is None or not wants_draft(verdict, relation, addressed):return verdict, Nonetry:return verdict, await compose_reply(person, message, thread, relation=relation, own=own)@@ -784,7 +819,8 @@ def _card_payload("subject": one_line(message.subject, 200),"received_at": message.received_at,"they_wrote": sender_new_text(message.text or "")[:_THEY_WROTE_CHARS],- "draft_to": reply.to,+ # Everyone it goes to: Send checks the draft against this list.+ "draft_to": [*reply.to, *reply.cc],"draft_subject": reply.subject,"draft_body": reply.body,"open_questions": reply.open_questions,@@ -1010,7 +1046,7 @@ async def _consider(from openexecutive.delegation import caps, draftsfrom openexecutive.delegation.ghostwriter import ComposeErrorfrom openexecutive.delegation.gmail import DraftSpec, GmailError- from openexecutive.delegation.inbox_classifier import classify, wants_draft+ from openexecutive.delegation.inbox_classifier import addressing, classify, wants_draftemail = (person.email or "").strip().lower()thread = await client.get_thread(thread_id)@@ -1036,14 +1072,16 @@ async def _consider(return Falseif not _claim(person.id, message, relation=relation, outcome=PROCESSING, now=now):return False- verdict = await classify(message, relation=relation)+ asked = addressing(message, name=person.full_name or "", own=own, exec_address=exec_address)+ verdict = await classify(message, relation=relation, addressed=asked)_set_outcome(person.id, message.id, PROCESSING, classified=1)if verdict is None:# The call failed or answered nonsense: that may pass._count_retry(result, _retry_later(person.id, message.id, "classify_failed"))return False- if not wants_draft(verdict, relation):- _set_outcome(person.id, message.id, NOT_NEEDED, reason=verdict.kind)+ if not wants_draft(verdict, relation, asked):+ reason = verdict.kind if not wants_draft(verdict, relation) else "asks_someone_else"+ _set_outcome(person.id, message.id, NOT_NEEDED, reason=reason)result.not_needed += 1return Falsesettings = get_settings()@@ -1077,6 +1115,7 @@ async def _consider(try:draft = await client.create_draft(DraftSpec(to=reply.to,+ cc=reply.cc,subject=reply.subject,body=reply.body,thread_id=thread.id,diff --git a/packages/core/openexecutive/delegation/inbox_classifier.py b/packages/core/openexecutive/delegation/inbox_classifier.pyindex a69b4fca..69b322cf 100644--- a/packages/core/openexecutive/delegation/inbox_classifier.py+++ b/packages/core/openexecutive/delegation/inbox_classifier.py@@ -10,6 +10,12 @@ person has written to before, 0.85 for a stranger (and for anyone whoseaddress Gmail couldn't authenticate: ``inbox.handling_relation``). Anythingelse, and any failure, means no draft.+An email that also went to other people is drafted for only when it asks+this person themselves (``asked_of_them``): it names or greets them, or they+are its only addressee. One that greets someone else by name ("Brennan: ...")+or puts a question to the group in general is theirs to answer, and one that+merely copies the person is never drafted for.+The model sees a few header lines and the sender's own new words (quotedreplies stripped, at most 3000 characters), as data in a labelled block. Ithas no tools but this one, no company context and no memory, so the email can@@ -69,6 +75,10 @@ needs no answer.reply), or fyi, thanks, pitch (a cold sales or partnership email), \notification, newsletter, phishing (it asks for credentials, payment or a \click with urgency or a disguised sender), other.+- asked_of_them: true only when the email asks this person themselves: it \+names or greets them, or they are its only addressee. False when it is \+addressed to someone else by name ("Brennan: ..."), when it asks a group \+without naming them, or when they are only copied (Cc).- confidence: how sure you are that needs_reply and kind are right, from 0 to 1.When unsure, say needs_reply false."""@@ -81,9 +91,10 @@ _CLASSIFY_TOOL: dict[str, Any] = {"properties": {"needs_reply": {"type": "boolean"},"kind": {"type": "string", "enum": list(KINDS)},+ "asked_of_them": {"type": "boolean"},"confidence": {"type": "number", "minimum": 0, "maximum": 1},},- "required": ["needs_reply", "kind", "confidence"],+ "required": ["needs_reply", "kind", "asked_of_them", "confidence"],},}@@ -93,16 +104,47 @@ class Verdict:needs_reply: boolkind: strconfidence: float+ asked_of_them: bool = False+++@dataclass(frozen=True)+class Addressing:+ """Who an email went to, from the person's side."""++ # The person's name, as the email may greet them.+ name: str = ""+ # "to", "cc" or "" (not addressed: the scan skips those anyway).+ position: str = "to"+ # Everyone else it was addressed to, the sender and the Executive aside.+ others: int = 0-def wants_draft(verdict: Verdict, relation: str) -> bool:+def addressing(message: Any, *, name: str, own: set[str], exec_address: str = "") -> Addressing:+ """``message``'s :class:`Addressing` for a person with addresses ``own``."""+ to = {a.lower() for a in getattr(message, "to", []) or []}+ cc = {a.lower() for a in getattr(message, "cc", []) or []}+ position = "to" if to & own else "cc" if cc & own else ""+ skip = {*own, (getattr(message, "from_addr", "") or "").lower(), exec_address.lower()}+ return Addressing(name=name, position=position, others=len((to | cc) - skip))+++def wants_draft(verdict: Verdict, relation: str, addressed: Addressing | None = None) -> bool:"""Whether code drafts a reply for ``verdict`` from a sender of this- ``relation`` (unknown relations get the stranger's bar)."""+ ``relation`` (unknown relations get the stranger's bar). With+ ``addressed``, the person must be in To (only copied, it is never theirs+ to answer), and an email that also went to others must ask them+ themselves."""bar = THRESHOLDS.get(relation, THRESHOLDS["stranger"])- return verdict.needs_reply and verdict.kind in DRAFT_KINDS and verdict.confidence >= bar+ if not (verdict.needs_reply and verdict.kind in DRAFT_KINDS and verdict.confidence >= bar):+ return False+ if addressed is None:+ return True+ if addressed.position != "to":+ return False+ return addressed.others == 0 or verdict.asked_of_them-def render_email(message: Any, *, relation: str) -> str:+def render_email(message: Any, *, relation: str, addressed: Addressing | None = None) -> str:"""The user turn: a few header lines and the sender's own new words, asdata in one ``<email>`` block."""from openexecutive.delegation.ghostwriter import one_line@@ -117,6 +159,14 @@ def render_email(message: Any, *, relation: str) -> str:f"Sender: {relation}"+ ("" if getattr(message, "sender_authenticated", False) else " (address not verified)"),f"Recipients: {others}",+ ]+ if addressed is not None:+ header += [+ f"This person: {one_line(addressed.name, 80) or 'unknown'}, in "+ + ("To" if addressed.position == "to" else "Cc" if addressed.position == "cc" else "neither To nor Cc"),+ f"Also addressed: {addressed.others} other people",+ ]+ header += [f"Subject: {one_line(getattr(message, 'subject', '') or '', 200)}",]lines = [scrub_block_line(line, "</email>") for line in [*header, "", *body.splitlines()]]@@ -151,11 +201,15 @@ def classifier_model() -> str:return settings.delegation_classifier_model or settings.routing_model-async def classify(message: Any, *, relation: str, model: str | None = None) -> Verdict | None:+async def classify(+ message: Any, *, relation: str, addressed: Addressing | None = None, model: str | None = None+) -> Verdict | None:"""The verdict on ``message``, or None when there is none to trust (thecall failed or returned something malformed). Never raises."""try:- payload = await _call_model(model or classifier_model(), render_email(message, relation=relation))+ payload = await _call_model(+ model or classifier_model(), render_email(message, relation=relation, addressed=addressed)+ )except Exception:logger.warning("delegation.inbox: classifying an email failed", exc_info=True)return None@@ -166,4 +220,7 @@ async def classify(message: Any, *, relation: str, model: str | None = None) ->return Noneif isinstance(confidence, bool) or not isinstance(confidence, int | float):return None- return Verdict(needs_reply=needs_reply, kind=str(kind), confidence=max(0.0, min(1.0, float(confidence))))+ return Verdict(+ needs_reply=needs_reply, kind=str(kind), confidence=max(0.0, min(1.0, float(confidence))),+ asked_of_them=payload.get("asked_of_them") is True,+ )diff --git a/packages/core/openexecutive/evals/_scenarios/delegation_inbox_008.yaml b/packages/core/openexecutive/evals/_scenarios/delegation_inbox_008.yamlnew file mode 100644index 00000000..bdab83c2--- /dev/null+++ b/packages/core/openexecutive/evals/_scenarios/delegation_inbox_008.yaml@@ -0,0 +1,21 @@+id: delegation_inbox_008+domain: delegation+type: inbox+description: "Inbox watcher: a colleague writes to three people, greets one of the others by name and asks the group for a strategy. It asks someone else, so nothing is drafted for the person."+inbox:+ person:+ full_name: Olivia Owner+ email: [email protected]+ relation: team+ expect: no_draft+ thread:+ id: t-regions+ subject: Regions LP interest+ messages:+ - from: "Annette Bray <[email protected]>"+ text: |+ Brennan: I would like to approach Regions about purchasing the LP interest in these+ two partnerships. We have a valuation for Pine View and the waterfall analysis for each.++ I'm asking for a strategy. I'm thinking Brennan can approach Regions. What are your thoughts?diff --git a/packages/core/openexecutive/evals/_scenarios/delegation_inbox_009.yaml b/packages/core/openexecutive/evals/_scenarios/delegation_inbox_009.yamlnew file mode 100644index 00000000..9f140fa6--- /dev/null+++ b/packages/core/openexecutive/evals/_scenarios/delegation_inbox_009.yaml@@ -0,0 +1,21 @@+id: delegation_inbox_009+domain: delegation+type: inbox+description: "Inbox watcher: a colleague writes to three people and asks the person by name for something they own. It asks them, so a reply is drafted."+inbox:+ person:+ full_name: Olivia Owner+ email: [email protected]+ relation: team+ expect: draft+ thread:+ id: t-waterfall+ subject: Waterfall for Pine View+ messages:+ - from: "Annette Bray <[email protected]>"+ text: |+ Olivia, could you send round the waterfall analysis for Pine View before Thursday?+quality_criteria:+ draft_is_olivias_first_person_reply_to_annette: true+ promises_nothing_new: truediff --git a/packages/core/openexecutive/evals/runner.py b/packages/core/openexecutive/evals/runner.pyindex 6d174c69..f42a5182 100644--- a/packages/core/openexecutive/evals/runner.py+++ b/packages/core/openexecutive/evals/runner.py@@ -284,7 +284,7 @@ def _make_triage_runner(async def run_inbox_scenario(scenario: dict[str, Any]) -> dict[str, Any]:"""One ``type: inbox`` scenario: ``{"outcome", "scores", "passed"}``."""- from openexecutive.delegation.inbox import handling_relation, reply_for+ from openexecutive.delegation.inbox import addressed_for, handling_relation, reply_forfrom openexecutive.delegation.inbox_classifier import wants_draftcase = scenario_inbox(scenario)@@ -294,7 +294,8 @@ async def run_inbox_scenario(scenario: dict[str, Any]) -> dict[str, Any]:case.person, case.message, case.thread, relation=case.relation, own={case.person.email})handled_as = handling_relation(case.relation, case.message)- wanted = verdict is not None and wants_draft(verdict, handled_as)+ addressed = addressed_for(case.person, case.message, {case.person.email})+ wanted = verdict is not None and wants_draft(verdict, handled_as, addressed)drafted = reply is not None and not isinstance(reply, str)outcome: dict[str, Any] = {"verdict": asdict(verdict) if verdict is not None else None,diff --git a/packages/core/tests/unit/test_delegation_evals.py b/packages/core/tests/unit/test_delegation_evals.pyindex 84bf1af4..0ecaaa12 100644--- a/packages/core/tests/unit/test_delegation_evals.py+++ b/packages/core/tests/unit/test_delegation_evals.py@@ -218,6 +218,23 @@ def test_the_inbox_runner_checks_the_verdict_before_judging(assert result["outcome"]["no_reply_because"] == (reply if reply not in ("reply", None) else None)+def test_the_inbox_runner_scores_a_group_email_as_the_scan_decides(monkeypatch: pytest.MonkeyPatch) -> None:+ from openexecutive.delegation import inbox+ from openexecutive.delegation.inbox_classifier import Verdict++ async def fake_reply_for(*a: Any, **kw: Any) -> Any:+ # Wants a reply, but not from this person: the scan drafts nothing.+ return Verdict(True, "question", 0.95, asked_of_them=False), None++ monkeypatch.setattr(inbox, "reply_for", fake_reply_for)+ group = _INBOX.replace(+ 'text: "2pm or 4pm?", verified: false}',+ 'text: "2pm or 4pm?", verified: false, to: [[email protected], [email protected]]}',+ ).replace("expect: draft", "expect: no_draft")+ result = asyncio.run(runner_module.run_inbox_scenario(validate_scenario_yaml(group)))+ assert result["passed"] is True and result["scores"]["notes"] == "drafted nothing, as expected"++def test_the_inbox_kind_streams_through_the_suite_runner(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:from openexecutive.delegation import inboxfrom openexecutive.delegation.inbox_classifier import Verdictdiff --git a/packages/core/tests/unit/test_delegation_inbox.py b/packages/core/tests/unit/test_delegation_inbox.pyindex 25171ac6..4ef353bd 100644--- a/packages/core/tests/unit/test_delegation_inbox.py+++ b/packages/core/tests/unit/test_delegation_inbox.py@@ -225,7 +225,7 @@ def models(monkeypatch: pytest.MonkeyPatch) -> dict[str, Any]:for marker, verdict in seen["verdicts"].items():if marker in turn:return dict(verdict)- return {"needs_reply": True, "kind": "scheduling", "confidence": 0.9}+ return {"needs_reply": True, "kind": "scheduling", "asked_of_them": True, "confidence": 0.9}async def composer(model: str, system: str, turn: str) -> dict[str, Any]:seen["composed"].append(turn)@@ -284,9 +284,9 @@ def test_a_question_from_a_contact_gets_a_draft_and_a_private_card(mailbox.add(_msg("m1", "t1", cc=("[email protected]",)))result = _scan(owner, mailbox)assert (result.status, result.drafted) == ("ok", 1)- # To the sender only, in the thread, as a reply.+ # To everyone it went to (reply to all), in the thread, as a reply.spec = mailbox.specs[0]- assert spec.to == [DANA] and spec.cc == [] and spec.thread_id == "t1"+ assert spec.to == [DANA] and spec.cc == ["[email protected]"] and spec.thread_id == "t1"assert spec.in_reply_to == "<[email protected]>"# The composer was told to commit to nothing new.assert "commit to nothing" in models["composed"][0]@@ -296,6 +296,7 @@ def test_a_question_from_a_contact_gets_a_draft_and_a_private_card(payload = inbox.card_payload(cards[0])assert payload["private"] is True and payload["draft_id"] == "d1"assert payload["relation"] == "contact" and "others_on_thread" in payload["flags"]+ assert payload["draft_to"] == [DANA, "[email protected]"]assert payload["open_questions"] == ["Can the call move to Friday at 10?"]assert "Thursday" in payload["they_wrote"]assert _ledger(db)["m1"] == ("drafted", None)@@ -418,6 +419,100 @@ def test_a_classifier_failure_is_tried_again_then_given_up(assert _ledger(db)["m3"] == ("failed", "classify_failed")+def test_a_group_email_is_drafted_for_only_when_it_asks_them(+ db: Path, owner: Any, models: dict[str, Any]+) -> None:+ group = [OWNER, "[email protected]", "[email protected]"]+ models["verdicts"]["Brennan:"] = {+ "needs_reply": True, "kind": "question", "asked_of_them": False, "confidence": 0.95,+ }+ mailbox = FakeInbox()+ mailbox.add(_msg("m1", "t1", to=group, text="Brennan: can you approach Regions? Thoughts?"))+ mailbox.add(_msg("m2", "t2", to=group, text="Olivia, can you send the waterfall?", minutes_ago=25))+ mailbox.add(_msg("m3", "t3", to=["[email protected]"], cc=(OWNER,), text="Olivia, thoughts?", minutes_ago=20))+ _scan(owner, mailbox)+ ledger = _ledger(db)+ assert ledger["m1"] == ("not_needed", "asks_someone_else")+ assert ledger["m2"][0] == "drafted"+ # Only copied: never theirs to answer, whatever the model says.+ assert ledger["m3"] == ("not_needed", "asks_someone_else")+ turns = models["classified"]+ assert any("This person: Olivia Owner, in To\nAlso addressed: 2 other people" in t for t in turns)+ assert any("This person: Olivia Owner, in Cc\nAlso addressed: 1 other people" in t for t in turns)+++def test_reply_to_all_never_copies_the_person_or_the_executive_and_spares_strangers(+ db: Path, owner: Any, models: dict[str, Any], monkeypatch: pytest.MonkeyPatch+) -> None:+ from openexecutive.config import get_settings++ exec_address = (get_settings().exec_email_address or "").lower()+ mailbox = FakeInbox()+ mailbox.add(_msg("m1", "t1", to=[OWNER, "[email protected]"], cc=(exec_address,)))+ stranger = "[email protected]"+ mailbox.add(_msg("m2", "t2", sender=stranger, to=[OWNER, "[email protected]"], minutes_ago=25))+ _scan(owner, mailbox)+ by_thread = {spec.thread_id: spec for spec in mailbox.specs}+ assert by_thread["t1"].cc == ["[email protected]"]+ assert by_thread["t2"].to == [stranger] and by_thread["t2"].cc == []+++def test_the_eval_path_counts_recipients_as_the_scan_does(owner: Any, models: dict[str, Any]) -> None:+ # Only the Executive copied: not a group email, on the scan or in reply_for.+ from openexecutive.config import get_settings++ exec_address = (get_settings().exec_email_address or "").lower()+ models["verdicts"]["Thursday"] = {+ "needs_reply": True, "kind": "scheduling", "asked_of_them": False, "confidence": 0.9,+ }+ message = _msg("m1", "t1", cc=(exec_address,))+ thread = MailThread(id="t1", messages=[message])+ verdict, reply = asyncio.run(inbox.reply_for(owner, message, thread, relation="contact", own={OWNER}))+ assert verdict is not None and isinstance(reply, inbox.Reply) and reply.cc == []+++def test_reply_to_all_is_trimmed_to_the_send_limit_and_flagged(owner: Any, models: dict[str, Any]) -> None:+ # The scan skips mail this wide; the eval path still writes it, trimmed.+ others = [f"p{i}@co.example" for i in range(11)]+ message = _msg("m1", "t1", to=[OWNER, *others], text="Olivia, can you send the waterfall?")+ thread = MailThread(id="t1", messages=[message])+ _, reply = asyncio.run(inbox.reply_for(owner, message, thread, relation="contact", own={OWNER}))+ assert isinstance(reply, inbox.Reply)+ assert reply.cc == others[: inbox.MAX_RECIPIENTS - 1] and "cc_trimmed" in reply.flags+ assert len([*reply.to, *reply.cc]) == inbox.MAX_RECIPIENTS+++def test_only_a_real_true_counts_as_asked_of_them(monkeypatch: pytest.MonkeyPatch) -> None:+ async def says(model: str, turn: str) -> dict[str, Any]:+ return {"needs_reply": True, "kind": "question", "asked_of_them": "true", "confidence": 0.9}++ monkeypatch.setattr(ic, "_call_model", says)+ verdict = asyncio.run(ic.classify(_msg("m1", "t1"), relation="team"))+ assert verdict is not None and verdict.asked_of_them is False+++def test_someone_only_copied_never_gets_a_draft() -> None:+ verdict = ic.Verdict(needs_reply=True, kind="question", confidence=0.95, asked_of_them=True)+ assert ic.wants_draft(verdict, "team", ic.Addressing(name="Olivia", position="to", others=1)) is True+ assert ic.wants_draft(verdict, "team", ic.Addressing(name="Olivia", position="cc", others=1)) is False+ # Copied on mail to the Executive alone: nobody else, still not theirs.+ assert ic.wants_draft(verdict, "team", ic.Addressing(name="Olivia", position="cc", others=0)) is False+ assert ic.wants_draft(verdict, "team", ic.Addressing(name="Olivia", position="", others=0)) is False+++def test_mail_to_the_executive_that_copies_them_gets_no_draft(+ db: Path, owner: Any, models: dict[str, Any]+) -> None:+ from openexecutive.config import get_settings++ exec_address = (get_settings().exec_email_address or "").lower()+ mailbox = FakeInbox()+ mailbox.add(_msg("m1", "t1", to=[exec_address], cc=(OWNER,)))+ _scan(owner, mailbox)+ assert _ledger(db)["m1"] == ("not_needed", "asks_someone_else")+ assert mailbox.specs == []++def test_a_stranger_needs_more_certainty_and_gets_a_holding_reply(db: Path, owner: Any, models: dict[str, Any]) -> None: