Skip to content

AI-powered virtual executive team — a single coherent executive persona backed by 8 specialist agents (FastAPI + Next.js).

feat(delegation): answer meeting invites from a card, and on its own under Handle it for me (#568)

Rufus85f457ed97eb
diff --git a/docs/deployment.md b/docs/deployment.md
index 1df26371..7fd8417a 100644
--- a/docs/deployment.md
+++ b/docs/deployment.md
@@ -322,12 +322,16 @@ has no Outlook address of its own on file is matched by that sign-in address,
so use it on the People page and with `--email`.
**Read my calendar (optional).** Run either script with `--calendar` to also
-grant read-only access to the person's own calendar (`calendar.readonly` on
-Google, which the OAuth client's consent screen must list; the delegated
-`Calendars.Read` permission on the Microsoft app). Then turn on **Read my
+grant access to the person's own calendar (`calendar.events` on Google, which
+the OAuth client's consent screen must list; the delegated
+`Calendars.ReadWrite` permission on the Microsoft app). Then turn on **Read my
calendar** in Delegate → Act as me. The Executive reads events fresh each time
-and keeps nothing; a credential minted without `--calendar` keeps working for
-mail, and the switch says to reconnect with the flag.
+and keeps nothing. The one change it makes there is answering a meeting
+invite: Accept or Decline on an invite card on Home, or an accept on its own
+under Handle it for me. A credential minted without `--calendar` keeps working
+for mail, and the switch says to reconnect with the flag; one minted earlier
+with read-only calendar access (`calendar.readonly`, `Calendars.Read`) keeps
+reading, and its invite cards say to connect again to answer.
```bash
MS365_MCP_CLIENT_ID=<app id> uv run python scripts/connect-own-outlook.py --email [email protected]
diff --git a/packages/core/openexecutive/api/routes/decisions.py b/packages/core/openexecutive/api/routes/decisions.py
index 38eb4871..1714cccd 100644
--- a/packages/core/openexecutive/api/routes/decisions.py
+++ b/packages/core/openexecutive/api/routes/decisions.py
@@ -70,6 +70,11 @@ class ApproveBody(BaseModel):
were shown) and ``thread_moved_on: true``; and Send + allow in training:
``allow: true``, with ``example: true`` to keep an edited draft as an
example (``delegation.training``).
+
+ For a meeting invite card (``delegation_invite``): ``answer``, ``accept``
+ (the default) or ``decline``, answered in the person's own calendar; and
+ ``allow: true`` with accept, in training, to accept that sender's
+ invites on their own from now on (``delegation.invites``).
"""
edits: dict[str, Any] | None = None
@@ -703,6 +708,44 @@ _DELEGATED_ACTIONS = DecisionClassSpec(
after_reject=_actions_dismissed,
)
+async def _answer_invite(
+ instance: DecisionInstance, body: ApproveBody, request: Request, resolver: int | None
+) -> DecisionInstance:
+ """Accept or decline a meeting invite in its person's own calendar, on
+ their tap (``delegation.invites``, which checks the caller and the card
+ again first). ``edits.answer``: accept (the default) or decline."""
+ from openexecutive.delegation.invites import AnswerRefused, answer
+
+ edits = body.edits or {}
+ try:
+ await answer(
+ instance, caller=api_caller.caller(request), resolver=resolver,
+ answer=edits.get("answer", "accept"), allow=edits.get("allow") is True,
+ )
+ except AnswerRefused as refused:
+ raise HTTPException(
+ status_code=refused.status, detail={"code": refused.code, "message": refused.message},
+ ) from None
+ return _refresh(instance.id)
+
+
+async def _invite_dismissed(instance: DecisionInstance) -> None:
+ from openexecutive.delegation.invites import dismissed
+
+ await dismissed(instance)
+
+
+# A meeting invite from someone the person knows (delegation.invites): theirs
+# alone, like a reply card, and never an alert. Dismiss answers nothing.
+_DELEGATED_INVITE = DecisionClassSpec(
+ name="delegation_invite",
+ principal_only=False,
+ approver_only=True,
+ alert_source=None,
+ approve=_answer_invite,
+ after_reject=_invite_dismissed,
+)
+
async def _carry_out_department_action(
instance: DecisionInstance, body: ApproveBody, request: Request, resolver: int | None
) -> DecisionInstance:
@@ -847,7 +890,7 @@ DECISION_CLASSES: dict[str, DecisionClassSpec] = {
spec.name: spec
for spec in (
_MEETING_BOOKING, _DELEGATED_REPLY, _TAKE_THE_LEAD, _DELEGATED_ACTIONS, _DEPARTMENT_ACTION,
- _APP_ACTION,
+ _APP_ACTION, _DELEGATED_INVITE,
)
}
diff --git a/packages/core/openexecutive/api/routes/delegation.py b/packages/core/openexecutive/api/routes/delegation.py
index f6b0f032..0bdbb933 100644
--- a/packages/core/openexecutive/api/routes/delegation.py
+++ b/packages/core/openexecutive/api/routes/delegation.py
@@ -85,9 +85,16 @@ Routes:
GET|POST /delegation/take-the-lead/rules, DELETE …/rules/{id}
— the caller's own rules for it (removing
one needs the same provable caller)
+ GET /delegation/invites — the meeting invite cards waiting for the
+ caller (delegation.invites; from the
+ database, no calendar call). Accept and
+ Decline are POST /decisions/{id}/approve
+ with edits.answer
GET /delegation/handled — the caller's replies sent on its own in
the last 7 days, with the questions each
- left for them
+ left for them, and the invites it
+ accepted on its own (source "invite",
+ with a one-line summary)
GET /delegation/voice — "How I write"
POST /delegation/voice/learn — learn it from the caller's sent mail (409
in_progress / locked / too_soon /
@@ -327,8 +334,12 @@ class HandledReplyOut(BaseModel):
body: str
open_questions: list[str]
gmail_link: str
- # "follow_up" for a follow-up to the caller's own unanswered email.
+ # "follow_up" for a follow-up to the caller's own unanswered email;
+ # "invite" for a meeting invite it accepted on its own.
source: str = ""
+ # What it did, in one line, for an invite: "Accepted Dana's Pilot
+ # review, Wed 21 Oct, 14:30".
+ summary: str = ""
class HandledOut(BaseModel):
@@ -459,6 +470,37 @@ class CardActionOut(BaseModel):
text: str
+class InviteCardOut(BaseModel):
+ decision_id: int
+ status: str
+ created_at: str
+ from_name: str
+ from_email: str
+ relation: str
+ title: str
+ # When, as the caller reads it: "Wed 21 Oct, 14:30–15:00".
+ when: str
+ start: str
+ end: str
+ all_day: bool
+ # Busy times on their calendar that overlap it ("14:00–14:30"); times only.
+ clashes: list[str]
+ # False: their calendar couldn't be read for clashes.
+ clash_checked: bool
+ # False: their sign-in reads the calendar but can't answer invites, so the
+ # card says to connect again (connect_command) instead of offering Accept.
+ can_answer: bool
+ # In training: the "Accept from them on its own next time" tick.
+ can_allow: bool
+ # Why Handle it for me left it for them, in words ("" when it was off).
+ waited_because: str
+ connect_command: str
+
+
+class InviteCardsOut(BaseModel):
+ cards: list[InviteCardOut]
+
+
class ActionCardOut(BaseModel):
decision_id: int
status: str
@@ -1057,6 +1099,22 @@ def get_delegation_actions(request: Request) -> ActionCardsOut:
])
[email protected]("/delegation/invites", response_model=InviteCardsOut)
+def get_delegation_invites(request: Request) -> InviteCardsOut:
+ """The meeting invite cards waiting for the caller to accept or decline.
+ Their own only: everyone else gets the 403 every route here gives."""
+ from openexecutive.delegation.invites import cards
+
+ person = _caller(request)
+ _person_id(person)
+ try:
+ found = cards(person)
+ except Exception as exc:
+ logger.exception("delegation: reading the invite cards failed")
+ raise _refuse(503, "unavailable", "Couldn't read the invites waiting for you.") from exc
+ return InviteCardsOut(cards=[InviteCardOut(**asdict(card)) for card in found])
+
+
def _set_handle_it(person_id: int, *, enabled: bool | None, mode: str | None) -> None:
from openexecutive.delegation import handle_it
@@ -1429,6 +1487,7 @@ def get_delegation_handled(request: Request) -> HandledOut:
subject=h.subject, body=h.body, open_questions=h.open_questions,
gmail_link=mailbox_link(email, thread_id=h.thread_id) if email and h.thread_id else "",
source=h.source,
+ summary=h.summary,
)
for h in found
])
diff --git a/packages/core/openexecutive/api/routes/today.py b/packages/core/openexecutive/api/routes/today.py
index 219e5bf6..7a0ba857 100644
--- a/packages/core/openexecutive/api/routes/today.py
+++ b/packages/core/openexecutive/api/routes/today.py
@@ -2253,7 +2253,7 @@ def _sent_as_caller(request: Request) -> list[ActivityItem]:
return [
ActivityItem(
kind="sent_as_you",
- summary=(
+ summary=h.summary if h.source == "invite" and h.summary else (
f"{'Followed up with' if h.source == 'follow_up' else 'Replied to'} "
f"{h.to_name or h.to_email}: {h.subject}"
),
diff --git a/packages/core/openexecutive/architecture/architecture-facts.yaml b/packages/core/openexecutive/architecture/architecture-facts.yaml
index 83f2db84..2f82466b 100644
--- a/packages/core/openexecutive/architecture/architecture-facts.yaml
+++ b/packages/core/openexecutive/architecture/architecture-facts.yaml
@@ -10352,16 +10352,20 @@ delegation:
Eval: delegation_014.
calendar: |
Read my calendar (delegation.calendar, table delegation_calendar, one
- row per person, absent/unreadable = off). Read-only, on the Act as me
- sign-in: Google calendar.readonly, Microsoft Calendars.Read, added by
- connect-own-gmail.py / connect-own-outlook.py --calendar. Optional
+ row per person, absent/unreadable = off). On the Act as me sign-in:
+ Google calendar.events, Microsoft Calendars.ReadWrite, added by
+ connect-own-gmail.py / connect-own-outlook.py --calendar; the only
+ write is answering a meeting invite (see invites). A sign-in minted
+ earlier with calendar.readonly / Calendars.Read keeps reading
+ (CALENDAR_READ_SCOPES, CALENDAR_SCOPES) and its invite cards say to
+ connect again (calendar_write_granted False). Optional
scopes: the token refresh still requires only the mail ones; the
clients keep the scope string the refresh returns (_GRANTED) and
list_events raises CalendarNotGranted (a GmailError, not an auth error)
before calling when it is missing, or on a 403. An Outlook refresh asks
- for Calendars.Read too only when the credential file's scopes list it
- (_refresh_scope); a mail-only one never asks, so its refresh can't fail
- on it. PUT /delegation/calendar
+ for Calendars.ReadWrite (or Calendars.Read for an older file) only when
+ the credential file's scopes list it (_refresh_scope); a mail-only one
+ never asks, so its refresh can't fail on it. PUT /delegation/calendar
{enabled}: on needs Act as me on, gmail_status connected and a one-hour
list_events that works (409 act_as_me_off / calendar_not_granted, 503
calendar_error); off always works; Act as me off turns it off;
@@ -10375,6 +10379,57 @@ delegation:
calendarView, cancelled and working-location left out, one-line fields,
data-not-instructions note. Nothing kept. The Act as me addendum names
it and says reading the calendar counts as reading their mail.
+ invites: |
+ Meeting invites (delegation.invites), only with Read my calendar on
+ (watching = calendar.enabled); off, an invite is skipped "automatic" as
+ before. In inbox._consider, a message with calendar_invite goes to
+ invites.skip_reason (the watcher's rules less the reply-writing ones:
+ a calendar service's Sender header is not "automatic", no recipient
+ cap, no you_replied/draft_exists) then invites.consider. No model call.
+ Sender: inbox.relation_of + handling_relation; a stranger or an
+ unverified known sender is skipped invite_stranger / invite_unverified.
+ Event: mailbox find_invite (Gmail: the invite's iCalendar UID from its
+ text/calendar part, gmail.ics_invite, or its attached .ics, then
+ events.list?iCalUID= on the primary calendar; Outlook: GET
+ /messages/{id}?$expand=microsoft.graph.eventMessage/event, only
+ meetingMessageType meetingRequest). Skipped with reasons
+ invite_not_found, invite_not_organizer (organizer != From),
+ invite_answered, invite_past, invite_calendar_not_granted. A calendar
+ GmailError (not auth / rate limit) is retried later without backing off
+ the mail scan. Clashes (invites.clashes): calendar.events_for over the
+ meeting's window, other events' start/end only (never titles), the
+ meeting itself and declined / all-day events left out; None when
+ unreadable (clash_checked False). Card: delegation_invite decision,
+ approver_only, never an alert, payload private + event_id, title, start,
+ end, clashes, can_answer (calendar_write_granted is not False),
+ connect_command when it can't; idempotency key
+ delegation_invite:<person>:<message_id> via invites.create_once, which
+ also fixes reply cards: an open card under the key is that card, a
+ settled one gets a new card under key:<uuid>. Ledger outcome
+ invite_card, then accepted / declined / dismissed / expired. GET
+ /delegation/invites lists them (no calendar call). Approve =
+ invites.answer: caller_refusal (403 not_yours / 409
+ caller_signing_required), Act as me + Read my calendar on, live (start
+ ahead, under CARD_TTL 7 days), gmail_status connected,
+ claim_for_execution, mailbox.answer_invite(event_id, accept) — Gmail GET
+ event, set the self attendee's responseStatus, PATCH attendees with
+ sendUpdates=all; Outlook POST /events/{id}/accept|decline
+ {sendResponse: true}. CalendarWriteNotGranted -> release, can_answer
+ False on the card, 409 calendar_write_needed; GmailNotFound -> failed,
+ 409 gone; other GmailError -> release, 502 calendar_error (answering is
+ idempotent). Reject answers nothing. On its own (invites.refusal, plain
+ code): Handle it for me on; relation in KNOWN_RELATIONS; Replies in
+ training -> training.allowed_inviter (key
+ act_as_me|person:<id>|invite_from|<address>, setting replies), else
+ Take the lead as you or the dial's level; signing_ok; clash None ->
+ calendar_unread, any clash -> clash; can_answer; not sensitive(title);
+ lead rules; handle_it.count_refusal (daily limit, once a day per
+ thread). Then gate auto_execute, claim, answer_invite(accept=True),
+ finish executed, record_handled; any failure releases and hands the
+ card back. Never declines on its own. handle_it.handled includes them
+ (source invite, summary "Accepted <first>'s <title>, <when>"), so GET
+ /delegation/handled and Today's sent_as_you show them. Audit, private:
+ delegation_invite_carded / _answered / _handled / _dismissed.
forward_and_remind: |
ghostwrite_email takes forward (a thread id) with to: a draft forwarding
the thread's latest non-draft message, intent the note above it (the
@@ -10533,7 +10588,10 @@ delegation:
registered with the MCP gateway. Methods profile_email, search_threads
(metadata only), list_message_ids, get_thread, get_message, list_sent,
send_as_signature, send_as_addresses, create_draft, get_draft (None on
- a 404) and delete_draft (False on a 404), and ONE send method, send_draft:
+ a 404) and delete_draft (False on a 404); on the calendar list_events,
+ calendar_granted, calendar_write_granted, find_invite (reads) and
+ answer_invite (the person's own attendee answer on one event,
+ sendUpdates=all; delegation.invites only); and ONE send method, send_draft:
an existing draft by its id — POST drafts/send with the body {"id": ...}
and nothing else, never messages.send — called only by
delegation.reply_send (unit tests pin the method set, the one endpoint,
diff --git a/packages/core/openexecutive/architecture/prebuilt/api.json b/packages/core/openexecutive/architecture/prebuilt/api.json
index c824483a..172fd6ae 100644
--- a/packages/core/openexecutive/architecture/prebuilt/api.json
+++ b/packages/core/openexecutive/architecture/prebuilt/api.json
@@ -1,7 +1,7 @@
{
"section_id": "api",
"title": "API Reference",
- "markdown": "The FastAPI surface lives in `openexecutive.api.main`, which mounts one router per topic. A shared-secret middleware gates every request via an `x-api-key` header, except `/health` and the `/webhook/*` callbacks (which carry their own verification). A request it lets through is marked `request.state.shared_secret_ok`, which is what lets an MCP request turn on \"may act\" with `x-mcp-client-actions: on` (`mcp_server.may_act`; with no secret the header is ignored and `MCP_CLIENT_ACTIONS` decides). With local login (`OE_LOCAL_LOGIN=1`, which only `make dev` sets, and only while neither Google nor SSO sign-in is set up) a second middleware answers 403 to any request whose raw `Host` is not `localhost`, `127.0.0.1` or `[::1]` (except a webhook that verifies its caller: Google Chat and Slack always, Telegram only with a `TELEGRAM_WEBHOOK_SECRET` Telegram can send), and to any write whose `Sec-Fetch-Site` is present and not `same-origin`/`none`. The UI signs that owner in with no password and this API usually has no secret, so without it a web page in the owner's browser could drive the API as the principal — by DNS-rebinding its own hostname to 127.0.0.1, or by posting a plain form from another site or localhost port. CORS is restricted to the UI origins in `BACKEND_ALLOWED_ORIGINS`, plus the `make dev` UI on `localhost:3000` only when `OE_PUBLIC_DEPLOYMENT` is unset, so a public instance never answers a localhost page with credentials. The gate is off when `BACKEND_SHARED_SECRET` is unset — intended for local development only — so any internet-reachable deployment sets `OE_PUBLIC_DEPLOYMENT`, and `create_app()` then refuses to boot without the secret rather than serving an unauthenticated API.\n\n**Who is calling** is read in one place, `api/caller.py`, which answers with a `Caller` kind and email; a test fails on any other read of an `x-caller-*` header. By default (`open`) it is the `x-caller-email` the UI proxy stamps from the sign-in, trusted because whoever holds the shared secret is trusted as the proxy, and a request with none runs as the principal. **Signed callers** remove that trust. With `CALLER_ASSERTION_PUBLIC_KEYS` set, the proxy signs every request with an Ed25519 key only the UI holds, and a third middleware checks the `x-caller-assertion` header:\n\n- **What it covers.** It is good for one method, the exact path and query, at most 120 seconds, and one use. The API keeps used ids in memory.\n- **What it names.** A `user`, by email, or the `operator`: local login, which runs as the principal.\n- **No caller header at all** is a `service`, for scripts or MCP clients holding only the secret. It is never the principal, not even on an install with no owner yet, so it can't save a first setup.\n- **Anything else is a 401.** That includes an `x-caller-email` without an assertion (`caller_assertion_required`), and a bad, expired, reused or mismatched assertion (`caller_assertion_invalid`).\n\nPublic keys that can't be read stop the boot, rather than fall back to trusting the header. `scripts/make-caller-keys.py` makes the pair, and `scripts/mint-caller-assertion.py` signs one request for curl. The API holds only public keys. Setup's API-protection check warns while a shared secret is set without them.\n\nEndpoints grouped by router:\n\n| Router | Key endpoints | Purpose |\n|---|---|---|\n| `chat` | `POST /chat`, `POST /chat/stop`, `POST /chat/add`, `POST /chat/background`, `GET /chat/voice`, `POST /chat/transcribe` | SSE stream of a live Executive turn, with a `: keepalive` comment every `CHAT_STREAM_KEEPALIVE_S` while the turn is quiet. `POST /chat/background` starts a new chat that the server answers to the end with nobody connected (a phone approving a card, then closing the app): it answers `202` with the new `session_id` once the same caller, access and quota checks as `/chat` pass, the turn saves itself as a `/chat` turn does, and one caller may have three running at once (`429` beyond that). `POST /chat/add` hands the running turn a message the person typed while it works; the turn takes it at its next step and the stream names it in a `message_added` event, and a second `POST /chat` on the same conversation waits for the first to finish. `GET /chat/voice` says whether the chat mic shows (`available`, `max_seconds`); `POST /chat/transcribe` takes one recording (multipart `file`) and answers `{text}` for the message box, nothing kept: `404` when speech to text isn't set up, `400` for a file that isn't audio, `413` over 25 MB, `502` when the speech server fails. The request body optionally carries `page_context` (route, page title, guide section id, and a form descriptor with current values) — sent only by the Ask OE side panel so the Executive can explain the current page or propose form values. When the Executive calls its `propose_form_values` tool, the stream emits a `form_patch` event (`{type, form_id, fields, rationale, iteration}`) that the panel applies into the on-screen form as highlighted suggestions; the user reviews and saves through the form's normal submit path. Each round of tool calls also emits an `activity` event (`{type, label, tool, iteration}`) naming what is running — progress only, forwarded verbatim and never persisted with the message, unlike an `action_taken` chip. A `session_id` in the body must be a chat the caller may use (the same ownership rule as `sessions`). If it isn't, the turn runs in a fresh chat instead, so nothing is written into someone else's session and the reply looks the same as for an unknown id. An unknown namespaced id (`slack:…`, `telegram:…` and so on) is ignored and a fresh chat is started, because those ids belong to the channel adapters and claiming one first would make the caller its owner. The client mints a `client_turn_id` and sends it with the turn; `POST /chat/stop` takes that id and halts the turn mid-flight, so the button is live from the moment Send is pressed rather than only once the first SSE byte arrives. A stopped turn emits a `stopped` event and then the usual `done` over the same still-open stream — never an `error` — and whatever streamed so far is persisted and flagged. The endpoint returns 404 both for an unknown id and for another caller's turn, so it cannot be used to probe which turns are live. An optional `memory_text` (1–2000 chars) is what peer memory records as the caller's words instead of `message` — the briefing handoffs send it because their seed quotes the Executive's own card; `POST /chat/upload` derives it from the typed text and filenames. Since it never reaches the transcript, the `chat_turn` audit row keeps it beside `message`. After the reply — a stopped or timed-out one too, before the `stopped` / `error` / `done` frames — a turn that looked at anything sends one `sources` event, `{type, session_id, sources: [{kind, title, url}], unavailable: [area]}`: `kind` is `company`, `knowledge`, `notion`, `research`, `document` or `web`, `url` is only ever an http(s) link or, for an earlier document, `/artifacts/<id>`, at most 12 sources (6 from the web, pages the reply cites first), and `unavailable` names parts of the analysis (\"finance\") whose specialist failed or said nothing every time it was asked. It is persisted with the reply as `chat_messages.sources`. A request that carries `x-caller-email` marks its turn signed in (`Session.web_caller_signed_in`), which Act as me needs on a deployment without local login. |\n| `sessions` | `GET /sessions`, `GET /sessions/shared-with-me`, `GET /sessions/topics`, `PATCH\\|DELETE /sessions/topics/{topic_id}`, `POST /sessions/topics/{topic_id}/merge`, `POST /sessions/topic-areas/rename`, `POST /sessions/topic-areas/ungroup`, `GET\\|PATCH /sessions/{id}`, `GET /sessions/{id}/messages`, `DELETE /sessions/{id}`, `POST /sessions/{id}/messages/{message_id}/feedback`, `GET /sessions/{id}/followup`, `GET\\|PUT /sessions/{id}/shares`, `DELETE /sessions/{id}/shares/me`, `GET /sessions/{id}/people`, `GET /sessions/{id}/live`, `POST /sessions/{id}/typing`, `GET /sessions/{id}/export`, `POST /sessions/{id}/rewind` | List, read and delete saved chat sessions (assistant messages carry their row `id` and any `feedback`). The list is scoped to the caller, and each chat carries `preview`: its last message as one plain line, Markdown marks stripped and cut at a word near 120 characters, with `You:` before the person's own words. With `?q=` it is a search: the caller's own chats whose title or message text contains the words (case-insensitive, `LIKE` with wildcards escaped), each with `match_count` (messages that contain them; 0 for a title-only match) and `snippet` (the newest matching message, around the match, prefixed `You:` or `Executive:`). Scoped exactly like the list, so nobody else's conversation can match. The Chats page searches this way and opens a result with `?find=`, so the chat starts on that message and steps through the others. Each of the owner's chats also carries `topic_id`, the topic it is filed under (`memory.chat_topics`). `GET /sessions/topics` lists the caller's topics (`id`, `name`, `chat_count`, `kept`, `pinned_at`, `area`, `updated_at`) and, when some of their chats have no topic yet or some topics no area, starts filing them in the background from their titles and answers `organizing: true` until done. `PATCH /sessions/topics/{topic_id}` renames (a name another of their topics has merges the two) or pins one, `POST …/merge` moves its chats into another (`into_id`), and `DELETE` ungroups it, leaving its chats under no topic; another person's topic is a 404. `POST /sessions/topic-areas/rename` (`area`, `name`) renames one of the caller's areas and `…/ungroup` (`area`) drops it, its topics standing alone; an area they don't have is a 404. `PATCH /sessions/{id}` also takes `topic_id` (null for none) or `topic_name` (made if new) to file the chat, which then is never refiled on its own. A chat-app conversation started with /new is left off the list until its first turn (`memory.conversations`). Every per-session route checks ownership, because session ids are guessable (`slack:dm:<user id>`, `telegram:<chat id>`): only the session's owner or the principal gets through, and a legacy row with no owner is the principal's alone. A teammate's own chat (a web chat, a DM, a private Telegram chat; not a channel or group conversation, `chat._shared_space`) is theirs alone, the principal included, as their mail with the Executive is. Anyone else gets the same 404 as for an unknown id, so the routes can't be used to find out which chats exist. The one other way in is having started the chat in this process (matched by Person id or verified email, so it survives the caller being added to the roster), which is how a caller the roster can't resolve keeps using their own chat. That record is in memory, so after a restart such an ownerless chat is refused for reads. The principal can continue someone else's ownerless chat without becoming its owner. Deleting a session also drops its in-memory copy, so a later turn naming that id starts fresh. The feedback route records 👍/👎 (`{\"feedback\": \"up\"|\"down\"|null}`) on one assistant reply; only the session's own caller or the principal may rate it. The rater is stored (`feedback_by_person_id`), and a 👎 on a reply to the rater's own message triggers a working-style pass for them (paced; see attunement). The chat stream's `done` event carries `message_id` for the persisted reply. The followup route returns `{\"suggestion\": string|null}` — one suggested next user message, written by the utility-fast model from the last few turns, that the chat composer shows as its greyed placeholder (Tab / → or the inline chip fills it in without sending). It is null unless the session ends on a persisted assistant reply, and null (uncached) when the model fails. Same ownership check as feedback; successful suggestions are cached in-process per (session, reply id). Messages from `GET /sessions/{id}/messages` carry each assistant reply's saved `sources` (the same shape as the chat stream's `sources` event, without `type`), so a reloaded chat shows them again. The owner (not the principal on someone else's chat; the principal for an ownerless one) also has the chat controls. `PATCH` takes `{title?, pinned?}`: a name they give is kept (`sessions.title_locked`, so the automatic title never replaces it) and a pinned chat lists first, newest pin first, with `pinned_at`. `PUT /sessions/{id}/shares {person_ids}` adds exactly those team members to it (not contacts, the archived or the owner: 422), audited `session_shared`; a chat that read its owner's own mail (`mail_private`) is never shared (409) and stops being open to those it was shared with before, and a chat-app conversation is never shared (409). Those added get it from `GET /sessions/shared-with-me` (with `shared_with_you`, `shared_by`, `shared_at`) and **write in it with the owner**: `POST /chat` with its id runs their turn as themselves (`chat._shared_member` widens the turn's access, never its ownership), and they may read it, its messages (without the owner's ratings) and its export. They can't rate, rename, delete, share or redo it, and `DELETE /sessions/{id}/shares/me` takes them out of it (audited `session_shared`, with them under `removed`). In a chat several people are in, messages carry `sender_person_id` and `sender_name` (a message from before it was shared is the owner's), `GET /sessions/{id}/people` returns `{you, people: [{person_id, full_name, owner}]}` (owner first; empty for a chat of one), and redo is refused (409) when the last message is someone else's. `GET /sessions/{id}/live` is a server-sent event stream each open page holds (`api.chat_live`, one in-process broker): `ready` first (with the running turn so far, if any), then `turn_started` (who sent what), the reply's `chunk` / `thinking` / `activity` / `action_taken` / `phase`, `turn_ended` (the page reads the chat again), `typing` (from `POST /sessions/{id}/typing`, at most once per 2 s per person) and `people`. `removed`, `deleted` and `resync` (a page that fell 1024 events behind) end it; the access check runs again on every 20 s keepalive. At most 12 pages per person, 40 per chat and 2000 per process (429). Archiving someone takes them out of every chat shared with them, and their open streams close at the next keepalive. The page closes it while its tab is hidden. `GET /sessions/{id}/export` returns the chat as a Markdown file (`memory.chat_export`: each message under its writer's People name or `Executive`, the reply's sources listed under it). `POST /sessions/{id}/rewind {last_message_id}` takes back the last turn for Try again and Edit: under the conversation's turn lock it deletes the last reply and the messages it answered, but only while that reply is still the chat's last row, and returns those messages' words (`{message}`), which the page sends again as an ordinary `/chat` turn through the usual gates. 409 while a turn is answering, for a stale reply id, and for a chat-app conversation (its reply also lives in Slack, Telegram or Discord); audited `session_rewound`. |\n| `today` | `GET /today`, `GET /today/activity`, `GET /today/activity/daily`, `GET /today/brief-delivery`, `GET /today/value`, `GET /today/top-three`, `GET /today/weekly-review`, `POST /today/seen` | Morning-brief aggregation (in the install's first week, for the principal, `first_week_card` `{needs_goal, findings: [{title, summary}], brief_tomorrow}` or null), recent-action rail, Pulse heartbeat heatmap (per-day activity counts), and the owner's month tally for Pulse's Done for you (`GET /today/value?period=month|week&offset=N`: counted lines beside the period before plus the finished reports, owner only, 403 otherwise; see Today). `GET /today` carries the viewer's cached \"What's going on\" `narrative` with `narrative_generated_at` (when it was written) and `narrative_stale` (a fresher one is being written — the page re-polls; see Today), the same text split for Home's Right now card (`narrative_lead`, `narrative_points` `[{text, since}]`, `narrative_move`), `narrative_seen_at` (this reader's last look, which `POST /today/seen` records and returns as `{seen_at}`) and, for the principal, `morning_brief` `{at, text}` and `calendar_next` `[{title, start, all_day}]`. A proposal backed by a roster request carries `roster_request` (the new sender's server-derived details and held-message previews; the principal's only) and is answered through the `people` routes below. `brief-delivery` returns the latest morning brief or end-of-day digest that didn't reach the owner, as `{brief, at, problem, fix, readable}` in plain language (`readable` is false when it couldn't be written, so there is nothing to read), or null — null while briefs go out, once the cause is fixed, while the scheduler is off, and for anyone but the owner (`chat._caller_is_principal_or_unclaimed`); it carries no address or channel id. `top-three` and `weekly-review` feed the solo Briefing's own cards and answer only in solo mode and only to the principal (`workflows._caller_is_the_principal`: a principal match or no caller header, never an unclaimed roster); anyone else, and team mode, get null. `top-three` returns `{items: [{key, kind, text, why, slot}]}` — the morning brief's top three from the same code (`build_top_three(principal_due_soon())`), `slot` a free block like `10:00–11:00`, `\"\"` when none is left, null when no calendar was read — and is kept off `GET /today` because its calendar read may take up to 4 s. `weekly-review` returns the latest completed `weekly_review` run as `{run_id, completed_at, period, top_three, excerpt}` (next week's top three as plain text; `excerpt` when that list is empty), or null when none has completed. |\n| `people` | `GET\\|POST\\|PATCH /people`, `POST /people/{id}/archive`, `GET /people/requests`, `GET /people/requests/{id}`, `POST /people/requests/{id}/approve`, `POST /people/requests/{id}/decline`, `GET\\|POST /people/{id}/open-loops` (a `POST` tells the owner once and returns `notified`: `sent` with the channel, `held`, `not_reached` or `skipped`; see Attunement), `POST /open-loops/{loop_id}/close`, `GET /people/{id}/outreach`, `GET\\|PUT\\|DELETE /people/{id}/attunement` | Roster CRUD and scope lookups. Every `Person` carries `kind` (`team` / `contact`). `GET /people` lists team members only unless `?include_contacts=true` (the People page asks for both; the department-head and workflow pickers keep the default); `POST` / `PATCH` accept `kind`, and a principal contact is a 422 either way. They also take `email_aliases` (other addresses the person writes from, at most 10; on `PATCH` the full list replaces the current one, omitted leaves it): an alias matches their mail and may be emailed but never signs in; a malformed one is a 422, and an alias — or a new primary `email` — that is already someone else's address or alias is a 409. Every `POST` / `PATCH` then closes any pending roster request whose sender now matches someone and replays its held messages. Adding, editing and archiving (`POST`, `PATCH`, `/archive`) are the principal's only, or anyone's while no one is principal yet so a first setup can add its owner (`chat._caller_is_principal_or_unclaimed`, the check behind `PUT /workspace`; a request with no `x-caller-email`, such as the CLI or local login, counts as the principal). Anyone else, a person editing their own row included, gets 403 before the person lookup, so it can't probe which ids exist. Contacts are private to the principal (`caller_is_principal`: the signed-in email is the principal's, or no `x-caller-email`; stricter than the owner rule above, so while no one is principal nobody is): for anyone else `include_contacts` is ignored, a contact's id is a 404 on `GET /people/{id}` and open-loops (exactly as for a missing id; `PATCH` and archive are already a 403 for them), and creating a contact or turning someone into one is a 403, even on a first setup with no principal yet. `GET /people/me` returns `{person_id, is_principal}` so the UI offers contacts to the principal only. `GET /people/by-scope/{token}` never returns a contact. Archiving a person closes their open loops. The open-loop routes list what a person owes (soonest due first) and close one (`reason`: done / not_needed / cancelled) — both the principal's or the owner's only (403 otherwise, via `people.store.is_principal_or_self`). `POST /people/{id}/open-loops` `{task, due_date?}` assigns that person a task (201 with the loop; `due_date` is a local date, due 17:00 in the user's timezone, clamped to 60 days, default 2 days): any active team member may assign anyone on the team, 403 for anyone else; 409 for an archived person, a contact (as seen by the principal), a person at the open-loop cap, a duplicate or open loops turned off; 422 for an empty task. Nobody is messaged at assignment — the owner is chased once it is due. `/outreach` returns, per kind of proactive outreach over 30 days, `sent` / `replied` / `acted` / `ignored` / `pending` (voided DMs are excluded) — same access rule, checked before the person lookup so it can't probe which ids exist. `/attunement` reads, replaces (`rules`: up to 4 strings, or omitted to only set `locked`) or resets the person's working-style rules — same access rule, 404 for an archived person; `PUT` rejects a rule that is not purely about style with 422. Archiving a person also drops their working style and frees their aliases. The **roster-request** routes (declared before `/people/{person_id}`) are the principal's alone (`caller_is_principal`; anyone else gets 404, as for a missing id): `GET /people/requests?status=pending|approved|linked|declined|expired|superseded|all` lists up to 100 (`id`, `channel`, `channel_ref`, sanitised `display_name`, `profile_email`, `on_company_domain`, `suggested_kind`, `suggested_person_id` / `_name`, `status`, `resolved_person_id` / `_kind`, `message_count`, timestamps, `ack_sent`, and `previews` of the held messages while pending — shown to the principal, never to a model); `approve` takes either `link_person_id` (+ `replace_channel_id`) or `full_name` + `kind` (no default: 422 without both) + optional `role`; `decline` takes no body. An answered request is a 409, a chat id or address already on someone else is a 409; the held messages are replayed (or dropped) in the background. |\n| `contacts` | `GET /contacts/changes?person_id=`, `PUT /contacts/keeper`, `POST /contacts/changes/seen`, `POST /contacts/changes/{id}/undo`, `POST /contacts/changes/{id}/accept`, `POST /contacts/changes/{id}/dismiss` | The contact keeper (see Org), principal only (404 for anyone else). `GET` returns `{mode, status, last_run_at, changes}`: the switch (`on` / `ask` / `off`), how the last pass went (`ok`, `act_as_me_off`, `not_connected`, …) and the last 30 days of changes (each `id`, `person_id`, `action` add/update, `field`, `email`, `full_name`, `old_value`, `new_value`, `reason`, `evidence`, `status` applied/suggested/undone/dismissed, `seen`, `created_at`); with `person_id`, that person's every change. `PUT` sets the switch; `seen` is Got it; `undo` / `accept` / `dismiss` return the change, 409 when there is nothing to undo or decide. |\n| `chat-directory` | `GET /chat-directory/people`, `GET /chat-directory/channels`, `GET /chat-directory/slack/lookup?email=` | The Slack, Discord and Telegram people and rooms the bots can reach, by name, for the People and department pickers (`integrations/chat_directory.py`). Each answers `{slack, discord, telegram}`, every one `{configured, ok, options: [{id, name, detail, email}], truncated, members_available}`: `configured` false (and no options) when that bot has no token, `ok` false when the provider could not be read, `members_available` false when Discord refuses to list server members (the Server Members intent is off). `lookup` returns `{configured, match}`, the Slack person with that work email or null. Cached in-process for 60 s; tokens are never returned. The principal's alone, like changing the People list (`chat._caller_is_principal_or_unclaimed`); channels also open while no one is principal yet, people and lookup wait for one; a 403 otherwise, and the pickers then keep only the by-hand id field. |\n| `departments` | `GET\\|POST\\|PATCH\\|DELETE /departments`, `.../goals`, `POST /goals` | Department state and per-department goals. `POST /goals` takes a goal plus `area` (a name, ≤80): an existing area by slug or title, else a new one of that name (no specialist, as with `POST /departments`), else **General** when blank; the Goals page uses it while a workspace has no areas (setup makes none for solo or a team that names none). `PATCH /departments/{slug}` also takes `watched_entities` (≤50 names, `[]` clears) — the entities the research watch policy may add watches for and route to this department. A `cadences` spec that does not parse is rejected with a 422 (empty means no cadence, i.e. the check-in is off); a changed `check_in` cancels the pending check-in and queues the next one on the new schedule. `GET` and `PATCH /departments/{slug}` return the department state plus `next_check_in_at` (ISO UTC of the pending check-in, `null` when it is off, the workspace is solo or none is queued); the list route does not carry it. A new `head_person_id` must be a team member: an unknown id and one of the principal's contacts get the same name-free 422 (`person_id N is not on the team.`), so the route — open to any signed-in user — never reveals that a contact exists; an unchanged head is not re-checked. `POST .../goals` requires only `key_result`: a missing or blank `period_value` is filled with the current period for `period_type` in the user's zone (the same label `create_goal` uses), and `target` defaults to empty. `PATCH .../goals/{id}` rejects a blank `key_result` or `period_value` with a 422; `target` may be cleared. |\n| `agents` | `GET /agents`, `GET /agents/models`, `GET /agents/models/options`, `GET /agents/presets`, `POST /agents/presets/{id}`, `PATCH /agents/{id}`, `POST /agents/{id}/test` | Specialist metadata and Council overrides. `/agents/models` is the flat model allowlist the PATCH validator uses; `/agents/models/options` returns the same ids in the same order, each tagged with `provider`, `provider_label`, `route` (`direct` / `openrouter` / `local`) and a display `label`, for the Council's Provider → Model picker. `AgentDetail` carries `instructions` (additional instructions, appended after `prompt`, which stays the built-in prompt or its replacement); `PATCH` and `/test` accept `instructions` (max 4,000 chars, blank clears it). `GET /agents/presets` lists the Fast, Balanced and Thorough quality presets (each with `available` and the resolved `model` for this install) plus `active` (null when the council is Custom), `base` and `custom_agents`; `POST /agents/presets/{id}` applies one by writing per-agent model and deep-reasoning overrides and returns the same shape (404 unknown preset, 409 when the install allows none of its models). Each `AgentMeta` carries `visibility` (`core` or `internal`) so the Council's simple view can list core agents first. |\n| `personas` | `GET\\|PUT\\|POST\\|DELETE /personas` | Executive persona definitions. |\n| `alerts` | `POST /alerts/{id}/approve`, `GET /alerts/approvals/{id}`, `POST /alerts/{id}/ack`, `POST /alerts/bulk-ack`, `POST /alerts/{id}/snooze`, `POST /alerts/{id}/reopen`, `POST /alerts/review` | Groom the briefing queue. `approve` (body `{edited_body?}`, 202) carries a proposal card out on the server and records who approved it and when (`alerts.approvals`, see Today): it queues the scheduled action a department-gated card held, or runs one Executive turn as the approver in a new chat (`session_id`). 409 for a card already approved or closed, a decision-backed card (approved at `/decisions`), a roster request or a drafted artifact; 403 unless the caller is the card's routed person or the principal (an unrouted card is the principal's); 429 when the caller already has three background turns running. `GET /alerts/approvals/{id}` reads one back (`running`, then `done` / `failed` with `outcome`) for its approver, the card's person or the principal (404 for anyone else). `snooze` (`until`, an ISO time up to 30 days ahead; `null` clears it, the Undo) hides an `unread` card until then by setting `snoozed_until` (409 on a closed card or a roster request); the TTL then counts from the snooze, so a card snoozed past its TTL still comes back. `ack` (`read`/`ack`/`dismissed`, optional `mute_topic`) also teaches a watch-sourced alert's watch (`trust_score`); `bulk-ack` takes explicit `alert_ids` and/or `older_than_days` + `category` (exempt sources skipped); `reopen` is the Undo for a `resolved` / `expired` / `dismissed` alert (never `ack` or an artifact / decision row; back to `unread` with every review stamp cleared and its TTL anchor refreshed, so it is live again even if older than its TTL); `review` runs the Executive's relevance review on demand (ignores the interval; still honours `ALERT_REVIEW_ENABLED`, the per-pass caps, the single-flight lock and per-alert idempotency) and returns the move counts. `bulk-ack` caps ids at 500, needs `older_than_days >= 1`, and applies watch feedback per row; `mute_topic` must be one of the alert's tags or a scoped `external:` / `department:` pattern. Alerts still surface only through the briefing (`/today` reads the live view) — there is no list, prefs, mutes, or live-stream endpoint. |\n| `artifacts` | `GET /artifacts`, `GET /artifacts/{id}`, `GET /artifacts/{id}/download?as=`, `POST /artifacts/{id}/archive`, `POST /artifacts/{id}/restore`, `DELETE /artifacts/{id}` | Browsable deliverables in any format — Markdown, HTML, Word, Excel, or a link into a connected app — with `format`, `downloads`, `external_url`, `supersedes_id` and, for an extension's kind of document, `collection` / `collection_label` on every summary (`orchestrator.extensions`; archive, restore and delete tell the collection first and answer 502 if it refuses). `download` renders the file (Word/Excel built at request time from the stored text; any Markdown artifact, workflow output included, can export `?as=docx`) and is always an attachment with `nosniff` and a sandbox CSP. Every route answers for the signed-in caller (`artifact_records.Viewer`): a drafted artifact is its owner's alone (`alerts.owner_person_id`, the person whose conversation published it; none = the principal's), a workflow output follows its run (`persistence.run_visible_to`), and anything the caller may not see is a 404 like a missing id, the principal included. `POST /alerts/{id}/ack` and `/reopen` answer 404 for someone else's drafted artifact the same way. |\n| `decisions` | `GET /decisions`, `POST /decisions/{id}/{approve,reject,cancel}`, `GET`/`PUT /decisions/classes/meeting_scheduling`, `GET /audit/reliability` | Approval-gated decision instances (e.g. calendar bookings). What approve/reject/cancel do is per class (`DECISION_CLASSES`, one `DecisionClassSpec` each; meeting booking books on approve and deletes on cancel; `delegation_reply`, an inbox reply card, is its approver's alone (`approver_only`) — hidden from everyone else, the principal included when it is a team member's — sends its Gmail draft on approve and, after a reject, deletes the draft unless it was edited; `department_action`, a team member's chat send or edit their department held (see Org), is the principal's and its approver's alone (`principal_and_approver`), makes that exact call on approve and audits `department_action_done` / `_failed` / `_declined`), and an instance of a class with no spec gets 409 instead of being carried out as another. Only the principal, or the person the decision went to for approval (`approver_person_id`), may approve, reject or cancel it. Anyone else gets 403, and a decision nobody was asked about, or one private to the principal, is the principal's alone. The resolver is recorded as `resolver_person_id`, and a reject that loses the race to another answer is a 409. `GET /audit/reliability` is the principal's alone (403 otherwise), because it counts private decisions too. A proposed booking is surfaced on the briefing as a companion alert; approve/reject/cancel here also clear that alert. An approval whose caller resolves to the principal runs the booking inside `grant_contact_egress()`, so a meeting the principal proposed with a contact can be created. Such a booking's payload is marked `private`: it is proposed to the principal, left out of anyone else's `GET /decisions`, and a 404 for them on `GET /decisions/{id}` and every action route. Reviewed in the briefing — there is no separate proposals page. The class routes read and set how meetings are handled: both return `{decision_class: \"meeting_scheduling\", mode: \"propose\" \\| \"auto_execute\"}` (default `propose`); the `PUT` body is `{mode}`, principal-only (403 otherwise, open before a principal exists — but then only `propose` can be set: `auto_execute` is a 409 until a non-archived principal is on the roster), 422 on any other mode, and a change writes a `decision_class_mode_changed` audit row. In solo mode the class mode decides a booking, and `auto_execute` applies only to a turn the principal started on a verified surface — any other turn gets a proposal. |\n| `delegation` | `GET`/`PUT /delegation`, `GET`/`PUT`/`DELETE /delegation/voice`, `POST /delegation/voice/learn`, `POST /delegation/voice/describe`, `POST /delegation/voice/signature`, `PUT /delegation/inbox`, `POST /delegation/inbox/check`, `GET /delegation/replies`, `PUT /delegation/replies/{id}/text`, `PUT /delegation/replies/{id}/recipients`, `POST /delegation/replies/{id}/answer`, `GET /delegation/actions`, `PUT /delegation/handle-it`, `PUT /delegation/disclosure`, `PUT /delegation/training`, `DELETE /delegation/learned/{id}`, `GET /delegation/handled`, `PUT /delegation/team` | Act as me — the **caller's own** delegation only; nobody sets it for anyone else. It answers the principal, and a team member once the owner lets them; anyone else gets 403 `not_available_yet`. `GET /delegation` returns `{enabled, gmail: {status, message, email, connect_command, outlook_connect_command, provider}, inbox: {enabled, status, message, watch_since, last_poll_at, checking}, handle_it: {enabled, mode, available, sent_today, lead, lead_available}, training: {replies, follow_ups, actions, drafts, learned}, disclosure: {enabled, handle_it, approved_sends, line}, team}`, where `team` is the owner's switch for the principal while `DELEGATION_TEAM_MEMBERS` allows it — `{enabled, members: [{person_id, name, enabled, inbox, drafts_30d, sent_30d}]}`, counts only — and `null` otherwise. `PUT /delegation/handle-it` takes `{enabled?, mode?}` (`mode` is `careful`, `balanced` or `bold`; anything else is a 422 `bad_mode`) from a caller the API knows is that person — 403 `not_yours`, 409 `caller_signing_required` with only the shared secret — and turning it on needs Act as me and Draft replies to my inbox on (409 `act_as_me_off` / `inbox_off`); `GET /delegation/handled` returns `{replies: [{decision_id, sent_at, to_name, to_email, subject, body, open_questions, gmail_link, source}]}`, the caller's replies and follow-ups (`source` `follow_up`) sent on its own in the last 7 days; a card on `GET /delegation/replies` carries `source` the same way, `can_allow` while Replies (Follow-ups, on a follow-up) is in training, and `learns_style` while Drafts is. `PUT /delegation/disclosure` takes `{handle_it?, approved_sends?}` (any other field is a 422), the caller's own switches for the AI line on replies sent as them (`disclosure.enabled` is the install's `AI_DISCLOSURE`); turning one on needs no signed sign-in, turning one off does (409 `caller_signing_required`), and a change is audited as `delegation_disclosure_changed`. `PUT /delegation/training` takes `{replies?, follow_ups?, actions?, drafts?, actions_on?}` (any other field is a 422; `actions_on` is Suggested actions On, and `actions` and `actions_on` set true clear each other) and returns the `GET /delegation` shape, whose `training` carries `actions_on` too; putting Replies or Follow-ups in, or Suggested actions out of training or On, needs no signed sign-in, anything else does (409 `caller_signing_required`), and putting Replies or Follow-ups in turns Take the lead as you off (`PUT /delegation/take-the-lead` on answers 409 `in_training` while they are). `training.learned` is `[{id, label, setting, example, uses, created_at}]`, what the caller allowed or kept in training (`setting` `replies`, `follow_ups`, `actions` or `drafts`; the kept example, or \"\"); `DELETE /delegation/learned/{id}` removes one of the caller's own (404 for anyone else's). `PUT /delegation/team` takes `{enabled}` from the principal alone (403 `principal_only`; 409 `not_available` when the install doesn't allow it). The Gmail `status` is `connected`, `not_configured`, `needs_reconnect`, `mismatch`, `no_email`, `shared_mailbox` or `error`, checked live with Google on each call. `PUT` takes `{enabled}` (any other field is a 422); turning it on needs the caller's own Gmail connected, otherwise a 409 whose code says why (`gmail_not_connected`, `gmail_needs_reconnect`, `gmail_mismatch`, `no_email`, `shared_mailbox`, `gmail_error`). The voice routes show, learn (from the caller's sent mail, one pass at a time — a 409 `in_progress`, `locked`, `too_soon`, `not_enough_mail`, `no_profile` or `changed` when it was locked or edited while learning, or a Gmail code), write it from the caller's own description (`POST /delegation/voice/describe` with `{description}`: one model call applies their words to the profile they have and returns it with a short `sample_reply`, saving nothing, so they review it and save it with `PUT`; a 409 `empty`, `too_long`, `in_progress`, `too_many` past 10 an hour or `no_profile`; no mailbox needed), edit and lock, and reset \"How I write\": a typed field that fails validation is a 422 `invalid_voice` listing each `rejected` field, and `clear_exemplars` / `clear_signature` drop those. `POST /delegation/voice/signature` reads the signature from the caller's Gmail settings again and changes nothing else (a locked profile stays locked), with the same Gmail codes as learning: a 409 when their mailbox isn't connected, it refuses the sign-in or the check itself fails (`gmail_error`), and a 502 `gmail_error` when reading the signature fails. On an Outlook mailbox it is a 409 `signature_unavailable`, since Outlook gives apps no signature to read, and the stored one is left alone. A caller `can_delegate` refuses — anyone but the principal, for now — gets 403 `not_available_yet`, which hides the Settings card. A request with no `x-caller-email` is a 403 `sign_in_required` unless the API runs under local login — a header-less call is not a sign-in (the caller is read through `api/caller.py`, as on every principal-only route). `PUT /delegation/inbox` takes `{enabled}` and turns **Draft replies to my inbox** on or off, returning the same shape as `GET /delegation`: on needs Act as me on (409 `act_as_me_off`) and the mailbox connected (the Gmail codes above, which keep their names for an Outlook mailbox too), and turning Act as me off turns it off too. `POST /delegation/inbox/check` starts a scan now in the background and answers 202 with the `inbox` state (409 `inbox_off` or `in_progress`). `GET /delegation/replies` returns `{cards: [...]}`, the caller's open reply cards from the database alone (no Gmail call): the decision id, the sender's name, address, relation and whether it was verified, the subject, when it arrived, what they wrote, the draft's recipients, subject and body, `open_questions`, `flags` and a Gmail link built from a fixed prefix. **Send** is `POST /decisions/{id}/approve`: it sends the card's draft exactly as it is in Gmail, after checking again that the caller is its owner — which on a server needs signed callers (409 `caller_signing_required` otherwise) — that both switches are on (`inbox_off`), no client slot is active (`client_slot`), the Gmail is connected (the Gmail codes), the draft is still there and unanswered (`draft_gone`, `you_replied`) and its recipients are allowed (`no_recipients`, `too_many_recipients`, `executive_recipient`, `not_from_you`). Recipients that changed, or a newer message in the thread, answer 409 `{code: \"confirm\", message, reasons, recipients}`; approving again with `edits: {recipients: <the list shown>, thread_moved_on: true}` is the second yes. Send with the *on its own next time* tick adds `edits.allow: true`: 422 `cant_allow` unless Replies (Follow-ups, on a follow-up card) is in training, 409 `learned_full` when their list is full, both before anything is sent; `edits.example: true` keeps a draft edited in the mailbox as how they write to that person while Drafts is in training. A draft edited in Gmail between those checks and the send is not sent (`draft_changed`). A double tap sends once (`already_handled`); Gmail refusing answers 429 `rate_limited` or 502 `gmail_error` with nothing sent, and a send Gmail didn't confirm answers 502 `send_unconfirmed` and is settled by the next inbox scan. Dismiss is `POST /decisions/{id}/reject`. `GET /delegation/actions` returns `{cards: [...]}`, the caller's own approval cards (`delegation_actions`): the decision id, when it was made, a one-line `why`, and each action's `index`, `kind` (`invite`, `message`, `add_contact`), `summary` and `text` (a message as it will be sent, or a meeting's description). **Approve** is `POST /decisions/{id}/approve` with `edits: {only: [indexes]}` (and `allow: true` for the *Do this on its own next time* tick while Suggested actions is in training: 422 `cant_allow` otherwise or when nothing on it can be allowed, 409 `learned_full`; a card carries `can_allow`); it needs the card's own person signed in (403 `not_yours`, 409 `caller_signing_required`), Act as me on (409 `act_as_me_off`) and a card under a week old (409 `expired`), runs once (409 `already_handled`), and returns the decision with `final_payload_json.results`: per action `done`, `waiting` (sent to whoever approves meetings), `failed` with why, or `skipped`. Every change writes a private audit row. |\n| `history` | `GET /memories/history` (`?q=`), `PUT /memories/history/settings`, `PATCH`/`DELETE /memories/history/{id}`, `POST /memories/history/{id}/forget-conversation` | Always in the loop: the **caller's own** notes and switches only, resolved as for Act as me (a signed-in person on the roster, or the principal under local login; otherwise 403 `sign_in_required` / `not_on_roster`). `GET` returns `{notes, reply_notes, retention_days, effective_retention_days, company_retention_days, retention_choices, can_keep_notes, can_note_replies, can_set_company_retention, share_work_style, can_share_work_style}` (`can_keep_notes`: a team member on the People list may turn notes on; `can_note_replies`: they can use Act as me, so email replies are noted too; `share_work_style`: their own \"Share my work style with the team\" switch, `can_share_work_style`: a team member in a team workspace). `PUT` turns notes on only for someone who may keep them, and `share_work_style` on only for someone who may share it (403 `not_available` for either; turning either off always works), takes a person's retention only when shorter than the company's (422 `invalid_setting`), and the company retention only from the principal (403 `principal_only`). `PATCH` pins or corrects a note; `DELETE` forgets it; `forget-conversation` is \"Don't remember this\". A note that isn't the caller's is 404. Every change is audited privately to its person. |\n| `reflection` | `GET /memories/reflection` (`?person_id=`), `DELETE /memories/reflection/misses/{id}` | Learning: the turns the conversation review graded a miss (`memory.chat_review`), with the person's words, the reply, the tools run, what they wanted instead, the `kind` (`company` / `product`) and the signals, plus `weeks` (`{week, graded, misses}` per ISO week, newest first) and `sees_everyone`. The caller is resolved as for `history` (403 `sign_in_required` / `not_on_roster`); each person sees their own, the principal those from chats `chat._session_access` lets them open (a teammate's own web chat or DM and a mail-private conversation stay their owner's; channels and groups are open), or one person's with `?person_id=` (a teammate naming someone else gets 403 `not_yours`); the weekly counts carry no words and are not filtered. The same response carries `lessons` (`memory/lessons.py`: live first, then retired, each with `shown`/`fine_after`/`miss_after` and `retired_reason`), filtered by the same rule, and `DELETE /memories/reflection/lessons/{id}` retires one (204; 404 for a lesson the caller may not see, already retired, or missing). `DELETE` forgets one miss (`is_principal_or_self`; 404 `not_found` otherwise) and writes a `chat_review` audit row. Each miss also carries its nightly replay (`memory/replay.py`): `replay_state` (`open` / `closed` / `evidence`), `replayed_at`, `closed_at`, `replay_notes`; and the response carries `replay` (`{misses, would_pass, evidence, last_run_at}`: of the caller's visible misses from the last 30 days, how many would go right today). |\n| `notifications` | `GET /notifications/settings`, `PUT /notifications/settings` | Settings → Notifications: the **caller's own** settings only, resolved as for the notes (a signed-in person on the People list, or the principal under local login; otherwise 403 `sign_in_required` / `not_on_roster`). `GET` returns `{quiet_hours: {enabled, start, end, days}, delivery, urgent_through, timezone, effective_timezone, held_count, gets_briefs, updated_at}` — `days` is `every_day` or `weekdays`, `delivery` `instant` or `digest`, `timezone` the zone they chose (`\"\"` for the workspace's), `held_count` how many messages wait for their quiet hours or brief (counted, never listed), `gets_briefs` whether they are the principal. `PUT` takes `{quiet_hours, delivery, urgent_through, timezone}` and replaces them (extra fields, equal start and end, a bad time or an unknown zone → 422); switching `digest` → `instant` makes what waited for the brief go now. Audited as `notification_settings_changed`. See Org. |\n| `audit` | `GET /audit/logs`, `GET /audit/logs/{id}`, `GET /audit/sessions/{id}`, `GET /audit/usage`, `POST /audit/log` | Durable audit trail of side effects. `/audit/sessions/{id}` adds a per-session token cost summary; `/audit/usage` aggregates token usage and OpenRouter cost across all sessions (totals, by day, by model, and by source — the part of the system that made the calls — including server-side web-search counts), plus `scripts`: how many `run_script` scripts ran (and worked, and in workflows), the tool calls they made, their time, and `turns_avoided` — an upper bound on the model turns those calls would otherwise have needed (each call past a script's first) — and `python_jobs`: how many Python jobs ran (and worked, ran a kept Custom tool, took a chat attachment), their time, CPU, largest peak memory and bytes in and out, and the tokens and charge of the turns that ran one. The Token usage page shows it as a Scripts section. Rows private to the principal (`private_to_principal`: a turn about their private mail, or a row naming one of their contacts on their own turn) are theirs alone: for any other caller, resolved as for `/alerts`, the usage totals leave them out. Once a principal is on the roster, anyone else reads only their own rows (a teammate's own turns, their Act as me work) in the list, by id and in a session, and the principal reads those as actions only — what was done, when and in whose conversation, with the text, details and `full` left out, and no text search over them; any other row's id is a 404, and a session shows only the rows the caller reads. |\n| `architecture` | `GET /architecture/sections`, `.../sections/{id}` | This documentation surface. |\n| `guide` | `GET /guide/sections`, `.../sections/{id}` | Plain-language user-guide content surface — mirrors `architecture` (static, version-controlled files; no LLM on the serving path). |\n| `health` | `GET /health`, `GET /health/honcho` | Liveness probes. Only `/health` is unauthenticated; `/health/honcho` sits behind the gate like everything else, because the exemption is an exact-path set. `/health` also carries `google_tools_missing`, the pinned Google tools startup priming could not find: `[]` once it has checked and they are all there, a list of names when a workspace-mcp rename or the configured services and tool tier left one out, and `null` for no answer — Google Workspace is not configured, or the probe has not finished or it failed. Only `[]` asserts they are present. It also carries `gateway`, the MCP gateway's state from its supervisor (`orchestrator.gateway_boot`): `state` is `off` (MCP not enabled), `no_servers` (enabled, the config names none), `starting` (an attempt is running), `up` or `down` (every attempt so far failed; `next_retry_at` is the next one), with `attempts`, `up_since` and `email_poller` (whether the poller that rides on the gateway runs); the failure's own text stays out, since the route is open to anyone, and goes to the log and the owner's notice on Home. A hosted instance whose gateway never came up used to answer `ok` here with no email going out or in. Only `[]` asserts the tools are present, so a probe that died cannot read as healthy; Setup status says which of the three `null` means. |\n| `version` | `GET /version` | The running version, the latest release on GitHub and `update_available`, for Settings → About. The GitHub answer is cached 6h, only a semver `tag_name` is used and the release link is built from it; `UPDATE_CHECK_ENABLED=false` skips the call and still returns the running version. No in-app updater: upgrading is host-side (`docs/deployment.md#upgrading`). |\n| `setup_status` | `GET /setup/status` | Settings → Setup status: one light per part of the install — AI model, company setup, owner, the Executive's address, API protection, Gmail, your own mailbox (Act as me), Slack, Discord, Telegram, Google Chat, the scheduler, the daily brief (when and where it goes) and Honcho — as `{checked_at, checks: [{id, label, state, summary, fix, link, last_activity}]}`, where `state` is `ok`, `warn`, `error` or `off` (optional and not set up), `fix` says what to do in plain language, `link` is an in-app page that helps (`/people`, `/onboard`) and `last_activity` is the channel's latest `integration_inbound` audit time. It tests live, with at most one free read-only call per service, each bounded to 5 s: Anthropic `models.list` (so an organisation key missing `ANTHROPIC_WORKSPACE_ID` shows up), Slack `auth.test`, Telegram `getMe` and `getWebhookInfo`, Discord `users/@me` only while the bot is still connecting, and — once the owner's own Gmail credential exists — Google's token refresh and Gmail `users/me/profile`. It also reads the listeners the lifespan leaves on `app.state` (Slack's socket, the Discord bot and its task, the MCP gateway), the scheduler heartbeat and the pause switch. When `google_workspace` is configured, the lifespan also starts `MCPGateway.prime_pinned_tools()` in the background (held on `app.state.mcp_prime_task`, cancelled at shutdown), so the pinned Google tools named in the prompt are callable without a search. With `DRIVE_SYNC_ENABLED` the lifespan also bootstraps the `drive_sync_scan` heartbeat beside Notion's (see Scheduler); the Drive folder sync has no HTTP route, only the `openexecutive sync-drive` / `purge-drive` CLI. With `CONFLUENCE_SYNC_ENABLED` it bootstraps the `confluence_sync_scan` heartbeat the same way; that sync is run by hand with `openexecutive sync-confluence` / `purge-confluence`. Sample values copied from `.env.example` are named as such without being sent anywhere. No token reaches a response or a log line: probes report a status code, a service's short error code or an exception's class name. Requests within 5 s of a run get that run's answer and concurrent requests share one run (kept per app on `app.state`), so the button can't become a stream of calls to those services. Gated like every other route; the UI adds a sign-in light of its own, from its own settings. |\n| `documents` | `POST\\|GET\\|DELETE /documents`, `GET /documents/{filename}`, `GET /documents/sources`, `POST /documents/sources/{drive\\|onedrive\\|notion}/sync`, `GET /documents/{drive\\|onedrive\\|notion}`, `GET /documents/{drive\\|onedrive\\|notion}/{id}` | Upload, list, view extracted text, and delete indexed company docs. `GET /documents` rows carry `source: \"upload\"` and the `domain` the upload was indexed under. The connected-source routes back the knowledge page's single Company documents list: `/documents/sources` gives each source's `{id, label, enabled, syncing, last_run, last_error, interval_minutes, file_count}`; `/documents/drive`, `/documents/onedrive` and `/documents/notion` list synced files from the sync state (`{enabled, last_run, last_error, files: [{id, name, url, modified_at, synced_at, indexed}]}`; a Drive row also carries `unreadable_reason`, why a file with `indexed: false` has no text — e.g. a scan OCR could not read — or null); `/documents/{drive\\|onedrive\\|notion}/{id}` returns the stored text (a OneDrive id is `<drive id>:<item id>`) for an id on record (the path comes from the state, never the caller). They are read-only — a synced file is removed where it lives. `POST …/sync` starts one tick of the same sync the scheduler runs as a background task (202); 409 when the source is not connected or a tick is already running (every sync holds a per-process run lock, so a manual run never overlaps the heartbeat; the route also keeps its own started task per source and re-checks just before starting one, so two simultaneous requests start one tick, not two), 429 with `Retry-After` within 60 s of the last successful run or of the end of the last tick in this process, failed ones included, so a failing or slow source can't be re-run back-to-back. The page's text view never loads images from synced content (a remote image would be a read beacon for whoever edits the shared folder). Upload is keyed on the filename, so re-uploading a document replaces its chunks rather than duplicating them, and `DELETE` removes the rows as well as the file. `domain` must be one of the nine specialist domains (including `sales`) or `general`; anything else is a 400 rather than a 200 that indexes where no specialist can retrieve. A scanned PDF is converted (`knowledge.pdf_reader`) before it is indexed and in the text view, as are scanned PDFs in `POST /chat/upload` and the client / onboarding intake uploads. The upload is streamed to disk 1 MB at a time and refused with a 413 once it passes 50 MB, and the file is parsed in a short-lived child process (see the RAG section), so a large document does not stay in the API process's memory. A Word or Excel file that cannot be parsed, or whose parse runs out of time, is a 422 with a readable reason. When every parser is busy, the response is a 503 with `Retry-After`. |\n| `executive` | `GET /executive/status`, `POST /executive/pause`, `POST /executive/resume` | Operator pause switch for all autonomous work (scheduler, Gmail poller, workflow resumer); inbound chat and DMs stay live. Status returns `{paused, paused_at, paused_by, reason, held_actions, can_resume, name}` — `held_actions` counts due `pending` rows that fire on resume, and `name` is the Executive's name (`EXEC_DISPLAY_NAME`), which the web chat shows over its replies. `pause` takes an optional `reason` (≤200 chars) and is idempotent (re-pausing keeps the original start and reason); `paused_by` is the UI proxy's `x-caller-email`, else `api`. Behind the shared-secret middleware — not `SCHEDULED_ADMIN_TOKEN`, which the UI cannot send. Any caller may pause; `resume` is principal-only (`is_principal_or_self`, 403 otherwise; open while no principal is rostered; a header-less caller resolves to the principal as in `chat`), and status carries `can_resume` for the viewer so the UI hides Resume from everyone else. |\n| `workspace` | `GET /workspace`, `PUT /workspace` | Solo/team mode, the user's time zone and the principal's role (`memory.workspace_settings`). Both return `{mode, timezone, effective_timezone, role_kind, role_title, reports_to, remit, measured_on, company_domains, company_domains_custom}` — `timezone` is what the user set (null when unset), `effective_timezone` the zone in effect (`timezone`, else `USER_TIMEZONE`, else UTC), and each role field is null until set. `PUT` is a partial update: only the fields sent change; `mode` is `solo` or `team` (not null), `timezone` an IANA zone, or null/blank to clear it; `role_kind` is `owner`, `in_house`, `independent` or `other`, and `role_title` / `reports_to` / `remit` / `measured_on` are free text (trimmed, at most 120 / 120 / 500 / 300 characters), each null or blank to clear it; an unknown zone, a bad mode or role kind, an over-long role field or an unknown field is a 422 and changes nothing. Switching to solo cancels every pending department check-in, switching to team re-schedules them, and a new zone re-times the pending briefs and reflection; a role change has no side effects (the next turn reads it). `company_domains` is the company's own email domains (a teammate matches by local part on them — see Org): `GET` returns the ones in effect (the stored list, or the domain of the principal's primary address, with `company_domains_custom` false) only to the same caller the role is shown to, `[]` for anyone else; `PUT` takes a list (at most 10 plain domain names, never a free-mail provider's — 422 otherwise, the value never quoted) or null / `[]` to go back to deriving them, and a change is audited with the new list. Each change writes a `workspace_settings_changed` audit row (a role change adds `details.role_fields_changed`, the names of the fields that changed — never their text). The role is the principal's: `GET` returns it only to a caller `PUT` would accept and reads it as nulls for anyone else. `PUT` is the principal's alone (`is_principal_or_self`, 403 otherwise; a header-less caller resolves to the principal as in `chat`) and open while no principal is rostered, so first-run setup can pick a mode. Both work before onboarding — unlike `company-profile`, nothing here needs a profile. |\n| `scheduled` | `GET\\|DELETE` scheduled actions (`?status=…&order=asc\\|desc`) | Pending and fired scheduled actions; `order` flips the `run_at` sort (asc=soonest-first for the upcoming queue, desc=most-recent-first for terminal-status history). `DELETE /scheduled/{id}` cancels a `pending` row (409 otherwise). Like pause it only stops work, so any signed-in user may — the UI proxy's `x-caller-email` is trusted when the request also carries the `BACKEND_SHARED_SECRET` `x-api-key` — as may a matching `X-Admin-Token` (`SCHEDULED_ADMIN_TOKEN`) or a loopback caller with no token set; otherwise 401 (token set) or 503. Audited as `scheduled_action_cancelled`. |\n| `watchlist` | `GET\\|POST\\|PATCH\\|DELETE /watchlist`, `POST /watchlist/describe`, `POST /watchlist/{slug}/approve`, `POST /watchlist/{slug}/decline` | External-monitoring watchlist + signals. `POST /watchlist/describe` `{text}` drafts a watch from a sentence (one forced tool call on the utility-fast model, `monitoring.describe`; the company profile's name, competitors, vendors and tickers ride in the user turn) and saves nothing: it returns the create fields (`slug`, `signal_type`, `target`, `display_label`, `trigger`, `cadence`, `mode`, `severity_floor`, `severity_ceiling`, `notes`) plus four plain lines (`watching`, `tell_you_when`, `how_often`, `how_loud`) written by code from those fields, after the create route's checks (registered kind, cadence, severity, the URL guard, the rss feed check, a free slug); 422 with a plain reason when it can't be a watch, 429 past 30 drafts an hour, 502/504 when the model fails. `GET /watchlist/{slug}` also returns `noise` `{recent_alerts, recent_dismissed, noisy}` (its last 8 alerts, noisy at 6 dismissed, `monitoring.noise`), and `PATCH` takes `quiet_noise_nudge: true` to stop that question for the alerts so far. `display_label` on create maps to the adapter's label key for every kind. Rows carry `origin` (`manual` \\| `executive` \\| `research` \\| `research_proposed`); `approve` turns a research suggestion (`research_proposed`, `dry_run`) into a live watch, `decline` `{reason: not_relevant \\| too_noisy \\| wrong_source}` removes it and records the decline (or, for `too_noisy`, keeps it live at a high floor), both 409 unless the row is a pending suggestion; `DELETE ?reason=` on a research-origin row records the decline too. |\n| `workflows` | `GET /workflows`, `POST /workflows/{name}/runs`, `GET\\|POST\\|PUT\\|DELETE /workflows/custom`, `GET\\|DELETE /workflows/custom/{name}/targets`, `POST /workflows/runs/{run_id}/decision`, `POST /workflows/runs/{run_id}/rerun`, `GET /workflows/tools/search?q=`, `GET /workflows/tools/describe?names=` | Workflow catalog, run management, and user-created (dynamic) workflow CRUD. `rerun` queues a failed scheduled run (a department check-in, a saved workflow on a cadence) once more, due now (see Scheduler); the principal may, and for a saved workflow the person it delivers to; 409 for a run that did not fail, one started from `/jobs` (\"Start this one again from its page\") or one already queued again. Custom definitions come back with a server-managed `owner_person_id` (the creator — the web caller on `POST`, set on insert only; a client-sent value is ignored), who is asked to approve a workflow's first write to a new target. `GET /workflows/custom/{name}/targets` lists the targets its tool steps may write to without asking and `DELETE …/targets?value=` forgets one. `POST /workflows/{name}/runs` is a 403 (\"Only the principal can run this workflow.\"), audited, before any run row exists, when the workflow is one only the principal may start in the workspace's mode (`weekly_review` always, `morning_brief` in solo) and the caller is not the principal. A request with no `x-caller-email` counts as the principal; with no principal on the roster, no signed-in caller does. This governs starting a run only. A run started by hand (this endpoint, or `run_workflow` / research in chat) records its starter as `owner_person_id` and is theirs alone: `GET /workflows/runs` lists the team's (scheduled, no owner) runs plus the caller's own and the ones waiting on them, and `GET` / `DELETE /workflows/runs/{run_id}` and `POST /workflows/runs/{run_id}/decision` are a 404 for anyone else's, the principal included. A signed-in email that is on nobody's People entry cannot start one (403), and a run whose starter can't be read is refused (503); its steps read and draft documents as the starter only. `POST /workflows/runs/{run_id}/decision` with `{decision: \"approve\"|\"reject\"}` answers a run awaiting a yes/no sign-off from the web app — 403 unless the caller is the person it waits on or the principal, 409 if it isn't awaiting or needs a written reply — through the same `apply_resolution` a chat reply uses. Custom create/update also rejects (422) any action-step tool that does not resolve, and so does `POST /workflows/custom/{name}/activate` when turning a workflow **on** — that click is the approval for a tool workflow chat saved switched off (turning off is never checked). Turning on a workflow with action steps requires the body `{is_active: true, definition}` carrying the definition the user reviewed; if the stored one differs (ignoring `is_active` and timestamps) it returns 409, and the switch itself is a compare-and-set on the validated revision (`dynamic_store.activate_if_unchanged`, keyed on `updated_at`), so a save that lands while the tool check awaits the gateway — even from another process — is a 409 too, so only what was shown gets switched on. `GET /workflows/custom` lists inactive definitions too; `GET /workflows/{name}` 404s for them. The two `tools` endpoints return `{tools: [{name, description, read_only, source}]}` for the advanced editor's tool picker and the review card; `read_only` is true only when the name says it reads (a label, not a control). The run stream adds a `progress` event (`step_id`, `summary`) while an action step uses tools. Each catalog entry (`WorkflowMeta`) carries `is_custom`, `background` (true for the system-run built-ins the UI files under “System”) and `quick` (true for a Quick workflow, one per playbook nothing else follows, named `quick_<playbook>`). The run endpoint streams SSE; its `awaiting_human` event carries `delivery` (`self` \\| `sent` \\| `suppressed` \\| `alerted` \\| `failed`) alongside `person_id` / `question` / `awaiting_until`, because the outbound guard or an unreachable approver means the question may never have been asked — a client must not render “waiting on them” for those. A paused run ends the stream with neither `done` nor `error`, so that `awaiting_human` frame carries `terminal: true` to say so explicitly, plus `resumable` — whether the run continues by itself once answered or stops at the gate. `GET /workflows/runs/{run_id}` returns the run row with the resume payload replaced by a small `resume_progress` summary (`gate_step_id`, `completed_step_ids`, or `null`): the payload holds every completed step's full text, and the run-detail page polls this endpoint while a run is unfinished. |\n| `knowledge` | `/knowledge/builtin`, `/external`, `/search` | MBA knowledge base and external sources. `/search` is the introspection parallel of `retriever.retrieve` and mirrors its filters — including the `general` catch-all on the company collection — so the panel cannot report a specialist seeing nothing that it does retrieve in chat. It accepts `general` in `domain_filter` for the same reason. `/search` applies the same review gate as `retrieve()` — withheld (pending or rejected) built-in, external and failure rows are dropped, so the panel never advertises knowledge the Executive cannot use; it degrades to unfiltered rather than failing if review state is unreadable. `POST /knowledge/builtin` refuses a name already held by shipped content, and `POST|DELETE /knowledge/failures` now register and deregister for review — without that a user-authored failure case study had no review row, so no SME decision could block it. |\n| `skills` | `/skills`, `/skills/search`, `/skills/{name}/restore` | Skill registry (the UI's **Playbooks**) CRUD and search. `PUT` on a built-in saves a company customization that shadows it; `DELETE` returns `{name, outcome}` — `deleted`, `reverted` (customization removed, built-in back) or `hidden` (built-in hidden for this company); `restore` un-hides; `GET /skills?include_hidden=true` lists hidden built-ins. List and detail carry `used_by` — `[{name, title, is_custom}]` of the workflows that follow the playbook (switched-off custom ones included) (`WorkflowMeta.playbooks` is the other direction). |\n| `evals` | `/evals/scenarios`, `/evals/runs` | Eval scenarios and run results. `POST /evals/runs` is a 403 when a workflow scenario names a workflow that only the principal may start in the mode it runs in (the weekly review; the morning brief in solo) and the caller is not the principal — the Jobs page's rule for starting a run; stored results are read under the existing `/evals/runs` rules. |\n| `memories` | `/memories/{decisions,initiatives,advice}`, `GET /memories/facts`, `POST /memories/facts/{fact_id}/{retire,approve,decline}`, `GET /memories/facts/approval`, `PUT /memories/facts/approval/{person_id}`, `GET /memories/people`, `GET /memories/people/{person_id}/conclusions` | Episodic-memory record management; the standing facts the Pulse Corrections tab reads (`{facts: [...], can_retire, retirable_ids, can_review}`; each fact carries `recorded_by_role` / `recorded_by_name`; `?include_inactive=` default true, honoured for the principal only; anyone else gets the active rows plus their own `proposed` ones, with the provenance (`session_id`, `turn_id`, `recorded_by_person_id`, `retired_reason`, and `source_quote` except on their own facts) blanked, never retired, replaced or declined text; `?limit=` 1–500) and their retire (the principal any fact, a teammate only one they recorded that the principal has not approved — else 403; the audit row names the teammate; 404 for an unknown or `profile` row, 409 when no longer active; writes a private `fact_retired` audit row); approve / decline a teammate's `proposed` fact (principal only, else 403; 409 when it is not proposed; private `fact_reviewed` row); and the per-teammate \"needs my approval\" switch (on by default; `GET` lists `[{person_id, full_name, needs_approval}]` for every active team member but the principal, `true` for anyone not yet set; `PUT` takes `{needs_approval}`, 404 for anyone else; both principal only; private `fact_approval_changed` row); plus the read-only peer-memory overview the Pulse People tab reads (`{status: ok|disabled|error, people: [...], conclusion_total}`; `?recent=` 1–50, default 5) and one person's full conclusion list, paged newest first (`{status, person_id, items, page, size, total, has_more}`; `?page=` ≥1, `?size=` 1–100, default 50; 404 when the person has no peer). Peer memory is each person's own: the overview holds only the caller's entry (none for a caller off the roster; `conclusion_total` counts only theirs), the principal included, and `/conclusions` for anyone but the caller is a 404. |\n| `review` | `/review/items`, `/review/stats`, `/review/trusted-defaults`, `POST /review/curate`, `POST /review/bulk-approve` | Knowledge review queue and annotations. Shipped knowledge registers as a trusted default (`approved` with a NULL `reviewed_at`), so the queue starts empty; `curate` (`{domain, action: start|stop}`, domain required) opts one domain in or out, and `trusted-defaults` returns domain → unreviewed count. `bulk-approve` takes a non-empty `domain`, `item_ids` (max 500) or `all_pending: true`, and 400s with no selector; it returns `{approved_count, item_ids}`. |\n| `onboarding` | `/onboard/interview/understand`, `/onboard/interview/start`, `/onboard/interview/message`, `/onboard/interview/draft`, `/onboard/interview/revise`, `/onboard/interview/{id}` (GET resumes, DELETE starts over), `/onboard/interview/commit` | Conversational company setup. The `onboarding_interviewer` agent asks clarifying questions, then emits a draft profile + people + departments. **Nothing is persisted until `POST /onboard/interview/commit`** — the interview itself never writes. `start` is multipart (description + optional deck/one-pager uploads). `revise` changes one earlier answer (0 = the description) and runs the interview again from there. `commit` answers 403 when the draft would make a different person the owner and the caller is not the current owner (setup demotes the old principal, and any signed-in user can open it). It also takes an optional `owner_email` — the principal's sign-in email, which the review screen pre-fills from the signed-in user — checked before anything is written (422 if it is malformed, already another person's, or would replace the principal's existing email — setup only fills in a missing one; 403 if the caller is not the owner and it is not the address they signed in with, since the roster is the sign-in allow-list) and saved on the principal's People row, so the owner's chats resolve to them from the first turn. |\n| `workflow_designer` | `POST /workflows/designer/start`, `POST /workflows/designer/edit`, `POST /workflows/designer/message`, `POST /workflows/designer/draft`, `GET /workflows/designer/{session_id}` | The conversational New workflow wizard, and editing a saved workflow by conversation. `/edit` (`{name}`) opens a session on a saved custom workflow with no model call: the stored definition is the starting draft, and every response then carries `editing` (its name) and `original` (the stored definition as the session opened on it); drafts keep that name and its on/off state whatever the model writes (404 for an unknown workflow). The UI saves one with `POST /workflows/custom/{name}/save-edit` (`{session_id, definition}`): the server saves the session's own draft, never a client-sent body, and only when it equals the `definition` the user reviewed (a later message is a 409, so the click saves only what was shown); it re-validates it, keeps the stored on/off state, and writes only if the stored workflow is still the version the conversation opened on — otherwise 409, as it is for a session about another workflow or one with nothing drafted yet. It sits under `/workflows/custom` so anything that limits writes to custom workflows covers it too. The `workflow_designer` agent asks clarifying questions (`phase: \"question\"`, with `hint` and up to four suggested `options`), then returns `phase: \"draft\"` with `draft.definition` (exactly the body `POST /workflows/custom` takes), `summary`, and `assumptions`; every response carries the `transcript`. **Nothing is persisted here** — sessions are in memory, and the UI saves through `POST /workflows/custom`. Errors are fixed strings (422 over the 8,000-char message cap or the transcript cap, 404 for an expired session, 409 while another turn on the same session is still running, 502/504 for model failure or timeout). Mounted ahead of the `workflows` router. |\n| `python_jobs` | `GET /python-jobs/{job_id}/{name}` | A result file a Python job (`run_python_job`) wrote, the principal's alone (403 otherwise), served as a download (`Content-Disposition: attachment`, `Content-Security-Policy: sandbox`, `nosniff`, `Cache-Control: no-store`); 404 for a bad id or name or a file past its 7 days. |\n| `saved_tools` | `GET /saved-tools`, `GET\\|PUT /saved-tools/{name}`, `POST /saved-tools/{name}/rollback` | The scripts the Executive saved as tools (Settings → Advanced → Saved tools), the owner's alone (403 otherwise). The list gives each tool's name, description, on/off, current version, `kind` (`script` or `python`, a kept Python job) and the tools it calls, plus whether `SAVED_TOOLS_ENABLED` is on; the detail adds the script, every version and the last 20 runs. `PUT {enabled?, workflows?, version?}` turns one on or off (off also turns it off for workflows, so turning it back on never re-arms unattended runs), and turns the named `version` — the one the owner looked at, never whatever is current by then — on for workflows (or workflows off); a Python tool never turns on for workflows (409) — turning workflows on lets more run unattended, so it needs a request tied to the owner (signed sign-ins or local login, as Take the lead's switches do; 409 otherwise); `rollback {version}` makes that version the one that runs. Both are audited as `saved_tool_changed`. The Executive saves tools itself through `run_script`; there is no create route. |\n| `onboarding` (fallback) | `/onboard/start`, `/onboard/answer`, `/onboard/status/{id}` | The original 12-step form wizard, kept as a fallback (UI at `/onboard?mode=form`) and used by the `openexecutive onboard` CLI. Its final answer saves the profile and adds people with their emails and a principal, so once there is an owner only they can send it (403, and the session rolls back so the owner can still finish it). `/onboard/start` reads the workspace mode once for the session: solo skips the Team Size, Team Members and Fractional Executives steps. Each status response's `current_step` / `total_steps` count only the steps that session asks, and `optional` says whether the current step can be skipped. |\n| `company-profile` | `GET\\|PATCH /company-profile` | Structured company profile. |\n| `alerts` (private cards) | `POST /alerts/{id}/ack`, `/reopen`, `/alerts/bulk-ack` | An alert tagged `private:principal` (see Today) is a 404 on ack and reopen for anyone but the principal, and their bulk sweep skips it. A roster-request card (source `roster_request`) is a 409 on `ack` even for the principal — it is answered at `/people/requests/{id}`, since acking would leave the sender waiting with nothing to show it — and, as an exempt source, `bulk-ack` and `reopen` skip it. |\n| `auth` | `GET /auth/allowed-emails` | Non-archived **team members** with an email, offered to the UI's sign-in gate — a contact is never on it, so adding a client to reach them by email no longer lets them sign in. The gate takes the **union** of this roster and its own `ALLOWED_EMAILS` env list, so env entries always work (and are checked first, short-circuiting the fetch) and roster entries are additive — a roster change can never revoke a configured operator. With local login (`make dev` with Google sign-in not set up — the UI then listens on 127.0.0.1 only) the UI signs in without an email, sends no `x-caller-email`, and the backend resolves the caller to the principal, as it does for the CLI. |\n| `fixtures` | `/fixtures`, `/fixtures/{name}/load` | Demo-company fixture load/reset/snapshot. `POST /fixtures/reset` leaves no departments, like a new install (`departments_seeded` is always 0). |\n| `clients` | `/clients`, `/clients/generate`, `/clients/cockpit`, `/clients/save`, `/clients/{slug}/activate` | Client-company slots — multi-client mode for fractional use; create from current/blank/AI-generated intake draft (pasted notes and/or file attachments, multipart on `/clients/generate`), save-back switching, engagement metadata (PATCH), cross-client cockpit, delete. See the Client Companies section. |\n| webhooks | `POST /webhook/telegram`, `POST /webhook/google-chat`, `POST /webhook/slack` | Inbound integration callbacks (self-verified). `/webhook/slack` answers 503 unless `SLACK_SIGNING_SECRET` is set. |\n| MCP server | `POST\\|GET /mcp` | Open Executive exposed as an MCP server (Streamable-HTTP). Not a router — a mounted FastMCP sub-app. Same shared-secret gate (`x-api-key`); exposes company context as resources and the specialist council as tools, answered as the verified caller (`api.caller`) by the web app's rules. See the MCP Server section. | A card the Executive left for something asked in chat (`app_action`, `orchestrator/app_control.py`) is its person's alone too: its payload holds `action`, `id`, `value`, `title` and the `card` line shown; **Confirm** is `POST /decisions/{id}/approve`, which runs the action through the route its button calls with that request (a refusal comes back as that route's status and words, and the card is marked `failed`), and a card older than a day is turned down with 409.\n\n**What it does for you** (`api/routes/may_do.py`): `GET /what-it-may-do` is read-only. It returns `{paused, sections}`, three sections in order (`as_you`, `executive`, `departments`), each `{key, title, available, unavailable, notes, rows, footer, goes}`, and each row `{id, what, outcome, then, why, setting, items}`: `outcome` is `goes`, `waits`, `always_waits`, `drafts` or `off`, and `setting` names where to change it (`act_as_me`, `handle_it`, `take_the_lead`, `pause`, `department:<slug>`, or empty). `as_you` is the caller's own (`available` false, with why, when they can't have Act as me); `executive` is the principal's alone (`available` false for anyone else); `departments` is everyone's. Any team member on People may call it; a contact, someone not on People, or a request with no caller outside local login gets 403. See Delegation → What it does for you.\n\n**How far it goes as you** (`api/routes/delegation.py`): `PUT /delegation/reach` takes `{step}`, one of `off`, `when_asked`, `inbox`, `careful`, `balanced`, `bold`, `everything`, and answers the caller's delegation state as `GET /delegation` does. Going down turns the switches above the step off, highest first; going up runs each switch's own route in order (`PUT /delegation`, `PUT /delegation/inbox`, `PUT /delegation/handle-it`, `PUT /delegation/take-the-lead`), so the first refusal (409 `gmail_not_connected`, a signed sign-in missing, `in_training`, 403 for Everything when not the owner) stops it at a whole step. See Delegation → How far it goes as you.\n\n**Take the lead** (`api/routes/take_the_lead.py`): `GET /take-the-lead` returns the As the Executive switch, its six Ask first switches (`{kind, label, hint, on}`, the hint a plain line on what each one catches), the company's rules, whether this server can tie a change to the owner (`available`), and whether the Executive is paused. `PUT /take-the-lead` takes `{enabled?, ask_first?}`, and `POST /take-the-lead/rules` / `DELETE /take-the-lead/rules/{id}` add or remove a company rule (`{kind: person|domain|words|amount, value}`, 422 on a bad one). All four are the principal's alone (403). Anything that lets more happen on its own (turning it on, turning an Ask first off, removing a rule) needs a caller the API can tie to them (`delegation.verified.caller_refusal`, else 409). `GET /today/activity` adds `took_the_lead` rows (what Take the lead did, named, not quoted) and, for the caller alone, `sent_as_you` rows for what Handle it for me sent as them and, for the principal, one `contacts_kept` row a day the contact keeper changed something (`detail` like \"2 added, 1 updated\"). Under `/delegation`: `PUT /delegation/take-the-lead {enabled}` is Take the lead as you (the owner's only for now; turning it on turns Handle it for me on), and `GET|POST /delegation/take-the-lead/rules` and `DELETE …/rules/{id}` manage the caller's own rules. `HandleItOut` gains `lead` and `lead_available`. A `take_the_lead_action` decision is approved or rejected through the existing `/decisions/{id}/approve|reject`. Training: the response also carries `training` (In training: everything waits unless allowed), `learned` (`{id, label, feature, example, uses, created_at}`: what it was allowed, the edit kept as an example by field) and `suggested` (`{key, label, approvals}`); `PUT` takes `training?` too, and leaving training while on needs the same provable owner as turning it on. `POST /take-the-lead/learned {key}` allows a current suggestion (404 for anything else; provable owner), `DELETE /take-the-lead/learned/{id}` makes it ask first again. `learned` also lists the owner's own Act as me senders (`feature` `act_as_me`), never anyone else's, and Remove works on those too. On a `take_the_lead_action` card, `POST /decisions/{id}/approve` takes `edits.input` (the card's editable fields, 422 for any other; the principal's alone, 403 for an area approver) and `edits.allow: true` (a training card only, 422 otherwise; the principal from a provable request, 403 otherwise), finishing `approved_with_edit` when a field changed.",
+ "markdown": "The FastAPI surface lives in `openexecutive.api.main`, which mounts one router per topic. A shared-secret middleware gates every request via an `x-api-key` header, except `/health` and the `/webhook/*` callbacks (which carry their own verification). A request it lets through is marked `request.state.shared_secret_ok`, which is what lets an MCP request turn on \"may act\" with `x-mcp-client-actions: on` (`mcp_server.may_act`; with no secret the header is ignored and `MCP_CLIENT_ACTIONS` decides). With local login (`OE_LOCAL_LOGIN=1`, which only `make dev` sets, and only while neither Google nor SSO sign-in is set up) a second middleware answers 403 to any request whose raw `Host` is not `localhost`, `127.0.0.1` or `[::1]` (except a webhook that verifies its caller: Google Chat and Slack always, Telegram only with a `TELEGRAM_WEBHOOK_SECRET` Telegram can send), and to any write whose `Sec-Fetch-Site` is present and not `same-origin`/`none`. The UI signs that owner in with no password and this API usually has no secret, so without it a web page in the owner's browser could drive the API as the principal — by DNS-rebinding its own hostname to 127.0.0.1, or by posting a plain form from another site or localhost port. CORS is restricted to the UI origins in `BACKEND_ALLOWED_ORIGINS`, plus the `make dev` UI on `localhost:3000` only when `OE_PUBLIC_DEPLOYMENT` is unset, so a public instance never answers a localhost page with credentials. The gate is off when `BACKEND_SHARED_SECRET` is unset — intended for local development only — so any internet-reachable deployment sets `OE_PUBLIC_DEPLOYMENT`, and `create_app()` then refuses to boot without the secret rather than serving an unauthenticated API.\n\n**Who is calling** is read in one place, `api/caller.py`, which answers with a `Caller` kind and email; a test fails on any other read of an `x-caller-*` header. By default (`open`) it is the `x-caller-email` the UI proxy stamps from the sign-in, trusted because whoever holds the shared secret is trusted as the proxy, and a request with none runs as the principal. **Signed callers** remove that trust. With `CALLER_ASSERTION_PUBLIC_KEYS` set, the proxy signs every request with an Ed25519 key only the UI holds, and a third middleware checks the `x-caller-assertion` header:\n\n- **What it covers.** It is good for one method, the exact path and query, at most 120 seconds, and one use. The API keeps used ids in memory.\n- **What it names.** A `user`, by email, or the `operator`: local login, which runs as the principal.\n- **No caller header at all** is a `service`, for scripts or MCP clients holding only the secret. It is never the principal, not even on an install with no owner yet, so it can't save a first setup.\n- **Anything else is a 401.** That includes an `x-caller-email` without an assertion (`caller_assertion_required`), and a bad, expired, reused or mismatched assertion (`caller_assertion_invalid`).\n\nPublic keys that can't be read stop the boot, rather than fall back to trusting the header. `scripts/make-caller-keys.py` makes the pair, and `scripts/mint-caller-assertion.py` signs one request for curl. The API holds only public keys. Setup's API-protection check warns while a shared secret is set without them.\n\nEndpoints grouped by router:\n\n| Router | Key endpoints | Purpose |\n|---|---|---|\n| `chat` | `POST /chat`, `POST /chat/stop`, `POST /chat/add`, `POST /chat/background`, `GET /chat/voice`, `POST /chat/transcribe` | SSE stream of a live Executive turn, with a `: keepalive` comment every `CHAT_STREAM_KEEPALIVE_S` while the turn is quiet. `POST /chat/background` starts a new chat that the server answers to the end with nobody connected (a phone approving a card, then closing the app): it answers `202` with the new `session_id` once the same caller, access and quota checks as `/chat` pass, the turn saves itself as a `/chat` turn does, and one caller may have three running at once (`429` beyond that). `POST /chat/add` hands the running turn a message the person typed while it works; the turn takes it at its next step and the stream names it in a `message_added` event, and a second `POST /chat` on the same conversation waits for the first to finish. `GET /chat/voice` says whether the chat mic shows (`available`, `max_seconds`); `POST /chat/transcribe` takes one recording (multipart `file`) and answers `{text}` for the message box, nothing kept: `404` when speech to text isn't set up, `400` for a file that isn't audio, `413` over 25 MB, `502` when the speech server fails. The request body optionally carries `page_context` (route, page title, guide section id, and a form descriptor with current values) — sent only by the Ask OE side panel so the Executive can explain the current page or propose form values. When the Executive calls its `propose_form_values` tool, the stream emits a `form_patch` event (`{type, form_id, fields, rationale, iteration}`) that the panel applies into the on-screen form as highlighted suggestions; the user reviews and saves through the form's normal submit path. Each round of tool calls also emits an `activity` event (`{type, label, tool, iteration}`) naming what is running — progress only, forwarded verbatim and never persisted with the message, unlike an `action_taken` chip. A `session_id` in the body must be a chat the caller may use (the same ownership rule as `sessions`). If it isn't, the turn runs in a fresh chat instead, so nothing is written into someone else's session and the reply looks the same as for an unknown id. An unknown namespaced id (`slack:…`, `telegram:…` and so on) is ignored and a fresh chat is started, because those ids belong to the channel adapters and claiming one first would make the caller its owner. The client mints a `client_turn_id` and sends it with the turn; `POST /chat/stop` takes that id and halts the turn mid-flight, so the button is live from the moment Send is pressed rather than only once the first SSE byte arrives. A stopped turn emits a `stopped` event and then the usual `done` over the same still-open stream — never an `error` — and whatever streamed so far is persisted and flagged. The endpoint returns 404 both for an unknown id and for another caller's turn, so it cannot be used to probe which turns are live. An optional `memory_text` (1–2000 chars) is what peer memory records as the caller's words instead of `message` — the briefing handoffs send it because their seed quotes the Executive's own card; `POST /chat/upload` derives it from the typed text and filenames. Since it never reaches the transcript, the `chat_turn` audit row keeps it beside `message`. After the reply — a stopped or timed-out one too, before the `stopped` / `error` / `done` frames — a turn that looked at anything sends one `sources` event, `{type, session_id, sources: [{kind, title, url}], unavailable: [area]}`: `kind` is `company`, `knowledge`, `notion`, `research`, `document` or `web`, `url` is only ever an http(s) link or, for an earlier document, `/artifacts/<id>`, at most 12 sources (6 from the web, pages the reply cites first), and `unavailable` names parts of the analysis (\"finance\") whose specialist failed or said nothing every time it was asked. It is persisted with the reply as `chat_messages.sources`. A request that carries `x-caller-email` marks its turn signed in (`Session.web_caller_signed_in`), which Act as me needs on a deployment without local login. |\n| `sessions` | `GET /sessions`, `GET /sessions/shared-with-me`, `GET /sessions/topics`, `PATCH\\|DELETE /sessions/topics/{topic_id}`, `POST /sessions/topics/{topic_id}/merge`, `POST /sessions/topic-areas/rename`, `POST /sessions/topic-areas/ungroup`, `GET\\|PATCH /sessions/{id}`, `GET /sessions/{id}/messages`, `DELETE /sessions/{id}`, `POST /sessions/{id}/messages/{message_id}/feedback`, `GET /sessions/{id}/followup`, `GET\\|PUT /sessions/{id}/shares`, `DELETE /sessions/{id}/shares/me`, `GET /sessions/{id}/people`, `GET /sessions/{id}/live`, `POST /sessions/{id}/typing`, `GET /sessions/{id}/export`, `POST /sessions/{id}/rewind` | List, read and delete saved chat sessions (assistant messages carry their row `id` and any `feedback`). The list is scoped to the caller, and each chat carries `preview`: its last message as one plain line, Markdown marks stripped and cut at a word near 120 characters, with `You:` before the person's own words. With `?q=` it is a search: the caller's own chats whose title or message text contains the words (case-insensitive, `LIKE` with wildcards escaped), each with `match_count` (messages that contain them; 0 for a title-only match) and `snippet` (the newest matching message, around the match, prefixed `You:` or `Executive:`). Scoped exactly like the list, so nobody else's conversation can match. The Chats page searches this way and opens a result with `?find=`, so the chat starts on that message and steps through the others. Each of the owner's chats also carries `topic_id`, the topic it is filed under (`memory.chat_topics`). `GET /sessions/topics` lists the caller's topics (`id`, `name`, `chat_count`, `kept`, `pinned_at`, `area`, `updated_at`) and, when some of their chats have no topic yet or some topics no area, starts filing them in the background from their titles and answers `organizing: true` until done. `PATCH /sessions/topics/{topic_id}` renames (a name another of their topics has merges the two) or pins one, `POST …/merge` moves its chats into another (`into_id`), and `DELETE` ungroups it, leaving its chats under no topic; another person's topic is a 404. `POST /sessions/topic-areas/rename` (`area`, `name`) renames one of the caller's areas and `…/ungroup` (`area`) drops it, its topics standing alone; an area they don't have is a 404. `PATCH /sessions/{id}` also takes `topic_id` (null for none) or `topic_name` (made if new) to file the chat, which then is never refiled on its own. A chat-app conversation started with /new is left off the list until its first turn (`memory.conversations`). Every per-session route checks ownership, because session ids are guessable (`slack:dm:<user id>`, `telegram:<chat id>`): only the session's owner or the principal gets through, and a legacy row with no owner is the principal's alone. A teammate's own chat (a web chat, a DM, a private Telegram chat; not a channel or group conversation, `chat._shared_space`) is theirs alone, the principal included, as their mail with the Executive is. Anyone else gets the same 404 as for an unknown id, so the routes can't be used to find out which chats exist. The one other way in is having started the chat in this process (matched by Person id or verified email, so it survives the caller being added to the roster), which is how a caller the roster can't resolve keeps using their own chat. That record is in memory, so after a restart such an ownerless chat is refused for reads. The principal can continue someone else's ownerless chat without becoming its owner. Deleting a session also drops its in-memory copy, so a later turn naming that id starts fresh. The feedback route records 👍/👎 (`{\"feedback\": \"up\"|\"down\"|null}`) on one assistant reply; only the session's own caller or the principal may rate it. The rater is stored (`feedback_by_person_id`), and a 👎 on a reply to the rater's own message triggers a working-style pass for them (paced; see attunement). The chat stream's `done` event carries `message_id` for the persisted reply. The followup route returns `{\"suggestion\": string|null}` — one suggested next user message, written by the utility-fast model from the last few turns, that the chat composer shows as its greyed placeholder (Tab / → or the inline chip fills it in without sending). It is null unless the session ends on a persisted assistant reply, and null (uncached) when the model fails. Same ownership check as feedback; successful suggestions are cached in-process per (session, reply id). Messages from `GET /sessions/{id}/messages` carry each assistant reply's saved `sources` (the same shape as the chat stream's `sources` event, without `type`), so a reloaded chat shows them again. The owner (not the principal on someone else's chat; the principal for an ownerless one) also has the chat controls. `PATCH` takes `{title?, pinned?}`: a name they give is kept (`sessions.title_locked`, so the automatic title never replaces it) and a pinned chat lists first, newest pin first, with `pinned_at`. `PUT /sessions/{id}/shares {person_ids}` adds exactly those team members to it (not contacts, the archived or the owner: 422), audited `session_shared`; a chat that read its owner's own mail (`mail_private`) is never shared (409) and stops being open to those it was shared with before, and a chat-app conversation is never shared (409). Those added get it from `GET /sessions/shared-with-me` (with `shared_with_you`, `shared_by`, `shared_at`) and **write in it with the owner**: `POST /chat` with its id runs their turn as themselves (`chat._shared_member` widens the turn's access, never its ownership), and they may read it, its messages (without the owner's ratings) and its export. They can't rate, rename, delete, share or redo it, and `DELETE /sessions/{id}/shares/me` takes them out of it (audited `session_shared`, with them under `removed`). In a chat several people are in, messages carry `sender_person_id` and `sender_name` (a message from before it was shared is the owner's), `GET /sessions/{id}/people` returns `{you, people: [{person_id, full_name, owner}]}` (owner first; empty for a chat of one), and redo is refused (409) when the last message is someone else's. `GET /sessions/{id}/live` is a server-sent event stream each open page holds (`api.chat_live`, one in-process broker): `ready` first (with the running turn so far, if any), then `turn_started` (who sent what), the reply's `chunk` / `thinking` / `activity` / `action_taken` / `phase`, `turn_ended` (the page reads the chat again), `typing` (from `POST /sessions/{id}/typing`, at most once per 2 s per person) and `people`. `removed`, `deleted` and `resync` (a page that fell 1024 events behind) end it; the access check runs again on every 20 s keepalive. At most 12 pages per person, 40 per chat and 2000 per process (429). Archiving someone takes them out of every chat shared with them, and their open streams close at the next keepalive. The page closes it while its tab is hidden. `GET /sessions/{id}/export` returns the chat as a Markdown file (`memory.chat_export`: each message under its writer's People name or `Executive`, the reply's sources listed under it). `POST /sessions/{id}/rewind {last_message_id}` takes back the last turn for Try again and Edit: under the conversation's turn lock it deletes the last reply and the messages it answered, but only while that reply is still the chat's last row, and returns those messages' words (`{message}`), which the page sends again as an ordinary `/chat` turn through the usual gates. 409 while a turn is answering, for a stale reply id, and for a chat-app conversation (its reply also lives in Slack, Telegram or Discord); audited `session_rewound`. |\n| `today` | `GET /today`, `GET /today/activity`, `GET /today/activity/daily`, `GET /today/brief-delivery`, `GET /today/value`, `GET /today/top-three`, `GET /today/weekly-review`, `POST /today/seen` | Morning-brief aggregation (in the install's first week, for the principal, `first_week_card` `{needs_goal, findings: [{title, summary}], brief_tomorrow}` or null), recent-action rail, Pulse heartbeat heatmap (per-day activity counts), and the owner's month tally for Pulse's Done for you (`GET /today/value?period=month|week&offset=N`: counted lines beside the period before plus the finished reports, owner only, 403 otherwise; see Today). `GET /today` carries the viewer's cached \"What's going on\" `narrative` with `narrative_generated_at` (when it was written) and `narrative_stale` (a fresher one is being written — the page re-polls; see Today), the same text split for Home's Right now card (`narrative_lead`, `narrative_points` `[{text, since}]`, `narrative_move`), `narrative_seen_at` (this reader's last look, which `POST /today/seen` records and returns as `{seen_at}`) and, for the principal, `morning_brief` `{at, text}` and `calendar_next` `[{title, start, all_day}]`. A proposal backed by a roster request carries `roster_request` (the new sender's server-derived details and held-message previews; the principal's only) and is answered through the `people` routes below. `brief-delivery` returns the latest morning brief or end-of-day digest that didn't reach the owner, as `{brief, at, problem, fix, readable}` in plain language (`readable` is false when it couldn't be written, so there is nothing to read), or null — null while briefs go out, once the cause is fixed, while the scheduler is off, and for anyone but the owner (`chat._caller_is_principal_or_unclaimed`); it carries no address or channel id. `top-three` and `weekly-review` feed the solo Briefing's own cards and answer only in solo mode and only to the principal (`workflows._caller_is_the_principal`: a principal match or no caller header, never an unclaimed roster); anyone else, and team mode, get null. `top-three` returns `{items: [{key, kind, text, why, slot}]}` — the morning brief's top three from the same code (`build_top_three(principal_due_soon())`), `slot` a free block like `10:00–11:00`, `\"\"` when none is left, null when no calendar was read — and is kept off `GET /today` because its calendar read may take up to 4 s. `weekly-review` returns the latest completed `weekly_review` run as `{run_id, completed_at, period, top_three, excerpt}` (next week's top three as plain text; `excerpt` when that list is empty), or null when none has completed. |\n| `people` | `GET\\|POST\\|PATCH /people`, `POST /people/{id}/archive`, `GET /people/requests`, `GET /people/requests/{id}`, `POST /people/requests/{id}/approve`, `POST /people/requests/{id}/decline`, `GET\\|POST /people/{id}/open-loops` (a `POST` tells the owner once and returns `notified`: `sent` with the channel, `held`, `not_reached` or `skipped`; see Attunement), `POST /open-loops/{loop_id}/close`, `GET /people/{id}/outreach`, `GET\\|PUT\\|DELETE /people/{id}/attunement` | Roster CRUD and scope lookups. Every `Person` carries `kind` (`team` / `contact`). `GET /people` lists team members only unless `?include_contacts=true` (the People page asks for both; the department-head and workflow pickers keep the default); `POST` / `PATCH` accept `kind`, and a principal contact is a 422 either way. They also take `email_aliases` (other addresses the person writes from, at most 10; on `PATCH` the full list replaces the current one, omitted leaves it): an alias matches their mail and may be emailed but never signs in; a malformed one is a 422, and an alias — or a new primary `email` — that is already someone else's address or alias is a 409. Every `POST` / `PATCH` then closes any pending roster request whose sender now matches someone and replays its held messages. Adding, editing and archiving (`POST`, `PATCH`, `/archive`) are the principal's only, or anyone's while no one is principal yet so a first setup can add its owner (`chat._caller_is_principal_or_unclaimed`, the check behind `PUT /workspace`; a request with no `x-caller-email`, such as the CLI or local login, counts as the principal). Anyone else, a person editing their own row included, gets 403 before the person lookup, so it can't probe which ids exist. Contacts are private to the principal (`caller_is_principal`: the signed-in email is the principal's, or no `x-caller-email`; stricter than the owner rule above, so while no one is principal nobody is): for anyone else `include_contacts` is ignored, a contact's id is a 404 on `GET /people/{id}` and open-loops (exactly as for a missing id; `PATCH` and archive are already a 403 for them), and creating a contact or turning someone into one is a 403, even on a first setup with no principal yet. `GET /people/me` returns `{person_id, is_principal}` so the UI offers contacts to the principal only. `GET /people/by-scope/{token}` never returns a contact. Archiving a person closes their open loops. The open-loop routes list what a person owes (soonest due first) and close one (`reason`: done / not_needed / cancelled) — both the principal's or the owner's only (403 otherwise, via `people.store.is_principal_or_self`). `POST /people/{id}/open-loops` `{task, due_date?}` assigns that person a task (201 with the loop; `due_date` is a local date, due 17:00 in the user's timezone, clamped to 60 days, default 2 days): any active team member may assign anyone on the team, 403 for anyone else; 409 for an archived person, a contact (as seen by the principal), a person at the open-loop cap, a duplicate or open loops turned off; 422 for an empty task. Nobody is messaged at assignment — the owner is chased once it is due. `/outreach` returns, per kind of proactive outreach over 30 days, `sent` / `replied` / `acted` / `ignored` / `pending` (voided DMs are excluded) — same access rule, checked before the person lookup so it can't probe which ids exist. `/attunement` reads, replaces (`rules`: up to 4 strings, or omitted to only set `locked`) or resets the person's working-style rules — same access rule, 404 for an archived person; `PUT` rejects a rule that is not purely about style with 422. Archiving a person also drops their working style and frees their aliases. The **roster-request** routes (declared before `/people/{person_id}`) are the principal's alone (`caller_is_principal`; anyone else gets 404, as for a missing id): `GET /people/requests?status=pending|approved|linked|declined|expired|superseded|all` lists up to 100 (`id`, `channel`, `channel_ref`, sanitised `display_name`, `profile_email`, `on_company_domain`, `suggested_kind`, `suggested_person_id` / `_name`, `status`, `resolved_person_id` / `_kind`, `message_count`, timestamps, `ack_sent`, and `previews` of the held messages while pending — shown to the principal, never to a model); `approve` takes either `link_person_id` (+ `replace_channel_id`) or `full_name` + `kind` (no default: 422 without both) + optional `role`; `decline` takes no body. An answered request is a 409, a chat id or address already on someone else is a 409; the held messages are replayed (or dropped) in the background. |\n| `contacts` | `GET /contacts/changes?person_id=`, `PUT /contacts/keeper`, `POST /contacts/changes/seen`, `POST /contacts/changes/{id}/undo`, `POST /contacts/changes/{id}/accept`, `POST /contacts/changes/{id}/dismiss` | The contact keeper (see Org), principal only (404 for anyone else). `GET` returns `{mode, status, last_run_at, changes}`: the switch (`on` / `ask` / `off`), how the last pass went (`ok`, `act_as_me_off`, `not_connected`, …) and the last 30 days of changes (each `id`, `person_id`, `action` add/update, `field`, `email`, `full_name`, `old_value`, `new_value`, `reason`, `evidence`, `status` applied/suggested/undone/dismissed, `seen`, `created_at`); with `person_id`, that person's every change. `PUT` sets the switch; `seen` is Got it; `undo` / `accept` / `dismiss` return the change, 409 when there is nothing to undo or decide. |\n| `chat-directory` | `GET /chat-directory/people`, `GET /chat-directory/channels`, `GET /chat-directory/slack/lookup?email=` | The Slack, Discord and Telegram people and rooms the bots can reach, by name, for the People and department pickers (`integrations/chat_directory.py`). Each answers `{slack, discord, telegram}`, every one `{configured, ok, options: [{id, name, detail, email}], truncated, members_available}`: `configured` false (and no options) when that bot has no token, `ok` false when the provider could not be read, `members_available` false when Discord refuses to list server members (the Server Members intent is off). `lookup` returns `{configured, match}`, the Slack person with that work email or null. Cached in-process for 60 s; tokens are never returned. The principal's alone, like changing the People list (`chat._caller_is_principal_or_unclaimed`); channels also open while no one is principal yet, people and lookup wait for one; a 403 otherwise, and the pickers then keep only the by-hand id field. |\n| `departments` | `GET\\|POST\\|PATCH\\|DELETE /departments`, `.../goals`, `POST /goals` | Department state and per-department goals. `POST /goals` takes a goal plus `area` (a name, ≤80): an existing area by slug or title, else a new one of that name (no specialist, as with `POST /departments`), else **General** when blank; the Goals page uses it while a workspace has no areas (setup makes none for solo or a team that names none). `PATCH /departments/{slug}` also takes `watched_entities` (≤50 names, `[]` clears) — the entities the research watch policy may add watches for and route to this department. A `cadences` spec that does not parse is rejected with a 422 (empty means no cadence, i.e. the check-in is off); a changed `check_in` cancels the pending check-in and queues the next one on the new schedule. `GET` and `PATCH /departments/{slug}` return the department state plus `next_check_in_at` (ISO UTC of the pending check-in, `null` when it is off, the workspace is solo or none is queued); the list route does not carry it. A new `head_person_id` must be a team member: an unknown id and one of the principal's contacts get the same name-free 422 (`person_id N is not on the team.`), so the route — open to any signed-in user — never reveals that a contact exists; an unchanged head is not re-checked. `POST .../goals` requires only `key_result`: a missing or blank `period_value` is filled with the current period for `period_type` in the user's zone (the same label `create_goal` uses), and `target` defaults to empty. `PATCH .../goals/{id}` rejects a blank `key_result` or `period_value` with a 422; `target` may be cleared. |\n| `agents` | `GET /agents`, `GET /agents/models`, `GET /agents/models/options`, `GET /agents/presets`, `POST /agents/presets/{id}`, `PATCH /agents/{id}`, `POST /agents/{id}/test` | Specialist metadata and Council overrides. `/agents/models` is the flat model allowlist the PATCH validator uses; `/agents/models/options` returns the same ids in the same order, each tagged with `provider`, `provider_label`, `route` (`direct` / `openrouter` / `local`) and a display `label`, for the Council's Provider → Model picker. `AgentDetail` carries `instructions` (additional instructions, appended after `prompt`, which stays the built-in prompt or its replacement); `PATCH` and `/test` accept `instructions` (max 4,000 chars, blank clears it). `GET /agents/presets` lists the Fast, Balanced and Thorough quality presets (each with `available` and the resolved `model` for this install) plus `active` (null when the council is Custom), `base` and `custom_agents`; `POST /agents/presets/{id}` applies one by writing per-agent model and deep-reasoning overrides and returns the same shape (404 unknown preset, 409 when the install allows none of its models). Each `AgentMeta` carries `visibility` (`core` or `internal`) so the Council's simple view can list core agents first. |\n| `personas` | `GET\\|PUT\\|POST\\|DELETE /personas` | Executive persona definitions. |\n| `alerts` | `POST /alerts/{id}/approve`, `GET /alerts/approvals/{id}`, `POST /alerts/{id}/ack`, `POST /alerts/bulk-ack`, `POST /alerts/{id}/snooze`, `POST /alerts/{id}/reopen`, `POST /alerts/review` | Groom the briefing queue. `approve` (body `{edited_body?}`, 202) carries a proposal card out on the server and records who approved it and when (`alerts.approvals`, see Today): it queues the scheduled action a department-gated card held, or runs one Executive turn as the approver in a new chat (`session_id`). 409 for a card already approved or closed, a decision-backed card (approved at `/decisions`), a roster request or a drafted artifact; 403 unless the caller is the card's routed person or the principal (an unrouted card is the principal's); 429 when the caller already has three background turns running. `GET /alerts/approvals/{id}` reads one back (`running`, then `done` / `failed` with `outcome`) for its approver, the card's person or the principal (404 for anyone else). `snooze` (`until`, an ISO time up to 30 days ahead; `null` clears it, the Undo) hides an `unread` card until then by setting `snoozed_until` (409 on a closed card or a roster request); the TTL then counts from the snooze, so a card snoozed past its TTL still comes back. `ack` (`read`/`ack`/`dismissed`, optional `mute_topic`) also teaches a watch-sourced alert's watch (`trust_score`); `bulk-ack` takes explicit `alert_ids` and/or `older_than_days` + `category` (exempt sources skipped); `reopen` is the Undo for a `resolved` / `expired` / `dismissed` alert (never `ack` or an artifact / decision row; back to `unread` with every review stamp cleared and its TTL anchor refreshed, so it is live again even if older than its TTL); `review` runs the Executive's relevance review on demand (ignores the interval; still honours `ALERT_REVIEW_ENABLED`, the per-pass caps, the single-flight lock and per-alert idempotency) and returns the move counts. `bulk-ack` caps ids at 500, needs `older_than_days >= 1`, and applies watch feedback per row; `mute_topic` must be one of the alert's tags or a scoped `external:` / `department:` pattern. Alerts still surface only through the briefing (`/today` reads the live view) — there is no list, prefs, mutes, or live-stream endpoint. |\n| `artifacts` | `GET /artifacts`, `GET /artifacts/{id}`, `GET /artifacts/{id}/download?as=`, `POST /artifacts/{id}/archive`, `POST /artifacts/{id}/restore`, `DELETE /artifacts/{id}` | Browsable deliverables in any format — Markdown, HTML, Word, Excel, or a link into a connected app — with `format`, `downloads`, `external_url`, `supersedes_id` and, for an extension's kind of document, `collection` / `collection_label` on every summary (`orchestrator.extensions`; archive, restore and delete tell the collection first and answer 502 if it refuses). `download` renders the file (Word/Excel built at request time from the stored text; any Markdown artifact, workflow output included, can export `?as=docx`) and is always an attachment with `nosniff` and a sandbox CSP. Every route answers for the signed-in caller (`artifact_records.Viewer`): a drafted artifact is its owner's alone (`alerts.owner_person_id`, the person whose conversation published it; none = the principal's), a workflow output follows its run (`persistence.run_visible_to`), and anything the caller may not see is a 404 like a missing id, the principal included. `POST /alerts/{id}/ack` and `/reopen` answer 404 for someone else's drafted artifact the same way. |\n| `decisions` | `GET /decisions`, `POST /decisions/{id}/{approve,reject,cancel}`, `GET`/`PUT /decisions/classes/meeting_scheduling`, `GET /audit/reliability` | Approval-gated decision instances (e.g. calendar bookings). What approve/reject/cancel do is per class (`DECISION_CLASSES`, one `DecisionClassSpec` each; meeting booking books on approve and deletes on cancel; `delegation_reply`, an inbox reply card, is its approver's alone (`approver_only`) — hidden from everyone else, the principal included when it is a team member's — sends its Gmail draft on approve and, after a reject, deletes the draft unless it was edited; `delegation_invite`, a meeting invite card, is its approver's alone too, and answers the invite in their own calendar on approve (`edits.answer`) and nothing on reject; `department_action`, a team member's chat send or edit their department held (see Org), is the principal's and its approver's alone (`principal_and_approver`), makes that exact call on approve and audits `department_action_done` / `_failed` / `_declined`), and an instance of a class with no spec gets 409 instead of being carried out as another. Only the principal, or the person the decision went to for approval (`approver_person_id`), may approve, reject or cancel it. Anyone else gets 403, and a decision nobody was asked about, or one private to the principal, is the principal's alone. The resolver is recorded as `resolver_person_id`, and a reject that loses the race to another answer is a 409. `GET /audit/reliability` is the principal's alone (403 otherwise), because it counts private decisions too. A proposed booking is surfaced on the briefing as a companion alert; approve/reject/cancel here also clear that alert. An approval whose caller resolves to the principal runs the booking inside `grant_contact_egress()`, so a meeting the principal proposed with a contact can be created. Such a booking's payload is marked `private`: it is proposed to the principal, left out of anyone else's `GET /decisions`, and a 404 for them on `GET /decisions/{id}` and every action route. Reviewed in the briefing — there is no separate proposals page. The class routes read and set how meetings are handled: both return `{decision_class: \"meeting_scheduling\", mode: \"propose\" \\| \"auto_execute\"}` (default `propose`); the `PUT` body is `{mode}`, principal-only (403 otherwise, open before a principal exists — but then only `propose` can be set: `auto_execute` is a 409 until a non-archived principal is on the roster), 422 on any other mode, and a change writes a `decision_class_mode_changed` audit row. In solo mode the class mode decides a booking, and `auto_execute` applies only to a turn the principal started on a verified surface — any other turn gets a proposal. |\n| `delegation` | `GET`/`PUT /delegation`, `GET`/`PUT`/`DELETE /delegation/voice`, `POST /delegation/voice/learn`, `POST /delegation/voice/describe`, `POST /delegation/voice/signature`, `PUT /delegation/inbox`, `POST /delegation/inbox/check`, `GET /delegation/replies`, `PUT /delegation/replies/{id}/text`, `PUT /delegation/replies/{id}/recipients`, `POST /delegation/replies/{id}/answer`, `GET /delegation/actions`, `GET /delegation/invites`, `PUT /delegation/handle-it`, `PUT /delegation/disclosure`, `PUT /delegation/training`, `DELETE /delegation/learned/{id}`, `GET /delegation/handled`, `PUT /delegation/team` | Act as me — the **caller's own** delegation only; nobody sets it for anyone else. It answers the principal, and a team member once the owner lets them; anyone else gets 403 `not_available_yet`. `GET /delegation` returns `{enabled, gmail: {status, message, email, connect_command, outlook_connect_command, provider}, inbox: {enabled, status, message, watch_since, last_poll_at, checking}, handle_it: {enabled, mode, available, sent_today, lead, lead_available}, training: {replies, follow_ups, actions, drafts, learned}, disclosure: {enabled, handle_it, approved_sends, line}, team}`, where `team` is the owner's switch for the principal while `DELEGATION_TEAM_MEMBERS` allows it — `{enabled, members: [{person_id, name, enabled, inbox, drafts_30d, sent_30d}]}`, counts only — and `null` otherwise. `PUT /delegation/handle-it` takes `{enabled?, mode?}` (`mode` is `careful`, `balanced` or `bold`; anything else is a 422 `bad_mode`) from a caller the API knows is that person — 403 `not_yours`, 409 `caller_signing_required` with only the shared secret — and turning it on needs Act as me and Draft replies to my inbox on (409 `act_as_me_off` / `inbox_off`); `GET /delegation/handled` returns `{replies: [{decision_id, sent_at, to_name, to_email, subject, body, open_questions, gmail_link, source, summary}]}`, the caller's replies and follow-ups (`source` `follow_up`) sent on its own in the last 7 days, and the meeting invites it accepted on its own (`source` `invite`, `subject` the meeting's title, `summary` one line such as \"Accepted Dana's Pilot review, Wed 21 Oct, 14:30\"); a card on `GET /delegation/replies` carries `source` the same way, `can_allow` while Replies (Follow-ups, on a follow-up) is in training, and `learns_style` while Drafts is. `PUT /delegation/disclosure` takes `{handle_it?, approved_sends?}` (any other field is a 422), the caller's own switches for the AI line on replies sent as them (`disclosure.enabled` is the install's `AI_DISCLOSURE`); turning one on needs no signed sign-in, turning one off does (409 `caller_signing_required`), and a change is audited as `delegation_disclosure_changed`. `PUT /delegation/training` takes `{replies?, follow_ups?, actions?, drafts?, actions_on?}` (any other field is a 422; `actions_on` is Suggested actions On, and `actions` and `actions_on` set true clear each other) and returns the `GET /delegation` shape, whose `training` carries `actions_on` too; putting Replies or Follow-ups in, or Suggested actions out of training or On, needs no signed sign-in, anything else does (409 `caller_signing_required`), and putting Replies or Follow-ups in turns Take the lead as you off (`PUT /delegation/take-the-lead` on answers 409 `in_training` while they are). `training.learned` is `[{id, label, setting, example, uses, created_at}]`, what the caller allowed or kept in training (`setting` `replies`, `follow_ups`, `actions` or `drafts`; the kept example, or \"\"); `DELETE /delegation/learned/{id}` removes one of the caller's own (404 for anyone else's). `PUT /delegation/team` takes `{enabled}` from the principal alone (403 `principal_only`; 409 `not_available` when the install doesn't allow it). The Gmail `status` is `connected`, `not_configured`, `needs_reconnect`, `mismatch`, `no_email`, `shared_mailbox` or `error`, checked live with Google on each call. `PUT` takes `{enabled}` (any other field is a 422); turning it on needs the caller's own Gmail connected, otherwise a 409 whose code says why (`gmail_not_connected`, `gmail_needs_reconnect`, `gmail_mismatch`, `no_email`, `shared_mailbox`, `gmail_error`). The voice routes show, learn (from the caller's sent mail, one pass at a time — a 409 `in_progress`, `locked`, `too_soon`, `not_enough_mail`, `no_profile` or `changed` when it was locked or edited while learning, or a Gmail code), write it from the caller's own description (`POST /delegation/voice/describe` with `{description}`: one model call applies their words to the profile they have and returns it with a short `sample_reply`, saving nothing, so they review it and save it with `PUT`; a 409 `empty`, `too_long`, `in_progress`, `too_many` past 10 an hour or `no_profile`; no mailbox needed), edit and lock, and reset \"How I write\": a typed field that fails validation is a 422 `invalid_voice` listing each `rejected` field, and `clear_exemplars` / `clear_signature` drop those. `POST /delegation/voice/signature` reads the signature from the caller's Gmail settings again and changes nothing else (a locked profile stays locked), with the same Gmail codes as learning: a 409 when their mailbox isn't connected, it refuses the sign-in or the check itself fails (`gmail_error`), and a 502 `gmail_error` when reading the signature fails. On an Outlook mailbox it is a 409 `signature_unavailable`, since Outlook gives apps no signature to read, and the stored one is left alone. A caller `can_delegate` refuses — anyone but the principal, for now — gets 403 `not_available_yet`, which hides the Settings card. A request with no `x-caller-email` is a 403 `sign_in_required` unless the API runs under local login — a header-less call is not a sign-in (the caller is read through `api/caller.py`, as on every principal-only route). `PUT /delegation/inbox` takes `{enabled}` and turns **Draft replies to my inbox** on or off, returning the same shape as `GET /delegation`: on needs Act as me on (409 `act_as_me_off`) and the mailbox connected (the Gmail codes above, which keep their names for an Outlook mailbox too), and turning Act as me off turns it off too. `POST /delegation/inbox/check` starts a scan now in the background and answers 202 with the `inbox` state (409 `inbox_off` or `in_progress`). `GET /delegation/replies` returns `{cards: [...]}`, the caller's open reply cards from the database alone (no Gmail call): the decision id, the sender's name, address, relation and whether it was verified, the subject, when it arrived, what they wrote, the draft's recipients, subject and body, `open_questions`, `flags` and a Gmail link built from a fixed prefix. **Send** is `POST /decisions/{id}/approve`: it sends the card's draft exactly as it is in Gmail, after checking again that the caller is its owner — which on a server needs signed callers (409 `caller_signing_required` otherwise) — that both switches are on (`inbox_off`), no client slot is active (`client_slot`), the Gmail is connected (the Gmail codes), the draft is still there and unanswered (`draft_gone`, `you_replied`) and its recipients are allowed (`no_recipients`, `too_many_recipients`, `executive_recipient`, `not_from_you`). Recipients that changed, or a newer message in the thread, answer 409 `{code: \"confirm\", message, reasons, recipients}`; approving again with `edits: {recipients: <the list shown>, thread_moved_on: true}` is the second yes. Send with the *on its own next time* tick adds `edits.allow: true`: 422 `cant_allow` unless Replies (Follow-ups, on a follow-up card) is in training, 409 `learned_full` when their list is full, both before anything is sent; `edits.example: true` keeps a draft edited in the mailbox as how they write to that person while Drafts is in training. A draft edited in Gmail between those checks and the send is not sent (`draft_changed`). A double tap sends once (`already_handled`); Gmail refusing answers 429 `rate_limited` or 502 `gmail_error` with nothing sent, and a send Gmail didn't confirm answers 502 `send_unconfirmed` and is settled by the next inbox scan. Dismiss is `POST /decisions/{id}/reject`. `GET /delegation/invites` returns `{cards: [...]}`, the caller's own meeting invite cards (`delegation_invite`, Read my calendar on): `decision_id`, `status`, `created_at`, `from_name`, `from_email`, `relation`, `title`, `when` (in the workspace time zone), `start`, `end`, `all_day`, `clashes` (busy times only, `\"14:00–14:30\"`), `clash_checked`, `can_answer` (false for a sign-in that reads but can't answer the calendar; then `connect_command`), `can_allow` (Replies in training) and `waited_because`. **Accept** / **Decline** is `POST /decisions/{id}/approve` with `edits: {answer: \"accept\" | \"decline\"}` (accept is the default; `allow: true` with accept for the *Accept from them on its own next time* tick), on the same caller checks Send uses (403 `not_yours`, 409 `caller_signing_required`); 409 `calendar_write_needed` when the sign-in can't answer (the card stays), `gone` when the event left their calendar, `expired` once the meeting started, `already_handled`; 502 `calendar_error` leaves the card for another try. **Dismiss** is `POST /decisions/{id}/reject` and answers nothing. `GET /delegation/actions` returns `{cards: [...]}`, the caller's own approval cards (`delegation_actions`): the decision id, when it was made, a one-line `why`, and each action's `index`, `kind` (`invite`, `message`, `add_contact`), `summary` and `text` (a message as it will be sent, or a meeting's description). **Approve** is `POST /decisions/{id}/approve` with `edits: {only: [indexes]}` (and `allow: true` for the *Do this on its own next time* tick while Suggested actions is in training: 422 `cant_allow` otherwise or when nothing on it can be allowed, 409 `learned_full`; a card carries `can_allow`); it needs the card's own person signed in (403 `not_yours`, 409 `caller_signing_required`), Act as me on (409 `act_as_me_off`) and a card under a week old (409 `expired`), runs once (409 `already_handled`), and returns the decision with `final_payload_json.results`: per action `done`, `waiting` (sent to whoever approves meetings), `failed` with why, or `skipped`. Every change writes a private audit row. |\n| `history` | `GET /memories/history` (`?q=`), `PUT /memories/history/settings`, `PATCH`/`DELETE /memories/history/{id}`, `POST /memories/history/{id}/forget-conversation` | Always in the loop: the **caller's own** notes and switches only, resolved as for Act as me (a signed-in person on the roster, or the principal under local login; otherwise 403 `sign_in_required` / `not_on_roster`). `GET` returns `{notes, reply_notes, retention_days, effective_retention_days, company_retention_days, retention_choices, can_keep_notes, can_note_replies, can_set_company_retention, share_work_style, can_share_work_style}` (`can_keep_notes`: a team member on the People list may turn notes on; `can_note_replies`: they can use Act as me, so email replies are noted too; `share_work_style`: their own \"Share my work style with the team\" switch, `can_share_work_style`: a team member in a team workspace). `PUT` turns notes on only for someone who may keep them, and `share_work_style` on only for someone who may share it (403 `not_available` for either; turning either off always works), takes a person's retention only when shorter than the company's (422 `invalid_setting`), and the company retention only from the principal (403 `principal_only`). `PATCH` pins or corrects a note; `DELETE` forgets it; `forget-conversation` is \"Don't remember this\". A note that isn't the caller's is 404. Every change is audited privately to its person. |\n| `reflection` | `GET /memories/reflection` (`?person_id=`), `DELETE /memories/reflection/misses/{id}` | Learning: the turns the conversation review graded a miss (`memory.chat_review`), with the person's words, the reply, the tools run, what they wanted instead, the `kind` (`company` / `product`) and the signals, plus `weeks` (`{week, graded, misses}` per ISO week, newest first) and `sees_everyone`. The caller is resolved as for `history` (403 `sign_in_required` / `not_on_roster`); each person sees their own, the principal those from chats `chat._session_access` lets them open (a teammate's own web chat or DM and a mail-private conversation stay their owner's; channels and groups are open), or one person's with `?person_id=` (a teammate naming someone else gets 403 `not_yours`); the weekly counts carry no words and are not filtered. The same response carries `lessons` (`memory/lessons.py`: live first, then retired, each with `shown`/`fine_after`/`miss_after` and `retired_reason`), filtered by the same rule, and `DELETE /memories/reflection/lessons/{id}` retires one (204; 404 for a lesson the caller may not see, already retired, or missing). `DELETE` forgets one miss (`is_principal_or_self`; 404 `not_found` otherwise) and writes a `chat_review` audit row. Each miss also carries its nightly replay (`memory/replay.py`): `replay_state` (`open` / `closed` / `evidence`), `replayed_at`, `closed_at`, `replay_notes`; and the response carries `replay` (`{misses, would_pass, evidence, last_run_at}`: of the caller's visible misses from the last 30 days, how many would go right today). |\n| `notifications` | `GET /notifications/settings`, `PUT /notifications/settings` | Settings → Notifications: the **caller's own** settings only, resolved as for the notes (a signed-in person on the People list, or the principal under local login; otherwise 403 `sign_in_required` / `not_on_roster`). `GET` returns `{quiet_hours: {enabled, start, end, days}, delivery, urgent_through, timezone, effective_timezone, held_count, gets_briefs, updated_at}` — `days` is `every_day` or `weekdays`, `delivery` `instant` or `digest`, `timezone` the zone they chose (`\"\"` for the workspace's), `held_count` how many messages wait for their quiet hours or brief (counted, never listed), `gets_briefs` whether they are the principal. `PUT` takes `{quiet_hours, delivery, urgent_through, timezone}` and replaces them (extra fields, equal start and end, a bad time or an unknown zone → 422); switching `digest` → `instant` makes what waited for the brief go now. Audited as `notification_settings_changed`. See Org. |\n| `audit` | `GET /audit/logs`, `GET /audit/logs/{id}`, `GET /audit/sessions/{id}`, `GET /audit/usage`, `POST /audit/log` | Durable audit trail of side effects. `/audit/sessions/{id}` adds a per-session token cost summary; `/audit/usage` aggregates token usage and OpenRouter cost across all sessions (totals, by day, by model, and by source — the part of the system that made the calls — including server-side web-search counts), plus `scripts`: how many `run_script` scripts ran (and worked, and in workflows), the tool calls they made, their time, and `turns_avoided` — an upper bound on the model turns those calls would otherwise have needed (each call past a script's first) — and `python_jobs`: how many Python jobs ran (and worked, ran a kept Custom tool, took a chat attachment), their time, CPU, largest peak memory and bytes in and out, and the tokens and charge of the turns that ran one. The Token usage page shows it as a Scripts section. Rows private to the principal (`private_to_principal`: a turn about their private mail, or a row naming one of their contacts on their own turn) are theirs alone: for any other caller, resolved as for `/alerts`, the usage totals leave them out. Once a principal is on the roster, anyone else reads only their own rows (a teammate's own turns, their Act as me work) in the list, by id and in a session, and the principal reads those as actions only — what was done, when and in whose conversation, with the text, details and `full` left out, and no text search over them; any other row's id is a 404, and a session shows only the rows the caller reads. |\n| `architecture` | `GET /architecture/sections`, `.../sections/{id}` | This documentation surface. |\n| `guide` | `GET /guide/sections`, `.../sections/{id}` | Plain-language user-guide content surface — mirrors `architecture` (static, version-controlled files; no LLM on the serving path). |\n| `health` | `GET /health`, `GET /health/honcho` | Liveness probes. Only `/health` is unauthenticated; `/health/honcho` sits behind the gate like everything else, because the exemption is an exact-path set. `/health` also carries `google_tools_missing`, the pinned Google tools startup priming could not find: `[]` once it has checked and they are all there, a list of names when a workspace-mcp rename or the configured services and tool tier left one out, and `null` for no answer — Google Workspace is not configured, or the probe has not finished or it failed. Only `[]` asserts they are present. It also carries `gateway`, the MCP gateway's state from its supervisor (`orchestrator.gateway_boot`): `state` is `off` (MCP not enabled), `no_servers` (enabled, the config names none), `starting` (an attempt is running), `up` or `down` (every attempt so far failed; `next_retry_at` is the next one), with `attempts`, `up_since` and `email_poller` (whether the poller that rides on the gateway runs); the failure's own text stays out, since the route is open to anyone, and goes to the log and the owner's notice on Home. A hosted instance whose gateway never came up used to answer `ok` here with no email going out or in. Only `[]` asserts the tools are present, so a probe that died cannot read as healthy; Setup status says which of the three `null` means. |\n| `version` | `GET /version` | The running version, the latest release on GitHub and `update_available`, for Settings → About. The GitHub answer is cached 6h, only a semver `tag_name` is used and the release link is built from it; `UPDATE_CHECK_ENABLED=false` skips the call and still returns the running version. No in-app updater: upgrading is host-side (`docs/deployment.md#upgrading`). |\n| `setup_status` | `GET /setup/status` | Settings → Setup status: one light per part of the install — AI model, company setup, owner, the Executive's address, API protection, Gmail, your own mailbox (Act as me), Slack, Discord, Telegram, Google Chat, the scheduler, the daily brief (when and where it goes) and Honcho — as `{checked_at, checks: [{id, label, state, summary, fix, link, last_activity}]}`, where `state` is `ok`, `warn`, `error` or `off` (optional and not set up), `fix` says what to do in plain language, `link` is an in-app page that helps (`/people`, `/onboard`) and `last_activity` is the channel's latest `integration_inbound` audit time. It tests live, with at most one free read-only call per service, each bounded to 5 s: Anthropic `models.list` (so an organisation key missing `ANTHROPIC_WORKSPACE_ID` shows up), Slack `auth.test`, Telegram `getMe` and `getWebhookInfo`, Discord `users/@me` only while the bot is still connecting, and — once the owner's own Gmail credential exists — Google's token refresh and Gmail `users/me/profile`. It also reads the listeners the lifespan leaves on `app.state` (Slack's socket, the Discord bot and its task, the MCP gateway), the scheduler heartbeat and the pause switch. When `google_workspace` is configured, the lifespan also starts `MCPGateway.prime_pinned_tools()` in the background (held on `app.state.mcp_prime_task`, cancelled at shutdown), so the pinned Google tools named in the prompt are callable without a search. With `DRIVE_SYNC_ENABLED` the lifespan also bootstraps the `drive_sync_scan` heartbeat beside Notion's (see Scheduler); the Drive folder sync has no HTTP route, only the `openexecutive sync-drive` / `purge-drive` CLI. With `CONFLUENCE_SYNC_ENABLED` it bootstraps the `confluence_sync_scan` heartbeat the same way; that sync is run by hand with `openexecutive sync-confluence` / `purge-confluence`. Sample values copied from `.env.example` are named as such without being sent anywhere. No token reaches a response or a log line: probes report a status code, a service's short error code or an exception's class name. Requests within 5 s of a run get that run's answer and concurrent requests share one run (kept per app on `app.state`), so the button can't become a stream of calls to those services. Gated like every other route; the UI adds a sign-in light of its own, from its own settings. |\n| `documents` | `POST\\|GET\\|DELETE /documents`, `GET /documents/{filename}`, `GET /documents/sources`, `POST /documents/sources/{drive\\|onedrive\\|notion}/sync`, `GET /documents/{drive\\|onedrive\\|notion}`, `GET /documents/{drive\\|onedrive\\|notion}/{id}` | Upload, list, view extracted text, and delete indexed company docs. `GET /documents` rows carry `source: \"upload\"` and the `domain` the upload was indexed under. The connected-source routes back the knowledge page's single Company documents list: `/documents/sources` gives each source's `{id, label, enabled, syncing, last_run, last_error, interval_minutes, file_count}`; `/documents/drive`, `/documents/onedrive` and `/documents/notion` list synced files from the sync state (`{enabled, last_run, last_error, files: [{id, name, url, modified_at, synced_at, indexed}]}`; a Drive row also carries `unreadable_reason`, why a file with `indexed: false` has no text — e.g. a scan OCR could not read — or null); `/documents/{drive\\|onedrive\\|notion}/{id}` returns the stored text (a OneDrive id is `<drive id>:<item id>`) for an id on record (the path comes from the state, never the caller). They are read-only — a synced file is removed where it lives. `POST …/sync` starts one tick of the same sync the scheduler runs as a background task (202); 409 when the source is not connected or a tick is already running (every sync holds a per-process run lock, so a manual run never overlaps the heartbeat; the route also keeps its own started task per source and re-checks just before starting one, so two simultaneous requests start one tick, not two), 429 with `Retry-After` within 60 s of the last successful run or of the end of the last tick in this process, failed ones included, so a failing or slow source can't be re-run back-to-back. The page's text view never loads images from synced content (a remote image would be a read beacon for whoever edits the shared folder). Upload is keyed on the filename, so re-uploading a document replaces its chunks rather than duplicating them, and `DELETE` removes the rows as well as the file. `domain` must be one of the nine specialist domains (including `sales`) or `general`; anything else is a 400 rather than a 200 that indexes where no specialist can retrieve. A scanned PDF is converted (`knowledge.pdf_reader`) before it is indexed and in the text view, as are scanned PDFs in `POST /chat/upload` and the client / onboarding intake uploads. The upload is streamed to disk 1 MB at a time and refused with a 413 once it passes 50 MB, and the file is parsed in a short-lived child process (see the RAG section), so a large document does not stay in the API process's memory. A Word or Excel file that cannot be parsed, or whose parse runs out of time, is a 422 with a readable reason. When every parser is busy, the response is a 503 with `Retry-After`. |\n| `executive` | `GET /executive/status`, `POST /executive/pause`, `POST /executive/resume` | Operator pause switch for all autonomous work (scheduler, Gmail poller, workflow resumer); inbound chat and DMs stay live. Status returns `{paused, paused_at, paused_by, reason, held_actions, can_resume, name}` — `held_actions` counts due `pending` rows that fire on resume, and `name` is the Executive's name (`EXEC_DISPLAY_NAME`), which the web chat shows over its replies. `pause` takes an optional `reason` (≤200 chars) and is idempotent (re-pausing keeps the original start and reason); `paused_by` is the UI proxy's `x-caller-email`, else `api`. Behind the shared-secret middleware — not `SCHEDULED_ADMIN_TOKEN`, which the UI cannot send. Any caller may pause; `resume` is principal-only (`is_principal_or_self`, 403 otherwise; open while no principal is rostered; a header-less caller resolves to the principal as in `chat`), and status carries `can_resume` for the viewer so the UI hides Resume from everyone else. |\n| `workspace` | `GET /workspace`, `PUT /workspace` | Solo/team mode, the user's time zone and the principal's role (`memory.workspace_settings`). Both return `{mode, timezone, effective_timezone, role_kind, role_title, reports_to, remit, measured_on, company_domains, company_domains_custom}` — `timezone` is what the user set (null when unset), `effective_timezone` the zone in effect (`timezone`, else `USER_TIMEZONE`, else UTC), and each role field is null until set. `PUT` is a partial update: only the fields sent change; `mode` is `solo` or `team` (not null), `timezone` an IANA zone, or null/blank to clear it; `role_kind` is `owner`, `in_house`, `independent` or `other`, and `role_title` / `reports_to` / `remit` / `measured_on` are free text (trimmed, at most 120 / 120 / 500 / 300 characters), each null or blank to clear it; an unknown zone, a bad mode or role kind, an over-long role field or an unknown field is a 422 and changes nothing. Switching to solo cancels every pending department check-in, switching to team re-schedules them, and a new zone re-times the pending briefs and reflection; a role change has no side effects (the next turn reads it). `company_domains` is the company's own email domains (a teammate matches by local part on them — see Org): `GET` returns the ones in effect (the stored list, or the domain of the principal's primary address, with `company_domains_custom` false) only to the same caller the role is shown to, `[]` for anyone else; `PUT` takes a list (at most 10 plain domain names, never a free-mail provider's — 422 otherwise, the value never quoted) or null / `[]` to go back to deriving them, and a change is audited with the new list. Each change writes a `workspace_settings_changed` audit row (a role change adds `details.role_fields_changed`, the names of the fields that changed — never their text). The role is the principal's: `GET` returns it only to a caller `PUT` would accept and reads it as nulls for anyone else. `PUT` is the principal's alone (`is_principal_or_self`, 403 otherwise; a header-less caller resolves to the principal as in `chat`) and open while no principal is rostered, so first-run setup can pick a mode. Both work before onboarding — unlike `company-profile`, nothing here needs a profile. |\n| `scheduled` | `GET\\|DELETE` scheduled actions (`?status=…&order=asc\\|desc`) | Pending and fired scheduled actions; `order` flips the `run_at` sort (asc=soonest-first for the upcoming queue, desc=most-recent-first for terminal-status history). `DELETE /scheduled/{id}` cancels a `pending` row (409 otherwise). Like pause it only stops work, so any signed-in user may — the UI proxy's `x-caller-email` is trusted when the request also carries the `BACKEND_SHARED_SECRET` `x-api-key` — as may a matching `X-Admin-Token` (`SCHEDULED_ADMIN_TOKEN`) or a loopback caller with no token set; otherwise 401 (token set) or 503. Audited as `scheduled_action_cancelled`. |\n| `watchlist` | `GET\\|POST\\|PATCH\\|DELETE /watchlist`, `POST /watchlist/describe`, `POST /watchlist/{slug}/approve`, `POST /watchlist/{slug}/decline` | External-monitoring watchlist + signals. `POST /watchlist/describe` `{text}` drafts a watch from a sentence (one forced tool call on the utility-fast model, `monitoring.describe`; the company profile's name, competitors, vendors and tickers ride in the user turn) and saves nothing: it returns the create fields (`slug`, `signal_type`, `target`, `display_label`, `trigger`, `cadence`, `mode`, `severity_floor`, `severity_ceiling`, `notes`) plus four plain lines (`watching`, `tell_you_when`, `how_often`, `how_loud`) written by code from those fields, after the create route's checks (registered kind, cadence, severity, the URL guard, the rss feed check, a free slug); 422 with a plain reason when it can't be a watch, 429 past 30 drafts an hour, 502/504 when the model fails. `GET /watchlist/{slug}` also returns `noise` `{recent_alerts, recent_dismissed, noisy}` (its last 8 alerts, noisy at 6 dismissed, `monitoring.noise`), and `PATCH` takes `quiet_noise_nudge: true` to stop that question for the alerts so far. `display_label` on create maps to the adapter's label key for every kind. Rows carry `origin` (`manual` \\| `executive` \\| `research` \\| `research_proposed`); `approve` turns a research suggestion (`research_proposed`, `dry_run`) into a live watch, `decline` `{reason: not_relevant \\| too_noisy \\| wrong_source}` removes it and records the decline (or, for `too_noisy`, keeps it live at a high floor), both 409 unless the row is a pending suggestion; `DELETE ?reason=` on a research-origin row records the decline too. |\n| `workflows` | `GET /workflows`, `POST /workflows/{name}/runs`, `GET\\|POST\\|PUT\\|DELETE /workflows/custom`, `GET\\|DELETE /workflows/custom/{name}/targets`, `POST /workflows/runs/{run_id}/decision`, `POST /workflows/runs/{run_id}/rerun`, `GET /workflows/tools/search?q=`, `GET /workflows/tools/describe?names=` | Workflow catalog, run management, and user-created (dynamic) workflow CRUD. `rerun` queues a failed scheduled run (a department check-in, a saved workflow on a cadence) once more, due now (see Scheduler); the principal may, and for a saved workflow the person it delivers to; 409 for a run that did not fail, one started from `/jobs` (\"Start this one again from its page\") or one already queued again. Custom definitions come back with a server-managed `owner_person_id` (the creator — the web caller on `POST`, set on insert only; a client-sent value is ignored), who is asked to approve a workflow's first write to a new target. `GET /workflows/custom/{name}/targets` lists the targets its tool steps may write to without asking and `DELETE …/targets?value=` forgets one. `POST /workflows/{name}/runs` is a 403 (\"Only the principal can run this workflow.\"), audited, before any run row exists, when the workflow is one only the principal may start in the workspace's mode (`weekly_review` always, `morning_brief` in solo) and the caller is not the principal. A request with no `x-caller-email` counts as the principal; with no principal on the roster, no signed-in caller does. This governs starting a run only. A run started by hand (this endpoint, or `run_workflow` / research in chat) records its starter as `owner_person_id` and is theirs alone: `GET /workflows/runs` lists the team's (scheduled, no owner) runs plus the caller's own and the ones waiting on them, and `GET` / `DELETE /workflows/runs/{run_id}` and `POST /workflows/runs/{run_id}/decision` are a 404 for anyone else's, the principal included. A signed-in email that is on nobody's People entry cannot start one (403), and a run whose starter can't be read is refused (503); its steps read and draft documents as the starter only. `POST /workflows/runs/{run_id}/decision` with `{decision: \"approve\"|\"reject\"}` answers a run awaiting a yes/no sign-off from the web app — 403 unless the caller is the person it waits on or the principal, 409 if it isn't awaiting or needs a written reply — through the same `apply_resolution` a chat reply uses. Custom create/update also rejects (422) any action-step tool that does not resolve, and so does `POST /workflows/custom/{name}/activate` when turning a workflow **on** — that click is the approval for a tool workflow chat saved switched off (turning off is never checked). Turning on a workflow with action steps requires the body `{is_active: true, definition}` carrying the definition the user reviewed; if the stored one differs (ignoring `is_active` and timestamps) it returns 409, and the switch itself is a compare-and-set on the validated revision (`dynamic_store.activate_if_unchanged`, keyed on `updated_at`), so a save that lands while the tool check awaits the gateway — even from another process — is a 409 too, so only what was shown gets switched on. `GET /workflows/custom` lists inactive definitions too; `GET /workflows/{name}` 404s for them. The two `tools` endpoints return `{tools: [{name, description, read_only, source}]}` for the advanced editor's tool picker and the review card; `read_only` is true only when the name says it reads (a label, not a control). The run stream adds a `progress` event (`step_id`, `summary`) while an action step uses tools. Each catalog entry (`WorkflowMeta`) carries `is_custom`, `background` (true for the system-run built-ins the UI files under “System”) and `quick` (true for a Quick workflow, one per playbook nothing else follows, named `quick_<playbook>`). The run endpoint streams SSE; its `awaiting_human` event carries `delivery` (`self` \\| `sent` \\| `suppressed` \\| `alerted` \\| `failed`) alongside `person_id` / `question` / `awaiting_until`, because the outbound guard or an unreachable approver means the question may never have been asked — a client must not render “waiting on them” for those. A paused run ends the stream with neither `done` nor `error`, so that `awaiting_human` frame carries `terminal: true` to say so explicitly, plus `resumable` — whether the run continues by itself once answered or stops at the gate. `GET /workflows/runs/{run_id}` returns the run row with the resume payload replaced by a small `resume_progress` summary (`gate_step_id`, `completed_step_ids`, or `null`): the payload holds every completed step's full text, and the run-detail page polls this endpoint while a run is unfinished. |\n| `knowledge` | `/knowledge/builtin`, `/external`, `/search` | MBA knowledge base and external sources. `/search` is the introspection parallel of `retriever.retrieve` and mirrors its filters — including the `general` catch-all on the company collection — so the panel cannot report a specialist seeing nothing that it does retrieve in chat. It accepts `general` in `domain_filter` for the same reason. `/search` applies the same review gate as `retrieve()` — withheld (pending or rejected) built-in, external and failure rows are dropped, so the panel never advertises knowledge the Executive cannot use; it degrades to unfiltered rather than failing if review state is unreadable. `POST /knowledge/builtin` refuses a name already held by shipped content, and `POST|DELETE /knowledge/failures` now register and deregister for review — without that a user-authored failure case study had no review row, so no SME decision could block it. |\n| `skills` | `/skills`, `/skills/search`, `/skills/{name}/restore` | Skill registry (the UI's **Playbooks**) CRUD and search. `PUT` on a built-in saves a company customization that shadows it; `DELETE` returns `{name, outcome}` — `deleted`, `reverted` (customization removed, built-in back) or `hidden` (built-in hidden for this company); `restore` un-hides; `GET /skills?include_hidden=true` lists hidden built-ins. List and detail carry `used_by` — `[{name, title, is_custom}]` of the workflows that follow the playbook (switched-off custom ones included) (`WorkflowMeta.playbooks` is the other direction). |\n| `evals` | `/evals/scenarios`, `/evals/runs` | Eval scenarios and run results. `POST /evals/runs` is a 403 when a workflow scenario names a workflow that only the principal may start in the mode it runs in (the weekly review; the morning brief in solo) and the caller is not the principal — the Jobs page's rule for starting a run; stored results are read under the existing `/evals/runs` rules. |\n| `memories` | `/memories/{decisions,initiatives,advice}`, `GET /memories/facts`, `POST /memories/facts/{fact_id}/{retire,approve,decline}`, `GET /memories/facts/approval`, `PUT /memories/facts/approval/{person_id}`, `GET /memories/people`, `GET /memories/people/{person_id}/conclusions` | Episodic-memory record management; the standing facts the Pulse Corrections tab reads (`{facts: [...], can_retire, retirable_ids, can_review}`; each fact carries `recorded_by_role` / `recorded_by_name`; `?include_inactive=` default true, honoured for the principal only; anyone else gets the active rows plus their own `proposed` ones, with the provenance (`session_id`, `turn_id`, `recorded_by_person_id`, `retired_reason`, and `source_quote` except on their own facts) blanked, never retired, replaced or declined text; `?limit=` 1–500) and their retire (the principal any fact, a teammate only one they recorded that the principal has not approved — else 403; the audit row names the teammate; 404 for an unknown or `profile` row, 409 when no longer active; writes a private `fact_retired` audit row); approve / decline a teammate's `proposed` fact (principal only, else 403; 409 when it is not proposed; private `fact_reviewed` row); and the per-teammate \"needs my approval\" switch (on by default; `GET` lists `[{person_id, full_name, needs_approval}]` for every active team member but the principal, `true` for anyone not yet set; `PUT` takes `{needs_approval}`, 404 for anyone else; both principal only; private `fact_approval_changed` row); plus the read-only peer-memory overview the Pulse People tab reads (`{status: ok|disabled|error, people: [...], conclusion_total}`; `?recent=` 1–50, default 5) and one person's full conclusion list, paged newest first (`{status, person_id, items, page, size, total, has_more}`; `?page=` ≥1, `?size=` 1–100, default 50; 404 when the person has no peer). Peer memory is each person's own: the overview holds only the caller's entry (none for a caller off the roster; `conclusion_total` counts only theirs), the principal included, and `/conclusions` for anyone but the caller is a 404. |\n| `review` | `/review/items`, `/review/stats`, `/review/trusted-defaults`, `POST /review/curate`, `POST /review/bulk-approve` | Knowledge review queue and annotations. Shipped knowledge registers as a trusted default (`approved` with a NULL `reviewed_at`), so the queue starts empty; `curate` (`{domain, action: start|stop}`, domain required) opts one domain in or out, and `trusted-defaults` returns domain → unreviewed count. `bulk-approve` takes a non-empty `domain`, `item_ids` (max 500) or `all_pending: true`, and 400s with no selector; it returns `{approved_count, item_ids}`. |\n| `onboarding` | `/onboard/interview/understand`, `/onboard/interview/start`, `/onboard/interview/message`, `/onboard/interview/draft`, `/onboard/interview/revise`, `/onboard/interview/{id}` (GET resumes, DELETE starts over), `/onboard/interview/commit` | Conversational company setup. The `onboarding_interviewer` agent asks clarifying questions, then emits a draft profile + people + departments. **Nothing is persisted until `POST /onboard/interview/commit`** — the interview itself never writes. `start` is multipart (description + optional deck/one-pager uploads). `revise` changes one earlier answer (0 = the description) and runs the interview again from there. `commit` answers 403 when the draft would make a different person the owner and the caller is not the current owner (setup demotes the old principal, and any signed-in user can open it). It also takes an optional `owner_email` — the principal's sign-in email, which the review screen pre-fills from the signed-in user — checked before anything is written (422 if it is malformed, already another person's, or would replace the principal's existing email — setup only fills in a missing one; 403 if the caller is not the owner and it is not the address they signed in with, since the roster is the sign-in allow-list) and saved on the principal's People row, so the owner's chats resolve to them from the first turn. |\n| `workflow_designer` | `POST /workflows/designer/start`, `POST /workflows/designer/edit`, `POST /workflows/designer/message`, `POST /workflows/designer/draft`, `GET /workflows/designer/{session_id}` | The conversational New workflow wizard, and editing a saved workflow by conversation. `/edit` (`{name}`) opens a session on a saved custom workflow with no model call: the stored definition is the starting draft, and every response then carries `editing` (its name) and `original` (the stored definition as the session opened on it); drafts keep that name and its on/off state whatever the model writes (404 for an unknown workflow). The UI saves one with `POST /workflows/custom/{name}/save-edit` (`{session_id, definition}`): the server saves the session's own draft, never a client-sent body, and only when it equals the `definition` the user reviewed (a later message is a 409, so the click saves only what was shown); it re-validates it, keeps the stored on/off state, and writes only if the stored workflow is still the version the conversation opened on — otherwise 409, as it is for a session about another workflow or one with nothing drafted yet. It sits under `/workflows/custom` so anything that limits writes to custom workflows covers it too. The `workflow_designer` agent asks clarifying questions (`phase: \"question\"`, with `hint` and up to four suggested `options`), then returns `phase: \"draft\"` with `draft.definition` (exactly the body `POST /workflows/custom` takes), `summary`, and `assumptions`; every response carries the `transcript`. **Nothing is persisted here** — sessions are in memory, and the UI saves through `POST /workflows/custom`. Errors are fixed strings (422 over the 8,000-char message cap or the transcript cap, 404 for an expired session, 409 while another turn on the same session is still running, 502/504 for model failure or timeout). Mounted ahead of the `workflows` router. |\n| `python_jobs` | `GET /python-jobs/{job_id}/{name}` | A result file a Python job (`run_python_job`) wrote, the principal's alone (403 otherwise), served as a download (`Content-Disposition: attachment`, `Content-Security-Policy: sandbox`, `nosniff`, `Cache-Control: no-store`); 404 for a bad id or name or a file past its 7 days. |\n| `saved_tools` | `GET /saved-tools`, `GET\\|PUT /saved-tools/{name}`, `POST /saved-tools/{name}/rollback` | The scripts the Executive saved as tools (Settings → Advanced → Saved tools), the owner's alone (403 otherwise). The list gives each tool's name, description, on/off, current version, `kind` (`script` or `python`, a kept Python job) and the tools it calls, plus whether `SAVED_TOOLS_ENABLED` is on; the detail adds the script, every version and the last 20 runs. `PUT {enabled?, workflows?, version?}` turns one on or off (off also turns it off for workflows, so turning it back on never re-arms unattended runs), and turns the named `version` — the one the owner looked at, never whatever is current by then — on for workflows (or workflows off); a Python tool never turns on for workflows (409) — turning workflows on lets more run unattended, so it needs a request tied to the owner (signed sign-ins or local login, as Take the lead's switches do; 409 otherwise); `rollback {version}` makes that version the one that runs. Both are audited as `saved_tool_changed`. The Executive saves tools itself through `run_script`; there is no create route. |\n| `onboarding` (fallback) | `/onboard/start`, `/onboard/answer`, `/onboard/status/{id}` | The original 12-step form wizard, kept as a fallback (UI at `/onboard?mode=form`) and used by the `openexecutive onboard` CLI. Its final answer saves the profile and adds people with their emails and a principal, so once there is an owner only they can send it (403, and the session rolls back so the owner can still finish it). `/onboard/start` reads the workspace mode once for the session: solo skips the Team Size, Team Members and Fractional Executives steps. Each status response's `current_step` / `total_steps` count only the steps that session asks, and `optional` says whether the current step can be skipped. |\n| `company-profile` | `GET\\|PATCH /company-profile` | Structured company profile. |\n| `alerts` (private cards) | `POST /alerts/{id}/ack`, `/reopen`, `/alerts/bulk-ack` | An alert tagged `private:principal` (see Today) is a 404 on ack and reopen for anyone but the principal, and their bulk sweep skips it. A roster-request card (source `roster_request`) is a 409 on `ack` even for the principal — it is answered at `/people/requests/{id}`, since acking would leave the sender waiting with nothing to show it — and, as an exempt source, `bulk-ack` and `reopen` skip it. |\n| `auth` | `GET /auth/allowed-emails` | Non-archived **team members** with an email, offered to the UI's sign-in gate — a contact is never on it, so adding a client to reach them by email no longer lets them sign in. The gate takes the **union** of this roster and its own `ALLOWED_EMAILS` env list, so env entries always work (and are checked first, short-circuiting the fetch) and roster entries are additive — a roster change can never revoke a configured operator. With local login (`make dev` with Google sign-in not set up — the UI then listens on 127.0.0.1 only) the UI signs in without an email, sends no `x-caller-email`, and the backend resolves the caller to the principal, as it does for the CLI. |\n| `fixtures` | `/fixtures`, `/fixtures/{name}/load` | Demo-company fixture load/reset/snapshot. `POST /fixtures/reset` leaves no departments, like a new install (`departments_seeded` is always 0). |\n| `clients` | `/clients`, `/clients/generate`, `/clients/cockpit`, `/clients/save`, `/clients/{slug}/activate` | Client-company slots — multi-client mode for fractional use; create from current/blank/AI-generated intake draft (pasted notes and/or file attachments, multipart on `/clients/generate`), save-back switching, engagement metadata (PATCH), cross-client cockpit, delete. See the Client Companies section. |\n| webhooks | `POST /webhook/telegram`, `POST /webhook/google-chat`, `POST /webhook/slack` | Inbound integration callbacks (self-verified). `/webhook/slack` answers 503 unless `SLACK_SIGNING_SECRET` is set. |\n| MCP server | `POST\\|GET /mcp` | Open Executive exposed as an MCP server (Streamable-HTTP). Not a router — a mounted FastMCP sub-app. Same shared-secret gate (`x-api-key`); exposes company context as resources and the specialist council as tools, answered as the verified caller (`api.caller`) by the web app's rules. See the MCP Server section. | A card the Executive left for something asked in chat (`app_action`, `orchestrator/app_control.py`) is its person's alone too: its payload holds `action`, `id`, `value`, `title` and the `card` line shown; **Confirm** is `POST /decisions/{id}/approve`, which runs the action through the route its button calls with that request (a refusal comes back as that route's status and words, and the card is marked `failed`), and a card older than a day is turned down with 409.\n\n**What it does for you** (`api/routes/may_do.py`): `GET /what-it-may-do` is read-only. It returns `{paused, sections}`, three sections in order (`as_you`, `executive`, `departments`), each `{key, title, available, unavailable, notes, rows, footer, goes}`, and each row `{id, what, outcome, then, why, setting, items}`: `outcome` is `goes`, `waits`, `always_waits`, `drafts` or `off`, and `setting` names where to change it (`act_as_me`, `handle_it`, `take_the_lead`, `pause`, `department:<slug>`, or empty). `as_you` is the caller's own (`available` false, with why, when they can't have Act as me); `executive` is the principal's alone (`available` false for anyone else); `departments` is everyone's. Any team member on People may call it; a contact, someone not on People, or a request with no caller outside local login gets 403. See Delegation → What it does for you.\n\n**How far it goes as you** (`api/routes/delegation.py`): `PUT /delegation/reach` takes `{step}`, one of `off`, `when_asked`, `inbox`, `careful`, `balanced`, `bold`, `everything`, and answers the caller's delegation state as `GET /delegation` does. Going down turns the switches above the step off, highest first; going up runs each switch's own route in order (`PUT /delegation`, `PUT /delegation/inbox`, `PUT /delegation/handle-it`, `PUT /delegation/take-the-lead`), so the first refusal (409 `gmail_not_connected`, a signed sign-in missing, `in_training`, 403 for Everything when not the owner) stops it at a whole step. See Delegation → How far it goes as you.\n\n**Take the lead** (`api/routes/take_the_lead.py`): `GET /take-the-lead` returns the As the Executive switch, its six Ask first switches (`{kind, label, hint, on}`, the hint a plain line on what each one catches), the company's rules, whether this server can tie a change to the owner (`available`), and whether the Executive is paused. `PUT /take-the-lead` takes `{enabled?, ask_first?}`, and `POST /take-the-lead/rules` / `DELETE /take-the-lead/rules/{id}` add or remove a company rule (`{kind: person|domain|words|amount, value}`, 422 on a bad one). All four are the principal's alone (403). Anything that lets more happen on its own (turning it on, turning an Ask first off, removing a rule) needs a caller the API can tie to them (`delegation.verified.caller_refusal`, else 409). `GET /today/activity` adds `took_the_lead` rows (what Take the lead did, named, not quoted) and, for the caller alone, `sent_as_you` rows for what Handle it for me sent as them (and the meeting invites it accepted as them, \"Accepted Dana's Pilot review, Wed 21 Oct, 14:30\") and, for the principal, one `contacts_kept` row a day the contact keeper changed something (`detail` like \"2 added, 1 updated\"). Under `/delegation`: `PUT /delegation/take-the-lead {enabled}` is Take the lead as you (the owner's only for now; turning it on turns Handle it for me on), and `GET|POST /delegation/take-the-lead/rules` and `DELETE …/rules/{id}` manage the caller's own rules. `HandleItOut` gains `lead` and `lead_available`. A `take_the_lead_action` decision is approved or rejected through the existing `/decisions/{id}/approve|reject`. Training: the response also carries `training` (In training: everything waits unless allowed), `learned` (`{id, label, feature, example, uses, created_at}`: what it was allowed, the edit kept as an example by field) and `suggested` (`{key, label, approvals}`); `PUT` takes `training?` too, and leaving training while on needs the same provable owner as turning it on. `POST /take-the-lead/learned {key}` allows a current suggestion (404 for anything else; provable owner), `DELETE /take-the-lead/learned/{id}` makes it ask first again. `learned` also lists the owner's own Act as me senders (`feature` `act_as_me`), never anyone else's, and Remove works on those too. On a `take_the_lead_action` card, `POST /decisions/{id}/approve` takes `edits.input` (the card's editable fields, 422 for any other; the principal's alone, 403 for an area approver) and `edits.allow: true` (a training card only, 422 otherwise; the principal from a provable request, 403 otherwise), finishing `approved_with_edit` when a field changed.",
"mermaid": null,
- "generated_at": "2026-10-19T17:58:25.847949+00:00"
+ "generated_at": "2026-10-19T19:00:00Z"
}
diff --git a/packages/core/openexecutive/architecture/prebuilt/audit.json b/packages/core/openexecutive/architecture/prebuilt/audit.json
index c06389cc..a6ef2f7e 100644
--- a/packages/core/openexecutive/architecture/prebuilt/audit.json
+++ b/packages/core/openexecutive/architecture/prebuilt/audit.json
@@ -1,7 +1,7 @@
{
"section_id": "audit",
"title": "Audit Log",
- "markdown": "The audit log is a persistent, searchable, append-only record of what the system did — distinct from episodic memory (which biases future LLM behavior). Every event flows through `audit/logger.log_event`, a synchronous SQLite writer (WAL + 5s busy_timeout) that appends one row to the `audit_log` table in `episodic_memory.db`.\n\n### Event types\nRows are tagged by `event_type`, including `chat_turn`, `specialist_consult`, `tool_invocation`, `scheduled_action`, `alert`, `integration_inbound` (Slack / Discord / email / Telegram / Google Chat), plus `knowledge_retrieval`, `fact_confirmation` (an emailed standing-fact change held, applied, cancelled or refused; private), `fact_reviewed` (the principal approved or declined a teammate's proposed standing fact; private), `fact_approval_changed` (the principal turned \"needs my approval\" on or off for a teammate; private), `fact_retired` (the principal, or the teammate who recorded it, retired a standing fact from the Pulse page; private, since it names the fact a teammate can no longer read; the fact tools' own rows and their `skill:` dispatch rows are private `tool_invocation` rows, since they quote the principal and name their session and turn), `memory_extraction` (one row per episodic-extraction pass, written in a `finally` so a crashed pass is recorded too: how many items the model proposed, how many were stored, a `{kind, reason}` record per drop, a `malformed` count for payload shapes that were never usable items, and a `failure` naming the exception type when the pass raised — including `CancelledError`, which is a `BaseException` and so would otherwise be logged as a clean empty pass — a `proposed>0, stored=0` streak means the quote validator is rejecting everything, which is otherwise invisible), `cache_event` (one row per model call from every call site — Executive turns, specialist consults (chat turns and workflow steps), research specialists, the research routing and watchlist passes, triage, memory extraction, alert review, the brief's narrative and its grounding repair, the digest, reflection and weekly-review workflows, committee reviewers, and the small utility calls (session titles, the chat-channel response gate, reply parsing, PDF transcription); a unit test fails any model call in the `openexecutive` package that records no row — carrying tokens, cache hits, cost, server-side search count and, inside a research run, its `run_id`), `memory_snapshot`, `committee_review`, `peer_memory`, `attunement` (one row per open-loop extraction pass — opened / closed / dropped with a reason per drop and a `failure` type — plus a row per loop opened or closed and per 👍/👎 on a reply; see Attunement), `executive_paused` / `executive_resumed` (the operator pause switch; actor is the caller's email, details carry the reason, or on resume the held-action count), `scheduled_action_cancelled` (a pending scheduled action cancelled from the Pulse page or a script; actor is the signed-in email, `admin-token` or `local`), `workspace_settings_changed` (solo/team mode, the user's time zone or the principal's role changed through `PUT /workspace`; actor is the caller's email or `api`, details carry the mode's and zone's from/to, plus `role_fields_changed` — the names of the role fields that changed, never their text — when the role changed, and the new `company_domains` list when the company's email domains changed), `decision_class_mode_changed` (a decision class switched between `propose` and `auto_execute` through `PUT /decisions/classes/meeting_scheduling`; same actor rule, details carry the class and the mode's from/to), the Act as me events — `delegation_settings_changed` (a person turned it on or off for themselves), `delegation_reminder_set` and `delegation_reminder_sent` (a person set a reminder for themselves with `remind_me`, and it went to them; ids and times only, never the text; private to that person), `delegation_actions_proposed`, `delegation_actions_approved` and `delegation_actions_dismissed` (the Executive left a person an approval card, which they approved or dismissed; kinds and outcomes only, never the text; private to that person), `delegation_gmail_verified` (their own Gmail checked before turning it on), `delegation_voice_changed` (\"How I write\" learned, edited, locked or reset, or its signature read from Gmail again), `delegation_voice_described` (a style written from the person's own description, counts only; nothing saved until they save it as an edit), `delegation_drafted` (one per draft saved in their Gmail from chat), `delegation_inbox_changed` (Draft replies to my inbox turned on or off), `delegation_inbox_scanned` (one per inbox scan, with its counts and status), `delegation_reply_drafted` (the inbox watcher saved a reply and made its card), `delegation_reply_dismissed` (a card dismissed, and whether its draft was deleted or kept), `delegation_reply_closed` (a card Gmail already settled: sent or deleted there, answered, gone or expired) and `delegation_reply_sent` (the person tapped Send and the draft went, or the reconciler confirmed an unconfirmed send did) — always private and metadata only: ids, counts and flags, never the draft or the thread; the roster-request events (see Org) — `roster_request_created`, `roster_ack_sent`, `roster_ack_withheld` (an acknowledgement the adapter declined — an email Gmail did not authenticate), `roster_request_resolved` (actor is where it was answered: `web`, a chat channel, `email` or `people_page`), `roster_message_replayed` (one per held message: replayed, dropped, failed or unavailable) and `roster_email_answer_refused` (an emailed answer with no live token, or failing DMARC) — always private to the principal and never carrying what the new sender wrote, like the `integration_outbound` row (`kind: roster_ack`) for the one gateway send allowed to an address off the roster, the fixed acknowledgement; `grounding` (unattended prose that named people or figures its inputs don't hold — a brief or digest that held back lines or used its repair call, a reflection tool call refused or flag held back, a triage or review rewrite replaced; details carry the surface, the mode, the ungrounded names and figures and up to five held-back lines cut to 200 chars, private when the brief read the principal's private rows or the alert is private; in `GROUNDING_CHECKS=report` mode these rows are written and nothing is changed); and the external-signal/monitor events. An unknown chat sender's `integration_inbound` row still reads `rejected_unknown_sender` — it means the message did not reach the Executive, not that it was discarded: a DM or mention is held as a roster request.\n\n### Session & turn context\nEach row carries `session_id`, `turn_id`, `actor`, `summary`, `details_json`, `full_json`, `department`, `private_to_principal` and `private_to_person`. A `turn_id` (`f\"t-{uuid12}\"`) is set per Executive turn and propagated automatically via ContextVars to retriever / specialist / tool / cache emits, grouping one user-assistant exchange. `summary` is the searchable column (LIKE, ~300 char cap); `details_json` is structured and not searched. `department` is filterable in SQL (`AuditLogger.query(department=…)`) — the department check-in's skip rule uses it to ask whether anything was logged for a department since its Goals were last reviewed. A turn another AI app asked over the MCP server and allowed to act runs inside `audit.via_app(name)`: every row it writes gets `details.via`, the client's `clientInfo.name` or \"an AI app\", and an approval card it proposed keeps `via` on its payload and its approved, handled and held rows (`unscoped_audit_rows` clears it for unattended work started inside).\n\n### Rows private to the principal\nThe principal reads `/audit`, and others their own rows (see below), so a row about something private to the principal is marked `private_to_principal` as it is written, and only the principal reads it. `AuditLogger.log` marks a row private when its caller passes `private=True` — the email poller's two inbound rows for mail from one of the principal's contacts or mail they forwarded, and `create_alert`'s row for a private alert — or when `people_tools.audit_row_private_to_principal` says so at write time:\n- every row a turn private to the principal writes (`Session.private_to_principal`): its reply, each tool call, the model-call rows, and the background passes that inherit the turn;\n- on the principal's own verified turn (or inside `grant_contact_egress`), any row whose summary, details or full payload names one of their contacts — their email address or full name anywhere in the text, or their person id or chat id in a person or recipient field (`person_id`, `attendee_person_ids`, `user_id`, `chat_id`, `channel_ref`), JSON tool results included.\n- every row an Act as me turn writes once `ghostwrite_email` or a mailbox or calendar read (`search_my_email`, `read_my_email`, `read_my_email_attachment`, `my_email_awaiting_reply`, `my_calendar`) has touched the speaker's mailbox (`TurnDelegation.touched_mail`, set before the tool's first read): the tool row, the reply's `chat_turn` row carrying the draft's preview, the model-call rows, and anything it starts in the background, under `private_rows` (it runs no learning passes). Only the principal can have Act as me for now, so private to the principal is the right visibility; the tool's input and result are also redacted (`ghostwrite`, `my_email` and `my_calendar` are sensitive tool names).\n- every row the Act as me inbox watcher, a reply card's Send or Dismiss, an action card's Approve (or the card carried out on its own, in training), or a person's Act as me settings write: they run under `rows_for_person(person_id)` (or pass `private_to_person`), so their model-call rows and events are private, and the reply cards are their own person's alone. That includes a person changing the AI line on replies sent as them (`delegation_disclosure_changed`) or turning Read my calendar on or off (`delegation_calendar_changed`) and what training records: `delegation_training_changed`, `delegation_reply_allowed`, `delegation_example_kept`, `delegation_actions_allowed`, `delegation_actions_handled`, `delegation_actions_held` and `delegation_learned_removed`.\n\n### Rows that belong to one team member\nAct as me can be on for team members as well as the principal (see Act as me). What a team member's own mailbox touches must not reach the principal either, so such a row also carries `private_to_person` — the team member's id — as it is written. A teammate's own conversation with the Executive is theirs the same way, as their mail is: every row of a turn a team member other than the principal speaks on a verified surface (the web app signed in, their own Slack or Discord, a secret-verified private Telegram chat) or by email Gmail authenticated as theirs (`people_tools.teammate_turn_owner`), its reply, tool calls, model calls and memory snapshot included. The rows written before the turn binds its session follow the same rule: the chat adapters' `audit_rows_on_senders_turn` holds `rows_for_person` for a verified teammate (`sent_by_teammate`), the web chat route for a signed-in teammate, and the email poller for authenticated teammate mail, which it checks before writing its inbound row. An unproven sender (a forged From, an unverified Telegram chat) keeps the ordinary rule, so nobody can hide a turn from the principal by claiming to be a teammate. `people_tools.audit_row_owner` decides it: the id a caller passes, else the `rows_for_person` scope, else the speaker of a turn whose `touched_mail` is set, else the teammate whose own turn it is; the principal's own id is never stored, so their rows stay private to the principal exactly as above, and a principal lookup that fails keeps the owner. A row with an owner is always private, and `AuditLogger.query` and `count` leave it out in SQL unless the caller asks for that person's rows (`owned_by`; `only_owned` keeps those alone, as the read routes do for a teammate) — so the brief's handled-overnight block and every other internal reader skip it. The read routes show it to the principal as an action only (`api.routes.audit._redact`): the summary is rebuilt from the event type and a plain tool name with whose conversation it was (\"mcp:send_gmail_message (Ben's conversation, details private)\"), the details keep only what was done and what it cost (`tool`, `kind`, `ok`, `refused`, token counts, …), and `full` is dropped; a text search (`q`) leaves such rows out, so their words never decide a match. The person it belongs to reads it in full. Only `usage_summary` counts it, so spend stays whole. `usage_summary` also adds up the sandboxed scripts (`run_script`) from their own rows — chat's `tool_invocation` with `kind: script` and a workflow step's `workflow_tool_call` with `tool: run_script`, each carrying `calls` and `duration_ms` — into `scripts` (scripts run and worked, tool calls, time, and `turns_avoided`, an upper bound on the model turns those calls would otherwise have needed); a script's individual calls are not counted twice. It also sums the `python_job` rows (one per `run_python_job`: `ok`, `duration_ms`, `cpu_ms`, `peak_mb`, files and bytes in and out, `attachments`, `saved_tool`) into `python_jobs`, with the `cache_event` usage of the turns that ran a job, each turn counted once. Rows that quote someone's own documents follow the same `rows_for_person` scope: a `draft_artifact` / `get_artifact` / `list_artifacts` dispatch row, the document tools' own rows, and a turn's `memory_snapshot` when its retrieval recalled a published document are private to the speaker (to the principal when they are the speaker).\n\nSome rows are written before their turn binds its session, so two scopes in `audit.context` count too. The email poller holds `private_rows` for the whole handling of a mail from a contact or a principal forward: every row is private, the knowledge retrieval (which quotes the mail) included. The chat adapters hold `principal_turn_rows` once they know the principal sent the message on a verified surface (`people_tools.audit_rows_on_senders_turn` on Slack, Discord and Telegram; the web chat route checks its caller), so the inbound row, the knowledge retrieval, alert triage and the start of the web stream follow the principal-turn rule above. Tasks started inside inherit the scope, except unattended work: a workflow run a chat reply resumes and each scheduled action start with neither (`unscoped_audit_rows`), so their rows follow the ordinary rule. A sender lookup that fails counts as not the principal, as the turn's own check does. Neither scope lets the turn reach anyone. A caller can add privacy but never remove it, and a check that cannot run keeps the row private. On anyone else's turn a contact is a stranger, so a row that names one keeps its visibility: hiding it would tell whoever wrote it that the address belongs to a contact. The poller handles each message with no session bound, so one message's private turn never marks the next message's rows.\n\nEvery read route resolves the caller as `/alerts` and `/decisions` do (`people.caller_is_principal`: the principal's signed-in email, or no `x-caller-email` — the CLI, direct curl, local login — once a principal is on the roster; before anyone is principal, nobody), in `api.routes.audit._view`. The principal reads every row, a teammate's own as an action only (above). Once a principal is on the roster, anyone else reads their own rows (`owned_by` = them, `only_owned`) and nothing more, since the log holds what everyone said to the Executive; a caller the roster can't resolve reads none. Before anyone is principal, everyone reads the rows not private to one. All of it is filtered in SQL, so `total` and pagination stay honest: `GET /audit/logs` leaves the rest out, `GET /audit/logs/{id}` answers 404 exactly as for a missing id, and `GET /audit/sessions/{id}` shows only the rows the caller reads (404 when none are left). `GET /audit/usage` is spend, not content: for anyone but the principal it leaves out the rows private to the principal, as before. Internal readers see every row unless they ask otherwise; the department check-in, whose report goes to the department, reads its recent activity without them, and its \"nothing new since the review\" skip rule ignores them too. Ids are one autoincrement sequence, so anyone else can still see a gap where a private row was written; that is accepted.\n\nAlways in the loop writes `history_notes_added` (count and source, never the note) and `history_settings_changed`, `history_note_changed`, `history_note_forgotten` and `history_conversation_forgotten` from its routes. Every one is private and belongs to its person alone (`private_to_person`). `recall_history` is a sensitive tool name, so its input and result are redacted.\n\n### Views\n- `GET /audit` — filterable list with a \"Group by session\" toggle and session pills.\n- `GET /audit/session/{id}` — full ordered timeline plus a server-derived node/edge graph rendered as a three-pane React Flow chart.\n\n### Invariant\nAudit writes never break a chat turn: all writes swallow exceptions and log a warning, and instrumentation observes only — it never touches request building or the cached prompt blocks. Audit is append-only: no UPDATE or DELETE paths exist in product code.",
+ "markdown": "The audit log is a persistent, searchable, append-only record of what the system did — distinct from episodic memory (which biases future LLM behavior). Every event flows through `audit/logger.log_event`, a synchronous SQLite writer (WAL + 5s busy_timeout) that appends one row to the `audit_log` table in `episodic_memory.db`.\n\n### Event types\nRows are tagged by `event_type`, including `chat_turn`, `specialist_consult`, `tool_invocation`, `scheduled_action`, `alert`, `integration_inbound` (Slack / Discord / email / Telegram / Google Chat), plus `knowledge_retrieval`, `fact_confirmation` (an emailed standing-fact change held, applied, cancelled or refused; private), `fact_reviewed` (the principal approved or declined a teammate's proposed standing fact; private), `fact_approval_changed` (the principal turned \"needs my approval\" on or off for a teammate; private), `fact_retired` (the principal, or the teammate who recorded it, retired a standing fact from the Pulse page; private, since it names the fact a teammate can no longer read; the fact tools' own rows and their `skill:` dispatch rows are private `tool_invocation` rows, since they quote the principal and name their session and turn), `memory_extraction` (one row per episodic-extraction pass, written in a `finally` so a crashed pass is recorded too: how many items the model proposed, how many were stored, a `{kind, reason}` record per drop, a `malformed` count for payload shapes that were never usable items, and a `failure` naming the exception type when the pass raised — including `CancelledError`, which is a `BaseException` and so would otherwise be logged as a clean empty pass — a `proposed>0, stored=0` streak means the quote validator is rejecting everything, which is otherwise invisible), `cache_event` (one row per model call from every call site — Executive turns, specialist consults (chat turns and workflow steps), research specialists, the research routing and watchlist passes, triage, memory extraction, alert review, the brief's narrative and its grounding repair, the digest, reflection and weekly-review workflows, committee reviewers, and the small utility calls (session titles, the chat-channel response gate, reply parsing, PDF transcription); a unit test fails any model call in the `openexecutive` package that records no row — carrying tokens, cache hits, cost, server-side search count and, inside a research run, its `run_id`), `memory_snapshot`, `committee_review`, `peer_memory`, `attunement` (one row per open-loop extraction pass — opened / closed / dropped with a reason per drop and a `failure` type — plus a row per loop opened or closed and per 👍/👎 on a reply; see Attunement), `executive_paused` / `executive_resumed` (the operator pause switch; actor is the caller's email, details carry the reason, or on resume the held-action count), `scheduled_action_cancelled` (a pending scheduled action cancelled from the Pulse page or a script; actor is the signed-in email, `admin-token` or `local`), `workspace_settings_changed` (solo/team mode, the user's time zone or the principal's role changed through `PUT /workspace`; actor is the caller's email or `api`, details carry the mode's and zone's from/to, plus `role_fields_changed` — the names of the role fields that changed, never their text — when the role changed, and the new `company_domains` list when the company's email domains changed), `decision_class_mode_changed` (a decision class switched between `propose` and `auto_execute` through `PUT /decisions/classes/meeting_scheduling`; same actor rule, details carry the class and the mode's from/to), the Act as me events — `delegation_settings_changed` (a person turned it on or off for themselves), `delegation_reminder_set` and `delegation_reminder_sent` (a person set a reminder for themselves with `remind_me`, and it went to them; ids and times only, never the text; private to that person), `delegation_actions_proposed`, `delegation_actions_approved` and `delegation_actions_dismissed` (the Executive left a person an approval card, which they approved or dismissed; kinds and outcomes only, never the text; private to that person), `delegation_gmail_verified` (their own Gmail checked before turning it on), `delegation_voice_changed` (\"How I write\" learned, edited, locked or reset, or its signature read from Gmail again), `delegation_voice_described` (a style written from the person's own description, counts only; nothing saved until they save it as an edit), `delegation_drafted` (one per draft saved in their Gmail from chat), `delegation_inbox_changed` (Draft replies to my inbox turned on or off), `delegation_inbox_scanned` (one per inbox scan, with its counts and status), `delegation_reply_drafted` (the inbox watcher saved a reply and made its card), `delegation_reply_dismissed` (a card dismissed, and whether its draft was deleted or kept), `delegation_reply_closed` (a card Gmail already settled: sent or deleted there, answered, gone or expired) and `delegation_reply_sent` (the person tapped Send and the draft went, or the reconciler confirmed an unconfirmed send did) — always private and metadata only: ids, counts and flags, never the draft or the thread; the roster-request events (see Org) — `roster_request_created`, `roster_ack_sent`, `roster_ack_withheld` (an acknowledgement the adapter declined — an email Gmail did not authenticate), `roster_request_resolved` (actor is where it was answered: `web`, a chat channel, `email` or `people_page`), `roster_message_replayed` (one per held message: replayed, dropped, failed or unavailable) and `roster_email_answer_refused` (an emailed answer with no live token, or failing DMARC) — always private to the principal and never carrying what the new sender wrote, like the `integration_outbound` row (`kind: roster_ack`) for the one gateway send allowed to an address off the roster, the fixed acknowledgement; `grounding` (unattended prose that named people or figures its inputs don't hold — a brief or digest that held back lines or used its repair call, a reflection tool call refused or flag held back, a triage or review rewrite replaced; details carry the surface, the mode, the ungrounded names and figures and up to five held-back lines cut to 200 chars, private when the brief read the principal's private rows or the alert is private; in `GROUNDING_CHECKS=report` mode these rows are written and nothing is changed); and the external-signal/monitor events. An unknown chat sender's `integration_inbound` row still reads `rejected_unknown_sender` — it means the message did not reach the Executive, not that it was discarded: a DM or mention is held as a roster request.\n\n### Session & turn context\nEach row carries `session_id`, `turn_id`, `actor`, `summary`, `details_json`, `full_json`, `department`, `private_to_principal` and `private_to_person`. A `turn_id` (`f\"t-{uuid12}\"`) is set per Executive turn and propagated automatically via ContextVars to retriever / specialist / tool / cache emits, grouping one user-assistant exchange. `summary` is the searchable column (LIKE, ~300 char cap); `details_json` is structured and not searched. `department` is filterable in SQL (`AuditLogger.query(department=…)`) — the department check-in's skip rule uses it to ask whether anything was logged for a department since its Goals were last reviewed. A turn another AI app asked over the MCP server and allowed to act runs inside `audit.via_app(name)`: every row it writes gets `details.via`, the client's `clientInfo.name` or \"an AI app\", and an approval card it proposed keeps `via` on its payload and its approved, handled and held rows (`unscoped_audit_rows` clears it for unattended work started inside).\n\n### Rows private to the principal\nThe principal reads `/audit`, and others their own rows (see below), so a row about something private to the principal is marked `private_to_principal` as it is written, and only the principal reads it. `AuditLogger.log` marks a row private when its caller passes `private=True` — the email poller's two inbound rows for mail from one of the principal's contacts or mail they forwarded, and `create_alert`'s row for a private alert — or when `people_tools.audit_row_private_to_principal` says so at write time:\n- every row a turn private to the principal writes (`Session.private_to_principal`): its reply, each tool call, the model-call rows, and the background passes that inherit the turn;\n- on the principal's own verified turn (or inside `grant_contact_egress`), any row whose summary, details or full payload names one of their contacts — their email address or full name anywhere in the text, or their person id or chat id in a person or recipient field (`person_id`, `attendee_person_ids`, `user_id`, `chat_id`, `channel_ref`), JSON tool results included.\n- every row an Act as me turn writes once `ghostwrite_email` or a mailbox or calendar read (`search_my_email`, `read_my_email`, `read_my_email_attachment`, `my_email_awaiting_reply`, `my_calendar`) has touched the speaker's mailbox (`TurnDelegation.touched_mail`, set before the tool's first read): the tool row, the reply's `chat_turn` row carrying the draft's preview, the model-call rows, and anything it starts in the background, under `private_rows` (it runs no learning passes). Only the principal can have Act as me for now, so private to the principal is the right visibility; the tool's input and result are also redacted (`ghostwrite`, `my_email` and `my_calendar` are sensitive tool names).\n- every row the Act as me inbox watcher, a reply card's Send or Dismiss, an action card's Approve (or the card carried out on its own, in training), or a person's Act as me settings write: they run under `rows_for_person(person_id)` (or pass `private_to_person`), so their model-call rows and events are private, and the reply cards are their own person's alone. That includes a person changing the AI line on replies sent as them (`delegation_disclosure_changed`) or turning Read my calendar on or off (`delegation_calendar_changed`) and what training records: `delegation_training_changed`, `delegation_reply_allowed`, `delegation_example_kept`, `delegation_actions_allowed`, `delegation_actions_handled`, `delegation_actions_held`, `delegation_learned_removed`, and the meeting-invite rows `delegation_invite_carded`, `delegation_invite_answered`, `delegation_invite_handled` and `delegation_invite_dismissed`.\n\n### Rows that belong to one team member\nAct as me can be on for team members as well as the principal (see Act as me). What a team member's own mailbox touches must not reach the principal either, so such a row also carries `private_to_person` — the team member's id — as it is written. A teammate's own conversation with the Executive is theirs the same way, as their mail is: every row of a turn a team member other than the principal speaks on a verified surface (the web app signed in, their own Slack or Discord, a secret-verified private Telegram chat) or by email Gmail authenticated as theirs (`people_tools.teammate_turn_owner`), its reply, tool calls, model calls and memory snapshot included. The rows written before the turn binds its session follow the same rule: the chat adapters' `audit_rows_on_senders_turn` holds `rows_for_person` for a verified teammate (`sent_by_teammate`), the web chat route for a signed-in teammate, and the email poller for authenticated teammate mail, which it checks before writing its inbound row. An unproven sender (a forged From, an unverified Telegram chat) keeps the ordinary rule, so nobody can hide a turn from the principal by claiming to be a teammate. `people_tools.audit_row_owner` decides it: the id a caller passes, else the `rows_for_person` scope, else the speaker of a turn whose `touched_mail` is set, else the teammate whose own turn it is; the principal's own id is never stored, so their rows stay private to the principal exactly as above, and a principal lookup that fails keeps the owner. A row with an owner is always private, and `AuditLogger.query` and `count` leave it out in SQL unless the caller asks for that person's rows (`owned_by`; `only_owned` keeps those alone, as the read routes do for a teammate) — so the brief's handled-overnight block and every other internal reader skip it. The read routes show it to the principal as an action only (`api.routes.audit._redact`): the summary is rebuilt from the event type and a plain tool name with whose conversation it was (\"mcp:send_gmail_message (Ben's conversation, details private)\"), the details keep only what was done and what it cost (`tool`, `kind`, `ok`, `refused`, token counts, …), and `full` is dropped; a text search (`q`) leaves such rows out, so their words never decide a match. The person it belongs to reads it in full. Only `usage_summary` counts it, so spend stays whole. `usage_summary` also adds up the sandboxed scripts (`run_script`) from their own rows — chat's `tool_invocation` with `kind: script` and a workflow step's `workflow_tool_call` with `tool: run_script`, each carrying `calls` and `duration_ms` — into `scripts` (scripts run and worked, tool calls, time, and `turns_avoided`, an upper bound on the model turns those calls would otherwise have needed); a script's individual calls are not counted twice. It also sums the `python_job` rows (one per `run_python_job`: `ok`, `duration_ms`, `cpu_ms`, `peak_mb`, files and bytes in and out, `attachments`, `saved_tool`) into `python_jobs`, with the `cache_event` usage of the turns that ran a job, each turn counted once. Rows that quote someone's own documents follow the same `rows_for_person` scope: a `draft_artifact` / `get_artifact` / `list_artifacts` dispatch row, the document tools' own rows, and a turn's `memory_snapshot` when its retrieval recalled a published document are private to the speaker (to the principal when they are the speaker).\n\nSome rows are written before their turn binds its session, so two scopes in `audit.context` count too. The email poller holds `private_rows` for the whole handling of a mail from a contact or a principal forward: every row is private, the knowledge retrieval (which quotes the mail) included. The chat adapters hold `principal_turn_rows` once they know the principal sent the message on a verified surface (`people_tools.audit_rows_on_senders_turn` on Slack, Discord and Telegram; the web chat route checks its caller), so the inbound row, the knowledge retrieval, alert triage and the start of the web stream follow the principal-turn rule above. Tasks started inside inherit the scope, except unattended work: a workflow run a chat reply resumes and each scheduled action start with neither (`unscoped_audit_rows`), so their rows follow the ordinary rule. A sender lookup that fails counts as not the principal, as the turn's own check does. Neither scope lets the turn reach anyone. A caller can add privacy but never remove it, and a check that cannot run keeps the row private. On anyone else's turn a contact is a stranger, so a row that names one keeps its visibility: hiding it would tell whoever wrote it that the address belongs to a contact. The poller handles each message with no session bound, so one message's private turn never marks the next message's rows.\n\nEvery read route resolves the caller as `/alerts` and `/decisions` do (`people.caller_is_principal`: the principal's signed-in email, or no `x-caller-email` — the CLI, direct curl, local login — once a principal is on the roster; before anyone is principal, nobody), in `api.routes.audit._view`. The principal reads every row, a teammate's own as an action only (above). Once a principal is on the roster, anyone else reads their own rows (`owned_by` = them, `only_owned`) and nothing more, since the log holds what everyone said to the Executive; a caller the roster can't resolve reads none. Before anyone is principal, everyone reads the rows not private to one. All of it is filtered in SQL, so `total` and pagination stay honest: `GET /audit/logs` leaves the rest out, `GET /audit/logs/{id}` answers 404 exactly as for a missing id, and `GET /audit/sessions/{id}` shows only the rows the caller reads (404 when none are left). `GET /audit/usage` is spend, not content: for anyone but the principal it leaves out the rows private to the principal, as before. Internal readers see every row unless they ask otherwise; the department check-in, whose report goes to the department, reads its recent activity without them, and its \"nothing new since the review\" skip rule ignores them too. Ids are one autoincrement sequence, so anyone else can still see a gap where a private row was written; that is accepted.\n\nAlways in the loop writes `history_notes_added` (count and source, never the note) and `history_settings_changed`, `history_note_changed`, `history_note_forgotten` and `history_conversation_forgotten` from its routes. Every one is private and belongs to its person alone (`private_to_person`). `recall_history` is a sensitive tool name, so its input and result are redacted.\n\n### Views\n- `GET /audit` — filterable list with a \"Group by session\" toggle and session pills.\n- `GET /audit/session/{id}` — full ordered timeline plus a server-derived node/edge graph rendered as a three-pane React Flow chart.\n\n### Invariant\nAudit writes never break a chat turn: all writes swallow exceptions and log a warning, and instrumentation observes only — it never touches request building or the cached prompt blocks. Audit is append-only: no UPDATE or DELETE paths exist in product code.",
"mermaid": "flowchart TD\n Chat[\"Chat turn / consult / tool call\"]\n Sched[\"Scheduled action\"]\n Inbound[\"Inbound integration\"]\n Log[\"audit/logger.log_event\"]\n Priv[\"private_to_principal? private turn, or names a contact on the principal's turn\"]\n DB[\"audit_log table (append-only)\"]\n Gate[\"read routes: private rows for the principal only\"]\n ListView[\"/audit list view\"]\n SessView[\"/audit/session/{id} flow chart\"]\n Chat -->|event + turn_id| Log\n Sched --> Log\n Inbound --> Log\n Log --> Priv\n Priv -->|swallow errors, never block| DB\n DB --> Gate\n Gate --> ListView\n Gate --> SessView\n class Chat entry\n class Sched entry\n class Inbound entry\n class Log compute\n class Priv compute\n class DB storage\n class Gate compute\n class ListView hot\n class SessView hot",
- "generated_at": "2026-10-14T13:07:16Z"
+ "generated_at": "2026-10-19T19:00:00Z"
}
diff --git a/packages/core/openexecutive/architecture/prebuilt/delegation.json b/packages/core/openexecutive/architecture/prebuilt/delegation.json
index e591c54f..c3a9ae9c 100644
--- a/packages/core/openexecutive/architecture/prebuilt/delegation.json
+++ b/packages/core/openexecutive/architecture/prebuilt/delegation.json
@@ -1,7 +1,7 @@
{
"section_id": "delegation",
"title": "Act as Me (Delegation)",
- "markdown": "The **delegation** module (`openexecutive.delegation`) is **Act as me**: the one place the Executive writes *as* a person instead of as itself. Everywhere else it has its own Google account and bots and signs as itself. Here — when the person asks, or, with a second switch, for mail in their inbox that needs them — it writes an email in their voice and saves it as a **draft in their own mailbox** — Gmail or Outlook — for them to review and send. The one thing it ever sends is one of those inbox drafts, exactly as it is in their mailbox: when the person taps **Send** on its card, or, with a third switch, **Handle it for me**, on its own when plain-code rules allow it (below); chat never sends. The principal can turn it on for themselves, and so can each team member once the owner lets them. It is off by default, and off changes nothing: the prompts, tool lists and prompt caches are byte-identical to an install without it.\n\n## Who can have it, and when it is offered\n\n`delegation.settings.can_delegate(person)` is the single rule for who may turn it on: the principal (a non-archived team member flagged `is_principal`), and any other non-archived team member — never a contact — once team members may have it (`team_members_enabled`). That takes two things: the install allows it (`DELEGATION_TEAM_MEMBERS`, default off, which offers the owner the switch) and the owner turned on **Let team members use it** (`PUT /delegation/team`, principal only, one row in `delegation_team`). Turning the owner's switch off takes it away from every team member from their next message, and their inbox watchers stop at their next check; their own switches, drafts and cards are kept. Everything is keyed by `person_id`. A person turns it on for themselves (`PUT /delegation`); nobody turns it on for anyone else. The setting is one row per person in `delegation_settings`, and a missing, unreadable or zero row all mean off.\n\nAt the start of every chat turn (`Executive.stream_chat` and the committee path) `pin_turn_delegation(session, speaker_text)` runs next to the workspace-mode pin and records a `TurnDelegation` on the session. `ghostwrite_email` is **offered** only when all of these hold:\n\n- the speaker may have it and turned it on — read fresh every turn, so turning it off applies from the next message;\n- the speaker is on a surface that verified it is them — the principal through `people_tools.is_principal_on_verified_surface`, a team member through `teammate_on_verified_surface` (the web app signed in, their own Slack or Discord, never an email turn) — and a web turn also carried a signed-in caller (`Session.web_caller_signed_in`, set from `x-caller-email`) or runs under local login — a request with no caller header is not a sign-in and never gets it (whoever holds the shared secret is trusted as the UI proxy that stamps that header, as on every principal-only route);\n- the conversation is private to the speaker: the web chat, a Slack or Discord DM, a verified private Telegram chat, or a chat its channel adapter verified the sender of and marked private (`Session.speaker_verified` + `Session.private_chat`) — never a shared channel or thread, where the draft's preview or the matching threads would be posted for everyone and other people's messages sit in the model's context;\n- the turn is neither unattended (the scheduler's proactive run) nor private to the principal (the email poller's turns), so inbound text can never reach it. The MCP server, workflows, reflection and research never carry it at all.\n\nThe mailbox connection is deliberately **not** part of the offer: the handler checks it on every call and says how to fix it, so the cached tool prefix never flips when a token lapses. The pin lives in a context variable for the turn's task as well as on the session, so two turns running at once on one session (a second browser tab) each read their own. It also carries the speaker's own words for the turn (a new email may go to an address they just typed — the turn's message joins the history only once the turn ends), a per-turn draft count, and `touched_mail` (see Privacy). `own_words` reads those words back for every own-words check (addresses here, facts and task assignments elsewhere): it first removes the hydrated `<outbound_reply_context>` backstory by its exact, anchored shape, so a look-alike closing tag quoted inside it cannot pass the rest off as the speaker's, then drops other adapter tag blocks, and returns nothing for a message carrying an attachment.\n\n## The tool: `ghostwrite_email`\n\nIt lives in its own registry (`orchestrator.delegation_tools.DELEGATION_TOOLS` / `DELEGATION_TOOL_HANDLERS`), **never** `_ALL_SKILL_TOOLS`, so no other toolkit can carry it. On a turn it is offered to, the agent loop adds it to the pool *before* the sort and builds that turn's handler map from both registries; on any other turn a call to it is an unknown tool. The handler re-checks the pin and the surface anyway, then:\n\n1. **Caps** — at most 5 drafts per turn, and `DELEGATION_MAX_DRAFTS_PER_DAY` (default 50, at most 1000) per person per UTC day, shared with the inbox watcher (`delegation.caps`). It is counted from `delegation_drafts`, one row of ids per draft saved from either place, with a count kept in the process as a floor in case a row was lost. Each slot is taken before the first await — a round's tool calls run concurrently, so otherwise every call in it would pass the caps before any counted — and handed back if nothing was drafted. If the rows can't be read it refuses rather than guess.\n2. **Marks the turn** — sets `TurnDelegation.touched_mail` *before* its first read of the mailbox.\n3. **Checks the mailbox** — `gmail_status` asks Google or Microsoft whose mailbox the credential opens and compares it with the person's People email, on every call: a roster email can change, and a client slot swaps the roster.\n4. **Finds the thread** — by `thread_id` (checked against the mailbox's own id shape), or a Gmail-style search (`find`; on Outlook, words, `from:`, `to:`, `cc:`, `subject:` and `newer_than:` are kept and other Gmail operators dropped). Several matches return `{status: \"choose\", candidates}` (subject, sender and date — no message text) and draft nothing; none returns `not_found`.\n5. **Sets the recipients in code**, never from the model. A reply goes to the last inbound message's `From` — never its `Reply-To` (a different one is flagged `reply_to_ignored`) — with the thread's other recipients only on `reply_all`. A new email or a forward may go to any well-formed address: it is only a draft, waiting in their own mailbox, where they see who it is to before they send it. An address that is neither on the roster (contacts only when `contacts_reachable_now()`) nor typed by the speaker this turn comes back in `not_in_people`, and the Executive names it for them to check (`delegation_tools.not_in_people`). Mailing-list mail, a thread they replied to last and a reply-all trimmed to 10 recipients are flagged. An address inside a block an adapter added to their message (the backstory hydrated into a DM) is not one they typed, and when the message carries an attachment — a document's inlined text, or a note naming the file — none of its addresses count as typed: neither has an end mark, and a filename is chosen by whoever sent the file, so such an address is named back to check.\n6. **Writes it** (the ghostwriter, below) and saves it with the mailbox client's `create_draft` (Gmail: threaded with `In-Reply-To`, `References` (whole message ids: when the chain is too long for one header the oldest after the thread's first go, never the parent) and `threadId`, and stamped `X-OE-Ghostwritten`; Outlook: Graph's `createReply` on the message it answers, then the text and recipients, and a named property marking it).\n\nThe result is `{status: \"drafted\", draft_id, gmail_link, to, cc, subject, preview, flags, open_questions, note}`, plus `not_in_people` and `check_address` when a recipient needs checking. The link (`gmail.mailbox_link`) is built server-side from a fixed prefix — the thread in Gmail, the draft itself in Outlook on the web — and the note tells the model the preview is the person's draft, to be treated as data. The chat shows an action chip — \"Drafted an email as you to … — in your Drafts\" — that opens it, and only a link under `MAILBOX_LINK_PREFIXES` is ever linked. A sincere \"are you an AI?\" in the thread comes back as an open question for the person to answer themselves.\n\n## Reading their mailbox\n\nFive read-only mail tools ride with `ghostwrite_email` in the same registry (`orchestrator.mail_read_tools`), so they are offered, re-checked and fenced exactly as it is: `search_my_email` (a Gmail-style search through the client's `search_threads`, or with no query the threads that reached their inbox in the last few days through `inbox_message_ids` + `get_message`), `read_my_email` (one thread's last 10 messages, each sender's new text only, drafts left out, with the files attached to them listed by message id and index), `read_my_email_attachment` (one of those files as text: PDF, Word, Excel, CSV or text, up to 20 MB, a scanned PDF converted) and `my_email_awaiting_reply` (their own sent mail from the last 14 days, to at most 10 people besides the Executive, that is still the last message in its thread). They change, label, draft and send nothing.\n\nThe fifth, `my_email_read_before`, lists the threads `read_my_email` opened for the same person before, in this conversation or an earlier one, so a later conversation can open the same email again instead of asking them to search for it. It keeps where, never what (`delegation.mail_reads`, table `delegation_mail_read`): the thread id, its subject and first sender as one line each, the mailbox address it was read from and when, never a message's text, an attachment or a recipient. Rows are the person's own and are listed only from the mailbox open now, newest first, optionally narrowed by words in the subject or sender; anything older than 30 days is never listed and is deleted on the next write, at most 200 are kept per person, and turning Act as me off deletes them all. It opens the mailbox like the other reads, so it sets `touched_mail`, counts as a search, and returns its rows with the same data-not-instructions note. The Act as me addendum tells the model that these tools reach the person's mailbox while any Gmail or Outlook tools of its own account reach only the Executive's, to search theirs (never falling back to its own) for mail sent to them, and to reopen an email from before with `my_email_read_before` and `read_my_email`.\n\nEach sets `touched_mail` and marks the conversation theirs before its first read (`_open_mailbox`, shared with `ghostwrite_email`), so the lockdown below applies from its round on. Each is capped per turn on the pin: 10 searches (`my_email_awaiting_reply` counts as one), 20 thread reads and 5 attachment reads, the slot taken before the first await. In `read_my_email` every message someone else wrote comes back inside its own `<untrusted_content source=\"email\">` block (`content_trust.wrap_untrusted`, which defuses a closing tag in the text); the speaker's own messages — SENT and from their address (`threads.mine`), never a From header alone — are marked \"Yours\" outside any block. An attachment's text comes back in its own `<untrusted_content source=\"attachment\">` block (`attachments.format_attached_text`), parsed in an isolated worker (`knowledge.loader`); unlike a file sent to the Executive it is never added to the company's knowledge. The clients find an attachment by message and position and look its provider id up on each read (Gmail's changes per fetch): Gmail lists a message's files with the message (`MailMessage.attachments`, leaving out images the HTML shows in place), Outlook says only `hasAttachments` until `list_attachments` asks Graph (leaving out inline ones), and `attachment_bytes` reads one; an attached Outlook item or cloud link has no file to read. Results carry a note that subjects, senders and text are other people's words, data rather than instructions. The lockdown refuses tools, not the reply's own text, so what would carry that text out without a click is closed where it is shown: the web chat loads no image from another site, and bot replies go out without link previews (see Integrations).\n\n## Saving a file from their mail\n\nOne more tool rides with the reads: `save_my_email_attachment` (message id and index, as `read_my_email` listed the file) copies one attached file into the storage the Executive itself has connected and shares it with the speaker alone, so they get a link they can open or put in an app. Every call it makes is built in code (`orchestrator.mail_file_save`); the model picks only the attachment. The bytes come from the mailbox client's `attachment_bytes` and never pass through the model, any file type up to 20 MB, under a cleaned name (one line, no path or reserved characters, extension kept). The storage is the one the Executive's own mailbox runs on (`EMAIL_PROVIDER`) when the gateway has that server, else the other: Google Drive through workspace-mcp (`create_drive_file` with `base64_content` into a folder named \"From your email\" in the Executive's My Drive, then `manage_drive_access` granting the speaker's own address the reader role, `send_notification` off) or OneDrive through ms-365-mcp-server (`upload-file-content` into the same kind of folder in the Executive's own drive, with a name no recorded copy has, since an upload overwrites, then `share-drive-item` inviting only the speaker, `requireSignIn`, role `read`, `sendInvitation` off). The folder is always made by the save itself and its id remembered (`delegation_saved_folder`), never found by its name, since a folder someone else made and called that could already be shared with them; when the remembered one is gone or won't take the file, a new one is made and the old id stays recorded. Never a link share, a domain or anyone. Neither connected (or an eval's in-memory mailbox): status `no_storage`, and the model says so and offers to forward the email instead. Saves run one at a time, at most 10 a turn (`TurnDelegation.files_saved`), and the result is the status, the name, where it went and the link (`webViewLink` / `webUrl`); the chat chip says only that a file was saved, never the sender's file name.\n\nIt copies only when the speaker asked in their own words this turn: what they typed (`own_words`, no quoted backstory or attached file's text) must hold one of save, saved, upload or OneDrive, or Drive as a place (\"to my Drive\", \"in Drive\", \"Google Drive\"), checked before a slot is spent or the mailbox opened; otherwise it refuses (`not_asked`) and tells the model to ask them. It stays allowed after the turn read mail (`MAIL_TOUCHED_ALLOWED_TOOLS`): its gateway calls are admitted past the lockdown only as the very objects the handler built (`mcp_gateway.code_built_call`, for its seven Drive and OneDrive tools: folder create, file create or upload, the speaker's share, and OneDrive's `list-drives`), so a model's own `call_tool` on that turn is still refused, and every other gateway gate still runs on them (the acting account, URL fetches, sheet formulas, the share gates' roster check, writes kept to the Executive's own drives).\n\nEach copy is recorded before it is shared (`delegation.saved_files`, table `delegation_saved_files`: the person, the storage, the file id, its name and when; never content or the mail it came from), and the folder in `delegation_saved_folder`. The gateway reads that table on every Google Workspace and Microsoft 365 call: on a turn whose speaker is not the file's owner (the owner is the speaker only when Act as me was offered to them, so a shared chat, a workflow or the poller sees none), a call naming a recorded file id, raw or percent-encoded (OneDrive's `download-bytes` path is decoded by Graph), is refused, and a result, filtered against the table as it stands after the call so a copy recorded while a listing ran is caught too, loses each list entry or line naming one, with any id left masked. It matches ids as text, so a result that names such a file without its id (a notification quoting its title) still shows the name, and a copy someone makes is a new file. The folders are guarded harder, on every turn and for every speaker, the owner too: a model call whose arguments name any recorded folder id, or an OneDrive item path through the folder (`root:/From your email/x.pdf:` or `<folder id>:/x.pdf:`), is refused, so nobody can share, move, rename, copy, list or delete the folder from chat, and folder ids are dropped from or masked in every result; only the save's own code-built calls touch it. When a copy is made but its row can't be written, it is not shared, the save reports `failed` and logs an error, and the copy's id is hidden from every turn, the owner's included, for the life of the process. When the table can't be read, the file tools (`_FILE_TOOL_RE`: Drive, folder, file, Docs, Sheets, Slides and presentation tools, attachment bytes) are refused (fail closed) while mail and calendar run. The rows are kept when Act as me is turned off: the copies stay in the Executive's storage, and the rows keep them out of other people's turns.\n\n## Reading their calendar\n\nA third switch under Act as me, **Read my calendar** (`delegation.calendar`, table `delegation_calendar`: one row per person, absent or unreadable meaning off), lets the Executive read the person's own calendar, read-only. It rides on the same per-person sign-in as their mailbox: `calendar.readonly` on Google, `Calendars.Read` on Microsoft, added when they run the connect script with `--calendar` (`scripts/connect-own-gmail.py`, `scripts/connect-own-outlook.py`). Those scopes are optional, so a mail-only sign-in keeps working for mail; the mailbox clients note the scopes the token refresh reports, and `list_events` raises `CalendarNotGranted` before calling the calendar when the scope is missing (or when the calendar answers 403). Only the person turns it on (`PUT /delegation/calendar`), only while Act as me is on and a one-hour read works; a sign-in without the calendar is refused with `calendar_not_granted` and the command to run. Turning Act as me off turns it off. Changes are audited privately (`delegation_calendar_changed`).\n\n`my_calendar` sits with the mailbox reads, offered and fenced the same way: it refuses while the switch is off (before anything is opened), then takes a search slot, opens the mailbox privately (`_open_mailbox`, so `touched_mail` and the lockdown apply: an invite's title is in the words of whoever sent it) and lists the events from `start` (default today) for `days` days (1 to 31) in the workspace time zone, recurring events expanded and cancelled ones left out: title, start, end, all-day, location, organizer, attendees (25 at most) and the person's own answer, each on one line, with a data-not-instructions note. Google's `events.list` on the primary calendar and Graph's `calendarView` (times asked for in UTC) are its only calls; it changes nothing and keeps nothing. The first week's brief also lists today's meetings from it on the principal's own delivery (see Today).\n\n## Forwarding and reminders\n\n`ghostwrite_email` also forwards: with `forward` (a thread id) and `to`, it drafts a forward of the thread's latest message, or of the earlier one `forward_message_id` names (the one with the files, say, when their own reply came after it), `intent` becoming the short note above it (the ghostwriter writes only the note; the forwarded email's subject, someone else's words, is never put in the intent). Recipients follow the new-email rule (`_new_recipients`: the roster, or addresses the speaker typed this turn). Gmail's draft quotes a forward header and the original's own words under the note and attaches the original's files, up to 10 and 20 MB (`FORWARD_MAX_FILES`, `FORWARD_MAX_BYTES`; any left off are flagged `attachments_left_off`); Outlook uses Graph's `createForward`, which keeps the original and its files, with the note as its comment and the body never patched. It is still only a draft.\n\nThe principal's new email or reply can also carry Google Drive files: `drive_files` takes up to 10 Drive file ids (not with a forward; a team member is refused, since the files come from the Executive's own Drive). `orchestrator.drive_attach` sizes each one first and then downloads it with code-built `get_drive_file_permissions` and `get_drive_file_download_url` calls as the Executive's Google account (`mcp_gateway.code_built_call`, so the mail lockdown admits those exact calls). It takes the saved copy only from workspace-mcp's own anchored `Saved to:` line, exactly one, whose name ends in workspace-mcp's uuid (the answer echoes the Drive name first, which whoever shares a file chooses), names the attachment from that saved name, reads the bytes only from the tool download folders, removes the copy, and puts them on the draft under the forward caps. When the turn had read outside content before choosing them, the result asks the Executive to name each file so the person checks it. The file's text never reaches the model, so attaching is not an outside read. A file someone saved from their own mail, or a save folder (`delegation.saved_files`), is refused for anyone else, checked before and after the downloads and failing closed when that record can't be read, and a file that can't be fetched makes no draft. Gmail attaches them in `build_raw`; Outlook uploads each to the new draft (Graph's one-request upload, 3 MB a file, larger ones left off and flagged), and removes the draft if an upload fails. The result lists the attached file names.\n\n`remind_me(text, when)` (`orchestrator.reminder_tools`) rides with the same tools and checks, but opens no mailbox, so it never marks or locks a turn (`MAILBOX_TOOL_NAMES` are the ones that do). It stores the text once cleaned — one line, anything a chat app could turn into a link (a URL of any scheme, an address, a domain-like word, a host and port, an IP address) replaced with \"[link]\", at most 300 characters — with its time (stored in UTC) in `delegation_reminders` (5 a turn, 25 waiting, a year ahead, refused when the person has no channel). When it is due the scheduler sends that text to the person alone, as \"Reminder you set on <date>: …\", running nothing (see Scheduler); the Slack and Discord DMs it may go by turn link previews off. The chat chip shows the text as it will be sent. A reminder that comes due in the person's quiet hours or leave (when `OUTBOUND_RESPECT_QUIET_HOURS` is on) waits unclaimed and goes once they end, rather than being suppressed and lost. It is allowed after mail is read and in later turns of that conversation: it reaches only the speaker, as plain text. `schedule_followup`, which runs a turn with tools and is listed to everyone, stays refused there.\n\n## Approval cards\n\nA turn that read someone's mail may not message anyone, invite anyone or change the roster (see the lockdown above), yet what the mail asks for is often right. `propose_actions` (`orchestrator.action_card_tools`) leaves the speaker a card instead: up to five actions, each spelled out exactly as it will happen, done only when they tap Approve. It rides with the other Act as me tools and checks (`_writer`), opens no mailbox, and is allowed after mail is read because it does nothing on the turn.\n\n- **Kinds.** `invite` (a meeting with people on the roster), `message` (a direct message to someone on the roster, as written) and `add_contact` (a new contact; the principal's cards only, since contacts are theirs). A team member's card can't name a contact. Each action is checked when the card is made (`delegation.action_cards.check`) and again when it is carried out, so an archived person or a time that has passed fails that action alone.\n- **Whose.** A card is a `delegation_actions` decision for the speaker, `approver_only` like a reply card: only they see it (`GET /delegation/actions`) or resolve it, a team member's answers 404 to the principal too, and it is never an alert. The same actions still waiting are that card, not a new one. 3 cards a turn, 25 waiting, dropped after 7 days.\n- **Approve.** In the chat, under the reply that left it (the `propose_actions` chip carries the card's `decision_id`, and `ChatActionCards` shows the card while it waits), and on the Briefing's Needs you list, with a box per action. Approve (`POST /decisions/{id}/approve`, `edits.only`) needs the card's person signed in (`verified.caller_refusal`) with Act as me on; the card is claimed first so it runs once, then each ticked action runs as stored with no model call, in an unattended session (the principal's with contact egress) under `rows_for_person`, so every audit row it writes is theirs and nothing reaches the team's activity rail: `message_person` (a direct message or nothing; never its Briefing-alert fallback, which more people read), `create_calendar_event`, or a contact row. Approving also needs the person still allowed Act as me (`can_delegate`) and switched on. An invite is booked straight away when the person approving is the one the meeting gate would ask (`calendar_tools.approved_by`), and otherwise goes to that approver as usual, so a card never widens anyone's authority. Per-action results (`done`, `waiting`, `failed`, `skipped`) are kept on the decision and shown on the card. Dismiss rejects it and does nothing else. With Suggested actions in training the card adds the *Do this on its own next time* tick, and a card of actions all allowed is carried out on its own (see In training above); with Suggested actions On, any card that reaches nobody new is.\n- **Channels.** A card can come from any surface Act as me runs on; it is approved in the web app, since the chat apps have no buttons here.\n\n## The ghostwriter\n\n`delegation.ghostwriter.compose` writes the text. The Executive decides *what* to say (`intent`); this call decides *how* the person would say it, and it is deliberately small:\n\n- a constant `GHOSTWRITER_PROMPT` plus the person's voice block as the system prompt;\n- the thread (each message cut to its sender's own words, every line scrubbed, all labelled alike), then the writer's own earlier words in it (`<writer_said>`, from their sent mail only), the intent and the recipients' names in the user turn — no company profile, memory or roster;\n- with Always in the loop on, `<writer_noted>`: what the writer's own notes say they told these same people in earlier Act as me replies (`memory.history_drafts.notes_for_draft`: only notes from mail **every** recipient of the new draft was on, so nothing told to one person reaches another; chat notes name no recipient and never qualify; at most 8, newest first, the person's own words or their correction, with dates). The prompt's rule 6 makes it a consistency check, never content: a draft that contradicts it is still written as the intent says, and the conflict becomes an open question on the card, which only the writer sees. Both the chat tool and the inbox watcher pass it;\n- **no tools** but the forced `compose_reply` return, so text in the thread can ask for anything and there is nothing to do it with.\n\nIt is not a Council agent — the Council's edit routes have no principal check — and runs on `DELEGATION_COMPOSER_MODEL` (default: the default model), logged as `ghostwriter` usage. `lint` then runs in code on what comes back: a link or an email address survives only if it appears in the intent, the signature or the recipients, so a link planted in the thread is removed and flagged; the Executive's own name is flagged; and the body is capped, cut at a paragraph, line or word break in its last fifth. A draft with nothing left after that is refused. The signature from the person's Gmail settings (or the one already stored, for Outlook) is appended.\n\n## How I write\n\n`delegation.voice` learns how a person writes *their own* email (`attunement.style` learns how the Executive should write *to* someone). `POST /delegation/voice/learn` reads up to 40 recent sent messages, keeps only what they wrote (quoted replies stripped with the email poller's `sender_new_text`), skips automatic mail, every thread chat drafted into, and every sent message that began as a draft written for them (`delegation_drafts.sent_message_id`), and makes one forced-tool call (`record_voice_profile`). Code validates every field before it is stored:\n\n- greetings per audience (their team, their contacts, anyone else), a sign-off of at most two lines, and a usual length and tone (a backslash-n the model wrote instead of a line break is read as one, keeping the first lines that fit, which also repairs a profile stored before that rule);\n- up to 8 habits and 6 things to avoid, through the same deny-list as working-style rules — no actions, links, handles, amounts, tool names or names of people; the conversation review (`memory.chat_review`) adds one when the person states how they write in a chat (`add_conversation_rule`, `updated_by=conversation`; never on a locked or full list, and an edit or lock made meanwhile wins);\n- up to 3 short exemplars, each checked to be verbatim from a sample, with addresses and phone numbers masked — and none while a client slot is active, so one client's mail never lands in another's state.\n\nThe signature comes from Gmail's `sendAs` settings, not the model (Outlook gives apps no way to read one, so a learn keeps the stored signature and `POST /delegation/voice/signature` answers 409 `signature_unavailable` rather than clearing it), as plain text with its lines kept (`gmail.html_to_text`: a `<br>` always ends a line, and a block tag, opening or closing, ends one when it has text, so Gmail's layout of a first line followed by one `<div>` per line comes out line by line). `POST /delegation/voice/signature` reads it again without relearning: nothing else changes and a locked profile stays locked, so it picks up a changed Gmail signature and undoes **Don't add my signature**. A person can also describe their style in their own words: `POST /delegation/voice/describe` applies the description to the profile they have through the same forced tool (a separate system prompt, no exemplars) and the same validation, keeps their signature and writing examples, and returns the result with a short sample reply for them to review. It saves nothing and needs no mailbox; Save stores it as an ordinary edit. The person can edit the profile, lock it (a locked profile is never relearned) and reset it, and every change is kept in `delegation_voice_history`. One learn runs at a time per person, and a lock or an edit made while it runs wins: the learned profile is dropped (`changed`).\n\n## Draft replies to my inbox\n\nA second switch under Act as me, **Draft replies to my inbox** (`delegation.inbox`), has the Executive watch the person's own inbox and write a first reply to mail that needs them. The reply waits on a private card on Today; nothing is sent until they tap **Send** (below). Where the reply lives is the person's choice, **Also save replies in my Gmail Drafts** (`mailbox_drafts`, off by default): off, it lives on the card alone (`delegation.card_drafts`: the card keeps the draft's recipients, subject and thread headers as `draft_spec`, and Send makes the mailbox draft from exactly that just before the send-time checks, taking it back out if they refuse), so their Drafts folder doesn't fill with replies they may never send; on, it is also saved in their Drafts as before. The switch is one row per person in `delegation_inbox_watch`. Turning it on needs Act as me on and their mailbox connected, and sets `watch_since` to now every time, so it never drafts for mail that arrived before; turning Act as me off turns it off too. Off means no mailbox call and no row written, with one exception: a send the person started that the mailbox never confirmed is still followed through until it is settled.\n\n### When it looks\n\nA throttled hook in the scheduler tick (`_maybe_scan_inbox`, after the pause, company-profile and rotation gates) checks each person whose switch is on every `DELEGATION_INBOX_POLL_MINUTES` (default 5). It is not a scheduled action, because those are listed on `/scheduled` for everyone and anyone may cancel them. One scan task runs at a time, one scan per person, and none while a client slot is active. **Check now** on the Settings card runs the same scan. Every row a scan writes is private and the person's own (`audit.rows_for_person`: a team member's rows are hidden from the principal too, see Privacy), and the process log carries counts and codes, never an address or a line of mail. The scan never marks mail read or changes a label.\n\n### What it drafts for\n\nA scan first settles the open cards (below), and stops with `backlog_full` once 25 are waiting, counting the ones it makes. It then lists the inbox since `watch_since` (`inbox_message_ids`) — not chats, not mail from the person, and not the promotions, social, updates or forums tabs (on Outlook: the Focused inbox only) — up to 100 messages, and takes the newest message of each thread that still needs a look, at most 10: settled threads and threads with an open card are passed over first, so a burst of mail, or a pause for a limit or a back-off, never hides older threads for good. `delegation_inbox_messages` is its durable cursor: one row per message (`UNIQUE(person_id, message_id)`) with what happened to it, the reason, how many tries it took, and the draft and card ids. It stores a hash of the sender's address, never the address. A message is skipped, with the reason recorded, when:\n\n- it came before `watch_since`, or more than three days ago;\n- it is from the person or one of their send-as addresses, from the Executive, or one of this module's own drafts;\n- it is automatic — `Auto-Submitted`, a bulk or auto-reply `Precedence`, a bounce, a calendar invite or a no-reply sender — or from a mailing list, or in a Gmail tab, spam or trash;\n- the person is not in To or Cc, or it has more than 10 recipients;\n- the person replied last, or a draft already sits in the thread.\n\nThree kinds are left unrecorded, so a later scan looks again: mail under 10 minutes old (mail the person answers straight away never gets a card), mail in a thread whose card is still open, and mail a daily limit holds back.\n\n### Deciding, then writing\n\nTwo model calls, and code decides between them. The classifier (`delegation.inbox_classifier`) is one forced-tool call, `classify_email`, returning whether the email needs a personal reply, what kind it is and how sure it is. It sees a few one-lined header lines and the sender's own new words (at most 3000 characters, every line scrubbed) inside one `<email>` block marked as data, after the person's own last email in the thread in a `<their_last_email>` block (`their_last_words`: only mail their own mailbox sent, at most 1500 characters), so a reply to something they asked reads as one: an answer to their request for a call that says when the sender is free, without settling a time, is scheduling and gets a draft even when the sender says they will come back with times. It has no other tools, context or memory, so an email can ask for anything and there is nothing to do it with. A reply is drafted only for a question, a request, scheduling, an introduction or a follow-up, and only when the confidence clears a bar that rises the less the sender is known: 0.6 for their team or a contact (the principal's contacts count only for the principal: a team member's mail is weighed by the team and their own sent mail), 0.7 for someone they have written to before (`has_written_to`, a search of their sent mail), 0.85 for a stranger. Pitches, notes of thanks, FYIs, notifications, newsletters and phishing get nothing, and so does any failure. An email that also went to other people is drafted for only when the person is in To and it asks them themselves: the classifier is told their name, whether they are in To or Cc and how many others it went to, and lists the names the email greets or asks by name (`asked_names`). Code matches those against the person's name, whole name parts only (\"Alexis\" never counts for \"Alex\", and a nickname misses, which means no draft), so mail that greets someone else (\"Good morning, Brennan, could you sign ...\") is never theirs, whatever the model makes of it as a whole. When it names nobody, the model's `asked_of_them` decides, false for a question to the group at large. One that only copies them is never drafted for. Either is recorded `not_needed` with the reason `asks_someone_else`. It runs on `DELEGATION_CLASSIFIER_MODEL`, else the routing model. A sender whose address Gmail couldn't authenticate is handled as a stranger whatever the roster says — anyone can put a colleague's or a client's address in From — so they get the stranger's bar, a holding reply and the stranger limits; the card still says who they claim to be, and that the address isn't verified.\n\nThe reply is written by the same ghostwriter, in the person's voice, but from a fixed intent the module builds rather than words the person typed. Because the intent lets it restate the person's own earlier words, which words are theirs is never written inside the thread, where a sender could imitate any marker with a look-alike: every message there is labelled alike, and the person's own words come in a separate `<writer_said>` block after the thread, taken only from mail their own mailbox sent. Nothing inside the thread can close the thread block or open another. The intent: acknowledge the sender; say again only what the person's *own* earlier messages in the thread already said; commit to nothing new — no yes or no, date, time, price, fact or promise — and say they will get back to them; and put every question it could not answer from their words in **open questions**. A stranger always gets a short holding reply. The lint still strips any link or address that isn't the person's own. The reply goes to the sender (never `Reply-To`) and, on a group email, to everyone else it went to as Cc (reply to all, never the person's own addresses or the Executive); a stranger's holding reply starts with the sender alone. When others were on the email the card offers **Reply to**: the sender only, or everyone (`PUT /delegation/replies/{id}/recipients`, `card_drafts.set_recipients`). It picks between the two lists fixed when the card was written (`reply_others`), never an address from the request, and changes the mailbox draft's To/Cc too. Its `draft_to` lists who it goes to, which Send checks.\n\nThe order: record the message, classify, reserve a slot in the shared daily limit, write, save the draft in Gmail (from the alias the mail went to, when it went to one) and store its id, then create the card (idempotent on the message) and mark it drafted. Nothing that fails along the way loses the message. A failure that may pass — the classifier or the writer failing, Gmail refusing the draft, a card that couldn't be made (its draft is deleted first, so no draft is left without a card), any other error with that one message — leaves it for a later scan (`retry`), and it is given up on only after three tries; one message's trouble never holds up the rest. A daily limit reached while it was being read leaves it for later without counting as a try.\n\n### The reply cards\n\nA card is a `delegation_reply` decision whose class is **its approver's alone** (`DecisionClassSpec.approver_only`): only the person it was drafted for sees or resolves it on any decisions route — a team member's card answers 404 to the principal too — and it is never an alert: alerts feed chat turns, which would put other people's mail into memory. It carries the sender with who they are to the person and whether Gmail could verify the address (SPF/DKIM/DMARC, through `fact_confirmation.headers_authenticated`), the subject, what they wrote, the draft, the open questions and its warnings. `GET /delegation/replies` lists the open ones from the database alone, so Today never waits on Google.\n\n- **Send** approves the card, which sends its draft exactly as it is in their mailbox (see *Send on your tap*). **Edit** changes the reply's words right on the card (`PUT /delegation/replies/{id}/text`, `card_drafts.edit`): only its own person, from a caller the API can tie to them (as for Send), never while it is being sent on its own; a reply in their Drafts is rewritten there too (`update_draft_text`, every header kept), and only while it is still the version the card last saw, so a change made in the mailbox is never overwritten. A card edit counts as edited (`approved_with_edit`, and **Do it like this next time** keeps it), and one made by hand sets `questions_settled`.\n- **Decide before sending** with taps (`delegation.answers`): the ghostwriter returns each open question with 2 to 4 short answers the person might pick (`choices`) and what it is `about` (time, document, other); plain strings still parse, and `open_questions` stays a list of strings for every other reader, with `question_choices` beside it on the card. After the draft is written, code fills two kinds: a time question gets up to 3 free half hours on the person's own calendar (Read my calendar on; one a day over the next 5 working days, busy times only, no event title reaches a model), \"I checked your calendar: these are free.\"; a document question whose words match a company document's name gets 'I'll send \"<name>\" separately', \"Found \"<name>\" in your documents.\" Nothing is attached: a card's draft is plain text. A tap, or **Something else…**, calls `POST /delegation/replies/{id}/answer`: one composer-model call rewrites the body with the answers in their voice (signature and AI line kept out and put back), `ghostwriter.lint` runs on it, and it is saved through `card_drafts.edit` with the same caller and card checks and the same Drafts update. It returns the card with `changed_sentences`, which the card lightly marks. 30 rewrites an hour per person (429). Send waits until every question with choices is answered, or the words were changed with Edit. A card made before choices shows its plain questions. **Open in Gmail** (or **Open in Outlook**), shown only when the reply is in their Drafts, opens it there.\n- **Dismiss** rejects the card; the class's after-reject step then deletes the draft if nobody edited it — its message id is still the one it was saved with, since Gmail gives an edited draft a new one, and the Outlook client makes a draft's message id `<id>.<changeKey>` so an edit there changes it too — and keeps it otherwise. What happened is recorded even when Gmail fails.\n- Each scan first **settles** what Gmail already settled: a draft sent from Gmail, a draft deleted there, a reply the person wrote themselves, a thread that is gone, or a card left for 7 days (its draft stays in Gmail). Each is a compare-and-set close with the reason. A newer message from someone else flags the card instead. A card being sent at that moment is left alone.\n\n### Send on your tap\n\n`delegation.reply_send` is the only thing in Act as me that sends, and all it can send is the draft on a card, by its id: `DelegateGmail.send_draft` posts `{\"id\": …}` to Gmail's `drafts.send`, and `DelegateOutlook.send_draft` posts an empty body to that draft's Graph `send`, and nothing else, so no text, recipient or header is ever passed. It has two doors: `send_approved_reply`, reached only from `POST /decisions/{id}/approve` — a class only the card's own person may resolve — and `send_on_its_own`, reached only from the inbox watcher under Handle it for me (below). AST tests pin both call sites, so no model, chat turn, workflow, scheduled job or MCP call can. A tap is checked like this: At send time it checks everything again:\n\n1. **Who is asking.** The caller is the card's person and the API knows it: signed callers are on and the request carries that person's signed assertion (or the operator's, under local login), or the API runs for local login and answers this computer only. Anything else is a 409 `caller_signing_required` — with only the shared secret, whoever holds it could send as the owner — so on a server Send needs signed sign-ins.\n2. **The switches.** Act as me and Draft replies to my inbox are on, and no client slot is active.\n3. **The mailbox.** Their mailbox is connected.\n4. **The draft.** It still exists, in the same thread, and they haven't replied there themselves since; otherwise the card closes.\n5. **Who it goes to.** To, Cc and Bcc hold between 1 and 10 addresses, never the Executive's own, and it is from one of their own addresses.\n6. **What changed.** Recipients that differ from the card's, or a newer message from someone else, need a second yes: the first tap gets a 409 `confirm` naming the recipients and the reason, and the person approves again with what they were shown.\n\nThen it claims the card (`claim_for_execution`, proposed → executing, a compare-and-set, so a double tap sends once) and reads the draft once more: `drafts.send` sends whatever the draft is when Gmail gets the request, so if it was edited since the checks read it — in another tab, by a delegate — nothing is sent and the card comes back (`draft_changed`). Then it sends, and records the result: `approved_with_edit` when the draft was edited in Gmail, the sent message's id, the draft row's `sent_message_id`, and a private `delegation_reply_sent` row. A refusal that proves nothing went — a 4xx, a lapsed sign-in, a rate limit, a draft already gone — hands the card back. A failure that leaves it unclear — a timeout, a 5xx — leaves it `executing` and says to check the Sent folder, and the next scans ask Gmail: their message in the thread means it was sent; anything else is judged on the second scan that sees it: the draft still there and nothing sent means it was not (Gmail deletes a draft it sends), and the card comes back, flagged; the draft gone and nothing sent means it was deleted. Nothing is ever retried on its own. Sending is the person's own act, so it works while the Executive is paused.\n\n### Limits and failures\n\nAt most 5 drafts a scan; `DELEGATION_INBOX_MAX_DRAFTS_PER_DAY` (default 20) a day, inside the shared `DELEGATION_MAX_DRAFTS_PER_DAY` it shares with chat; 200 classifications, 2 drafts per sender (1 for a stranger) and 10 for strangers in all per day; and never more than 25 open cards. A lapsed Gmail sign-in sets the status and is looked at again every 30 minutes; a rate limit, an error reaching Gmail or a crash backs off from 5 minutes, doubling up to 2 hours. Neither turns the switch off: the Settings card shows the status in plain words.\n\n## Handle it for me\n\nA third switch under Act as me, **Handle it for me** (`delegation.handle_it`), lets the inbox watcher send some of its replies itself instead of leaving them on a card. It is one row per person in `delegation_handle_it` (`enabled`, `mode`); no row means off. One setting says how much goes without them, the way quality does on the Agent Council (`handle_it.RULES`): **Easy ones** (`careful`) sends only replies to people they know (someone on their team, a contact or someone they have written to) of at most 400 characters when the classifier is at least 0.9 sure; **People I know** (`balanced`), where it starts, sends replies to people they know up to 1200 characters at 0.8; **Most mail** (`bold`) also answers strangers, up to 2000 characters, and lets a link or an amount through when the classifier is at least 0.9 sure. Everything else waits on a card as before, so turning it on never drafts less. A table from before the setting gets the `mode` column on its next open (`schema._add_handle_it_mode`): someone who had strangers set to send keeps that as Bold, everyone else gets Balanced. Only the person turns it on (`PUT /delegation/handle-it`), from a session the API knows is theirs: the same rule Send uses (`delegation.verified.caller_refusal`), so with only the shared secret it answers 409 `caller_signing_required`. Turning it on needs Act as me and Draft replies to my inbox on, and turning the inbox watcher off (or Act as me, which turns it off) turns it off too.\n\n**In training** (`delegation.training`). Like someone new, each Act as me job can be put in training on its own, from that job's card on the Act as me page, the way Take the lead has it: **Write drafts as me** and **Handle it for me** each pick Off / In training / On (Handle it's In training puts Replies and Follow-ups in training together; its steps show under On only, since in training only allowed people go whatever the step), and **Suggested actions** picks Always ask / In training / On (On is the `actions_on` switch: a card is carried out with no allow, under the same checks, and only when it reaches nobody new: a new contact or anyone on the roster under a week waits; In training wins when both are set); what it learned is listed on each tab for its own jobs (Act as me: *What it's learned*, drafts and suggested actions; Handle it for me: *Who it's allowed to handle*, replies and follow-ups), each item named by its job (`PUT /delegation/training`, one row per person and setting in `delegation_training`, absent means not in training). In training it asks first and learns who and how from what the person approves; what it learns is a `take_the_lead_allowed` row (feature `act_as_me`, the person's id), theirs alone.\n\n- **Replies.** Every reply waits on its card (`handle_it_reason` `training`) whatever the dial says, and a reply card adds **Send + allow**: it sends that reply on the person's own tap, exactly as Send does, then allows replies to that sender (key `act_as_me|person:<id>|reply|<address>`). While Handle it for me is on, a reply to an allowed sender goes on its own under the dial's limits (a stranger they allowed included) and every check above (the topics that always wait, links and amounts, new recipients, once a thread a day, the daily limit); it's checked again at send time, so a sender removed since waits. Take the lead as you lifts nothing in training: putting Replies or Follow-ups in training turns it off, and it can't be turned on while they are (409 `in_training`).\n- **Follow-ups.** Every follow-up waits (`follow_up_training`); Send + allow on a follow-up card allows follow-ups to exactly the people it went to (`…|follow_up|<sorted addresses>`), whoever they are, under every other follow-up check.\n- **Suggested actions.** An action card (below) adds **Approve + allow**: it does the actions on the tap, then allows each one that happened (a message to that person, `…|message|person:<id>`; a meeting with exactly those people, the person left out, `…|invite|people:<ids>`). A new contact is never allowed. A card proposed later whose every action is allowed is carried out at once, with no tap (`action_cards.run_on_its_own`, `gate_mode` `auto_execute`, status `executed`), only if plain code finds nothing against it (`on_its_own_refusal`): still in training, Act as me on, a server that ties the switch to the person, nothing sensitive, no link or amount, a message of at most 1200 characters, and at most 10 actions carried out this way a day (checked one card at a time); anything refused is handed back to wait on its card as before. An invite carried out this way is never booked as approved by the person: the meeting gate decides as for any meeting nobody tapped, so a time taken from someone's mail can't land on a calendar unasked. The tool result and chip say what was done. The message text in such an action is model-written from the mail and goes without anyone reading it; the allowance covers who and what kind, not the words, which is why sensitive topics, links, amounts and long messages are held back.\n- **Drafts.** Nothing is sent. When the person changes a reply's draft in their mailbox before tapping Send (plain or + allow) and ticks **Do it like this next time**, what they sent is kept (its new text, quoted replies dropped, at most 1000 characters, `…|style|<address>`), and the ghostwriter gets it in its user turn as `<writer_example>` when it next writes to that person, from the inbox, a follow-up or a chat draft to that one person: style only, never its facts, and nothing in it can open or close a tag.\n\nSend and Approve with the *on its own next time* tick (`allow`; the tick replaced the separate Send + allow and Approve + allow buttons) are refused before anything is done unless their setting is in training (422 `cant_allow`) and the person's list has room (409 `learned_full`, at most 200 a person); allowing failing afterwards never undoes the send. Putting Replies or Follow-ups in, or Suggested actions out of training or On, only holds more back and works without signed sign-ins; anything else needs a caller the API knows is that person. What it learned is the person's alone: listed on `GET /delegation` (`training.learned`, each with its `setting`), removed with `DELETE /delegation/learned/{id}`, and for the owner also in Take the lead's \"What it's learned\" list; it never reaches anyone else's list or Take the lead's prompts. A dial left on In training by an older version (mode `training`) moves to People I know with Replies and Follow-ups in training (`schema._move_training_off_the_dial`).\n\n**No model decides whether a reply goes.** The watcher's two model calls are unchanged and tool-less, so text in an email can at most change the verdict and the draft. After the draft is written, `handle_it.refusal` — plain code — decides, and anything it refuses becomes the usual card with the reason kept on it (`handle_it_reason`). It refuses when:\n\n- it's off, or the sender is a stranger and the setting isn't Bold, or on a server signed sign-ins are off (`signing_ok`: signed callers, or local login);\n- Gmail couldn't authenticate the sender, whatever the roster says;\n- the email isn't a question, request, scheduling, introduction or follow-up, or the classifier was less sure than the setting needs (0.9 on Easy ones, 0.8 otherwise);\n- the reply goes to anyone the email didn't already go to (its From, To and Cc, less the person's own and the Executive's addresses), leaves out the sender, or goes to more than 10;\n- the email's subject, the sender's new words, or the reply touch money, contracts, legal, hiring, pay, layoffs, the board, investors, mergers, the press, health, or credentials and secrets (passwords, logins, tokens, API keys); or the reply carries an amount, a percentage or a link (a scheme, `www.`, a bare host with a path such as `bit.ly/…`, or a bare host on a common top-level domain) unless it's Bold and at least 0.9 sure, or runs over the setting's length (400, 1200 or 2000 characters);\n- the draft carries any flag but *others on the thread* or *Executive on the thread* (they asked if it's an AI, recipients were trimmed, …);\n- it already sent one in this thread in the last day, or the person's last message in the thread was itself sent on its own (no auto-reply ping-pong);\n- the day's limit is reached (`DELEGATION_HANDLE_IT_MAX_SENDS_PER_DAY`, default 20, within the watcher's drafts limit), or it can't be counted. Any error in the rules counts as a refusal.\n\nA reply the rules allow gets a card with `gate_mode` `auto_execute`, and the watcher sends it at once through `reply_send.send_on_its_own`, the second and last door into the send path (an AST test pins both callers: the approve route and the watcher). It runs the same send-time checks as a tap — switches, mailbox, draft, recipients, the claim and the last re-read — with no caller, and adds its own: the card must be `auto_execute`, Handle it for me still on with the setting still allowing that sender (or, for a follow-up, that recipient), signing still on, the once-a-thread-a-day rule and the daily limit counted again, and the draft untouched since it was saved (an edit in Gmail means the person has taken it over: `draft_changed`, the card waits for them). Every refusal hands the card back to the person (`decision_ledger.hand_back`, a compare-and-set to `propose`), with the reason kept on it when there are words for it, and a failure never stops the scan. Every card it left for the person says why on Today (`waited_because` on `GET /delegation/replies`). A reply sent on its own finishes as `executed` (not approved), is recorded in `delegation_handled` (for the per-thread and daily rules) and writes a private `delegation_reply_handled` row; an unconfirmed one is settled by the reconciler the same way. No History note is taken from it, since notes come only from the person's own words. It runs inside the watcher's scan, so it stops while the Executive is paused.\n\n**Follow-ups as you** (`delegation.follow_ups`). While Handle it for me is on, the watcher's scan also looks at the person's own sent mail, at most once an hour (`LOOK_EVERY`), for an email of theirs that asked something (a question mark in their own words), is 3 to 10 days old, went to at most 10 people other than the Executive, and is still the last message in its thread. Plain code picks it; each gets one follow-up ever (its `delegation_inbox_messages` row), at most two a look, within the drafts limit. The ghostwriter, tool-less as always, writes a short nudge in their voice from the thread, saved as a draft in that thread to exactly the people the email went to. `handle_it.follow_up_refusal` — plain code — decides whether it goes: by the setting it never goes on Easy ones, goes to their team and contacts on People I know and to anyone they wrote to on Most mail (`follow_up_refused` otherwise: `follow_up_level`); it also refuses on any change of recipients, a sensitive topic, an amount or a link, more than 600 characters, a flag, and the same per-thread and daily counts as replies. It goes through `send_on_its_own` on an ordinary `delegation_reply` card marked `source: follow_up`, which rechecks the setting for that recipient. A refused one waits on Today as **Follow-up waiting**, and closes by itself (its untouched draft deleted) when anyone answers in the thread first.\n\n**What it sent** is the person's alone: `GET /delegation/handled` lists the last 7 days (who, subject, the reply, the questions it left them and a link to the thread in their mailbox), and the Handle it for me tab shows it with how many went today, under its picker.\n\n### Take the lead as you\n\nOn Settings → Act as me, Handle it for me is one dial: **Off**, **Easy ones**, **People I know**, **Most mail** and, for the owner, **Everything**, which uses **Take the lead** (`PUT /delegation/take-the-lead`, one row `person:<id>` in `take_the_lead`; turning it on turns Handle it for me on). While it is on, `handle_it.refusal` drops the setting's limits: strangers, the classifier's confidence, amounts, and the length up to a 4000-character ceiling. A reply with a link still waits for a tap (refusal `link`). In their place it checks the company's and the person's own added rules (`take_the_lead.reply_hit`, refusal `lead_rule`). Everything Handle it always keeps still holds: signed sign-ins, an authenticated sender, a reply kind, exactly the thread's people, the topics that always wait, draft flags, never twice in a row, one a thread a day and the daily limit. Follow-ups under it may go to anyone the person wrote to, with the same sensitive, amount, link and length checks plus the added rules. `reply_send.send_on_its_own` accepts the card while both switches are on. Each person adds and removes their own rules (`/delegation/take-the-lead/rules`). Removing one needs a caller the API can tie to them.\n\n\n## AI line on replies\n\nReplies written as a person can end with **\"Drafted and sent by my AI assistant.\"** (`delegation.disclosure.LINE`), by two switches that are each person's own (`PUT /delegation/disclosure`, one row per person in `delegation_disclosure`, NULL following the install): **Handle it**, on by default (`AI_DISCLOSURE_HANDLE_IT`), for a reply Handle it for me will send on its own, which nobody reads before it goes; and **Approved sends**, off by default (`AI_DISCLOSURE_APPROVED_SENDS`), for one that waits on a card for them to send, since they read it first. The line is written into the reply when it is drafted (`disclosure.sign`, in `inbox._consider` and `follow_ups`), once the plain-code checks have decided whether it goes on its own, so the card, the mailbox draft and what is sent are the same words and Send's draft-changed checks see them; a switch changed later applies to the next reply, and a reply drafted to go on its own that is handed back keeps its line for the person to edit. `AI_DISCLOSURE` off turns both off and hides the card. Turning a switch on only adds the line, so it needs no signed sign-in; turning one off does. Each tab shows its own switch under Advanced (**AI line on drafts you send** on Act as me, **AI line on replies it sends** on Handle it for me), and turning off the Handle it line asks first.\n\n## The mailbox client\n\n`delegation.gmail.DelegateGmail` talks to the Gmail REST API directly and is **never registered with the MCP gateway**, so the model reaches the mailbox only through the typed handler. The credential is one file per person in `DELEGATION_GOOGLE_CREDENTIALS_DIR`, named from a hash of the address (0600 in a 0700 directory), minted by `scripts/connect-own-gmail.py` on the Executive's own OAuth client with the scopes `gmail.readonly` and `gmail.compose`. It never lives in `WORKSPACE_MCP_CREDENTIALS_DIR`, where workspace-mcp picks a credential by address. Besides reading threads and saving drafts it lists the inbox and checks whether they have written to an address, reads one message or draft, lists the person's send-as addresses and deletes a draft. Its **one send method**, `send_draft`, sends an existing draft by its id and nothing else — never `messages.send`, which sends any text it is given — and unit tests pin the method set, the endpoint, the request body and its single caller. A failed request says whether it may have been carried out anyway (a timeout after connecting, a 5xx), which is what the send path needs to know. A parsed message carries when it arrived, whether it is bulk, a bounce or a calendar invite, and whether Gmail's authentication results vouch for its sender.\n\n`gmail_status` answers `connected`, `not_configured`, `needs_reconnect` (Google refused the saved sign-in — an app in Testing mode has its tokens expire after 7 days; a rate limit, though Gmail may send it as a 403, is an `error` to retry, not a reconnect), `mismatch`, `no_email`, `shared_mailbox` or `error`. `shared_mailbox` means the person's address *is* the Executive's; it is refused before asking Google, because then everything the Executive writes would look like theirs. The gateway closes the other door: every `google_workspace__*` call must act as the Executive's own account, and a `user_google_email` naming anyone else is refused and audited (see Integrations).\n\n### Outlook\n\nA person may connect an Outlook mailbox instead (work, school or personal), with `scripts/connect-own-outlook.py`: a device-code sign-in on the Executive's own Entra app (`MS365_MCP_CLIENT_ID`, tenant `MS365_MCP_TENANT_ID` or `common`) asking for `User.Read`, `Mail.ReadWrite`, `Mail.Send` and `offline_access`. It writes the same per-person file with `\"provider\": \"microsoft\"`, so a person has one mailbox for Act as me, and `gmail_for` hands back `delegation.outlook.DelegateOutlook`, which keeps `DelegateGmail`'s methods, return types and errors, so every caller above runs unchanged. It talks to Microsoft Graph directly, never through the Microsoft 365 MCP server the Executive's own Outlook uses, and is never registered with the gateway. Microsoft rotates the refresh token on use; the new one is written back into the file (atomically, keeping every other key, and only if the file still holds the old one). Graph is asked for immutable ids, so a sent draft keeps its id; a thread is Outlook's `conversationId`. Gmail's labels are mapped onto what the callers read: `SENT` only for mail in their Sent Items folder (a From line set to their address by someone else never counts), `DRAFT`, `INBOX`, and Focused Inbox's Other read as a tab. A sender counts as authenticated only when the topmost `Authentication-Results` — the one Exchange wrote, above anything the sender added — holds exactly one DMARC verdict, a pass for From's own domain, and Exchange Online Protection's own `compauth=` verdict, so a header the sender wrote on mail EOP never stamped doesn't count. `delete_draft` refuses anything that isn't a draft, and deletes with the draft's etag (`If-Match`), so a draft sent in between — it keeps its id — is left alone. No client secret is ever written into a person's file, and Graph has no signature setting to read.\n\n## Privacy\n\nWhat a person's mailbox touches is theirs. For the principal that means private to the principal, as every private row is. For a team member it means theirs alone, the principal included: an audit row carries `private_to_person` (set by `audit.rows_for_person` around the inbox watcher, a card's Send and Dismiss and their settings changes, and by `people_tools.audit_row_owner` on a turn that read their mail) and is left out of every audit read — the log, a session's timeline, a row by id, the brief — with only the usage totals counting it; their reply cards are theirs alone (above); and the owner's view of their use is counts only (drafts and sends in 30 days, and whether their inbox watcher is on). The conversation itself becomes its owner's alone before the mailbox is first read: `ghostwrite_email` marks the session `mail_private` (`session_store.mark_mail_private`, creating a channel adapter's row early, with its owner) and refuses to read the mailbox if that can't be stored or the conversation already belongs to someone else (which it then leaves unmarked); from then on only its owner may open it (`chat._session_access`), and working-style learning skips it. Every later turn there starts private (`settings.pin_turn_delegation` reads the flag and fails closed, setting `touched_mail`), so a follow-up answered from history alone is still private to its owner and teaches no memory, and the web chat's rows before the turn (the inbound message and the knowledge lookup) are theirs too. It does not start locked down: the lockdown is `read_mail`, set only by a turn that reads the mailbox or notes itself, and it is never carried into the next turn, because history keeps only the speaker's words and the Executive's replies, never the mail a tool returned. Their next message is them asking again, having read that reply, so everything runs again there. Anyone else speaking in it is not offered Act as me.\n\nOnce `touched_mail` is set, every audit row the turn writes is private (`people_tools.audit_row_private_to_principal`), and a team member's is theirs alone: the tool row (its input and result redacted, since `ghostwrite` is a sensitive tool name), the reply's `chat_turn` row that carries the preview, the model-call rows, and the background passes, which run under `private_rows`. The Honcho peer and department syncs are skipped, because peer memory is read on other people's turns. No memory is learned from the turn at all: the episodic, open-loop and working-style passes are skipped too, since its reply quotes a draft built from other people's mail. The `delegation_*` audit events are always private and carry metadata only — ids, counts and flags, never the draft or the thread. The inbox watcher is private the same way: every row a scan or a card action writes is its person's alone, and it starts no chat turn, alert, scheduled action or workflow run and teaches no memory.\n\nThe turn also keeps one door shut (`delegation.lockdown`). Anyone can put text in the inbox, and that text could try to steer the model, so from the round that calls `ghostwrite_email` or one of the mailbox reads — a round's tools run together — until the turn ends, the dispatch guard refuses only what opens the open internet or reaches everyone: outside fetches (`read_document`, research, the watchlist, `load_mcp_server`, and any MCP `call_tool` outside the private-turn set of reads and recipient-checked sends), `run_script` and `run_python_job`, workflows (they run later, unattended, and may fetch or script), broadcasts, department messages and alerts, and changes to who is on the roster or holds authority (`archive_person`, `set_department_head`, `resolve_roster_request`), and text that steers later turns (`schedule_followup`, whose intent runs unattended when due, and goals and decision outcomes, shown to every later turn). Everything else the person asks for runs, because it is fenced on its own: DMs and `message_person` reach only the roster, invites name attendees by person id, the Executive's own email checks every recipient against the roster, standing facts and profile edits keep only the person's own words, and a workflow drafted in chat is saved only once a person confirms it. `upsert_person` runs only for a contact the person asked for (`speaker_named_contact`: a contact, never the team, an approval scope or a chat account, with a word of the name in what they typed, in a message that asks to add, save or change someone, a new contact's address one they typed or one that sent the mail the turn read under the contact's name (`TurnDelegation.mail_senders`), never one the mail's text only mentions, and on an update a changed address they typed), since the roster is what the send checks trust. Any other contact add is refused with a pointer to an approval card (`lockdown.CONTACT_REFUSAL`), so the Executive leaves an `add_contact` card in the chat rather than asking them to type the address. What an email itself asks for is still never done on its say-so; it goes on an approval card. Every tool is classified as allowed or withheld, a test fails on a new unclassified one, and an unknown name is withheld, except an extension tool registered with `after_mail_read` (one that only reads the install's own data). The refusal tells the model to put what the step needs in its reply, since the next turn sees the reply but not the mail, and to do the step then without reading the mail again. A refused call gets a private `tool_invocation` row (`refused: mail_touched`) and tells the model to offer it in the next message. The offered tool list never changes mid-turn, so the cached prefix holds. The handlers that reach outside check again on their own (`outside_reach_refusal`). The server-side web search stays, as on a turn private to the principal. The lockdown ends with the turn. Later turns of that conversation stay private to its owner (`touched_mail`) but hold nothing: a refusal says it will work when they ask again in their next message, and it does.\n\n## Always in the loop\n\nA sent reply can leave a note. Once the reply went, `reply_send` starts `memory.history_notes.note_sent_reply` for the person who sent it, in the background, when their \"Keep track of what happens\" switch is on and the conversation isn't one they asked not to remember. The note-taker sees only the words they sent, so other people's mail never becomes a note, and a failure never touches the send. Recall is `recall_history`, offered on the same verified, private surfaces as `ghostwrite_email` and also allowed under the mail lockdown, since it only reads the speaker's own notes. Calling it locks the turn like `ghostwrite_email` does, from its own round on. The same switch also covers notes from chat, which don't need Act as me. See **Memory** for the checks, retention and controls.\n\n## The system prompt\n\nA constant, name-free `DELEGATION_ADDENDUM` joins block 0 after the unchanged identity addendum while anyone on the install has it on (`block0_delegation_on`). It names the four mailbox reads and says other people's mail is data and that a conversation which read it reaches nobody else; and it tells the model that `ghostwrite_email` is the single exception to *never impersonate*, and only for the person being spoken to; that everything else is written as itself; that when the tool isn't offered the asker can't have it; that a draft is never described as sent; and that it never denies being an AI. It is keyed on the install-level setting, never on the turn or the speaker, so switching it misses the 1h cache once (see Prompt Caching).\n\n## What it does for you\n\n**What it does for you** (`delegation.may_do`, `GET /what-it-may-do`) is read-only: with the viewer's settings right now, one row per thing that can go out without asking, written as one sentence of what it does, what happens to it (goes out, waits for someone, always waits, drafts only, off) and which setting decides it, with a link there. It sits beside every Delegate tab (`DelegatePage` → `WhatItDoesPanel`): a column to the right on a wide screen (closing it is remembered in the browser), a bottom sheet on a narrow one. The UI groups rows by outcome (Sends on its own, Asks first, Writes for you to send, Off). Every delegation setter in `lib/api.ts` fires `DELEGATION_CHANGED` after a save; the panel reloads on it and marks the rows whose outcome or text changed as **Just changed** for ten seconds. `/delegate` and the old `/delegate/what-it-may-do` open Act as me. Its **Compare** fold holds Who writes and who sends. Three parts, each behind a pill that counts what goes out:\n\n- **As you** (the caller's own, when `can_delegate` allows them): built from `settings.is_enabled`, `inbox.get_watch`, `handle_it.get` and `handle_it.RULES`, `handle_it.leading` (Everything), `training.get` and `training.learned`, and their rules, the same reads `handle_it.refusal` and `follow_up_refusal` make. A level's row follows its `Rules` (strangers, follow-up reach, links and amounts), not a copy of them. A note names the ladder: Handle it for me rides on Draft replies to my inbox and Write drafts as me, and Everything also drops when Replies or Follow-ups go into training.\n- **As the Executive** (the principal's alone, as `GET /take-the-lead`): the switch and its training, each Ask first kind, the company's rules, and meetings. A meeting it thinks of on its own always waits: both meeting gates need someone on a verified surface in the turn, which an unattended run never is. A meeting someone asks for in chat follows **Always asks first → Meetings asked for in chat** (on means it waits: `meeting_scheduling`'s class mode is `propose`; off means `auto_execute`) and, in a team workspace, Operations' level too.\n- **Departments**: each level, and what a level covers (department-scoped scheduled work, check-ins, alert review, team members' chat sends, and Operations' meetings), and that it doesn't cover what the Executive does under Take the lead.\n\nIt also says when the Executive is paused, and when nothing can be sent as anyone because signed sign-ins are off. Nothing on it writes or reads mail. A contact, someone not on People, or a request with no caller (outside local login) gets 403.\n\n## How far it goes as you\n\nOne setting replaces the switches that used to turn each other off out of sight. The UI shows it as two pickers (`ReachCard.tsx`): **What it writes as you** (`WritesCard`) on the Act as me tab and **What it sends on its own** (`SendsCard`) on the Handle it for me tab; What it does for you links each row to its own picker. Its steps, each adding to the one before: **Off**, **Drafts when I ask** (Write drafts as me), **Drafts for my inbox** (Draft replies to my inbox), then the Handle it for me steps that send, **Easy ones**, **People I know** and **Most mail** (`careful`, `balanced`, `bold`), and for the owner **Everything** (Take the lead as you). Act as me shows the first three as **Off**, **When I ask** and **Draft replies automatically** (any sending step reads as Draft replies automatically there). Handle it for me shows **Off** (saved as the inbox step) and the sending steps, and opens only once Act as me is at Draft replies automatically, with a button that turns that on; moving Act as me below it says Handle it for me stops too. `PUT /delegation/reach` (`{step}`) moves it, and `reach_of` reads the step back from the switches, so the stored switches stay the source of truth and every gate reads them as before.\n\nGoing down turns the switches above the target off, highest first (`_lead_off`, then Handle it, then the inbox watcher, then Write drafts as me), so nothing is ever on above a switch that's off; the UI says what stops and asks before it saves. A lower sending level only holds more back and is set directly, so it needs no signed sign-in. Going up calls each switch's own route in order, so every check it makes still applies: the mailbox connected, signed sign-ins for sending, the owner alone and not in training for Everything. The first that refuses stops the move at a whole step and answers with that route's error. Handle it for me's own Off / In training / On (Replies and Follow-ups together) and, at Everything, **Your rules** sit with its picker, and **Learn from my edits** (drafts training) under the Act as me one; neither picker changes training.\n\n## Surfaces\n\n- **Settings → Act as me** (`ActAsMeCard`, hidden unless `GET /delegation` answers, so a team member sees it once the owner lets them): the mailbox connection (`provider` says which) with both connect commands (Gmail and Outlook) and **Check again**, **What it writes as you** (above), with the inbox watcher's status under Draft replies automatically (in plain words, when it last checked, **Check now** and **Also save inbox replies in my Gmail Drafts**), and **How I write**: length and tone, a greeting per audience (`{first}` is their first name), the sign-off, habits and never-rules in fields that grow to show every line, the signature with **Refresh from Gmail** and **Don't add my signature** (or **Add my Gmail signature** when none is added; on Outlook only **Don't add my signature**, with why), and each example quoted with **Remove examples**. The owner also gets **Let team members use it** where the install allows it, with each team member who has it on listed by name and counts only.\n- **Today → Replies waiting** (`RepliesWaiting`, the top of the left column; hidden unless `GET /delegation/replies` answers with cards): each card shows who wrote and who they are to you, whether their address was verified, the subject, **They wrote** as plain text, your draft, **Decide before sending** (the open questions, each with answers to tap and **Something else…**, and where they came from) and its warnings, with **Send** (a confirm naming who it goes to, and a second one when that or the thread changed), **Edit** (a text box on the card with Save and Cancel), **Open in Gmail** or **Open in Outlook** when the reply is in their Drafts, and **Dismiss**.\n- **Setup status**: a **Your own mailbox (Act as me)** light (`your_gmail`), amber while the inbox watcher can't reach the mailbox, is being rate-limited or has 25 replies waiting.\n- **Delegate** (main menu): **Act as me** (where `/delegate` and `/settings/act-as-me` land), **Handle it for me** (which step the dial is at, with **Change in Act as me**, then **What it sent**: how many went today and what it sent this week, as you) and **Take the lead** (the switch, then **Always asks first**, shown even while the switch is off and ending in **Meetings asked for in chat**, and the company's rules, as the Executive). Each switch that turns another off says so beside it. The pause is on **Settings → Your Executive**.\n- **API**: `GET`/`PUT /delegation`, `GET`/`PUT`/`DELETE /delegation/voice`, `POST /delegation/voice/learn`, `POST /delegation/voice/describe`, `POST /delegation/voice/signature`, `PUT /delegation/inbox` (`{enabled?, mailbox_drafts?}`), `POST /delegation/inbox/check`, `GET /delegation/replies`, `PUT /delegation/replies/{id}/text`, `PUT /delegation/handle-it`, `PUT /delegation/reach` (`{step}`, the dial), `PUT /delegation/training`, `DELETE /delegation/learned/{id}` and `GET /delegation/handled` — the caller's own delegation only — and `PUT /delegation/team`, the owner's switch (see API Reference). `GET /what-it-may-do` is the read-only summary above. Send is `POST /decisions/{id}/approve`; Dismiss is `POST /decisions/{id}/reject`.\n- **Evals**: a scenario's `delegation:` block runs the turn against an in-memory mailbox (`evals.mailbox.ScenarioMailbox`) and hands the saved drafts to the judge (`delegation_001`–`003`). A `type: inbox` scenario runs the watcher's two model calls on one thread: whether it drafts must match the scenario, and a draft is judged on saying nothing the person hadn't, copying no link or address, and listing every open question (`delegation_inbox_001`–`007`; the last checks a draft never claims anything was sent).\n\nActing within rules the person sets and standing in for them are later, separate changes, each behind its own switch, off by default.",
+ "markdown": "The **delegation** module (`openexecutive.delegation`) is **Act as me**: the one place the Executive writes *as* a person instead of as itself. Everywhere else it has its own Google account and bots and signs as itself. Here — when the person asks, or, with a second switch, for mail in their inbox that needs them — it writes an email in their voice and saves it as a **draft in their own mailbox** — Gmail or Outlook — for them to review and send. The one thing it ever sends is one of those inbox drafts, exactly as it is in their mailbox: when the person taps **Send** on its card, or, with a third switch, **Handle it for me**, on its own when plain-code rules allow it (below); chat never sends. The principal can turn it on for themselves, and so can each team member once the owner lets them. It is off by default, and off changes nothing: the prompts, tool lists and prompt caches are byte-identical to an install without it.\n\n## Who can have it, and when it is offered\n\n`delegation.settings.can_delegate(person)` is the single rule for who may turn it on: the principal (a non-archived team member flagged `is_principal`), and any other non-archived team member — never a contact — once team members may have it (`team_members_enabled`). That takes two things: the install allows it (`DELEGATION_TEAM_MEMBERS`, default off, which offers the owner the switch) and the owner turned on **Let team members use it** (`PUT /delegation/team`, principal only, one row in `delegation_team`). Turning the owner's switch off takes it away from every team member from their next message, and their inbox watchers stop at their next check; their own switches, drafts and cards are kept. Everything is keyed by `person_id`. A person turns it on for themselves (`PUT /delegation`); nobody turns it on for anyone else. The setting is one row per person in `delegation_settings`, and a missing, unreadable or zero row all mean off.\n\nAt the start of every chat turn (`Executive.stream_chat` and the committee path) `pin_turn_delegation(session, speaker_text)` runs next to the workspace-mode pin and records a `TurnDelegation` on the session. `ghostwrite_email` is **offered** only when all of these hold:\n\n- the speaker may have it and turned it on — read fresh every turn, so turning it off applies from the next message;\n- the speaker is on a surface that verified it is them — the principal through `people_tools.is_principal_on_verified_surface`, a team member through `teammate_on_verified_surface` (the web app signed in, their own Slack or Discord, never an email turn) — and a web turn also carried a signed-in caller (`Session.web_caller_signed_in`, set from `x-caller-email`) or runs under local login — a request with no caller header is not a sign-in and never gets it (whoever holds the shared secret is trusted as the UI proxy that stamps that header, as on every principal-only route);\n- the conversation is private to the speaker: the web chat, a Slack or Discord DM, a verified private Telegram chat, or a chat its channel adapter verified the sender of and marked private (`Session.speaker_verified` + `Session.private_chat`) — never a shared channel or thread, where the draft's preview or the matching threads would be posted for everyone and other people's messages sit in the model's context;\n- the turn is neither unattended (the scheduler's proactive run) nor private to the principal (the email poller's turns), so inbound text can never reach it. The MCP server, workflows, reflection and research never carry it at all.\n\nThe mailbox connection is deliberately **not** part of the offer: the handler checks it on every call and says how to fix it, so the cached tool prefix never flips when a token lapses. The pin lives in a context variable for the turn's task as well as on the session, so two turns running at once on one session (a second browser tab) each read their own. It also carries the speaker's own words for the turn (a new email may go to an address they just typed — the turn's message joins the history only once the turn ends), a per-turn draft count, and `touched_mail` (see Privacy). `own_words` reads those words back for every own-words check (addresses here, facts and task assignments elsewhere): it first removes the hydrated `<outbound_reply_context>` backstory by its exact, anchored shape, so a look-alike closing tag quoted inside it cannot pass the rest off as the speaker's, then drops other adapter tag blocks, and returns nothing for a message carrying an attachment.\n\n## The tool: `ghostwrite_email`\n\nIt lives in its own registry (`orchestrator.delegation_tools.DELEGATION_TOOLS` / `DELEGATION_TOOL_HANDLERS`), **never** `_ALL_SKILL_TOOLS`, so no other toolkit can carry it. On a turn it is offered to, the agent loop adds it to the pool *before* the sort and builds that turn's handler map from both registries; on any other turn a call to it is an unknown tool. The handler re-checks the pin and the surface anyway, then:\n\n1. **Caps** — at most 5 drafts per turn, and `DELEGATION_MAX_DRAFTS_PER_DAY` (default 50, at most 1000) per person per UTC day, shared with the inbox watcher (`delegation.caps`). It is counted from `delegation_drafts`, one row of ids per draft saved from either place, with a count kept in the process as a floor in case a row was lost. Each slot is taken before the first await — a round's tool calls run concurrently, so otherwise every call in it would pass the caps before any counted — and handed back if nothing was drafted. If the rows can't be read it refuses rather than guess.\n2. **Marks the turn** — sets `TurnDelegation.touched_mail` *before* its first read of the mailbox.\n3. **Checks the mailbox** — `gmail_status` asks Google or Microsoft whose mailbox the credential opens and compares it with the person's People email, on every call: a roster email can change, and a client slot swaps the roster.\n4. **Finds the thread** — by `thread_id` (checked against the mailbox's own id shape), or a Gmail-style search (`find`; on Outlook, words, `from:`, `to:`, `cc:`, `subject:` and `newer_than:` are kept and other Gmail operators dropped). Several matches return `{status: \"choose\", candidates}` (subject, sender and date — no message text) and draft nothing; none returns `not_found`.\n5. **Sets the recipients in code**, never from the model. A reply goes to the last inbound message's `From` — never its `Reply-To` (a different one is flagged `reply_to_ignored`) — with the thread's other recipients only on `reply_all`. A new email or a forward may go to any well-formed address: it is only a draft, waiting in their own mailbox, where they see who it is to before they send it. An address that is neither on the roster (contacts only when `contacts_reachable_now()`) nor typed by the speaker this turn comes back in `not_in_people`, and the Executive names it for them to check (`delegation_tools.not_in_people`). Mailing-list mail, a thread they replied to last and a reply-all trimmed to 10 recipients are flagged. An address inside a block an adapter added to their message (the backstory hydrated into a DM) is not one they typed, and when the message carries an attachment — a document's inlined text, or a note naming the file — none of its addresses count as typed: neither has an end mark, and a filename is chosen by whoever sent the file, so such an address is named back to check.\n6. **Writes it** (the ghostwriter, below) and saves it with the mailbox client's `create_draft` (Gmail: threaded with `In-Reply-To`, `References` (whole message ids: when the chain is too long for one header the oldest after the thread's first go, never the parent) and `threadId`, and stamped `X-OE-Ghostwritten`; Outlook: Graph's `createReply` on the message it answers, then the text and recipients, and a named property marking it).\n\nThe result is `{status: \"drafted\", draft_id, gmail_link, to, cc, subject, preview, flags, open_questions, note}`, plus `not_in_people` and `check_address` when a recipient needs checking. The link (`gmail.mailbox_link`) is built server-side from a fixed prefix — the thread in Gmail, the draft itself in Outlook on the web — and the note tells the model the preview is the person's draft, to be treated as data. The chat shows an action chip — \"Drafted an email as you to … — in your Drafts\" — that opens it, and only a link under `MAILBOX_LINK_PREFIXES` is ever linked. A sincere \"are you an AI?\" in the thread comes back as an open question for the person to answer themselves.\n\n## Reading their mailbox\n\nFive read-only mail tools ride with `ghostwrite_email` in the same registry (`orchestrator.mail_read_tools`), so they are offered, re-checked and fenced exactly as it is: `search_my_email` (a Gmail-style search through the client's `search_threads`, or with no query the threads that reached their inbox in the last few days through `inbox_message_ids` + `get_message`), `read_my_email` (one thread's last 10 messages, each sender's new text only, drafts left out, with the files attached to them listed by message id and index), `read_my_email_attachment` (one of those files as text: PDF, Word, Excel, CSV or text, up to 20 MB, a scanned PDF converted) and `my_email_awaiting_reply` (their own sent mail from the last 14 days, to at most 10 people besides the Executive, that is still the last message in its thread). They change, label, draft and send nothing.\n\nThe fifth, `my_email_read_before`, lists the threads `read_my_email` opened for the same person before, in this conversation or an earlier one, so a later conversation can open the same email again instead of asking them to search for it. It keeps where, never what (`delegation.mail_reads`, table `delegation_mail_read`): the thread id, its subject and first sender as one line each, the mailbox address it was read from and when, never a message's text, an attachment or a recipient. Rows are the person's own and are listed only from the mailbox open now, newest first, optionally narrowed by words in the subject or sender; anything older than 30 days is never listed and is deleted on the next write, at most 200 are kept per person, and turning Act as me off deletes them all. It opens the mailbox like the other reads, so it sets `touched_mail`, counts as a search, and returns its rows with the same data-not-instructions note. The Act as me addendum tells the model that these tools reach the person's mailbox while any Gmail or Outlook tools of its own account reach only the Executive's, to search theirs (never falling back to its own) for mail sent to them, and to reopen an email from before with `my_email_read_before` and `read_my_email`.\n\nEach sets `touched_mail` and marks the conversation theirs before its first read (`_open_mailbox`, shared with `ghostwrite_email`), so the lockdown below applies from its round on. Each is capped per turn on the pin: 10 searches (`my_email_awaiting_reply` counts as one), 20 thread reads and 5 attachment reads, the slot taken before the first await. In `read_my_email` every message someone else wrote comes back inside its own `<untrusted_content source=\"email\">` block (`content_trust.wrap_untrusted`, which defuses a closing tag in the text); the speaker's own messages — SENT and from their address (`threads.mine`), never a From header alone — are marked \"Yours\" outside any block. An attachment's text comes back in its own `<untrusted_content source=\"attachment\">` block (`attachments.format_attached_text`), parsed in an isolated worker (`knowledge.loader`); unlike a file sent to the Executive it is never added to the company's knowledge. The clients find an attachment by message and position and look its provider id up on each read (Gmail's changes per fetch): Gmail lists a message's files with the message (`MailMessage.attachments`, leaving out images the HTML shows in place), Outlook says only `hasAttachments` until `list_attachments` asks Graph (leaving out inline ones), and `attachment_bytes` reads one; an attached Outlook item or cloud link has no file to read. Results carry a note that subjects, senders and text are other people's words, data rather than instructions. The lockdown refuses tools, not the reply's own text, so what would carry that text out without a click is closed where it is shown: the web chat loads no image from another site, and bot replies go out without link previews (see Integrations).\n\n## Saving a file from their mail\n\nOne more tool rides with the reads: `save_my_email_attachment` (message id and index, as `read_my_email` listed the file) copies one attached file into the storage the Executive itself has connected and shares it with the speaker alone, so they get a link they can open or put in an app. Every call it makes is built in code (`orchestrator.mail_file_save`); the model picks only the attachment. The bytes come from the mailbox client's `attachment_bytes` and never pass through the model, any file type up to 20 MB, under a cleaned name (one line, no path or reserved characters, extension kept). The storage is the one the Executive's own mailbox runs on (`EMAIL_PROVIDER`) when the gateway has that server, else the other: Google Drive through workspace-mcp (`create_drive_file` with `base64_content` into a folder named \"From your email\" in the Executive's My Drive, then `manage_drive_access` granting the speaker's own address the reader role, `send_notification` off) or OneDrive through ms-365-mcp-server (`upload-file-content` into the same kind of folder in the Executive's own drive, with a name no recorded copy has, since an upload overwrites, then `share-drive-item` inviting only the speaker, `requireSignIn`, role `read`, `sendInvitation` off). The folder is always made by the save itself and its id remembered (`delegation_saved_folder`), never found by its name, since a folder someone else made and called that could already be shared with them; when the remembered one is gone or won't take the file, a new one is made and the old id stays recorded. Never a link share, a domain or anyone. Neither connected (or an eval's in-memory mailbox): status `no_storage`, and the model says so and offers to forward the email instead. Saves run one at a time, at most 10 a turn (`TurnDelegation.files_saved`), and the result is the status, the name, where it went and the link (`webViewLink` / `webUrl`); the chat chip says only that a file was saved, never the sender's file name.\n\nIt copies only when the speaker asked in their own words this turn: what they typed (`own_words`, no quoted backstory or attached file's text) must hold one of save, saved, upload or OneDrive, or Drive as a place (\"to my Drive\", \"in Drive\", \"Google Drive\"), checked before a slot is spent or the mailbox opened; otherwise it refuses (`not_asked`) and tells the model to ask them. It stays allowed after the turn read mail (`MAIL_TOUCHED_ALLOWED_TOOLS`): its gateway calls are admitted past the lockdown only as the very objects the handler built (`mcp_gateway.code_built_call`, for its seven Drive and OneDrive tools: folder create, file create or upload, the speaker's share, and OneDrive's `list-drives`), so a model's own `call_tool` on that turn is still refused, and every other gateway gate still runs on them (the acting account, URL fetches, sheet formulas, the share gates' roster check, writes kept to the Executive's own drives).\n\nEach copy is recorded before it is shared (`delegation.saved_files`, table `delegation_saved_files`: the person, the storage, the file id, its name and when; never content or the mail it came from), and the folder in `delegation_saved_folder`. The gateway reads that table on every Google Workspace and Microsoft 365 call: on a turn whose speaker is not the file's owner (the owner is the speaker only when Act as me was offered to them, so a shared chat, a workflow or the poller sees none), a call naming a recorded file id, raw or percent-encoded (OneDrive's `download-bytes` path is decoded by Graph), is refused, and a result, filtered against the table as it stands after the call so a copy recorded while a listing ran is caught too, loses each list entry or line naming one, with any id left masked. It matches ids as text, so a result that names such a file without its id (a notification quoting its title) still shows the name, and a copy someone makes is a new file. The folders are guarded harder, on every turn and for every speaker, the owner too: a model call whose arguments name any recorded folder id, or an OneDrive item path through the folder (`root:/From your email/x.pdf:` or `<folder id>:/x.pdf:`), is refused, so nobody can share, move, rename, copy, list or delete the folder from chat, and folder ids are dropped from or masked in every result; only the save's own code-built calls touch it. When a copy is made but its row can't be written, it is not shared, the save reports `failed` and logs an error, and the copy's id is hidden from every turn, the owner's included, for the life of the process. When the table can't be read, the file tools (`_FILE_TOOL_RE`: Drive, folder, file, Docs, Sheets, Slides and presentation tools, attachment bytes) are refused (fail closed) while mail and calendar run. The rows are kept when Act as me is turned off: the copies stay in the Executive's storage, and the rows keep them out of other people's turns.\n\n## Reading their calendar\n\nA third switch under Act as me, **Read my calendar** (`delegation.calendar`, table `delegation_calendar`: one row per person, absent or unreadable meaning off), lets the Executive read the person's own calendar. It rides on the same per-person sign-in as their mailbox: `calendar.events` on Google, `Calendars.ReadWrite` on Microsoft, added when they run the connect script with `--calendar` (`scripts/connect-own-gmail.py`, `scripts/connect-own-outlook.py`). The one change it ever makes there is answering a meeting invite (see Meeting invites below); a sign-in made earlier with read-only access (`calendar.readonly`, `Calendars.Read`) keeps reading, and the refresh asks Microsoft for whichever calendar scope the file was minted with. Those scopes are optional, so a mail-only sign-in keeps working for mail; the mailbox clients note the scopes the token refresh reports, and `list_events` raises `CalendarNotGranted` before calling the calendar when the scope is missing (or when the calendar answers 403). Only the person turns it on (`PUT /delegation/calendar`), only while Act as me is on and a one-hour read works; a sign-in without the calendar is refused with `calendar_not_granted` and the command to run. Turning Act as me off turns it off. Changes are audited privately (`delegation_calendar_changed`).\n\n`my_calendar` sits with the mailbox reads, offered and fenced the same way: it refuses while the switch is off (before anything is opened), then takes a search slot, opens the mailbox privately (`_open_mailbox`, so `touched_mail` and the lockdown apply: an invite's title is in the words of whoever sent it) and lists the events from `start` (default today) for `days` days (1 to 31) in the workspace time zone, recurring events expanded and cancelled ones left out: title, start, end, all-day, location, organizer, attendees (25 at most) and the person's own answer, each on one line, with a data-not-instructions note. Google's `events.list` on the primary calendar and Graph's `calendarView` (times asked for in UTC) are its only calls; it changes nothing and keeps nothing. The first week's brief also lists today's meetings from it on the principal's own delivery (see Today).\n\n## Forwarding and reminders\n\n`ghostwrite_email` also forwards: with `forward` (a thread id) and `to`, it drafts a forward of the thread's latest message, or of the earlier one `forward_message_id` names (the one with the files, say, when their own reply came after it), `intent` becoming the short note above it (the ghostwriter writes only the note; the forwarded email's subject, someone else's words, is never put in the intent). Recipients follow the new-email rule (`_new_recipients`: the roster, or addresses the speaker typed this turn). Gmail's draft quotes a forward header and the original's own words under the note and attaches the original's files, up to 10 and 20 MB (`FORWARD_MAX_FILES`, `FORWARD_MAX_BYTES`; any left off are flagged `attachments_left_off`); Outlook uses Graph's `createForward`, which keeps the original and its files, with the note as its comment and the body never patched. It is still only a draft.\n\nThe principal's new email or reply can also carry Google Drive files: `drive_files` takes up to 10 Drive file ids (not with a forward; a team member is refused, since the files come from the Executive's own Drive). `orchestrator.drive_attach` sizes each one first and then downloads it with code-built `get_drive_file_permissions` and `get_drive_file_download_url` calls as the Executive's Google account (`mcp_gateway.code_built_call`, so the mail lockdown admits those exact calls). It takes the saved copy only from workspace-mcp's own anchored `Saved to:` line, exactly one, whose name ends in workspace-mcp's uuid (the answer echoes the Drive name first, which whoever shares a file chooses), names the attachment from that saved name, reads the bytes only from the tool download folders, removes the copy, and puts them on the draft under the forward caps. When the turn had read outside content before choosing them, the result asks the Executive to name each file so the person checks it. The file's text never reaches the model, so attaching is not an outside read. A file someone saved from their own mail, or a save folder (`delegation.saved_files`), is refused for anyone else, checked before and after the downloads and failing closed when that record can't be read, and a file that can't be fetched makes no draft. Gmail attaches them in `build_raw`; Outlook uploads each to the new draft (Graph's one-request upload, 3 MB a file, larger ones left off and flagged), and removes the draft if an upload fails. The result lists the attached file names.\n\n`remind_me(text, when)` (`orchestrator.reminder_tools`) rides with the same tools and checks, but opens no mailbox, so it never marks or locks a turn (`MAILBOX_TOOL_NAMES` are the ones that do). It stores the text once cleaned — one line, anything a chat app could turn into a link (a URL of any scheme, an address, a domain-like word, a host and port, an IP address) replaced with \"[link]\", at most 300 characters — with its time (stored in UTC) in `delegation_reminders` (5 a turn, 25 waiting, a year ahead, refused when the person has no channel). When it is due the scheduler sends that text to the person alone, as \"Reminder you set on <date>: …\", running nothing (see Scheduler); the Slack and Discord DMs it may go by turn link previews off. The chat chip shows the text as it will be sent. A reminder that comes due in the person's quiet hours or leave (when `OUTBOUND_RESPECT_QUIET_HOURS` is on) waits unclaimed and goes once they end, rather than being suppressed and lost. It is allowed after mail is read and in later turns of that conversation: it reaches only the speaker, as plain text. `schedule_followup`, which runs a turn with tools and is listed to everyone, stays refused there.\n\n## Approval cards\n\nA turn that read someone's mail may not message anyone, invite anyone or change the roster (see the lockdown above), yet what the mail asks for is often right. `propose_actions` (`orchestrator.action_card_tools`) leaves the speaker a card instead: up to five actions, each spelled out exactly as it will happen, done only when they tap Approve. It rides with the other Act as me tools and checks (`_writer`), opens no mailbox, and is allowed after mail is read because it does nothing on the turn.\n\n- **Kinds.** `invite` (a meeting with people on the roster), `message` (a direct message to someone on the roster, as written) and `add_contact` (a new contact; the principal's cards only, since contacts are theirs). A team member's card can't name a contact. Each action is checked when the card is made (`delegation.action_cards.check`) and again when it is carried out, so an archived person or a time that has passed fails that action alone.\n- **Whose.** A card is a `delegation_actions` decision for the speaker, `approver_only` like a reply card: only they see it (`GET /delegation/actions`) or resolve it, a team member's answers 404 to the principal too, and it is never an alert. The same actions still waiting are that card, not a new one. 3 cards a turn, 25 waiting, dropped after 7 days.\n- **Approve.** In the chat, under the reply that left it (the `propose_actions` chip carries the card's `decision_id`, and `ChatActionCards` shows the card while it waits), and on the Briefing's Needs you list, with a box per action. Approve (`POST /decisions/{id}/approve`, `edits.only`) needs the card's person signed in (`verified.caller_refusal`) with Act as me on; the card is claimed first so it runs once, then each ticked action runs as stored with no model call, in an unattended session (the principal's with contact egress) under `rows_for_person`, so every audit row it writes is theirs and nothing reaches the team's activity rail: `message_person` (a direct message or nothing; never its Briefing-alert fallback, which more people read), `create_calendar_event`, or a contact row. Approving also needs the person still allowed Act as me (`can_delegate`) and switched on. An invite is booked straight away when the person approving is the one the meeting gate would ask (`calendar_tools.approved_by`), and otherwise goes to that approver as usual, so a card never widens anyone's authority. Per-action results (`done`, `waiting`, `failed`, `skipped`) are kept on the decision and shown on the card. Dismiss rejects it and does nothing else. With Suggested actions in training the card adds the *Do this on its own next time* tick, and a card of actions all allowed is carried out on its own (see In training above); with Suggested actions On, any card that reaches nobody new is.\n- **Channels.** A card can come from any surface Act as me runs on; it is approved in the web app, since the chat apps have no buttons here.\n\n## The ghostwriter\n\n`delegation.ghostwriter.compose` writes the text. The Executive decides *what* to say (`intent`); this call decides *how* the person would say it, and it is deliberately small:\n\n- a constant `GHOSTWRITER_PROMPT` plus the person's voice block as the system prompt;\n- the thread (each message cut to its sender's own words, every line scrubbed, all labelled alike), then the writer's own earlier words in it (`<writer_said>`, from their sent mail only), the intent and the recipients' names in the user turn — no company profile, memory or roster;\n- with Always in the loop on, `<writer_noted>`: what the writer's own notes say they told these same people in earlier Act as me replies (`memory.history_drafts.notes_for_draft`: only notes from mail **every** recipient of the new draft was on, so nothing told to one person reaches another; chat notes name no recipient and never qualify; at most 8, newest first, the person's own words or their correction, with dates). The prompt's rule 6 makes it a consistency check, never content: a draft that contradicts it is still written as the intent says, and the conflict becomes an open question on the card, which only the writer sees. Both the chat tool and the inbox watcher pass it;\n- **no tools** but the forced `compose_reply` return, so text in the thread can ask for anything and there is nothing to do it with.\n\nIt is not a Council agent — the Council's edit routes have no principal check — and runs on `DELEGATION_COMPOSER_MODEL` (default: the default model), logged as `ghostwriter` usage. `lint` then runs in code on what comes back: a link or an email address survives only if it appears in the intent, the signature or the recipients, so a link planted in the thread is removed and flagged; the Executive's own name is flagged; and the body is capped, cut at a paragraph, line or word break in its last fifth. A draft with nothing left after that is refused. The signature from the person's Gmail settings (or the one already stored, for Outlook) is appended.\n\n## How I write\n\n`delegation.voice` learns how a person writes *their own* email (`attunement.style` learns how the Executive should write *to* someone). `POST /delegation/voice/learn` reads up to 40 recent sent messages, keeps only what they wrote (quoted replies stripped with the email poller's `sender_new_text`), skips automatic mail, every thread chat drafted into, and every sent message that began as a draft written for them (`delegation_drafts.sent_message_id`), and makes one forced-tool call (`record_voice_profile`). Code validates every field before it is stored:\n\n- greetings per audience (their team, their contacts, anyone else), a sign-off of at most two lines, and a usual length and tone (a backslash-n the model wrote instead of a line break is read as one, keeping the first lines that fit, which also repairs a profile stored before that rule);\n- up to 8 habits and 6 things to avoid, through the same deny-list as working-style rules — no actions, links, handles, amounts, tool names or names of people; the conversation review (`memory.chat_review`) adds one when the person states how they write in a chat (`add_conversation_rule`, `updated_by=conversation`; never on a locked or full list, and an edit or lock made meanwhile wins);\n- up to 3 short exemplars, each checked to be verbatim from a sample, with addresses and phone numbers masked — and none while a client slot is active, so one client's mail never lands in another's state.\n\nThe signature comes from Gmail's `sendAs` settings, not the model (Outlook gives apps no way to read one, so a learn keeps the stored signature and `POST /delegation/voice/signature` answers 409 `signature_unavailable` rather than clearing it), as plain text with its lines kept (`gmail.html_to_text`: a `<br>` always ends a line, and a block tag, opening or closing, ends one when it has text, so Gmail's layout of a first line followed by one `<div>` per line comes out line by line). `POST /delegation/voice/signature` reads it again without relearning: nothing else changes and a locked profile stays locked, so it picks up a changed Gmail signature and undoes **Don't add my signature**. A person can also describe their style in their own words: `POST /delegation/voice/describe` applies the description to the profile they have through the same forced tool (a separate system prompt, no exemplars) and the same validation, keeps their signature and writing examples, and returns the result with a short sample reply for them to review. It saves nothing and needs no mailbox; Save stores it as an ordinary edit. The person can edit the profile, lock it (a locked profile is never relearned) and reset it, and every change is kept in `delegation_voice_history`. One learn runs at a time per person, and a lock or an edit made while it runs wins: the learned profile is dropped (`changed`).\n\n## Draft replies to my inbox\n\nA second switch under Act as me, **Draft replies to my inbox** (`delegation.inbox`), has the Executive watch the person's own inbox and write a first reply to mail that needs them. The reply waits on a private card on Today; nothing is sent until they tap **Send** (below). Where the reply lives is the person's choice, **Also save replies in my Gmail Drafts** (`mailbox_drafts`, off by default): off, it lives on the card alone (`delegation.card_drafts`: the card keeps the draft's recipients, subject and thread headers as `draft_spec`, and Send makes the mailbox draft from exactly that just before the send-time checks, taking it back out if they refuse), so their Drafts folder doesn't fill with replies they may never send; on, it is also saved in their Drafts as before. The switch is one row per person in `delegation_inbox_watch`. Turning it on needs Act as me on and their mailbox connected, and sets `watch_since` to now every time, so it never drafts for mail that arrived before; turning Act as me off turns it off too. Off means no mailbox call and no row written, with one exception: a send the person started that the mailbox never confirmed is still followed through until it is settled.\n\n### When it looks\n\nA throttled hook in the scheduler tick (`_maybe_scan_inbox`, after the pause, company-profile and rotation gates) checks each person whose switch is on every `DELEGATION_INBOX_POLL_MINUTES` (default 5). It is not a scheduled action, because those are listed on `/scheduled` for everyone and anyone may cancel them. One scan task runs at a time, one scan per person, and none while a client slot is active. **Check now** on the Settings card runs the same scan. Every row a scan writes is private and the person's own (`audit.rows_for_person`: a team member's rows are hidden from the principal too, see Privacy), and the process log carries counts and codes, never an address or a line of mail. The scan never marks mail read or changes a label.\n\n### What it drafts for\n\nA scan first settles the open cards (below), and stops with `backlog_full` once 25 are waiting, counting the ones it makes. It then lists the inbox since `watch_since` (`inbox_message_ids`) — not chats, not mail from the person, and not the promotions, social, updates or forums tabs (on Outlook: the Focused inbox only) — up to 100 messages, and takes the newest message of each thread that still needs a look, at most 10: settled threads and threads with an open card are passed over first, so a burst of mail, or a pause for a limit or a back-off, never hides older threads for good. `delegation_inbox_messages` is its durable cursor: one row per message (`UNIQUE(person_id, message_id)`) with what happened to it, the reason, how many tries it took, and the draft and card ids. It stores a hash of the sender's address, never the address. A message is skipped, with the reason recorded, when:\n\n- it came before `watch_since`, or more than three days ago;\n- it is from the person or one of their send-as addresses, from the Executive, or one of this module's own drafts;\n- it is automatic — `Auto-Submitted`, a bulk or auto-reply `Precedence`, a bounce, a calendar invite or a no-reply sender — or from a mailing list, or in a Gmail tab, spam or trash (with Read my calendar on, a calendar invite goes to `delegation.invites` instead: see Meeting invites);\n- the person is not in To or Cc, or it has more than 10 recipients;\n- the person replied last, or a draft already sits in the thread.\n\nThree kinds are left unrecorded, so a later scan looks again: mail under 10 minutes old (mail the person answers straight away never gets a card), mail in a thread whose card is still open, and mail a daily limit holds back.\n\n### Deciding, then writing\n\nTwo model calls, and code decides between them. The classifier (`delegation.inbox_classifier`) is one forced-tool call, `classify_email`, returning whether the email needs a personal reply, what kind it is and how sure it is. It sees a few one-lined header lines and the sender's own new words (at most 3000 characters, every line scrubbed) inside one `<email>` block marked as data, after the person's own last email in the thread in a `<their_last_email>` block (`their_last_words`: only mail their own mailbox sent, at most 1500 characters), so a reply to something they asked reads as one: an answer to their request for a call that says when the sender is free, without settling a time, is scheduling and gets a draft even when the sender says they will come back with times. It has no other tools, context or memory, so an email can ask for anything and there is nothing to do it with. A reply is drafted only for a question, a request, scheduling, an introduction or a follow-up, and only when the confidence clears a bar that rises the less the sender is known: 0.6 for their team or a contact (the principal's contacts count only for the principal: a team member's mail is weighed by the team and their own sent mail), 0.7 for someone they have written to before (`has_written_to`, a search of their sent mail), 0.85 for a stranger. Pitches, notes of thanks, FYIs, notifications, newsletters and phishing get nothing, and so does any failure. An email that also went to other people is drafted for only when the person is in To and it asks them themselves: the classifier is told their name, whether they are in To or Cc and how many others it went to, and lists the names the email greets or asks by name (`asked_names`). Code matches those against the person's name, whole name parts only (\"Alexis\" never counts for \"Alex\", and a nickname misses, which means no draft), so mail that greets someone else (\"Good morning, Brennan, could you sign ...\") is never theirs, whatever the model makes of it as a whole. When it names nobody, the model's `asked_of_them` decides, false for a question to the group at large. One that only copies them is never drafted for. Either is recorded `not_needed` with the reason `asks_someone_else`. It runs on `DELEGATION_CLASSIFIER_MODEL`, else the routing model. A sender whose address Gmail couldn't authenticate is handled as a stranger whatever the roster says — anyone can put a colleague's or a client's address in From — so they get the stranger's bar, a holding reply and the stranger limits; the card still says who they claim to be, and that the address isn't verified.\n\nThe reply is written by the same ghostwriter, in the person's voice, but from a fixed intent the module builds rather than words the person typed. Because the intent lets it restate the person's own earlier words, which words are theirs is never written inside the thread, where a sender could imitate any marker with a look-alike: every message there is labelled alike, and the person's own words come in a separate `<writer_said>` block after the thread, taken only from mail their own mailbox sent. Nothing inside the thread can close the thread block or open another. The intent: acknowledge the sender; say again only what the person's *own* earlier messages in the thread already said; commit to nothing new — no yes or no, date, time, price, fact or promise — and say they will get back to them; and put every question it could not answer from their words in **open questions**. A stranger always gets a short holding reply. The lint still strips any link or address that isn't the person's own. The reply goes to the sender (never `Reply-To`) and, on a group email, to everyone else it went to as Cc (reply to all, never the person's own addresses or the Executive); a stranger's holding reply starts with the sender alone. When others were on the email the card offers **Reply to**: the sender only, or everyone (`PUT /delegation/replies/{id}/recipients`, `card_drafts.set_recipients`). It picks between the two lists fixed when the card was written (`reply_others`), never an address from the request, and changes the mailbox draft's To/Cc too. Its `draft_to` lists who it goes to, which Send checks.\n\nThe order: record the message, classify, reserve a slot in the shared daily limit, write, save the draft in Gmail (from the alias the mail went to, when it went to one) and store its id, then create the card (idempotent on the message: a second call finds the open card, and a card dismissed or lapsed under that key doesn't stop a new one, while one sent or settled in the mailbox means no second card, `invites.create_once`) and mark it drafted. Nothing that fails along the way loses the message. A failure that may pass — the classifier or the writer failing, Gmail refusing the draft, a card that couldn't be made (its draft is deleted first, so no draft is left without a card), any other error with that one message — leaves it for a later scan (`retry`), and it is given up on only after three tries; one message's trouble never holds up the rest. A daily limit reached while it was being read leaves it for later without counting as a try.\n\n### The reply cards\n\nA card is a `delegation_reply` decision whose class is **its approver's alone** (`DecisionClassSpec.approver_only`): only the person it was drafted for sees or resolves it on any decisions route — a team member's card answers 404 to the principal too — and it is never an alert: alerts feed chat turns, which would put other people's mail into memory. It carries the sender with who they are to the person and whether Gmail could verify the address (SPF/DKIM/DMARC, through `fact_confirmation.headers_authenticated`), the subject, what they wrote, the draft, the open questions and its warnings. `GET /delegation/replies` lists the open ones from the database alone, so Today never waits on Google.\n\n- **Send** approves the card, which sends its draft exactly as it is in their mailbox (see *Send on your tap*). **Edit** changes the reply's words right on the card (`PUT /delegation/replies/{id}/text`, `card_drafts.edit`): only its own person, from a caller the API can tie to them (as for Send), never while it is being sent on its own; a reply in their Drafts is rewritten there too (`update_draft_text`, every header kept), and only while it is still the version the card last saw, so a change made in the mailbox is never overwritten. A card edit counts as edited (`approved_with_edit`, and **Do it like this next time** keeps it), and one made by hand sets `questions_settled`.\n- **Decide before sending** with taps (`delegation.answers`): the ghostwriter returns each open question with 2 to 4 short answers the person might pick (`choices`) and what it is `about` (time, document, other); plain strings still parse, and `open_questions` stays a list of strings for every other reader, with `question_choices` beside it on the card. After the draft is written, code fills two kinds: a time question gets up to 3 free half hours on the person's own calendar (Read my calendar on; one a day over the next 5 working days, busy times only, no event title reaches a model), \"I checked your calendar: these are free.\"; a document question whose words match a company document's name gets 'I'll send \"<name>\" separately', \"Found \"<name>\" in your documents.\" Nothing is attached: a card's draft is plain text. A tap, or **Something else…**, calls `POST /delegation/replies/{id}/answer`: one composer-model call rewrites the body with the answers in their voice (signature and AI line kept out and put back), `ghostwriter.lint` runs on it, and it is saved through `card_drafts.edit` with the same caller and card checks and the same Drafts update. It returns the card with `changed_sentences`, which the card lightly marks. 30 rewrites an hour per person (429). Send waits until every question with choices is answered, or the words were changed with Edit. A card made before choices shows its plain questions. **Open in Gmail** (or **Open in Outlook**), shown only when the reply is in their Drafts, opens it there.\n- **Dismiss** rejects the card; the class's after-reject step then deletes the draft if nobody edited it — its message id is still the one it was saved with, since Gmail gives an edited draft a new one, and the Outlook client makes a draft's message id `<id>.<changeKey>` so an edit there changes it too — and keeps it otherwise. What happened is recorded even when Gmail fails.\n- Each scan first **settles** what Gmail already settled: a draft sent from Gmail, a draft deleted there, a reply the person wrote themselves, a thread that is gone, or a card left for 7 days (its draft stays in Gmail). Each is a compare-and-set close with the reason. A newer message from someone else flags the card instead. A card being sent at that moment is left alone.\n\n### Send on your tap\n\n`delegation.reply_send` is the only thing in Act as me that sends, and all it can send is the draft on a card, by its id: `DelegateGmail.send_draft` posts `{\"id\": …}` to Gmail's `drafts.send`, and `DelegateOutlook.send_draft` posts an empty body to that draft's Graph `send`, and nothing else, so no text, recipient or header is ever passed. It has two doors: `send_approved_reply`, reached only from `POST /decisions/{id}/approve` — a class only the card's own person may resolve — and `send_on_its_own`, reached only from the inbox watcher under Handle it for me (below). AST tests pin both call sites, so no model, chat turn, workflow, scheduled job or MCP call can. A tap is checked like this: At send time it checks everything again:\n\n1. **Who is asking.** The caller is the card's person and the API knows it: signed callers are on and the request carries that person's signed assertion (or the operator's, under local login), or the API runs for local login and answers this computer only. Anything else is a 409 `caller_signing_required` — with only the shared secret, whoever holds it could send as the owner — so on a server Send needs signed sign-ins.\n2. **The switches.** Act as me and Draft replies to my inbox are on, and no client slot is active.\n3. **The mailbox.** Their mailbox is connected.\n4. **The draft.** It still exists, in the same thread, and they haven't replied there themselves since; otherwise the card closes.\n5. **Who it goes to.** To, Cc and Bcc hold between 1 and 10 addresses, never the Executive's own, and it is from one of their own addresses.\n6. **What changed.** Recipients that differ from the card's, or a newer message from someone else, need a second yes: the first tap gets a 409 `confirm` naming the recipients and the reason, and the person approves again with what they were shown.\n\nThen it claims the card (`claim_for_execution`, proposed → executing, a compare-and-set, so a double tap sends once) and reads the draft once more: `drafts.send` sends whatever the draft is when Gmail gets the request, so if it was edited since the checks read it — in another tab, by a delegate — nothing is sent and the card comes back (`draft_changed`). Then it sends, and records the result: `approved_with_edit` when the draft was edited in Gmail, the sent message's id, the draft row's `sent_message_id`, and a private `delegation_reply_sent` row. A refusal that proves nothing went — a 4xx, a lapsed sign-in, a rate limit, a draft already gone — hands the card back. A failure that leaves it unclear — a timeout, a 5xx — leaves it `executing` and says to check the Sent folder, and the next scans ask Gmail: their message in the thread means it was sent; anything else is judged on the second scan that sees it: the draft still there and nothing sent means it was not (Gmail deletes a draft it sends), and the card comes back, flagged; the draft gone and nothing sent means it was deleted. Nothing is ever retried on its own. Sending is the person's own act, so it works while the Executive is paused.\n\n### Limits and failures\n\nAt most 5 drafts a scan; `DELEGATION_INBOX_MAX_DRAFTS_PER_DAY` (default 20) a day, inside the shared `DELEGATION_MAX_DRAFTS_PER_DAY` it shares with chat; 200 classifications, 2 drafts per sender (1 for a stranger) and 10 for strangers in all per day; and never more than 25 open cards. A lapsed Gmail sign-in sets the status and is looked at again every 30 minutes; a rate limit, an error reaching Gmail or a crash backs off from 5 minutes, doubling up to 2 hours. Neither turns the switch off: the Settings card shows the status in plain words.\n\n## Handle it for me\n\nA third switch under Act as me, **Handle it for me** (`delegation.handle_it`), lets the inbox watcher send some of its replies itself instead of leaving them on a card. It is one row per person in `delegation_handle_it` (`enabled`, `mode`); no row means off. One setting says how much goes without them, the way quality does on the Agent Council (`handle_it.RULES`): **Easy ones** (`careful`) sends only replies to people they know (someone on their team, a contact or someone they have written to) of at most 400 characters when the classifier is at least 0.9 sure; **People I know** (`balanced`), where it starts, sends replies to people they know up to 1200 characters at 0.8; **Most mail** (`bold`) also answers strangers, up to 2000 characters, and lets a link or an amount through when the classifier is at least 0.9 sure. Everything else waits on a card as before, so turning it on never drafts less. A table from before the setting gets the `mode` column on its next open (`schema._add_handle_it_mode`): someone who had strangers set to send keeps that as Bold, everyone else gets Balanced. Only the person turns it on (`PUT /delegation/handle-it`), from a session the API knows is theirs: the same rule Send uses (`delegation.verified.caller_refusal`), so with only the shared secret it answers 409 `caller_signing_required`. Turning it on needs Act as me and Draft replies to my inbox on, and turning the inbox watcher off (or Act as me, which turns it off) turns it off too.\n\n**In training** (`delegation.training`). Like someone new, each Act as me job can be put in training on its own, from that job's card on the Act as me page, the way Take the lead has it: **Write drafts as me** and **Handle it for me** each pick Off / In training / On (Handle it's In training puts Replies and Follow-ups in training together; its steps show under On only, since in training only allowed people go whatever the step), and **Suggested actions** picks Always ask / In training / On (On is the `actions_on` switch: a card is carried out with no allow, under the same checks, and only when it reaches nobody new: a new contact or anyone on the roster under a week waits; In training wins when both are set); what it learned is listed on each tab for its own jobs (Act as me: *What it's learned*, drafts and suggested actions; Handle it for me: *Who it's allowed to handle*, replies and follow-ups), each item named by its job (`PUT /delegation/training`, one row per person and setting in `delegation_training`, absent means not in training). In training it asks first and learns who and how from what the person approves; what it learns is a `take_the_lead_allowed` row (feature `act_as_me`, the person's id), theirs alone.\n\n- **Replies.** Every reply waits on its card (`handle_it_reason` `training`) whatever the dial says, and a reply card adds **Send + allow**: it sends that reply on the person's own tap, exactly as Send does, then allows replies to that sender (key `act_as_me|person:<id>|reply|<address>`). While Handle it for me is on, a reply to an allowed sender goes on its own under the dial's limits (a stranger they allowed included) and every check above (the topics that always wait, links and amounts, new recipients, once a thread a day, the daily limit); it's checked again at send time, so a sender removed since waits. Take the lead as you lifts nothing in training: putting Replies or Follow-ups in training turns it off, and it can't be turned on while they are (409 `in_training`).\n- **Follow-ups.** Every follow-up waits (`follow_up_training`); Send + allow on a follow-up card allows follow-ups to exactly the people it went to (`…|follow_up|<sorted addresses>`), whoever they are, under every other follow-up check.\n- **Suggested actions.** An action card (below) adds **Approve + allow**: it does the actions on the tap, then allows each one that happened (a message to that person, `…|message|person:<id>`; a meeting with exactly those people, the person left out, `…|invite|people:<ids>`). A new contact is never allowed. A card proposed later whose every action is allowed is carried out at once, with no tap (`action_cards.run_on_its_own`, `gate_mode` `auto_execute`, status `executed`), only if plain code finds nothing against it (`on_its_own_refusal`): still in training, Act as me on, a server that ties the switch to the person, nothing sensitive, no link or amount, a message of at most 1200 characters, and at most 10 actions carried out this way a day (checked one card at a time); anything refused is handed back to wait on its card as before. An invite carried out this way is never booked as approved by the person: the meeting gate decides as for any meeting nobody tapped, so a time taken from someone's mail can't land on a calendar unasked. The tool result and chip say what was done. The message text in such an action is model-written from the mail and goes without anyone reading it; the allowance covers who and what kind, not the words, which is why sensitive topics, links, amounts and long messages are held back.\n- **Drafts.** Nothing is sent. When the person changes a reply's draft in their mailbox before tapping Send (plain or + allow) and ticks **Do it like this next time**, what they sent is kept (its new text, quoted replies dropped, at most 1000 characters, `…|style|<address>`), and the ghostwriter gets it in its user turn as `<writer_example>` when it next writes to that person, from the inbox, a follow-up or a chat draft to that one person: style only, never its facts, and nothing in it can open or close a tag.\n\nSend and Approve with the *on its own next time* tick (`allow`; the tick replaced the separate Send + allow and Approve + allow buttons) are refused before anything is done unless their setting is in training (422 `cant_allow`) and the person's list has room (409 `learned_full`, at most 200 a person); allowing failing afterwards never undoes the send. Putting Replies or Follow-ups in, or Suggested actions out of training or On, only holds more back and works without signed sign-ins; anything else needs a caller the API knows is that person. What it learned is the person's alone: listed on `GET /delegation` (`training.learned`, each with its `setting`), removed with `DELETE /delegation/learned/{id}`, and for the owner also in Take the lead's \"What it's learned\" list; it never reaches anyone else's list or Take the lead's prompts. A dial left on In training by an older version (mode `training`) moves to People I know with Replies and Follow-ups in training (`schema._move_training_off_the_dial`).\n\n**No model decides whether a reply goes.** The watcher's two model calls are unchanged and tool-less, so text in an email can at most change the verdict and the draft. After the draft is written, `handle_it.refusal` — plain code — decides, and anything it refuses becomes the usual card with the reason kept on it (`handle_it_reason`). It refuses when:\n\n- it's off, or the sender is a stranger and the setting isn't Bold, or on a server signed sign-ins are off (`signing_ok`: signed callers, or local login);\n- Gmail couldn't authenticate the sender, whatever the roster says;\n- the email isn't a question, request, scheduling, introduction or follow-up, or the classifier was less sure than the setting needs (0.9 on Easy ones, 0.8 otherwise);\n- the reply goes to anyone the email didn't already go to (its From, To and Cc, less the person's own and the Executive's addresses), leaves out the sender, or goes to more than 10;\n- the email's subject, the sender's new words, or the reply touch money, contracts, legal, hiring, pay, layoffs, the board, investors, mergers, the press, health, or credentials and secrets (passwords, logins, tokens, API keys); or the reply carries an amount, a percentage or a link (a scheme, `www.`, a bare host with a path such as `bit.ly/…`, or a bare host on a common top-level domain) unless it's Bold and at least 0.9 sure, or runs over the setting's length (400, 1200 or 2000 characters);\n- the draft carries any flag but *others on the thread* or *Executive on the thread* (they asked if it's an AI, recipients were trimmed, …);\n- it already sent one in this thread in the last day, or the person's last message in the thread was itself sent on its own (no auto-reply ping-pong);\n- the day's limit is reached (`DELEGATION_HANDLE_IT_MAX_SENDS_PER_DAY`, default 20, within the watcher's drafts limit), or it can't be counted. Any error in the rules counts as a refusal.\n\nA reply the rules allow gets a card with `gate_mode` `auto_execute`, and the watcher sends it at once through `reply_send.send_on_its_own`, the second and last door into the send path (an AST test pins both callers: the approve route and the watcher). It runs the same send-time checks as a tap — switches, mailbox, draft, recipients, the claim and the last re-read — with no caller, and adds its own: the card must be `auto_execute`, Handle it for me still on with the setting still allowing that sender (or, for a follow-up, that recipient), signing still on, the once-a-thread-a-day rule and the daily limit counted again, and the draft untouched since it was saved (an edit in Gmail means the person has taken it over: `draft_changed`, the card waits for them). Every refusal hands the card back to the person (`decision_ledger.hand_back`, a compare-and-set to `propose`), with the reason kept on it when there are words for it, and a failure never stops the scan. Every card it left for the person says why on Today (`waited_because` on `GET /delegation/replies`). A reply sent on its own finishes as `executed` (not approved), is recorded in `delegation_handled` (for the per-thread and daily rules) and writes a private `delegation_reply_handled` row; an unconfirmed one is settled by the reconciler the same way. No History note is taken from it, since notes come only from the person's own words. It runs inside the watcher's scan, so it stops while the Executive is paused.\n\n**Follow-ups as you** (`delegation.follow_ups`). While Handle it for me is on, the watcher's scan also looks at the person's own sent mail, at most once an hour (`LOOK_EVERY`), for an email of theirs that asked something (a question mark in their own words), is 3 to 10 days old, went to at most 10 people other than the Executive, and is still the last message in its thread. Plain code picks it; each gets one follow-up ever (its `delegation_inbox_messages` row), at most two a look, within the drafts limit. The ghostwriter, tool-less as always, writes a short nudge in their voice from the thread, saved as a draft in that thread to exactly the people the email went to. `handle_it.follow_up_refusal` — plain code — decides whether it goes: by the setting it never goes on Easy ones, goes to their team and contacts on People I know and to anyone they wrote to on Most mail (`follow_up_refused` otherwise: `follow_up_level`); it also refuses on any change of recipients, a sensitive topic, an amount or a link, more than 600 characters, a flag, and the same per-thread and daily counts as replies. It goes through `send_on_its_own` on an ordinary `delegation_reply` card marked `source: follow_up`, which rechecks the setting for that recipient. A refused one waits on Today as **Follow-up waiting**, and closes by itself (its untouched draft deleted) when anyone answers in the thread first.\n\n**What it sent** is the person's alone: `GET /delegation/handled` lists the last 7 days (who, subject, the reply, the questions it left them and a link to the thread in their mailbox), and the Handle it for me tab shows it with how many went today, under its picker.\n\n### Take the lead as you\n\nOn Settings → Act as me, Handle it for me is one dial: **Off**, **Easy ones**, **People I know**, **Most mail** and, for the owner, **Everything**, which uses **Take the lead** (`PUT /delegation/take-the-lead`, one row `person:<id>` in `take_the_lead`; turning it on turns Handle it for me on). While it is on, `handle_it.refusal` drops the setting's limits: strangers, the classifier's confidence, amounts, and the length up to a 4000-character ceiling. A reply with a link still waits for a tap (refusal `link`). In their place it checks the company's and the person's own added rules (`take_the_lead.reply_hit`, refusal `lead_rule`). Everything Handle it always keeps still holds: signed sign-ins, an authenticated sender, a reply kind, exactly the thread's people, the topics that always wait, draft flags, never twice in a row, one a thread a day and the daily limit. Follow-ups under it may go to anyone the person wrote to, with the same sensitive, amount, link and length checks plus the added rules. `reply_send.send_on_its_own` accepts the card while both switches are on. Each person adds and removes their own rules (`/delegation/take-the-lead/rules`). Removing one needs a caller the API can tie to them.\n\n\n## Meeting invites\n\nWith **Read my calendar** on, a calendar invite in the person's inbox no longer just gets skipped (`delegation.invites`). The watcher applies its usual rules, less the ones about writing a reply (a calendar service's own Sender header doesn't make it automatic; a big meeting isn't too many recipients), and then looks at who sent it: someone the person knows — their team, a contact, or someone they have written to (`inbox.relation_of`), with the sender confirmed by the mail service (`inbox.handling_relation`) — or it is skipped as `invite_stranger` / `invite_unverified`. It then finds the event on their own calendar: on Google by the invite's iCalendar UID (read from its `text/calendar` part, or its attached `.ics`) in their primary calendar, on Outlook as the invite message's own event; only a request counts (a cancellation or someone's answer doesn't). An event that can't be found, isn't organized by the sender, is already answered or has already started is skipped with that reason, as before. **No model is called** for an invite.\n\nWhat's left becomes a card, a `delegation_invite` decision that is its person's alone (`approver_only`) and never an alert, like a reply card: who invited them, the title, when (in the workspace time zone) and any **clash** — the busy times on their calendar that overlap the meeting, computed in code from the calendar read; only start and end times reach the card, never another event's title. **Accept** and **Decline** are `POST /decisions/{id}/approve` with `edits.answer` (`accept`, the default, or `decline`), on the same caller checks Send uses (`verified.caller_refusal`); the card is claimed, then answered with the mailbox client's `answer_invite`. Answering again is harmless, so a failure releases the card for another try; an event that has gone fails it. **Dismiss** (`reject`) answers nothing. A sign-in that reads but can't write the calendar keeps its card, which says to connect again under Read my calendar (with the command) instead of offering Accept. A card closes by itself once the meeting starts or after a week, and its thread waits until it's settled.\n\n**On its own.** Under Handle it for me (On, or Take the lead as you) it accepts with no tap when plain code finds nothing against it (`invites.refusal`): a sender on their team or in their contacts, never one known only from their Sent mail (with Replies in training, only one they ticked **Accept from them on its own next time** for), signed sign-ins or local login, no clash and a calendar it could read, nothing sensitive in the title, a sign-in that can answer, and Handle it for me's daily limit and once-a-day-per-thread rule (`handle_it.count_refusal`, `record_handled`). It never declines on its own. Anything against it leaves the usual card saying why. An accepted invite is listed with the replies it sent: `GET /delegation/handled` (`source: invite`, with a one-line `summary` such as \"Accepted Dana's Pilot review, Wed 21 Oct, 14:30\") and Today's `sent_as_you` activity, the person's alone.\n\n**In training.** With Replies in training, a card has the same tick as a reply card; ticking it and tapping Accept adds `Accept invites from <name>` to their learned list (key `act_as_me|person:<id>|invite_from|<address>`, under Replies), removable like any other.\n\nAudit rows, all private to the person: `delegation_invite_carded`, `delegation_invite_answered`, `delegation_invite_handled`, `delegation_invite_dismissed`.\n\n## AI line on replies\n\nReplies written as a person can end with **\"Drafted and sent by my AI assistant.\"** (`delegation.disclosure.LINE`), by two switches that are each person's own (`PUT /delegation/disclosure`, one row per person in `delegation_disclosure`, NULL following the install): **Handle it**, on by default (`AI_DISCLOSURE_HANDLE_IT`), for a reply Handle it for me will send on its own, which nobody reads before it goes; and **Approved sends**, off by default (`AI_DISCLOSURE_APPROVED_SENDS`), for one that waits on a card for them to send, since they read it first. The line is written into the reply when it is drafted (`disclosure.sign`, in `inbox._consider` and `follow_ups`), once the plain-code checks have decided whether it goes on its own, so the card, the mailbox draft and what is sent are the same words and Send's draft-changed checks see them; a switch changed later applies to the next reply, and a reply drafted to go on its own that is handed back keeps its line for the person to edit. `AI_DISCLOSURE` off turns both off and hides the card. Turning a switch on only adds the line, so it needs no signed sign-in; turning one off does. Each tab shows its own switch under Advanced (**AI line on drafts you send** on Act as me, **AI line on replies it sends** on Handle it for me), and turning off the Handle it line asks first.\n\n## The mailbox client\n\n`delegation.gmail.DelegateGmail` talks to the Gmail REST API directly and is **never registered with the MCP gateway**, so the model reaches the mailbox only through the typed handler. The credential is one file per person in `DELEGATION_GOOGLE_CREDENTIALS_DIR`, named from a hash of the address (0600 in a 0700 directory), minted by `scripts/connect-own-gmail.py` on the Executive's own OAuth client with the scopes `gmail.readonly` and `gmail.compose`. It never lives in `WORKSPACE_MCP_CREDENTIALS_DIR`, where workspace-mcp picks a credential by address. Besides reading threads and saving drafts it lists the inbox and checks whether they have written to an address, reads one message or draft, lists the person's send-as addresses and deletes a draft. Its **one send method**, `send_draft`, sends an existing draft by its id and nothing else — never `messages.send`, which sends any text it is given — and unit tests pin the method set, the endpoint, the request body and its single caller. On the calendar it reads (`list_events`, `find_invite`: an invite's event by its iCalendar UID) and makes one change, `answer_invite`: the person's own attendee answer on one event, with `sendUpdates=all` so the organizer hears (`calendar_write_granted` says whether the sign-in allows it; a read-only one raises `CalendarWriteNotGranted`). A failed request says whether it may have been carried out anyway (a timeout after connecting, a 5xx), which is what the send path needs to know. A parsed message carries when it arrived, whether it is bulk, a bounce or a calendar invite, and whether Gmail's authentication results vouch for its sender.\n\n`gmail_status` answers `connected`, `not_configured`, `needs_reconnect` (Google refused the saved sign-in — an app in Testing mode has its tokens expire after 7 days; a rate limit, though Gmail may send it as a 403, is an `error` to retry, not a reconnect), `mismatch`, `no_email`, `shared_mailbox` or `error`. `shared_mailbox` means the person's address *is* the Executive's; it is refused before asking Google, because then everything the Executive writes would look like theirs. The gateway closes the other door: every `google_workspace__*` call must act as the Executive's own account, and a `user_google_email` naming anyone else is refused and audited (see Integrations).\n\n### Outlook\n\nA person may connect an Outlook mailbox instead (work, school or personal), with `scripts/connect-own-outlook.py`: a device-code sign-in on the Executive's own Entra app (`MS365_MCP_CLIENT_ID`, tenant `MS365_MCP_TENANT_ID` or `common`) asking for `User.Read`, `Mail.ReadWrite`, `Mail.Send` and `offline_access` (and `Calendars.ReadWrite` with `--calendar`; an invite is the invite message's own `eventMessage.event`, answered with Graph's event `accept` or `decline` and `sendResponse`). It writes the same per-person file with `\"provider\": \"microsoft\"`, so a person has one mailbox for Act as me, and `gmail_for` hands back `delegation.outlook.DelegateOutlook`, which keeps `DelegateGmail`'s methods, return types and errors, so every caller above runs unchanged. It talks to Microsoft Graph directly, never through the Microsoft 365 MCP server the Executive's own Outlook uses, and is never registered with the gateway. Microsoft rotates the refresh token on use; the new one is written back into the file (atomically, keeping every other key, and only if the file still holds the old one). Graph is asked for immutable ids, so a sent draft keeps its id; a thread is Outlook's `conversationId`. Gmail's labels are mapped onto what the callers read: `SENT` only for mail in their Sent Items folder (a From line set to their address by someone else never counts), `DRAFT`, `INBOX`, and Focused Inbox's Other read as a tab. A sender counts as authenticated only when the topmost `Authentication-Results` — the one Exchange wrote, above anything the sender added — holds exactly one DMARC verdict, a pass for From's own domain, and Exchange Online Protection's own `compauth=` verdict, so a header the sender wrote on mail EOP never stamped doesn't count. `delete_draft` refuses anything that isn't a draft, and deletes with the draft's etag (`If-Match`), so a draft sent in between — it keeps its id — is left alone. No client secret is ever written into a person's file, and Graph has no signature setting to read.\n\n## Privacy\n\nWhat a person's mailbox touches is theirs. For the principal that means private to the principal, as every private row is. For a team member it means theirs alone, the principal included: an audit row carries `private_to_person` (set by `audit.rows_for_person` around the inbox watcher, a card's Send and Dismiss and their settings changes, and by `people_tools.audit_row_owner` on a turn that read their mail) and is left out of every audit read — the log, a session's timeline, a row by id, the brief — with only the usage totals counting it; their reply cards are theirs alone (above); and the owner's view of their use is counts only (drafts and sends in 30 days, and whether their inbox watcher is on). The conversation itself becomes its owner's alone before the mailbox is first read: `ghostwrite_email` marks the session `mail_private` (`session_store.mark_mail_private`, creating a channel adapter's row early, with its owner) and refuses to read the mailbox if that can't be stored or the conversation already belongs to someone else (which it then leaves unmarked); from then on only its owner may open it (`chat._session_access`), and working-style learning skips it. Every later turn there starts private (`settings.pin_turn_delegation` reads the flag and fails closed, setting `touched_mail`), so a follow-up answered from history alone is still private to its owner and teaches no memory, and the web chat's rows before the turn (the inbound message and the knowledge lookup) are theirs too. It does not start locked down: the lockdown is `read_mail`, set only by a turn that reads the mailbox or notes itself, and it is never carried into the next turn, because history keeps only the speaker's words and the Executive's replies, never the mail a tool returned. Their next message is them asking again, having read that reply, so everything runs again there. Anyone else speaking in it is not offered Act as me.\n\nOnce `touched_mail` is set, every audit row the turn writes is private (`people_tools.audit_row_private_to_principal`), and a team member's is theirs alone: the tool row (its input and result redacted, since `ghostwrite` is a sensitive tool name), the reply's `chat_turn` row that carries the preview, the model-call rows, and the background passes, which run under `private_rows`. The Honcho peer and department syncs are skipped, because peer memory is read on other people's turns. No memory is learned from the turn at all: the episodic, open-loop and working-style passes are skipped too, since its reply quotes a draft built from other people's mail. The `delegation_*` audit events are always private and carry metadata only — ids, counts and flags, never the draft or the thread. The inbox watcher is private the same way: every row a scan or a card action writes is its person's alone, and it starts no chat turn, alert, scheduled action or workflow run and teaches no memory.\n\nThe turn also keeps one door shut (`delegation.lockdown`). Anyone can put text in the inbox, and that text could try to steer the model, so from the round that calls `ghostwrite_email` or one of the mailbox reads — a round's tools run together — until the turn ends, the dispatch guard refuses only what opens the open internet or reaches everyone: outside fetches (`read_document`, research, the watchlist, `load_mcp_server`, and any MCP `call_tool` outside the private-turn set of reads and recipient-checked sends), `run_script` and `run_python_job`, workflows (they run later, unattended, and may fetch or script), broadcasts, department messages and alerts, and changes to who is on the roster or holds authority (`archive_person`, `set_department_head`, `resolve_roster_request`), and text that steers later turns (`schedule_followup`, whose intent runs unattended when due, and goals and decision outcomes, shown to every later turn). Everything else the person asks for runs, because it is fenced on its own: DMs and `message_person` reach only the roster, invites name attendees by person id, the Executive's own email checks every recipient against the roster, standing facts and profile edits keep only the person's own words, and a workflow drafted in chat is saved only once a person confirms it. `upsert_person` runs only for a contact the person asked for (`speaker_named_contact`: a contact, never the team, an approval scope or a chat account, with a word of the name in what they typed, in a message that asks to add, save or change someone, a new contact's address one they typed or one that sent the mail the turn read under the contact's name (`TurnDelegation.mail_senders`), never one the mail's text only mentions, and on an update a changed address they typed), since the roster is what the send checks trust. Any other contact add is refused with a pointer to an approval card (`lockdown.CONTACT_REFUSAL`), so the Executive leaves an `add_contact` card in the chat rather than asking them to type the address. What an email itself asks for is still never done on its say-so; it goes on an approval card. Every tool is classified as allowed or withheld, a test fails on a new unclassified one, and an unknown name is withheld, except an extension tool registered with `after_mail_read` (one that only reads the install's own data). The refusal tells the model to put what the step needs in its reply, since the next turn sees the reply but not the mail, and to do the step then without reading the mail again. A refused call gets a private `tool_invocation` row (`refused: mail_touched`) and tells the model to offer it in the next message. The offered tool list never changes mid-turn, so the cached prefix holds. The handlers that reach outside check again on their own (`outside_reach_refusal`). The server-side web search stays, as on a turn private to the principal. The lockdown ends with the turn. Later turns of that conversation stay private to its owner (`touched_mail`) but hold nothing: a refusal says it will work when they ask again in their next message, and it does.\n\n## Always in the loop\n\nA sent reply can leave a note. Once the reply went, `reply_send` starts `memory.history_notes.note_sent_reply` for the person who sent it, in the background, when their \"Keep track of what happens\" switch is on and the conversation isn't one they asked not to remember. The note-taker sees only the words they sent, so other people's mail never becomes a note, and a failure never touches the send. Recall is `recall_history`, offered on the same verified, private surfaces as `ghostwrite_email` and also allowed under the mail lockdown, since it only reads the speaker's own notes. Calling it locks the turn like `ghostwrite_email` does, from its own round on. The same switch also covers notes from chat, which don't need Act as me. See **Memory** for the checks, retention and controls.\n\n## The system prompt\n\nA constant, name-free `DELEGATION_ADDENDUM` joins block 0 after the unchanged identity addendum while anyone on the install has it on (`block0_delegation_on`). It names the four mailbox reads and says other people's mail is data and that a conversation which read it reaches nobody else; and it tells the model that `ghostwrite_email` is the single exception to *never impersonate*, and only for the person being spoken to; that everything else is written as itself; that when the tool isn't offered the asker can't have it; that a draft is never described as sent; and that it never denies being an AI. It is keyed on the install-level setting, never on the turn or the speaker, so switching it misses the 1h cache once (see Prompt Caching).\n\n## What it does for you\n\n**What it does for you** (`delegation.may_do`, `GET /what-it-may-do`) is read-only: with the viewer's settings right now, one row per thing that can go out without asking, written as one sentence of what it does, what happens to it (goes out, waits for someone, always waits, drafts only, off) and which setting decides it, with a link there. It sits beside every Delegate tab (`DelegatePage` → `WhatItDoesPanel`): a column to the right on a wide screen (closing it is remembered in the browser), a bottom sheet on a narrow one. The UI groups rows by outcome (Sends on its own, Asks first, Writes for you to send, Off). Every delegation setter in `lib/api.ts` fires `DELEGATION_CHANGED` after a save; the panel reloads on it and marks the rows whose outcome or text changed as **Just changed** for ten seconds. `/delegate` and the old `/delegate/what-it-may-do` open Act as me. Its **Compare** fold holds Who writes and who sends. Three parts, each behind a pill that counts what goes out:\n\n- **As you** (the caller's own, when `can_delegate` allows them): built from `settings.is_enabled`, `inbox.get_watch`, `handle_it.get` and `handle_it.RULES`, `handle_it.leading` (Everything), `training.get` and `training.learned`, and their rules, the same reads `handle_it.refusal` and `follow_up_refusal` make. A level's row follows its `Rules` (strangers, follow-up reach, links and amounts), not a copy of them. A note names the ladder: Handle it for me rides on Draft replies to my inbox and Write drafts as me, and Everything also drops when Replies or Follow-ups go into training.\n- **As the Executive** (the principal's alone, as `GET /take-the-lead`): the switch and its training, each Ask first kind, the company's rules, and meetings. A meeting it thinks of on its own always waits: both meeting gates need someone on a verified surface in the turn, which an unattended run never is. A meeting someone asks for in chat follows **Always asks first → Meetings asked for in chat** (on means it waits: `meeting_scheduling`'s class mode is `propose`; off means `auto_execute`) and, in a team workspace, Operations' level too.\n- **Departments**: each level, and what a level covers (department-scoped scheduled work, check-ins, alert review, team members' chat sends, and Operations' meetings), and that it doesn't cover what the Executive does under Take the lead.\n\nIt also says when the Executive is paused, and when nothing can be sent as anyone because signed sign-ins are off. Nothing on it writes or reads mail. A contact, someone not on People, or a request with no caller (outside local login) gets 403.\n\n## How far it goes as you\n\nOne setting replaces the switches that used to turn each other off out of sight. The UI shows it as two pickers (`ReachCard.tsx`): **What it writes as you** (`WritesCard`) on the Act as me tab and **What it sends on its own** (`SendsCard`) on the Handle it for me tab; What it does for you links each row to its own picker. Its steps, each adding to the one before: **Off**, **Drafts when I ask** (Write drafts as me), **Drafts for my inbox** (Draft replies to my inbox), then the Handle it for me steps that send, **Easy ones**, **People I know** and **Most mail** (`careful`, `balanced`, `bold`), and for the owner **Everything** (Take the lead as you). Act as me shows the first three as **Off**, **When I ask** and **Draft replies automatically** (any sending step reads as Draft replies automatically there). Handle it for me shows **Off** (saved as the inbox step) and the sending steps, and opens only once Act as me is at Draft replies automatically, with a button that turns that on; moving Act as me below it says Handle it for me stops too. `PUT /delegation/reach` (`{step}`) moves it, and `reach_of` reads the step back from the switches, so the stored switches stay the source of truth and every gate reads them as before.\n\nGoing down turns the switches above the target off, highest first (`_lead_off`, then Handle it, then the inbox watcher, then Write drafts as me), so nothing is ever on above a switch that's off; the UI says what stops and asks before it saves. A lower sending level only holds more back and is set directly, so it needs no signed sign-in. Going up calls each switch's own route in order, so every check it makes still applies: the mailbox connected, signed sign-ins for sending, the owner alone and not in training for Everything. The first that refuses stops the move at a whole step and answers with that route's error. Handle it for me's own Off / In training / On (Replies and Follow-ups together) and, at Everything, **Your rules** sit with its picker, and **Learn from my edits** (drafts training) under the Act as me one; neither picker changes training.\n\n## Surfaces\n\n- **Settings → Act as me** (`ActAsMeCard`, hidden unless `GET /delegation` answers, so a team member sees it once the owner lets them): the mailbox connection (`provider` says which) with both connect commands (Gmail and Outlook) and **Check again**, **What it writes as you** (above), with the inbox watcher's status under Draft replies automatically (in plain words, when it last checked, **Check now** and **Also save inbox replies in my Gmail Drafts**), and **How I write**: length and tone, a greeting per audience (`{first}` is their first name), the sign-off, habits and never-rules in fields that grow to show every line, the signature with **Refresh from Gmail** and **Don't add my signature** (or **Add my Gmail signature** when none is added; on Outlook only **Don't add my signature**, with why), and each example quoted with **Remove examples**. The owner also gets **Let team members use it** where the install allows it, with each team member who has it on listed by name and counts only.\n- **Today → Replies waiting** (`RepliesWaiting`, the top of the left column; hidden unless `GET /delegation/replies` answers with cards): each card shows who wrote and who they are to you, whether their address was verified, the subject, **They wrote** as plain text, your draft, **Decide before sending** (the open questions, each with answers to tap and **Something else…**, and where they came from) and its warnings, with **Send** (a confirm naming who it goes to, and a second one when that or the thread changed), **Edit** (a text box on the card with Save and Cancel), **Open in Gmail** or **Open in Outlook** when the reply is in their Drafts, and **Dismiss**.\n- **Today → Needs you, invites** (`InviteCards`, next to the reply cards; hidden unless `GET /delegation/invites` answers with cards): the meeting, when, who invited them and who they are to them, any clash (times only), and **Accept**, **Decline** and **Dismiss**, or the reconnect note for a read-only sign-in; with Replies in training, the **Accept from them on its own next time** tick.\n- **Setup status**: a **Your own mailbox (Act as me)** light (`your_gmail`), amber while the inbox watcher can't reach the mailbox, is being rate-limited or has 25 replies waiting.\n- **Delegate** (main menu): **Act as me** (where `/delegate` and `/settings/act-as-me` land), **Handle it for me** (which step the dial is at, with **Change in Act as me**, then **What it sent**: how many went today and what it sent this week, as you) and **Take the lead** (the switch, then **Always asks first**, shown even while the switch is off and ending in **Meetings asked for in chat**, and the company's rules, as the Executive). Each switch that turns another off says so beside it. The pause is on **Settings → Your Executive**.\n- **API**: `GET`/`PUT /delegation`, `GET`/`PUT`/`DELETE /delegation/voice`, `POST /delegation/voice/learn`, `POST /delegation/voice/describe`, `POST /delegation/voice/signature`, `PUT /delegation/inbox` (`{enabled?, mailbox_drafts?}`), `POST /delegation/inbox/check`, `GET /delegation/replies`, `PUT /delegation/replies/{id}/text`, `GET /delegation/invites`, `PUT /delegation/handle-it`, `PUT /delegation/reach` (`{step}`, the dial), `PUT /delegation/training`, `DELETE /delegation/learned/{id}` and `GET /delegation/handled` — the caller's own delegation only — and `PUT /delegation/team`, the owner's switch (see API Reference). `GET /what-it-may-do` is the read-only summary above. Send (and an invite's Accept or Decline, with `edits.answer`) is `POST /decisions/{id}/approve`; Dismiss is `POST /decisions/{id}/reject`.\n- **Evals**: a scenario's `delegation:` block runs the turn against an in-memory mailbox (`evals.mailbox.ScenarioMailbox`) and hands the saved drafts to the judge (`delegation_001`–`003`). A `type: inbox` scenario runs the watcher's two model calls on one thread: whether it drafts must match the scenario, and a draft is judged on saying nothing the person hadn't, copying no link or address, and listing every open question (`delegation_inbox_001`–`007`; the last checks a draft never claims anything was sent).\n\nActing within rules the person sets and standing in for them are later, separate changes, each behind its own switch, off by default.",
"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-19T17:00:00Z"
+ "generated_at": "2026-10-19T19:00:00Z"
}
diff --git a/packages/core/openexecutive/audit/logger.py b/packages/core/openexecutive/audit/logger.py
index ce0395d4..1fcb6b41 100644
--- a/packages/core/openexecutive/audit/logger.py
+++ b/packages/core/openexecutive/audit/logger.py
@@ -101,6 +101,10 @@ EVENT_TYPES: tuple[str, ...] = (
"delegation_training_changed", # a person put Act as me settings in or out of training (PUT /delegation/training)
"delegation_disclosure_changed", # a person changed the AI line on replies sent as them (PUT /delegation/disclosure)
"delegation_calendar_changed", # a person turned Read my calendar on or off (PUT /delegation/calendar, or off with Act as me)
+ "delegation_invite_carded", # an invite from someone they know became a card to accept or decline (delegation.invites)
+ "delegation_invite_answered", # the person tapped Accept or Decline; it answered in their own calendar
+ "delegation_invite_handled", # Handle it for me accepted an invite on its own (no clash, a sender they know)
+ "delegation_invite_dismissed", # the person dismissed an invite card (nothing answered)
"fact_retired", # the principal (or the teammate who recorded it) retired a standing fact from the Pulse page (memory/facts.py)
"fact_reviewed", # the principal approved or declined a teammate's proposed standing fact
"fact_approval_changed", # the principal turned "needs my approval" on or off for a teammate's standing facts
diff --git a/packages/core/openexecutive/delegation/calendar.py b/packages/core/openexecutive/delegation/calendar.py
index d6102dd6..c0703b20 100644
--- a/packages/core/openexecutive/delegation/calendar.py
+++ b/packages/core/openexecutive/delegation/calendar.py
@@ -1,11 +1,15 @@
"""Act as me: Read my calendar.
A person who has Act as me can also let the Executive read their own
-calendar, read-only: ``calendar.readonly`` on Google, ``Calendars.Read`` on
+calendar: ``calendar.events`` on Google, ``Calendars.ReadWrite`` on
Microsoft, granted on the same per-person sign-in as their mailbox when they
connect it with ``--calendar`` (``scripts/connect-own-gmail.py``,
-``scripts/connect-own-outlook.py``). A sign-in made without it keeps working
-for mail; only the calendar read says to connect again.
+``scripts/connect-own-outlook.py``). The only change it ever makes there is
+answering a meeting invite, on the person's tap or accepted on its own under
+Handle it for me (``delegation.invites``). A sign-in made before with
+read-only access (``calendar.readonly``, ``Calendars.Read``) keeps reading;
+its invite cards say to connect again. A sign-in made without it keeps
+working for mail; only the calendar read says to connect again.
**The switch.** One row per person in ``delegation_calendar``; absent,
unreadable or off all mean off. Only they turn it on (``PUT
@@ -19,6 +23,7 @@ is anyone's words. And the first week's private brief lists today's meetings
(``briefing.first_week``). And a reply card whose open question is when to
meet offers their next free slots (``delegation.answers.free_slots``): only
the busy times are used, in code, and no event's title reaches a model.
+And an invite card's clashes (``delegation.invites.clashes``), the same way.
Nothing is kept: each read asks the calendar again.
"""
from __future__ import annotations
diff --git a/packages/core/openexecutive/delegation/gmail.py b/packages/core/openexecutive/delegation/gmail.py
index 03f0c531..0525976b 100644
--- a/packages/core/openexecutive/delegation/gmail.py
+++ b/packages/core/openexecutive/delegation/gmail.py
@@ -13,9 +13,12 @@ named from a hash of the address and written by
{refresh_token, client_id, client_secret, token_uri}}``. It is never in
``WORKSPACE_MCP_CREDENTIALS_DIR`` — workspace-mcp picks a credential there by
address, which would hand the model this mailbox. Scopes: ``gmail.readonly``
-and ``gmail.compose``, and ``calendar.readonly`` when they connected with
+and ``gmail.compose``, and a calendar scope when they connected with
``--calendar`` for Read my calendar (``delegation.calendar``; ``list_events``
-refuses with ``CalendarNotGranted`` without it).
+refuses with ``CalendarNotGranted`` without it): ``calendar.events`` now,
+which also lets it answer a meeting invite as them (``answer_invite``,
+``delegation.invites``); a sign-in made with ``calendar.readonly`` before
+keeps reading, and ``answer_invite`` refuses with ``CalendarWriteNotGranted``.
**One way to send.** It reads mail and saves or deletes drafts. The only
send is ``send_draft``: an existing draft, by its id, exactly as it is in
@@ -67,6 +70,13 @@ SCOPE_COMPOSE = "https://www.googleapis.com/auth/gmail.compose"
SCOPES: tuple[str, ...] = (SCOPE_READONLY, SCOPE_COMPOSE)
# Read my calendar (delegation.calendar): optional, so a mail-only sign-in still works.
SCOPE_CALENDAR = "https://www.googleapis.com/auth/calendar.readonly"
+# What --calendar asks for now: reads, and answers a meeting invite as them
+# (delegation.invites). Either scope reads; only this one (or the full
+# calendar scope) answers.
+SCOPE_CALENDAR_EVENTS = "https://www.googleapis.com/auth/calendar.events"
+_SCOPE_CALENDAR_FULL = "https://www.googleapis.com/auth/calendar"
+CALENDAR_READ_SCOPES = frozenset({SCOPE_CALENDAR, SCOPE_CALENDAR_EVENTS, _SCOPE_CALENDAR_FULL})
+CALENDAR_WRITE_SCOPES = frozenset({SCOPE_CALENDAR_EVENTS, _SCOPE_CALENDAR_FULL})
CALENDAR_BASE = "https://www.googleapis.com/calendar/v3/calendars/primary"
CREDENTIAL_VERSION = 1
PROVIDER = "google"
@@ -121,6 +131,8 @@ STATUS_MESSAGES: dict[str, str] = {
# Gmail ids are short hex strings; anything else never reaches a URL path.
_ID_RE = re.compile(r"[A-Za-z0-9_-]{1,64}")
+# Google Calendar event ids: base32hex, with an instance's "_" suffix.
+_EVENT_ID_RE = re.compile(r"[A-Za-z0-9_]{1,1024}")
# A forward's attached files, at most (Gmail's own message limit is 25 MB).
FORWARD_MAX_FILES = 10
FORWARD_MAX_BYTES = 20 * 1024 * 1024
@@ -179,6 +191,16 @@ class CalendarNotGranted(GmailError):
they connected without it (``--calendar``), or took it back."""
+class CalendarWriteNotGranted(GmailError):
+ """Their saved sign-in reads their calendar but can't answer an invite:
+ it was made with read-only access (``calendar.readonly``,
+ ``Calendars.Read``). Connecting again with ``--calendar`` adds it."""
+
+
+class GmailChanged(GmailError):
+ """The item changed since it was read (an ``If-Match`` didn't match)."""
+
+
class GmailAuthError(GmailError):
"""Google refused the credential: revoked, expired, or missing a scope."""
@@ -311,6 +333,12 @@ class MailMessage:
# sender's own mail app put it ("" for none). Names a contact the
# person writes to (``people.contact_keeper``).
names: dict[str, str] = field(default_factory=dict)
+ # A calendar invite's own iCalendar method (REQUEST, CANCEL, REPLY, ...)
+ # and event UID, from its text/calendar part ("" when it has none, or
+ # it is only attached as a file). Outlook leaves them empty: Graph
+ # names the event itself (``find_invite``).
+ invite_method: str = ""
+ invite_uid: str = ""
@dataclass
@@ -600,6 +628,47 @@ _BULK_PRECEDENCE = frozenset({"bulk", "junk", "list", "auto_reply"})
# Set by out-of-office and other auto-responders.
_AUTOREPLY_HEADERS = ("x-autoreply", "x-autorespond", "x-autoresponder")
_CALENDAR_TYPES = frozenset({"text/calendar", "application/ics"})
+_ICS_UID_MAX = 1024
+
+
+def ics_invite(text: str) -> tuple[str, str]:
+ """An iCalendar text's method and its first event's UID, ``("", "")``
+ when it has neither. Only these two are read: nothing else in the file
+ (its title, its description) is used from here."""
+ unfolded = re.sub(r"\r?\n[ \t]", "", text or "")
+ method = uid = ""
+ in_event = False
+ for line in unfolded.splitlines():
+ name, sep, value = line.partition(":")
+ if not sep:
+ continue
+ key = name.split(";", 1)[0].strip().upper()
+ if key == "BEGIN" and value.strip().upper() == "VEVENT":
+ in_event = True
+ elif key == "END" and value.strip().upper() == "VEVENT":
+ if uid:
+ break
+ in_event = False
+ elif key == "METHOD" and not in_event and not method:
+ method = value.strip().upper()[:20]
+ elif key == "UID" and in_event and not uid:
+ candidate = value.strip()
+ if 0 < len(candidate) <= _ICS_UID_MAX and candidate.isprintable():
+ uid = candidate
+ return method, uid
+
+
+def _invite_part(payload: dict[str, Any]) -> tuple[str, str]:
+ """The method and UID of the message's inline text/calendar part."""
+ stack = [payload]
+ while stack:
+ part = stack.pop(0)
+ if str(part.get("mimeType") or "").lower() in _CALENDAR_TYPES:
+ found = ics_invite(_part_text(part))
+ if found[1]:
+ return found
+ stack.extend(p for p in part.get("parts") or [] if isinstance(p, dict))
+ return "", ""
def _header_message(payload: dict[str, Any]) -> Message:
@@ -677,6 +746,7 @@ def parse_message(raw: dict[str, Any]) -> MailMessage:
types = _part_types(payload)
local_part = normalize_email(from_addr).partition("@")[0]
attachments = _attachments(payload)
+ invite_method, invite_uid = _invite_part(payload) if types & _CALENDAR_TYPES else ("", "")
return MailMessage(
id=str(raw.get("id") or ""),
thread_id=str(raw.get("threadId") or ""),
@@ -704,6 +774,8 @@ def parse_message(raw: dict[str, Any]) -> MailMessage:
attachments=attachments,
has_attachments=bool(attachments),
names=_names(headers.get("to", ""), headers.get("cc", "")),
+ invite_method=invite_method,
+ invite_uid=invite_uid,
)
@@ -917,15 +989,19 @@ class DelegateGmail:
params: Any = None,
json_body: dict[str, Any] | None = None,
base: str = GMAIL_BASE,
+ if_match: str | None = None,
) -> dict[str, Any]:
token = await self._access_token(client)
+ headers = {"Authorization": f"Bearer {token}"}
+ if if_match:
+ headers["If-Match"] = if_match
try:
resp = await client.request(
method,
f"{base}{path}",
params=params,
json=json_body,
- headers={"Authorization": f"Bearer {token}"},
+ headers=headers,
)
except (httpx.ConnectError, httpx.ConnectTimeout) as exc:
# Never reached Google: nothing was done.
@@ -941,6 +1017,8 @@ class DelegateGmail:
raise GmailRateLimited(f"gmail {method} returned {resp.status_code}")
if resp.status_code == 404:
raise GmailNotFound(f"gmail {method} returned 404")
+ if resp.status_code == 412:
+ raise GmailChanged(f"gmail {method} returned 412")
if resp.status_code >= 500:
raise GmailError(f"gmail {method} returned {resp.status_code}", maybe_done=True)
if resp.status_code >= 400:
@@ -1244,21 +1322,32 @@ class DelegateGmail:
)
+ async def _granted_scopes(self, client: httpx.AsyncClient) -> str:
+ await self._access_token(client)
+ return _GRANTED.get(_token_key(self._cred()), "")
+
async def calendar_granted(self) -> bool | None:
- """Whether their saved sign-in includes ``calendar.readonly``; None
- when Google didn't say which scopes it carries."""
+ """Whether their saved sign-in reads their calendar
+ (``calendar.readonly`` or ``calendar.events``); None when Google
+ didn't say which scopes it carries."""
+ async with self._client() as client:
+ granted = await self._granted_scopes(client)
+ return bool(CALENDAR_READ_SCOPES & set(granted.split())) if granted else None
+
+ async def calendar_write_granted(self) -> bool | None:
+ """Whether their saved sign-in can answer a meeting invite
+ (``calendar.events``); None when Google didn't say."""
async with self._client() as client:
- await self._access_token(client)
- granted = _GRANTED.get(_token_key(self._cred()), "")
- return SCOPE_CALENDAR in granted.split() if granted else None
+ granted = await self._granted_scopes(client)
+ return bool(CALENDAR_WRITE_SCOPES & set(granted.split())) if granted else None
async def list_events(self, start: datetime, end: datetime, *, max_results: int = MAX_EVENTS) -> list[CalendarEvent]:
"""The events on their primary calendar between ``start`` and ``end``,
- recurring ones expanded, in order. Read-only (``calendar.readonly``)."""
+ recurring ones expanded, in order. A read (``calendar.readonly`` or
+ ``calendar.events``)."""
async with self._client() as client:
- await self._access_token(client)
- granted = _GRANTED.get(_token_key(self._cred()), "")
- if granted and SCOPE_CALENDAR not in granted.split():
+ granted = await self._granted_scopes(client)
+ if granted and not CALENDAR_READ_SCOPES & set(granted.split()):
raise CalendarNotGranted("calendar.readonly not granted")
params = {
"timeMin": start.astimezone(UTC).isoformat().replace("+00:00", "Z"),
@@ -1274,7 +1363,7 @@ class DelegateGmail:
raise
# With the scope granted, a refusal is the project's (the API
# not enabled, a quota), and reconnecting wouldn't fix it.
- if SCOPE_CALENDAR in granted.split():
+ if CALENDAR_READ_SCOPES & set(granted.split()):
raise GmailError("calendar read refused with the scope granted") from exc
raise CalendarNotGranted("calendar read refused") from exc
items_raw = data.get("items")
@@ -1282,6 +1371,98 @@ class DelegateGmail:
events = [parse_google_event(item) for item in items if isinstance(item, dict)]
return [e for e in events if e is not None]
+ async def _invite_uid(self, message: MailMessage) -> tuple[str, str]:
+ """The invite's method and UID: from its inline part, else from its
+ attached .ics file."""
+ if message.invite_uid:
+ return message.invite_method, message.invite_uid
+ for attachment in message.attachments:
+ if attachment.mime_type in _CALENDAR_TYPES or attachment.name.lower().endswith(".ics"):
+ _meta, data = await self.attachment_bytes(message.id, attachment.index)
+ found = ics_invite(data[:200_000].decode("utf-8", errors="replace"))
+ if found[1]:
+ return found
+ return "", ""
+
+ async def find_invite(self, message: MailMessage) -> CalendarEvent | None:
+ """The event a meeting invite ``message`` asks them to, as it is on
+ their own primary calendar (found by its iCalendar UID), or None:
+ not a request (a cancellation, someone's answer), or not on their
+ calendar. A read."""
+ method, uid = await self._invite_uid(message)
+ if not uid or method not in ("", "REQUEST"):
+ return None
+ async with self._client() as client:
+ granted = await self._granted_scopes(client)
+ if granted and not CALENDAR_READ_SCOPES & set(granted.split()):
+ raise CalendarNotGranted("calendar.readonly not granted")
+ try:
+ data = await self._request(
+ client, "GET", "/events", params={"iCalUID": uid, "maxResults": "5"}, base=CALENDAR_BASE,
+ )
+ except GmailAuthError as exc:
+ if str(exc) != "forbidden":
+ raise
+ if CALENDAR_READ_SCOPES & set(granted.split()):
+ raise GmailError("calendar read refused with the scope granted") from exc
+ raise CalendarNotGranted("calendar read refused") from exc
+ items_raw = data.get("items")
+ items: list[Any] = items_raw if isinstance(items_raw, list) else []
+ for item in items:
+ if isinstance(item, dict) and _EVENT_ID_RE.fullmatch(str(item.get("id") or "")):
+ event = parse_google_event(item)
+ if event is not None:
+ return event
+ return None
+
+ async def answer_invite(self, event_id: str, *, accept: bool) -> None:
+ """Answer the invite to ``event_id`` on their primary calendar, as
+ them: their own attendee entry's answer becomes accepted or declined,
+ and Google tells the organizer (``sendUpdates=all``). Nothing else on
+ the event changes: the write carries the event's ``etag``, so a change
+ made since it was read (a guest added, another answer) is read again
+ rather than overwritten, once. Called only by ``delegation.invites``,
+ on the person's tap or under Handle it for me (accept only).
+ Answering twice is the same as once. Raises ``CalendarWriteNotGranted`` for a
+ read-only sign-in, ``GmailNotFound`` when the event or their place on
+ it is gone."""
+ if not _EVENT_ID_RE.fullmatch(event_id or ""):
+ raise GmailError("invalid event id")
+ async with self._client() as client:
+ granted = await self._granted_scopes(client)
+ if granted and not CALENDAR_WRITE_SCOPES & set(granted.split()):
+ raise CalendarWriteNotGranted("calendar.events not granted")
+ path = f"/events/{event_id}"
+ try:
+ for attempt in range(2):
+ event = await self._request(client, "GET", path, base=CALENDAR_BASE)
+ attendees = [dict(a) for a in event.get("attendees") or [] if isinstance(a, dict)]
+ mine = next((a for a in attendees if a.get("self") is True), None)
+ if mine is None:
+ mine = next(
+ (a for a in attendees if normalize_email(str(a.get("email") or "")) == self.email),
+ None,
+ )
+ if mine is None:
+ raise GmailNotFound("not an attendee")
+ mine["responseStatus"] = "accepted" if accept else "declined"
+ try:
+ await self._request(
+ client, "PATCH", path, params={"sendUpdates": "all"},
+ json_body={"attendees": attendees}, base=CALENDAR_BASE,
+ if_match=str(event.get("etag") or "") or None,
+ )
+ return
+ except GmailChanged:
+ if attempt:
+ raise
+ except GmailAuthError as exc:
+ if str(exc) != "forbidden":
+ raise
+ if CALENDAR_WRITE_SCOPES & set(granted.split()):
+ raise GmailError("calendar write refused with the scope granted") from exc
+ raise CalendarWriteNotGranted("calendar write refused") from exc
+
def gmail_for(email: str) -> Any:
"""The client for ``email``'s own mailbox: ``DelegateGmail``, or
diff --git a/packages/core/openexecutive/delegation/handle_it.py b/packages/core/openexecutive/delegation/handle_it.py
index 54e25a41..c02a673b 100644
--- a/packages/core/openexecutive/delegation/handle_it.py
+++ b/packages/core/openexecutive/delegation/handle_it.py
@@ -53,6 +53,12 @@ with the reason recorded.
Never sent on its own whatever the setting: anything with an attachment (the
watcher's drafts have none), a new recipient, or a sensitive topic.
+**Meeting invites.** It also accepts a meeting invite on its own
+(``delegation.invites``, never a decline) from someone the person knows,
+when nothing on their calendar clashes and their sign-in can answer
+invites; it counts against the same daily limit and once-a-day-per-thread
+rule (``count_refusal``), and is listed with the replies (``handled``).
+
**After.** A reply sent on its own is a ``delegation_reply`` decision in
status ``executed`` with ``gate_mode`` ``auto_execute``; ``handled`` lists the
person's recent ones (``GET /delegation/handled``), theirs alone, with the
@@ -178,6 +184,11 @@ REASONS: dict[str, str] = {
# In training (delegation.training).
"training": "Replies are in training, and you haven't allowed replies to them yet.",
"follow_up_training": "Follow-ups are in training, and you haven't allowed follow-ups to them yet.",
+ # Meeting invites (delegation.invites).
+ "clash": "It clashes with something already on your calendar.",
+ "calendar_unread": "It couldn't check your calendar for clashes, so it asked instead.",
+ "calendar_write": "Your calendar sign-in can't answer invites yet. Connect it again under Read my calendar.",
+ "invite_training": "Replies are in training, and you haven't let it accept their invites on its own yet.",
}
# Take the lead as you lifts the setting's limits, but not this ceiling.
@@ -584,6 +595,9 @@ class HandledReply:
open_questions: list[str]
thread_id: str
source: str = ""
+ # One line saying what it did, for an accepted invite: "Accepted Dana's
+ # Pilot review, Wed 21 Oct, 14:30".
+ summary: str = ""
def handled(person_id: int, *, days: int = 7, limit: int = 50) -> list[HandledReply]:
@@ -615,5 +629,8 @@ def handled(person_id: int, *, days: int = 7, limit: int = 50) -> list[HandledRe
thread_id=str(payload.get("thread_id") or ""),
source="follow_up" if payload.get("source") == "follow_up" else "",
))
+ from openexecutive.delegation import invites
+
+ out.extend(invites.handled(person_id, since=since, limit=limit))
out.sort(key=lambda h: h.sent_at, reverse=True)
return out[:limit]
diff --git a/packages/core/openexecutive/delegation/inbox.py b/packages/core/openexecutive/delegation/inbox.py
index c89df229..c2591c90 100644
--- a/packages/core/openexecutive/delegation/inbox.py
+++ b/packages/core/openexecutive/delegation/inbox.py
@@ -27,7 +27,8 @@ still need a look, settled ones passed over first. Each is recorded once in
- it is from the person or one of their send-as addresses, from the
Executive, or one of this package's own drafts;
- it is automatic, bulk, a bounce or a calendar invite, or from a mailing
- list;
+ list (with Read my calendar on, an invite goes to ``delegation.invites``
+ instead: a card to accept or decline it, from someone the person knows);
- the person is not in To or Cc, or it has more than 10 recipients;
- the person replied last, or a draft already sits in the thread.
@@ -180,8 +181,11 @@ class ScanResult:
deferred: int = 0
failed: int = 0
closed: int = 0
- # Replies sent on their own under Handle it for me (delegation.handle_it).
+ # Replies sent on their own under Handle it for me (delegation.handle_it),
+ # and invites accepted on their own (delegation.invites).
handled: int = 0
+ # Meeting invite cards made (delegation.invites).
+ invites: int = 0
def counts(self) -> dict[str, Any]:
return asdict(self)
@@ -1050,13 +1054,16 @@ async def _scan(person: Any, client: Any, watch: InboxWatch, now: datetime) -> S
email = (person.email or "").strip().lower()
own = {email, *await client.send_as_addresses()}
exec_address = (get_settings().exec_email_address or "").strip().lower()
+ from openexecutive.delegation import invites
+
result = ScanResult("ok")
result.closed = await reconcile(person, client, now=now, own=own)
+ result.closed += invites.reconcile(person.id, now=now)
cards = open_cards(person.id)
if len(cards) >= OPEN_CARDS_MAX:
result.status = "backlog_full"
return result
- carded = {str(card_payload(c).get("thread_id") or "") for c in cards}
+ carded = {str(card_payload(c).get("thread_id") or "") for c in cards} | invites.carded_threads(person.id)
since = _parse(watch.watch_since) or now
listed = await client.inbox_message_ids(after=since, max_results=SCAN_LIST)
# The newest message of each thread that still needs a look, newest
@@ -1121,7 +1128,7 @@ async def _consider(
Once claimed, a message is finished or left for a later scan
(``_retry_later``); a Gmail failure is raised for the scan to back off."""
from openexecutive.config import get_settings
- from openexecutive.delegation import caps, card_drafts, drafts, handle_it
+ from openexecutive.delegation import caps, card_drafts, drafts, handle_it, invites
from openexecutive.delegation import disclosure as ai_disclosure
from openexecutive.delegation.ghostwriter import ComposeError
from openexecutive.delegation.gmail import DraftSpec, GmailError
@@ -1140,6 +1147,15 @@ async def _consider(
received = _parse(message.received_at)
if received is not None and now - received < GRACE:
return False # not yet: mail they answer straight away never gets a card
+ if message.calendar_invite and invites.watching(person.id):
+ # A meeting invite: a card to accept or decline it (Read my calendar on).
+ reason = invites.skip_reason(message, own=own, exec_address=exec_address, watch_since=since, now=now)
+ if reason is not None:
+ if _claim(person.id, message, relation="", outcome=SKIPPED, reason=reason, now=now):
+ result.skipped += 1
+ return False
+ await invites.consider(person, client, message, thread, now=now, result=result)
+ return False
reason = skip_reason(message, thread, own=own, exec_address=exec_address, watch_since=since, now=now)
if reason is not None:
if _claim(person.id, message, relation="", outcome=SKIPPED, reason=reason, now=now):
@@ -1321,28 +1337,23 @@ def _create_card(
kept: dict[str, Any] | None = None,
) -> int | None:
"""The card for this reply, made once per message (its idempotency key):
- a second call for the same message finds the one the first made. A card
- Handle it for me will send is ``auto_execute``; every other is ``propose``."""
- from openexecutive.memory.decision_ledger import create_decision_instance, get_live_by_idem
-
- key = f"{DECISION_CLASS}:{person.id}:{message.id}"
- try:
- return create_decision_instance(
- decision_class=DECISION_CLASS,
- department="",
- originating_session_id=None,
- proposed_payload=_card_payload(
- person, message, thread, reply, draft, relation=relation, handled_as=handled_as, verdict=verdict,
- handle_it_reason=handle_it_reason, source=source,
- ) | (kept or {}),
- idempotency_key=key,
- gate_mode="auto_execute" if on_its_own else "propose",
- approver_person_id=person.id,
- confidence=verdict.confidence,
- )
- except sqlite3.IntegrityError:
- existing = get_live_by_idem(key)
- return existing.id if existing is not None else None
+ a second call for the same message finds the open one the first made, a
+ card dismissed or lapsed under that key doesn't stop a new one, and one
+ sent or settled in the mailbox means None (``invites.create_once``). A card Handle it for me
+ will send is ``auto_execute``; every other is ``propose``."""
+ from openexecutive.delegation.invites import create_once
+
+ return create_once(
+ DECISION_CLASS,
+ f"{DECISION_CLASS}:{person.id}:{message.id}",
+ _card_payload(
+ person, message, thread, reply, draft, relation=relation, handled_as=handled_as, verdict=verdict,
+ handle_it_reason=handle_it_reason, source=source,
+ ) | (kept or {}),
+ approver_person_id=person.id,
+ gate_mode="auto_execute" if on_its_own else "propose",
+ confidence=verdict.confidence,
+ )
# --------------------------------------------------------------------------- #
diff --git a/packages/core/openexecutive/delegation/invites.py b/packages/core/openexecutive/delegation/invites.py
new file mode 100644
index 00000000..aa7c0b4e
--- /dev/null
+++ b/packages/core/openexecutive/delegation/invites.py
@@ -0,0 +1,861 @@
+"""Act as me: meeting invites, answered from a card or on their own.
+
+The inbox watcher (``delegation.inbox``) used to skip every calendar invite.
+With Read my calendar on (``delegation.calendar``), an invite from someone the
+person knows becomes a card on Home instead: who invited them, the meeting's
+title, when it is, and any clash with their calendar. **Accept** and
+**Decline** answer it in their own calendar, as them.
+
+**Which invites.** A meeting request (not a cancellation, nor someone's
+answer) in the inbox since the watcher was turned on, addressed to the
+person, from someone they know: their team, one of their contacts, or
+someone they have written to (``inbox.relation_of``), and only when the mail
+service confirmed the sender (``inbox.handling_relation``). The event must be
+on their own calendar (Google: found by the invite's iCalendar UID in their
+primary calendar; Outlook: the invite message's own event), organized by the
+sender, not answered yet and still ahead. Anything else is left alone as
+before: skipped and recorded with its reason (``invite_stranger``,
+``invite_unverified``, ``invite_not_found``, ...). With Read my calendar off
+nothing here runs: an invite is skipped as ``automatic``, as it always was.
+
+**Clashes.** The busy times on their calendar that overlap the meeting,
+computed in code from the calendar read (``calendar.events_for``): only the
+times reach the card, never another event's title, and no model is called
+anywhere in this module.
+
+**Answering.** ``answer``, on the card's person's tap (``POST
+/decisions/{id}/approve`` with ``edits.answer`` ``accept`` or ``decline``;
+the caller checks reply cards use, ``verified.caller_refusal``), claims the
+card and calls the mailbox client's ``answer_invite``: on Google their own
+attendee entry's answer, with the organizer told (``sendUpdates=all``); on
+Outlook Graph's event accept or decline (``sendResponse``). Dismiss
+(``reject``) answers nothing. A sign-in that only reads the calendar keeps
+reading; its card says to connect again under Read my calendar instead of
+offering Accept (``can_answer``).
+
+**On their own.** With Handle it for me on, or Take the lead as you, an
+invite is accepted with no tap when plain code finds nothing against it
+(``refusal``): the sender is someone they know (and, with Replies in
+training, one they ticked "Accept from them on its own next time" for),
+signed sign-ins or local login, nothing clashes, nothing sensitive in the
+title, their sign-in can answer, and the daily limit and once-a-day-per-thread
+rule of Handle it for me (``handle_it.count_refusal``) allow it. It never
+declines on its own. Accepted ones are listed with the replies it sent
+(``handled``: ``GET /delegation/handled``, Today's ``sent_as_you``), the
+person's alone.
+
+**Cards.** A ``delegation_invite`` decision, its person's alone
+(``approver_only``) and never an alert, like a reply card. Closed once the
+meeting has started or after ``CARD_TTL``. Every row it writes is private.
+"""
+from __future__ import annotations
+
+import asyncio
+import json
+import logging
+import sqlite3
+import uuid
+from dataclasses import dataclass, field
+from datetime import UTC, datetime, timedelta, tzinfo
+from email.utils import parseaddr
+from typing import Any
+
+logger = logging.getLogger(__name__)
+
+DECISION_CLASS = "delegation_invite"
+SOURCE = "invite"
+CARD_TTL = timedelta(days=7)
+OPEN_CARDS_MAX = 25
+TITLE_MAX = 200
+_CALENDAR_TIMEOUT_S = 10.0
+ANSWERS = ("accept", "decline")
+
+# What happened to an invite (delegation_inbox_messages.outcome).
+CARDED = "invite_card"
+ACCEPTED = "accepted"
+DECLINED = "declined"
+
+# Labels that mean the mail service filed it away.
+# A settled card under a message's key lets a new card be made for it only
+# when it was dismissed or lapsed; sent, answered or settled means done.
+# Who an invite is accepted from with no tap and no allowance: their team and
+# contacts, never a sender known only from their Sent mail.
+ON_ITS_OWN_RELATIONS = frozenset({"team", "contact"})
+RENEW_AFTER = frozenset({"rejected", "auto_no_response"})
+_FILED = frozenset({"SPAM", "TRASH"})
+_NO_REPLY_SENDERS = ("noreply", "no-reply", "do-not-reply", "donotreply", "mailer-daemon", "postmaster")
+
+
+class AnswerRefused(Exception):
+ """Why answering was refused: an HTTP status, a code and what to tell them."""
+
+ def __init__(self, status: int, code: str, message: str) -> None:
+ super().__init__(message)
+ self.status = status
+ self.code = code
+ self.message = message
+
+
+@dataclass
+class InviteCard:
+ """One invite waiting for its person, for ``GET /delegation/invites``."""
+
+ decision_id: int
+ status: str
+ created_at: str
+ from_name: str
+ from_email: str
+ relation: str
+ title: str
+ when: str
+ start: str
+ end: str
+ all_day: bool
+ clashes: list[str] = field(default_factory=list)
+ # False: the calendar couldn't be read for clashes.
+ clash_checked: bool = True
+ # False: their sign-in reads the calendar but can't answer invites.
+ can_answer: bool = True
+ # In training: the "Accept from them on its own next time" tick.
+ can_allow: bool = False
+ # Why it didn't accept on its own (Handle it for me on), in words.
+ waited_because: str = ""
+ connect_command: str = ""
+
+
+# --------------------------------------------------------------------------- #
+# Small helpers
+# --------------------------------------------------------------------------- #
+
+
+def _now() -> datetime:
+ return datetime.now(UTC)
+
+
+def _moment(value: str) -> datetime | None:
+ try:
+ parsed = datetime.fromisoformat(str(value or "").replace("Z", "+00:00"))
+ except ValueError:
+ return None
+ return parsed if parsed.tzinfo else parsed.replace(tzinfo=UTC)
+
+
+def _tz() -> tzinfo:
+ try:
+ from openexecutive.memory.workspace_settings import get_user_timezone
+
+ return get_user_timezone()
+ except Exception:
+ return UTC
+
+
+def when_text(start: str, end: str, all_day: bool, tz: tzinfo | None = None) -> str:
+ """When the meeting is, as the person reads it: "Wed 21 Oct, 14:30–15:00",
+ or "Wed 21 Oct, all day"."""
+ zone = tz or _tz()
+ if all_day:
+ try:
+ day = datetime.fromisoformat(start[:10])
+ except ValueError:
+ return start[:10]
+ return f"{day:%a} {day.day} {day:%b}, all day"
+ s, e = _moment(start), _moment(end)
+ if s is None:
+ return start[:25]
+ s = s.astimezone(zone)
+ text = f"{s:%a} {s.day} {s:%b}, {s:%H:%M}"
+ if e is not None:
+ e = e.astimezone(zone)
+ text += f"–{e:%H:%M}" if e.date() == s.date() else f" – {e:%a} {e.day} {e:%b}, {e:%H:%M}"
+ return text
+
+
+def short_when(start: str, all_day: bool, tz: tzinfo | None = None) -> str:
+ """The start alone: "Wed 21 Oct, 14:30"."""
+ return when_text(start, start, all_day, tz).split("–")[0]
+
+
+def _first_name(name: str, email: str) -> str:
+ return (name or "").split()[0] if (name or "").split() else email
+
+
+def _payload(card: Any) -> dict[str, Any]:
+ try:
+ payload = json.loads(card.proposed_payload_json)
+ except (TypeError, ValueError):
+ return {}
+ return payload if isinstance(payload, dict) else {}
+
+
+def _audit(event_type: str, summary: str, details: dict[str, Any]) -> None:
+ from openexecutive.delegation.inbox import _audit as inbox_audit
+
+ inbox_audit(event_type, summary, details)
+
+
+def watching(person_id: int | None) -> bool:
+ """Whether invites get cards for ``person_id``: Read my calendar on."""
+ from openexecutive.delegation import calendar
+
+ return calendar.enabled(person_id)
+
+
+def skip_reason(message: Any, *, own: set[str], exec_address: str, watch_since: datetime, now: datetime) -> str | None:
+ """Why an invite gets no card, or None: the watcher's own rules
+ (``inbox.skip_reason``), less the ones about writing a reply. A calendar
+ service sends invites with its own Sender header, so that alone isn't
+ "automatic"."""
+ from openexecutive.delegation.inbox import STALE, _parse
+
+ received = _parse(message.received_at)
+ if received is None or received < watch_since:
+ return "before_watch"
+ if now - received > STALE:
+ return "stale"
+ sender = message.from_addr
+ if not sender:
+ return "no_sender"
+ if sender in own:
+ return "from_you"
+ if exec_address and sender == exec_address:
+ return "from_executive"
+ if message.ghostwritten:
+ return "ours"
+ if message.delivery_report or any(mark in sender.partition("@")[0] for mark in _NO_REPLY_SENDERS):
+ return "automatic"
+ if message.mailing_list:
+ return "mailing_list"
+ if set(message.labels) & _FILED:
+ return "category"
+ if not {*message.to, *message.cc} & own:
+ return "not_addressed"
+ return None
+
+
+# --------------------------------------------------------------------------- #
+# Cards
+# --------------------------------------------------------------------------- #
+
+
+def open_cards(person_id: int) -> list[Any]:
+ """``person_id``'s open invite cards (waiting, or being answered), newest first."""
+ from openexecutive.memory.decision_ledger import OPEN_STATUSES, list_instances
+
+ found = [
+ c for status in OPEN_STATUSES
+ for c in list_instances(DECISION_CLASS, status=status, approver_person_id=person_id, limit=1000)
+ ]
+ return sorted(found, key=lambda c: c.created_at, reverse=True)
+
+
+def _live(payload: dict[str, Any], created_at: str, now: datetime) -> bool:
+ created = _moment(created_at)
+ start = _moment(str(payload.get("start") or ""))
+ if created is not None and now - created > CARD_TTL:
+ return False
+ return start is None or start > now
+
+
+def create_card(key: str, payload: dict[str, Any], *, person_id: int, on_its_own: bool) -> int | None:
+ """The card for one invite, made once per message (``key``): see
+ ``create_once``. None when the invite was already answered."""
+ return create_once(
+ DECISION_CLASS, key, payload, approver_person_id=person_id,
+ gate_mode="auto_execute" if on_its_own else "propose",
+ )
+
+
+def create_once(
+ decision_class: str, key: str, payload: dict[str, Any], *, approver_person_id: int, gate_mode: str,
+ confidence: float | None = None,
+) -> int | None:
+ """Create a card under idempotency ``key``: the open one already under it,
+ if any, else a new one. When a settled card holds the key, a new one is
+ made (under the key with a fresh suffix) only if that card was dismissed
+ or left to lapse: one that was sent, answered or settled in the mailbox
+ means the message is done, and the answer is None. One scan per person
+ at a time, so two new cards never race for one message."""
+ from openexecutive.memory.decision_ledger import create_decision_instance, get_live_by_idem
+
+ def make(idem: str) -> int:
+ return create_decision_instance(
+ decision_class=decision_class, department="", originating_session_id=None,
+ proposed_payload=payload, idempotency_key=idem, gate_mode=gate_mode,
+ approver_person_id=approver_person_id, confidence=confidence,
+ )
+
+ try:
+ return make(key)
+ except sqlite3.IntegrityError:
+ existing = get_live_by_idem(key)
+ if existing is not None:
+ return existing.id
+ if _last_status(key) not in RENEW_AFTER:
+ return None
+ return make(f"{key}:{uuid.uuid4().hex[:12]}")
+
+
+def _last_status(key: str) -> str | None:
+ """The status of the newest card under ``key`` (or its suffixed ones)."""
+ from openexecutive.memory.decision_ledger import _db_path, _get_conn
+
+ with _get_conn(_db_path()) as conn:
+ row = conn.execute(
+ "SELECT status FROM decision_instances WHERE idempotency_key = ? "
+ "OR substr(idempotency_key, 1, ?) = ? ORDER BY id DESC LIMIT 1",
+ (key, len(key) + 1, f"{key}:"),
+ ).fetchone()
+ return str(row[0]) if row is not None else None
+
+
+def cards(person: Any, *, now: datetime | None = None) -> list[InviteCard]:
+ """``person``'s invite cards still waiting, for ``GET /delegation/invites``."""
+ from openexecutive.delegation import handle_it, training
+
+ at = now or _now()
+ trained = training.get(person.id).replies
+ out: list[InviteCard] = []
+ for card in open_cards(person.id):
+ payload = _payload(card)
+ if payload.get("person_id") != person.id or not _live(payload, card.created_at, at):
+ continue
+ sender = str(payload.get("from_email") or "")
+ can_answer = payload.get("can_answer") is not False
+ out.append(InviteCard(
+ decision_id=card.id,
+ status=card.status,
+ created_at=card.created_at,
+ from_name=str(payload.get("from_name") or ""),
+ from_email=sender,
+ relation=str(payload.get("relation") or ""),
+ title=str(payload.get("title") or ""),
+ when=when_text(str(payload.get("start") or ""), str(payload.get("end") or ""),
+ payload.get("all_day") is True),
+ start=str(payload.get("start") or ""),
+ end=str(payload.get("end") or ""),
+ all_day=payload.get("all_day") is True,
+ clashes=[str(c) for c in payload.get("clashes") or [] if isinstance(c, str)],
+ clash_checked=payload.get("clash_checked") is not False,
+ can_answer=can_answer,
+ can_allow=bool(
+ trained and can_answer and sender and training.allowed_inviter(person.id, sender) is None
+ ),
+ waited_because=handle_it.REASONS.get(str(payload.get("handle_it_reason") or ""), ""),
+ connect_command=str(payload.get("connect_command") or ""),
+ ))
+ return out
+
+
+def reconcile(person_id: int, *, now: datetime) -> int:
+ """Close ``person_id``'s waiting invite cards whose meeting has started,
+ or that are older than ``CARD_TTL``. Returns how many closed."""
+ from openexecutive.delegation.inbox import EXPIRED, _set_outcome
+ from openexecutive.memory.decision_ledger import STATUS_PROPOSED, close_externally
+
+ closed = 0
+ for card in open_cards(person_id):
+ payload = _payload(card)
+ if card.status != STATUS_PROPOSED or _live(payload, card.created_at, now):
+ continue
+ if close_externally(card.id, reason="expired"):
+ _set_outcome(person_id, str(payload.get("message_id") or ""), EXPIRED, reason="expired")
+ closed += 1
+ return closed
+
+
+def carded_threads(person_id: int) -> set[str]:
+ """The threads an open invite card is for: the watcher leaves them until
+ the card is settled."""
+ return {str(_payload(c).get("thread_id") or "") for c in open_cards(person_id)}
+
+
+# --------------------------------------------------------------------------- #
+# Clashes and the rules for accepting on its own
+# --------------------------------------------------------------------------- #
+
+
+async def clashes(mailbox: Any, event: Any, *, tz: tzinfo | None = None) -> list[str] | None:
+ """The busy times on the person's calendar that overlap ``event``, as
+ "14:00–14:30" in their time zone; None when the calendar couldn't be
+ read. Only start and end times are used: no other event's title or
+ words leave this function."""
+ from openexecutive.delegation import calendar
+
+ if getattr(event, "all_day", False):
+ return []
+ start, end = _moment(event.start), _moment(event.end)
+ if start is None or end is None or end <= start:
+ return []
+ zone = tz or _tz()
+ try:
+ found = await asyncio.wait_for(calendar.events_for(mailbox, start, end), timeout=_CALENDAR_TIMEOUT_S)
+ except Exception as exc:
+ logger.info("delegation.invites: couldn't read the calendar for clashes (%s)", type(exc).__name__)
+ return None
+ out: list[str] = []
+ for other in found:
+ other_id = str(getattr(other, "id", "") or "")
+ if other_id and (other_id == event.id or other_id.startswith(f"{event.id}_")):
+ continue # the meeting itself (or one of its own occurrences)
+ if getattr(other, "all_day", False) or getattr(other, "response", "") == "declined":
+ continue
+ s, e = _moment(getattr(other, "start", "")), _moment(getattr(other, "end", ""))
+ if s is None or e is None or not (s < end and e > start):
+ continue
+ if s == start and e == end and getattr(other, "title", "") == getattr(event, "title", ""):
+ continue # an occurrence of this same series, under its own id
+ out.append(f"{s.astimezone(zone):%H:%M}–{e.astimezone(zone):%H:%M}")
+ return list(dict.fromkeys(out))
+
+
+def refusal(
+ person_id: int, *, sender: str, relation: str, title: str, thread_id: str, clash: list[str] | None,
+ can_answer: bool, now: datetime,
+) -> str | None:
+ """Why this invite may not be accepted on its own (a
+ ``handle_it.REASONS`` code), or None when it may. Plain code only;
+ never raises (an error refuses)."""
+ try:
+ return _refusal(
+ person_id, sender=sender, relation=relation, title=title, thread_id=thread_id, clash=clash,
+ can_answer=can_answer, now=now,
+ )
+ except Exception:
+ logger.warning("delegation.invites: the rules failed — asking instead", exc_info=True)
+ return "uncountable"
+
+
+def _refusal(
+ person_id: int, *, sender: str, relation: str, title: str, thread_id: str, clash: list[str] | None,
+ can_answer: bool, now: datetime,
+) -> str | None:
+ from openexecutive.delegation import handle_it, training
+
+ settings = handle_it.get(person_id)
+ if not settings.enabled:
+ return "level"
+ trained = handle_it.in_training(person_id, training.REPLIES)
+ lead = not trained and handle_it.leading(person_id)
+ if relation not in handle_it.KNOWN_RELATIONS:
+ return "level"
+ if trained:
+ if training.allowed_inviter(person_id, sender) is None:
+ return "invite_training"
+ elif relation not in ON_ITS_OWN_RELATIONS:
+ # Someone they have only written to (which a reply sent on its own
+ # can make anyone) gets a card, unless they allowed that sender.
+ return "level"
+ elif not lead and settings.level(handle_it.kind_for(relation)) != handle_it.LEVEL_HANDLE:
+ return "level"
+ if not handle_it.signing_ok():
+ return "signing_off"
+ if clash is None:
+ return "calendar_unread"
+ if clash:
+ return "clash"
+ if not can_answer:
+ return "calendar_write"
+ if handle_it.sensitive(title):
+ return "sensitive"
+ if lead and handle_it._lead_rule(person_id, [title], [sender], None):
+ return "lead_rule"
+ return handle_it.count_refusal(person_id, thread_id, now)
+
+
+# --------------------------------------------------------------------------- #
+# The watcher's step for one invite
+# --------------------------------------------------------------------------- #
+
+
+async def consider(
+ person: Any, client: Any, message: Any, thread: Any, *, now: datetime, result: Any,
+) -> None:
+ """Handle one invite the watcher found (``inbox._consider``, after the
+ skip rules): a card, an accept on its own, or skipped with a reason.
+ Once claimed, it is finished or left for a later scan."""
+ from openexecutive.delegation.gmail import (
+ CalendarNotGranted,
+ GmailAuthError,
+ GmailError,
+ GmailNotFound,
+ GmailRateLimited,
+ )
+ from openexecutive.delegation.inbox import (
+ PROCESSING,
+ SKIPPED,
+ _claim,
+ _retry_later,
+ _set_outcome,
+ handling_relation,
+ relation_of,
+ )
+
+ known_as = await relation_of(message.from_addr, client, contacts=bool(person.is_principal))
+ relation = handling_relation(known_as, message)
+ if relation == "stranger":
+ reason = "invite_stranger" if known_as == "stranger" else "invite_unverified"
+ if _claim(person.id, message, relation=relation, outcome=SKIPPED, reason=reason, now=now):
+ result.skipped += 1
+ return
+ if len(open_cards(person.id)) >= OPEN_CARDS_MAX:
+ result.deferred += 1 # not recorded: looked at again once there is room
+ return
+ if not _claim(person.id, message, relation=relation, outcome=PROCESSING, now=now):
+ return
+
+ def skip(reason: str) -> None:
+ _set_outcome(person.id, message.id, SKIPPED, reason=reason)
+ result.skipped += 1
+
+ try:
+ try:
+ event = await client.find_invite(message)
+ except GmailNotFound:
+ event = None
+ if event is None:
+ skip("invite_not_found")
+ return
+ organizer = parseaddr(event.organizer)[1].strip().lower() if event.organizer else ""
+ if organizer != message.from_addr:
+ skip("invite_not_organizer")
+ return
+ if event.response in ("accepted", "declined", "organizer"):
+ skip("invite_answered")
+ return
+ start = _moment(event.start)
+ if start is None or start <= now:
+ skip("invite_past")
+ return
+ tz = _tz()
+ clash = await clashes(client, event, tz=tz)
+ try:
+ granted = await client.calendar_write_granted()
+ except (GmailAuthError, GmailRateLimited):
+ raise
+ except GmailError:
+ granted = None
+ except CalendarNotGranted:
+ skip("invite_calendar_not_granted")
+ return
+ except (GmailAuthError, GmailRateLimited):
+ _retry_later(person.id, message.id, "invite_read_failed", count=False)
+ raise # the mailbox itself: the scan backs off
+ except GmailError:
+ # A calendar trouble only: tried again on a later scan, never a back-off for the mail.
+ from openexecutive.delegation.inbox import _count_retry
+
+ _count_retry(result, _retry_later(person.id, message.id, "invite_read_failed"))
+ return
+ can_answer = granted is not False
+ held = refusal(
+ person.id, sender=message.from_addr, relation=relation, title=event.title, thread_id=thread.id,
+ clash=clash, can_answer=can_answer, now=now,
+ )
+ handling_on = _handle_it_on(person.id)
+ payload = _card_payload(
+ person, message, thread, event, relation=known_as, clash=clash, can_answer=can_answer,
+ handle_it_reason=held if handling_on and held != "level" else None,
+ )
+ decision_id = create_card(
+ f"{DECISION_CLASS}:{person.id}:{message.id}", payload, person_id=person.id, on_its_own=held is None,
+ )
+ if decision_id is None:
+ _set_outcome(person.id, message.id, SKIPPED, reason="already_answered")
+ result.skipped += 1
+ return
+ _set_outcome(person.id, message.id, CARDED, decision_id=decision_id)
+ result.invites += 1
+ _audit("delegation_invite_carded", f"Left a meeting invite for person {person.id}", {
+ "person_id": person.id, "decision_id": decision_id, "thread_id": thread.id, "relation": relation,
+ "clash": bool(clash), "can_answer": can_answer,
+ **({"handle_it": held or "accept"} if handling_on else {}),
+ })
+ if held is None and await accept_on_its_own(person, client, decision_id, now=now):
+ result.handled += 1
+
+
+def _handle_it_on(person_id: int) -> bool:
+ from openexecutive.delegation import handle_it
+
+ return handle_it.get(person_id).enabled
+
+
+def _card_payload(
+ person: Any, message: Any, thread: Any, event: Any, *, relation: str, clash: list[str] | None,
+ can_answer: bool, handle_it_reason: str | None,
+) -> dict[str, Any]:
+ from openexecutive.delegation.ghostwriter import one_line
+
+ payload: dict[str, Any] = {
+ # A card is its person's alone (approver_only hides the class); this
+ # keeps every reader that checks the payload in step.
+ "private": True,
+ "person_id": person.id,
+ "message_id": message.id,
+ "thread_id": thread.id,
+ "event_id": event.id,
+ "from_name": one_line(message.from_name, 120),
+ "from_email": message.from_addr,
+ "relation": relation,
+ "sender_verified": bool(message.sender_authenticated),
+ "title": one_line(event.title, TITLE_MAX),
+ "start": event.start,
+ "end": event.end,
+ "all_day": bool(event.all_day),
+ "clashes": clash or [],
+ "clash_checked": clash is not None,
+ "can_answer": can_answer,
+ }
+ if not can_answer:
+ payload["connect_command"] = _connect_command(person)
+ if handle_it_reason:
+ payload["handle_it_reason"] = handle_it_reason
+ return payload
+
+
+def _connect_command(person: Any) -> str:
+ """The command that connects their mailbox again with calendar access."""
+ from openexecutive.delegation.gmail import credential_provider
+
+ email = (person.email or "").strip().lower()
+ if email and credential_provider(email) == "microsoft":
+ return f"uv run python scripts/connect-own-outlook.py --email {email} --calendar"
+ return f"uv run --with google-auth-oauthlib python scripts/connect-own-gmail.py --email {email} --calendar"
+
+
+# --------------------------------------------------------------------------- #
+# Answering
+# --------------------------------------------------------------------------- #
+
+
+async def accept_on_its_own(person: Any, client: Any, decision_id: int, *, now: datetime) -> bool:
+ """Accept the invite on card ``decision_id`` under Handle it for me,
+ checking the rules again first. Anything that stops it hands the card
+ back to the person, saying why. True when it accepted."""
+ from openexecutive.delegation import handle_it, training
+ from openexecutive.delegation.gmail import CalendarWriteNotGranted, GmailError
+ from openexecutive.delegation.inbox import _set_outcome
+ from openexecutive.memory.decision_ledger import (
+ STATUS_EXECUTED,
+ claim_for_execution,
+ finish_execution,
+ get_decision_instance,
+ hand_back,
+ release_claim,
+ )
+
+ card = get_decision_instance(decision_id)
+ if card is None or card.gate_mode != "auto_execute" or card.approver_person_id != person.id:
+ return False
+ payload = _payload(card)
+ sender = str(payload.get("from_email") or "")
+ held = refusal(
+ person.id, sender=sender, relation=str(payload.get("relation") or ""),
+ title=str(payload.get("title") or ""), thread_id=str(payload.get("thread_id") or ""),
+ clash=[str(c) for c in payload.get("clashes") or []] if payload.get("clash_checked") is not False else None,
+ can_answer=payload.get("can_answer") is not False, now=now,
+ )
+ if held is not None:
+ hand_back(decision_id, {**payload, "handle_it_reason": held})
+ return False
+ if not claim_for_execution(decision_id, resolver_person_id=None):
+ return False
+ try:
+ await client.answer_invite(str(payload.get("event_id") or ""), accept=True)
+ except Exception as exc:
+ reason = "calendar_write" if isinstance(exc, CalendarWriteNotGranted) else None
+ if not isinstance(exc, GmailError):
+ logger.warning("delegation.invites: accepting on its own failed (%s)", type(exc).__name__)
+ # Answering is the same however often it's done, so the card simply
+ # waits for the person's tap.
+ release_claim(decision_id)
+ back = {**payload, **({"handle_it_reason": reason} if reason else {})}
+ if reason:
+ back["can_answer"] = False
+ back["connect_command"] = _connect_command(person)
+ hand_back(decision_id, back)
+ return False
+ finish_execution(decision_id, STATUS_EXECUTED, final_payload={"answer": "accepted", "on_its_own": True})
+ try:
+ handle_it.record_handled(person.id, str(payload.get("thread_id") or ""), decision_id, None, now=now)
+ except Exception:
+ logger.exception("delegation.invites: recording an invite accepted on its own failed")
+ allowance = training.allowed_inviter(person.id, sender)
+ if allowance is not None:
+ training.used(allowance)
+ _set_outcome(person.id, str(payload.get("message_id") or ""), ACCEPTED, reason="handled")
+ _audit("delegation_invite_handled", f"Accepted a meeting invite as person {person.id}, on its own", {
+ "person_id": person.id, "decision_id": decision_id, "thread_id": payload.get("thread_id"),
+ })
+ return True
+
+
+async def answer(
+ instance: Any, *, caller: Any, resolver: int | None, answer: Any, allow: bool = False,
+ mailbox: Any = None, now: datetime | None = None,
+) -> str:
+ """Answer ``instance``'s invite for its person, on their tap: ``accept``
+ or ``decline``. ``allow`` (accept, Replies in training) also lets that
+ sender's invites be accepted on their own from now on. Returns
+ ``accepted`` or ``declined``; raises ``AnswerRefused``."""
+ from openexecutive.delegation import calendar, training
+ from openexecutive.delegation.gmail import (
+ BLOCKING_CODES,
+ STATUS_MESSAGES,
+ CalendarNotGranted,
+ CalendarWriteNotGranted,
+ GmailError,
+ GmailNotFound,
+ gmail_for,
+ gmail_status,
+ normalize_email,
+ )
+ from openexecutive.delegation.inbox import CLOSED, _set_outcome
+ from openexecutive.delegation.settings import can_delegate, is_enabled
+ from openexecutive.delegation.verified import NOT_YOURS, caller_refusal
+ from openexecutive.memory.decision_ledger import (
+ STATUS_APPROVED_UNCHANGED,
+ STATUS_FAILED,
+ claim_for_execution,
+ finish_execution,
+ release_claim,
+ update_open_payload,
+ )
+ from openexecutive.orchestrator import take_the_lead
+ from openexecutive.people.store import get_person
+
+ at = now or _now()
+ payload = _payload(instance)
+ person_id = payload.get("person_id")
+ person = get_person(person_id) if isinstance(person_id, int) else None
+ if person is None or person.id is None or person.archived or person.id != instance.approver_person_id:
+ raise AnswerRefused(404, "gone", "This invite is no longer here.")
+ email = normalize_email(person.email or "")
+ refused = caller_refusal(caller, email)
+ if refused == NOT_YOURS:
+ raise AnswerRefused(403, "not_yours", "Only the person this invite is for can answer it.")
+ if refused is not None:
+ raise AnswerRefused(
+ 409, "caller_signing_required",
+ "Answering needs signed sign-ins on this server, so that nobody else can answer for you.",
+ )
+ if answer not in ANSWERS:
+ raise AnswerRefused(422, "bad_answer", "Accept or decline.")
+ if not can_delegate(person) or not is_enabled(person.id):
+ raise AnswerRefused(409, "act_as_me_off", "Act as me is off, so this invite can't be answered from here.")
+ if not calendar.enabled(person.id):
+ raise AnswerRefused(409, "calendar_off", "Read my calendar is off, so this invite can't be answered from here.")
+ if not _live(payload, instance.created_at, at):
+ raise AnswerRefused(409, "expired", "This meeting has started or the card is too old. Answer it in your calendar.")
+ sender = str(payload.get("from_email") or "")
+ accept = answer == "accept"
+ if allow:
+ if not accept or not training.get(person.id).replies:
+ raise AnswerRefused(
+ 422, "cant_allow", "Accepting on its own next time is for invites you accept while Replies is in training.",
+ )
+ if not training.room_for(person.id, training.inviter_key(person.id, sender)):
+ raise AnswerRefused(409, "learned_full", "It has learned as much as it can hold. Remove something first.")
+ client = mailbox if mailbox is not None else gmail_for(email)
+ status = await gmail_status(email, gmail=client)
+ if status != "connected":
+ raise AnswerRefused(409, BLOCKING_CODES.get(status, "gmail_error"), STATUS_MESSAGES.get(status, ""))
+ if not claim_for_execution(instance.id, resolver_person_id=resolver):
+ raise AnswerRefused(409, "already_handled", "This invite was already answered.")
+ try:
+ await client.answer_invite(str(payload.get("event_id") or ""), accept=accept)
+ except (CalendarWriteNotGranted, CalendarNotGranted) as exc:
+ release_claim(instance.id)
+ update_open_payload(instance.id, {**payload, "can_answer": False, "connect_command": _connect_command(person)})
+ write = isinstance(exc, CalendarWriteNotGranted)
+ raise AnswerRefused(
+ 409, "calendar_write_needed" if write else "calendar_not_granted",
+ "Your calendar sign-in can read but not answer invites. Connect it again under Read my calendar, then try again."
+ if write else "Your saved sign-in doesn't include your calendar any more. Connect it again under Read my calendar.",
+ ) from None
+ except GmailNotFound:
+ finish_execution(instance.id, STATUS_FAILED, final_payload={"answer": answer, "error": "not_found"})
+ _set_outcome(person.id, str(payload.get("message_id") or ""), CLOSED, reason="invite_gone")
+ raise AnswerRefused(409, "gone", "This meeting isn't on your calendar any more.") from None
+ except GmailError:
+ # Answering again is harmless, so the card waits for another try.
+ release_claim(instance.id)
+ raise AnswerRefused(502, "calendar_error", "Couldn't reach your calendar. Try again in a moment.") from None
+ except Exception:
+ logger.exception("delegation.invites: answering failed")
+ release_claim(instance.id)
+ raise AnswerRefused(502, "calendar_error", "Couldn't reach your calendar. Try again in a moment.") from None
+ done = ACCEPTED if accept else DECLINED
+ finish_execution(instance.id, STATUS_APPROVED_UNCHANGED, final_payload={"answer": done})
+ _set_outcome(person.id, str(payload.get("message_id") or ""), done, reason="tapped")
+ _audit("delegation_invite_answered", f"Person {person.id} {done} a meeting invite", {
+ "person_id": person.id, "decision_id": instance.id, "answer": done, "allowed": allow,
+ })
+ if allow:
+ try:
+ found = training.allow_inviter(person.id, sender, str(payload.get("from_name") or ""), decision_id=instance.id)
+ except take_the_lead.RuleError:
+ logger.warning("delegation.invites: accepted, but the list filled up before allowing")
+ else:
+ _audit("delegation_reply_allowed", f"Person {person.id} allowed invites in training", {
+ "person_id": person.id, "decision_id": instance.id, "allowed_id": found.id, "invites": True,
+ })
+ return done
+
+
+async def dismissed(instance: Any) -> None:
+ """After a card was dismissed: nothing answered, the audit row and the
+ watcher's record."""
+ from openexecutive.delegation.inbox import DISMISSED, _set_outcome
+
+ payload = _payload(instance)
+ person_id = payload.get("person_id")
+ if isinstance(person_id, int):
+ _set_outcome(person_id, str(payload.get("message_id") or ""), DISMISSED, reason="dismissed")
+ _audit("delegation_invite_dismissed", f"Person {person_id} dismissed a meeting invite card", {
+ "person_id": person_id, "decision_id": instance.id,
+ })
+
+
+# --------------------------------------------------------------------------- #
+# Done for you
+# --------------------------------------------------------------------------- #
+
+
+def handled(person_id: int, *, since: str, limit: int = 50) -> list[Any]:
+ """``person_id``'s invites accepted on their own since ``since``, as
+ ``handle_it.HandledReply`` rows (``source`` ``invite``), theirs alone."""
+ from openexecutive.delegation.handle_it import HandledReply
+ from openexecutive.memory.decision_ledger import STATUS_EXECUTED, list_instances
+
+ out: list[Any] = []
+ tz = _tz()
+ for card in list_instances(
+ DECISION_CLASS, status=STATUS_EXECUTED, approver_person_id=person_id, resolved_since=since, limit=limit,
+ ):
+ payload = _payload(card)
+ if payload.get("person_id") != person_id:
+ continue
+ name = str(payload.get("from_name") or "")
+ sender = str(payload.get("from_email") or "")
+ title = str(payload.get("title") or "")
+ when = short_when(str(payload.get("start") or ""), payload.get("all_day") is True, tz)
+ out.append(HandledReply(
+ decision_id=card.id,
+ sent_at=card.resolved_at or card.created_at,
+ to_name=name,
+ to_email=sender,
+ subject=title,
+ body="",
+ open_questions=[],
+ thread_id=str(payload.get("thread_id") or ""),
+ source=SOURCE,
+ summary=f"Accepted {_first_name(name, sender)}'s {title or 'meeting'}, {when}",
+ ))
+ return out
+
+
+__all__ = [
+ "ANSWERS", "DECISION_CLASS", "AnswerRefused", "InviteCard", "answer", "cards", "clashes", "consider",
+ "create_once", "dismissed", "handled", "reconcile", "refusal", "skip_reason", "watching", "when_text",
+]
diff --git a/packages/core/openexecutive/delegation/outlook.py b/packages/core/openexecutive/delegation/outlook.py
index 6daa9a41..a0738644 100644
--- a/packages/core/openexecutive/delegation/outlook.py
+++ b/packages/core/openexecutive/delegation/outlook.py
@@ -14,7 +14,10 @@ as me: ``{"version": 1, "provider": "microsoft", "email": ..., "account":
"work" | "personal", "microsoft": {refresh_token, client_id, tenant}}``
(no client secret: the sign-in is a public client's). ``scripts/connect-own-outlook.py``
writes it. Delegated scopes: ``User.Read``, ``Mail.ReadWrite`` and
-``Mail.Send``, plus ``offline_access``. Microsoft rotates the refresh token on
+``Mail.Send``, plus ``offline_access``; with ``--calendar``,
+``Calendars.ReadWrite`` (reads, and answers a meeting invite as them:
+``answer_invite``), or ``Calendars.Read`` on a sign-in made before, which
+keeps reading. Microsoft rotates the refresh token on
use; the new one is written back into the same file, keeping every other key.
**One way to send.** It reads mail and saves or deletes drafts. The only send
@@ -66,6 +69,7 @@ from openexecutive.delegation.gmail import (
MAX_EVENTS,
CalendarEvent,
CalendarNotGranted,
+ CalendarWriteNotGranted,
CreatedDraft,
DraftChanged,
DraftInfo,
@@ -98,6 +102,8 @@ REQUEST_SCOPE = " ".join(["offline_access", *(GRAPH_RESOURCE + s for s in GRAPH_
# Read my calendar (delegation.calendar): optional, granted when they connected
# with --calendar. Microsoft's token lists every Graph scope they consented to.
CALENDAR_SCOPES: frozenset[str] = frozenset({"calendars.read", "calendars.readwrite"})
+# Answering a meeting invite (delegation.invites) needs this one.
+CALENDAR_WRITE_SCOPE = "calendars.readwrite"
# The tenant every personal Microsoft account (Outlook.com, Hotmail) is in.
CONSUMER_TENANT_ID = "9188040d-6c67-4c5b-b112-36a304b66dad"
CREDENTIAL_VERSION = 1
@@ -130,6 +136,10 @@ _TOKENS: dict[str, tuple[str, float]] = {}
# The scopes Microsoft said each of those tokens carries ("" when it didn't say).
_GRANTED: dict[str, str] = {}
_EVENT_SELECT = "id,subject,start,end,isAllDay,location,organizer,attendees,isCancelled,responseStatus,showAs"
+_UTC_PREFER = 'outlook.timezone="UTC", IdType="ImmutableId"'
+# The invites Graph files as a request to answer (an eventMessage's
+# meetingMessageType); a cancellation or an answer is not one.
+_MEETING_REQUEST = "meetingRequest"
@dataclass(frozen=True)
@@ -206,10 +216,13 @@ def load_credential(email: str, *, directory: Path | None = None) -> OutlookCred
def _refresh_scope(cred: OutlookCredential) -> str:
"""The scopes a refresh asks for: the mail ones, plus the calendar one
only when the credential was minted with it (asking a mail-only one for
- it would fail the refresh, and mail with it)."""
- if "calendars.read" not in cred.scopes:
- return REQUEST_SCOPE
- return f"{REQUEST_SCOPE} {GRAPH_RESOURCE}Calendars.Read"
+ it would fail the refresh, and mail with it): ``Calendars.ReadWrite``,
+ or ``Calendars.Read`` for a sign-in made before invites were answered."""
+ if CALENDAR_WRITE_SCOPE in cred.scopes:
+ return f"{REQUEST_SCOPE} {GRAPH_RESOURCE}Calendars.ReadWrite"
+ if "calendars.read" in cred.scopes:
+ return f"{REQUEST_SCOPE} {GRAPH_RESOURCE}Calendars.Read"
+ return REQUEST_SCOPE
def _store_rotated(email: str, old: str, new: str, directory: Path | None) -> None:
@@ -691,6 +704,67 @@ class DelegateOutlook:
events = [parse_event(item, zone) for item in items if isinstance(item, dict)]
return [e for e in events if e is not None]
+ async def calendar_write_granted(self) -> bool | None:
+ """Whether their saved sign-in can answer a meeting invite
+ (``Calendars.ReadWrite``); None when Microsoft didn't say."""
+ async with self._client() as client:
+ await self._access_token(client)
+ granted = _GRANTED.get(_token_key(self._cred()), "")
+ return CALENDAR_WRITE_SCOPE in _granted(granted) if granted else None
+
+ async def find_invite(self, message: MailMessage) -> CalendarEvent | None:
+ """The event a meeting invite ``message`` asks them to (Graph's
+ ``eventMessage.event``, on their own calendar), or None: not a
+ request (a cancellation, someone's answer), or no event. A read."""
+ if not valid_id(message.id):
+ raise GmailError("invalid message id")
+ async with self._client() as client:
+ await self._access_token(client)
+ granted = _GRANTED.get(_token_key(self._cred()), "")
+ if granted and not CALENDAR_SCOPES & _granted(granted):
+ raise CalendarNotGranted("Calendars.Read not granted")
+ try:
+ data = await self._request(
+ client, "GET", f"/messages/{quote(message.id, safe='')}",
+ params={"$expand": "microsoft.graph.eventMessage/event"}, prefer=_UTC_PREFER,
+ )
+ except GmailAuthError as exc:
+ if str(exc) == "forbidden":
+ raise CalendarNotGranted("calendar read refused") from exc
+ raise
+ if str(data.get("meetingMessageType") or "") != _MEETING_REQUEST:
+ return None
+ raw = data.get("event")
+ if not isinstance(raw, dict) or not valid_id(raw.get("id")):
+ return None
+ return parse_event(raw)
+
+ async def answer_invite(self, event_id: str, *, accept: bool) -> None:
+ """Answer the invite to ``event_id`` as them: Graph's event accept
+ or decline, telling the organizer (``sendResponse``). Called only by
+ ``delegation.invites``, on the person's tap or under Handle it for
+ me (accept only). Raises ``CalendarWriteNotGranted`` for a read-only
+ sign-in, ``GmailNotFound`` when the event is gone."""
+ if not valid_id(event_id):
+ raise GmailError("invalid event id")
+ async with self._client() as client:
+ await self._access_token(client)
+ granted = _GRANTED.get(_token_key(self._cred()), "")
+ if granted and CALENDAR_WRITE_SCOPE not in _granted(granted):
+ raise CalendarWriteNotGranted("Calendars.ReadWrite not granted")
+ answer = "accept" if accept else "decline"
+ try:
+ await self._request(
+ client, "POST", f"/events/{quote(event_id, safe='')}/{answer}",
+ json_body={"sendResponse": True},
+ )
+ except GmailAuthError as exc:
+ if str(exc) != "forbidden":
+ raise
+ if granted and CALENDAR_WRITE_SCOPE in _granted(granted):
+ raise GmailError("calendar write refused with the scope granted") from exc
+ raise CalendarWriteNotGranted("calendar write refused") from exc
+
async def profile_email(self) -> str:
"""The address of the mailbox the credential opens, from the directory."""
async with self._client() as client:
diff --git a/packages/core/openexecutive/delegation/training.py b/packages/core/openexecutive/delegation/training.py
index 490cbe18..b37f2866 100644
--- a/packages/core/openexecutive/delegation/training.py
+++ b/packages/core/openexecutive/delegation/training.py
@@ -9,7 +9,10 @@ card on the Act as me page:
it sends that reply on the person's tap, as Send does, and from then on
replies to that same sender may go on their own while Handle it for me is
on, under the dial's limits and every check Handle it always makes
- (``handle_it.refusal``), strangers included.
+ (``handle_it.refusal``), strangers included. A meeting invite card
+ (``delegation.invites``) adds the same tick, "Accept from them on its own
+ next time": from then on invites from that sender with no clash are
+ accepted on their own while Handle it for me is on.
- **Follow-ups** (``follow_ups``): every follow-up waits; Send + allow on a
follow-up card lets follow-ups to exactly those people go on their own.
- **Suggested actions** (``actions``): an action card from someone's mail
@@ -64,6 +67,7 @@ SWITCHES: tuple[str, ...] = (*SETTINGS, ACTIONS_ON)
# What each kind of key teaches, by the action in it.
_SETTING_OF_ACTION = {
"reply": REPLIES, "follow_up": FOLLOW_UPS, "message": ACTIONS, "invite": ACTIONS, "style": DRAFTS,
+ "invite_from": REPLIES,
}
# The longest example kept, after the quoted thread is dropped.
@@ -170,6 +174,10 @@ def reply_key(person_id: int, sender: str) -> str:
return f"{_prefix(person_id)}|reply|{_email(sender)}"
+def inviter_key(person_id: int, sender: str) -> str:
+ return f"{_prefix(person_id)}|invite_from|{_email(sender)}"
+
+
def follow_up_key(person_id: int, recipients: list[str]) -> str:
going = sorted({_email(a) for a in recipients if _email(a)})
return f"{_prefix(person_id)}|follow_up|{','.join(going)}"
@@ -261,6 +269,13 @@ def allowed_sender(person_id: int, sender: str, *, db_path: Path | None = None)
return _find(person_id, reply_key(person_id, sender), db_path=db_path)
+def allowed_inviter(person_id: int, sender: str, *, db_path: Path | None = None) -> Allowed | None:
+ """The allowance for accepting ``sender``'s meeting invites on their own."""
+ if not _email(sender):
+ return None
+ return _find(person_id, inviter_key(person_id, sender), db_path=db_path)
+
+
def allowed_follow_up(person_id: int, recipients: list[str], *, db_path: Path | None = None) -> Allowed | None:
"""The allowance for ``person_id``'s follow-ups to exactly ``recipients``."""
if not any(_email(a) for a in recipients):
@@ -327,6 +342,16 @@ def allow_sender(
decision_id=decision_id, db_path=db_path)
+def allow_inviter(
+ person_id: int, sender: str, name: str, *, decision_id: int | None, db_path: Path | None = None,
+) -> Allowed:
+ """Let ``sender``'s meeting invites be accepted on their own for
+ ``person_id`` (when nothing clashes). Raises ``take_the_lead.RuleError``
+ when their list is full."""
+ return _allow(person_id, inviter_key(person_id, sender), f"Accept invites from {_who(name, sender)}",
+ decision_id=decision_id, db_path=db_path)
+
+
def allow_follow_up(
person_id: int, recipients: list[str], *, decision_id: int | None, db_path: Path | None = None,
) -> Allowed:
diff --git a/packages/core/openexecutive/guide/prebuilt/delegate.json b/packages/core/openexecutive/guide/prebuilt/delegate.json
index 17514f94..62f6400b 100644
--- a/packages/core/openexecutive/guide/prebuilt/delegate.json
+++ b/packages/core/openexecutive/guide/prebuilt/delegate.json
@@ -1,7 +1,7 @@
{
"section_id": "delegate",
"title": "Delegate",
- "markdown": "**What it is:** The place where you decide what the Executive may do without asking you. **Delegate** is in the main menu. It has three tabs: **Act as me**, **Handle it for me** and **Take the lead**. Clicking **Delegate** opens **Act as me**. **What it does for you** sits beside each tab.\n\n**What it does:**\n\n- **What it does for you** says what the Executive does with your settings right now: what it sends on its own, what asks first and what it writes for you to send. It only reads. Nothing on it changes a setting.\n- **Act as me** lets the Executive write email drafts *as you*, from your own Gmail or Outlook mailbox. You send them. It can also write first replies to mail in your inbox that needs you.\n- **Handle it for me** lets it send some of those replies, and some follow-ups, on its own from your mailbox.\n- **Take the lead** (the owner only) lets the Executive act in its own name on what it finds, without waiting to be asked.\n- Normally the Executive writes only as itself, from its own email account. Nothing goes out as you unless you set it up here.\n\n**How to use:**\n\n1. Click **Delegate** in the sidebar. (On a phone, open the menu with the button at the top left.)\n2. Read **What it does for you**, beside the tab, to see what goes out on its own today.\n3. Open **Act as me**, connect your mailbox, and pick what it writes as you.\n4. If you want replies sent for you, open **Handle it for me** and pick how much it sends on its own.\n5. If you are the owner, open **Take the lead** to let the Executive act in its own name.\n\n**What it does for you:**\n\n- On a wide screen it sits to the right of each Delegate tab. Close it with **✕**, and **What it does** at the top of the tab brings it back; this browser remembers which. On a narrow screen, tap **What it does** at the top of the tab and it opens as a sheet from the bottom.\n- Change a setting on the tab and it updates at once. The rows that changed are marked **Just changed** for a few seconds.\n- Three pills: **As you**, **Executive** and **Departments**. The number on each pill is how many things go out on their own.\n- **As you** covers your own mailbox: emails you ask for in chat, inbox replies, what Handle it for me sends, what is in training, what it has learned and your own rules.\n- **Executive** covers what the Executive does in its own name: Take the lead, its Always asks first switches, the company's rules and meetings. Only the owner sees this pill.\n- **Departments** shows each department's authority level and what that level covers.\n- Rows are grouped: **Sends on its own** (green), **Asks first** (amber), **Writes for you to send** and **Off** (grey). Each row says what it does in one line, then why, with a link to the setting.\n- **Compare Act as me, Handle it for me and Take the lead**, at the bottom, opens **Who writes and who sends**. Pick a tab and one of its options. Three answers sit on top: who writes it, whose name is on it and who presses Send. Under them the steps appear one at a time and stay on screen, for example Dana emails you, you ask in chat, the Executive writes the draft, you tap Send. **Handle it for me** shows the same five emails at every level, each marked **Sent as you** or **Waits for you**. Tapping there changes no setting. **Play again** replays the steps.\n- While the Executive is paused, a note at the top says nothing runs on its own, with a **Resume** link.\n- Someone who is not on the People list sees \"Only people on the team can see this.\"\n\n**Act as me:**\n\n- Who can use it: the owner. Team members can use it once the owner turns on **Let team members use it** (under **Advanced** on this tab). That switch shows only when the install allows it. Anyone else sees \"Act as me isn't available to you here.\"\n- Each person connects their own mailbox and turns it on for themselves. What it reads in your mail, the drafts it writes and your reply cards are yours alone. The owner sees only each team member's name, how many drafts they had written and sent in the last 30 days, and whether inbox replies are on. A conversation in which it read someone's mail can be opened only by that person.\n- **Your mailbox**: until it is connected, the card shows the command to run on a computer with a browser (one for Gmail and, where the install supports it, one for Outlook). Sign in as yourself, put the file it writes where the API reads it, then click **Check again**. Once connected it shows \"Connected to\" your address. It won't connect the Executive's own address as yours.\n- **What it writes as you**: \"Nothing goes out until you send it.\" Pick one:\n - **Off**: the Executive only writes as itself.\n - **When I ask**: ask in chat, \"reply to Dana as me: yes to the 5th\", and the draft waits in your Gmail or Outlook Drafts.\n - **Draft replies automatically**: it also writes a first reply to mail that needs you, and puts it on Home.\n- You can't move up from **Off** until your mailbox is connected. Moving down asks first, says what stops, and saves when you click **Move down**. Moving to **When I ask** stops inbox replies. Moving to **Off** stops everything it writes as you and turns **Read my calendar** off. Either one also stops Handle it for me if it was sending.\n- **Learn from my edits** (a checkbox once you are above **Off**): when you change a draft before sending, tick **Do it like this next time** and it learns how you write to that person. Nothing more is sent.\n- **Read my calendar**: a switch. On, it reads your own calendar when you ask about your day or week in chat, and offers your free slots when a reply needs a time. It never changes your calendar. It stays off while **What it writes as you** is at **Off**. If your mailbox sign-in doesn't include your calendar, the card shows a command to run once to add it.\n- **Suggested actions**: meeting invites and messages your mail calls for. **Always ask** brings each one to you as a card, every time. **In training** also brings each one as a card; tick **Do this on its own next time** before **Approve** and it does that kind, with those people, on its own from then on. **On** sends the message or invite on its own, no card; new contacts, anyone added in the last week, money, links and the topics that always wait still come to you, up to 10 a day.\n- **What it's learned**: what it learned from your edits (drafts) and your approvals (suggested actions). Each item says when, how many times it has been used since, and an example. **Remove** forgets it, and it asks you again.\n- **Advanced** (closed by default) holds **How I write**, **AI line on drafts you send** (shown only when the install adds an AI line to mail) and, for the owner, **Let team members use it**.\n\n**Asking in chat:**\n\n- Ask in the web app (signed in), in a direct message to the Executive on Slack or Discord, or in a private Telegram chat: \"reply to Dana as me: yes to the 5th.\"\n- It saves a draft in your own Drafts and shows a card, \"Drafted an email as you to Dana — in your Drafts\". Asking in chat never sends anything.\n- It does not write as you in a shared channel or thread, on Google Chat, from an email, from a scheduled job or in anyone else's conversation.\n- If it isn't sure about something, it asks you instead of guessing.\n- There is a daily limit on drafts written as one person (50 a day unless the install changes it).\n\n**Draft replies automatically:**\n\n- About every five minutes it looks at new mail in your inbox. For mail that needs a personal reply from you (a question, a request, a meeting to arrange, an introduction or a follow-up), it writes a first reply and puts it at the top of **Needs you** on Home.\n- It only looks at mail that arrives after you turn it on. It leaves out newsletters, notifications, mailing lists, automatic mail, mail you are not in To or Cc on, mail you've already answered and anything that doesn't need you. Mail you answer within ten minutes never gets a draft.\n- The first reply only acknowledges. It repeats only what you've already said in the thread, commits you to nothing and lists what's left for you to decide, each with a few short answers to tap. Tap one, or **Something else…** to type your own, and it rewrites the reply with your answer. For a time, with **Read my calendar** on, it offers your next free slots. For a document, it offers one from your documents to say you'll send it (it can't attach files). **Send** waits until you've answered, or until you change the words with **Edit**. Someone you've never written to gets a short holding reply.\n- Under the picker you see how it is doing (for example, that your mailbox needs connecting again) and when it last looked. Click **Check now** to look straight away.\n- **Also save inbox replies in my Gmail Drafts** (or Outlook): off by default, so replies wait on their cards only. Tick it to keep each reply in your Drafts too.\n- On each card on Home: **Send** asks you to confirm who it goes to, then **Send now**. In training, tick **Reply to <name> on its own next time** before **Send** and replies to that person go on their own from then on. **Edit** changes the words on the card. **Open in Gmail** opens it when it is in your Drafts. **Dismiss** removes the card.\n- Limits: at most 5 drafts a check and 20 a day unless the install changes it, 2 a day per sender (1 for a stranger), and never more than 25 cards open. A card closes when the draft is sent or deleted in your mailbox, when you reply yourself, or after 7 days.\n\n**How I write (under Advanced):**\n\n- Shows your style as a few sentences, with where it came from (\"Learned from N of your sent emails\", or \"Set by you\") and whether it is locked.\n- **Describe it in your own words**: write how you write, the way you'd tell a new assistant (up to 2,000 characters). Buttons add common phrases, such as \"Short and to the point\" or \"No emojis\". Click **Write my style**; it shows the new style with new lines marked **New** and a sample reply. Click **Save** to keep it or **Change it** to edit your words. Nothing changes until you save.\n- **Learn from my sent mail** (or **Learn again from my sent mail**): reads your recent sent emails once and describes how you write. It needs your mailbox connected and is hidden while the style is locked.\n- **Fine-tune details** opens the fields: **Length** (short, medium, long), **Tone** (casual, neutral, formal), a **Greeting** **To your team**, **To your contacts** and **To anyone else** ({first} becomes their first name), **Sign-off**, **Habits** and **Never** (one per line), your **Signature** and **Examples of your writing**.\n- **Save changes** saves the fields. **Lock** stops it being relearned from your mail (you can still edit it); **Unlock** undoes that. **Reset** starts over. **Remove examples** drops the examples.\n- **Signature**: with Gmail, your signature is added to every draft. **Refresh from Gmail** picks up a change you made in Gmail, **Don't add my signature** stops adding it, and **Add my Gmail signature** brings it back. Outlook doesn't share signatures with apps, so Outlook drafts end with your sign-off.\n- **AI line on drafts you send**: a checkbox for whether drafts you approve and send end with the install's AI line. Off unless the install starts it on. A change applies to the next reply it writes.\n\n**Handle it for me:**\n\n- It sends from your own mailbox, on its own, some of the replies Act as me writes for your inbox, and some follow-ups.\n- It needs **Draft replies automatically** on the Act as me tab. Until then the card says so and offers **Turn on Draft replies automatically**, or **Connect your mailbox in Act as me** if your mailbox isn't connected.\n- Someone who can't have Act as me sees that Handle it for me isn't available to them.\n- **What it sends on its own**: **Off**, **In training** or **On**.\n - **Off**: every reply waits for you to send.\n - **In training**: every reply and follow-up comes to you first. Tick **Reply to <name> on its own next time** (or **Follow up with them on its own next time**) on a card before **Send** and it handles that person on its own from then on.\n - **On**: it sends what the step under **How much it sends** allows:\n - **Easy ones**: only short replies to people you know, when it's very sure. Follow-ups are written for you and wait on Home.\n - **People I know**: replies to people you know. Strangers, links and amounts wait for you. Follow-ups go to your team and contacts when they haven't answered a question of yours in a few days.\n - **Most mail**: also strangers and longer replies, and links or amounts when it's very sure. Follow-ups go to anyone you wrote to who hasn't answered a question of yours in a few days.\n - **Everything** (the owner only): it decides what to send as you. Replies with a link, the topics that always wait and your rules still hold it back.\n- **In training** and **On** need signed sign-ins on the server. Without them they are greyed out with \"Needs signed sign-ins on this server.\" Turning it off or moving down a step asks first and saves when you confirm.\n- Money, contracts, legal, hiring, the press and passwords always wait for you. It never writes to anyone the email didn't go to. A reply that names the Executive waits too.\n- **Your rules** (at **Everything**): replies matching one wait for you, on top of the company's rules. Pick **A person**, **A company**, **Words** or **An amount**, type the value and click **Add rule**. **Remove** deletes one.\n- **What it sent** (while it is on): \"Sent N replies on its own today\", then each reply and follow-up from the last week: who it went to, the subject, **Still yours to answer** for questions it left for you, and **Open in your mailbox**.\n- **Who it's allowed to handle**: the people you ticked to handle on their own. **Remove** takes one off, and it asks you again.\n- **AI line on replies it sends** (under **Advanced**, when the install adds an AI line): on by default. Turning it off asks you to confirm with **Turn it off** or **Keep it on**.\n- Limits: 20 replies sent on its own a day unless the install changes it, and one a conversation. Past the limit, replies wait on cards.\n\n**Take the lead:**\n\n- The owner's alone. Anyone else sees \"Only the account owner can turn this on.\"\n- **Off**: when it looks over your day, it tells you what it would do, and you do it.\n- **In training**: everything it would do comes to you as a card on Home first. What you allow, it does on its own from then on.\n- **On**: it acts on what it finds while it looks over your day: it messages people, books meetings and starts workflows. Anything under **Always asks first** waits for a yes.\n- **In training** and **On** need signed sign-ins on the server.\n- **What it's learned**: the actions you ticked **on its own next time** on a card. **Remove** takes one off. Something you approved unchanged three times shows as a suggestion with **Allow**.\n- **Always asks first**: a switch for each: **Money**, **Contracts and legal**, **Hiring and people decisions**, **Deleting, cancelling or sharing**, **Someone new** and **Big sends** (company-wide or department-wide, or more than five people). These wait for you, or for whoever approves that area, with a card on Home. **Meetings asked for in chat** is the last row: meetings you or a teammate ask it to book (in a team, Operations must also act on its own). A meeting it thinks of itself always waits. While Take the lead is off, only the meetings row applies.\n- Department levels don't hold what it does here. The switches and rules do.\n- **Company rules**: anything matching one always waits for a yes, for the Executive and for everyone's sending as themselves. Add them the same way as **Your rules**.\n- **Pause** on **Settings → Your Executive** stops everything on this tab. Anything you tap **Send** or **Approve** on still goes.\n\n**Example prompts:**\n\n- \"Reply to Dana as me: yes to the 5th, and ask her to send the deck first.\"\n- \"Write to the Acme team as me and push our call to Thursday.\"\n- \"What's on my calendar tomorrow?\" (with **Read my calendar** on)\n",
+ "markdown": "**What it is:** The place where you decide what the Executive may do without asking you. **Delegate** is in the main menu. It has three tabs: **Act as me**, **Handle it for me** and **Take the lead**. Clicking **Delegate** opens **Act as me**. **What it does for you** sits beside each tab.\n\n**What it does:**\n\n- **What it does for you** says what the Executive does with your settings right now: what it sends on its own, what asks first and what it writes for you to send. It only reads. Nothing on it changes a setting.\n- **Act as me** lets the Executive write email drafts *as you*, from your own Gmail or Outlook mailbox. You send them. It can also write first replies to mail in your inbox that needs you.\n- **Handle it for me** lets it send some of those replies, and some follow-ups, on its own from your mailbox.\n- **Take the lead** (the owner only) lets the Executive act in its own name on what it finds, without waiting to be asked.\n- Normally the Executive writes only as itself, from its own email account. Nothing goes out as you unless you set it up here.\n\n**How to use:**\n\n1. Click **Delegate** in the sidebar. (On a phone, open the menu with the button at the top left.)\n2. Read **What it does for you**, beside the tab, to see what goes out on its own today.\n3. Open **Act as me**, connect your mailbox, and pick what it writes as you.\n4. If you want replies sent for you, open **Handle it for me** and pick how much it sends on its own.\n5. If you are the owner, open **Take the lead** to let the Executive act in its own name.\n\n**What it does for you:**\n\n- On a wide screen it sits to the right of each Delegate tab. Close it with **✕**, and **What it does** at the top of the tab brings it back; this browser remembers which. On a narrow screen, tap **What it does** at the top of the tab and it opens as a sheet from the bottom.\n- Change a setting on the tab and it updates at once. The rows that changed are marked **Just changed** for a few seconds.\n- Three pills: **As you**, **Executive** and **Departments**. The number on each pill is how many things go out on their own.\n- **As you** covers your own mailbox: emails you ask for in chat, inbox replies, what Handle it for me sends, what is in training, what it has learned and your own rules.\n- **Executive** covers what the Executive does in its own name: Take the lead, its Always asks first switches, the company's rules and meetings. Only the owner sees this pill.\n- **Departments** shows each department's authority level and what that level covers.\n- Rows are grouped: **Sends on its own** (green), **Asks first** (amber), **Writes for you to send** and **Off** (grey). Each row says what it does in one line, then why, with a link to the setting.\n- **Compare Act as me, Handle it for me and Take the lead**, at the bottom, opens **Who writes and who sends**. Pick a tab and one of its options. Three answers sit on top: who writes it, whose name is on it and who presses Send. Under them the steps appear one at a time and stay on screen, for example Dana emails you, you ask in chat, the Executive writes the draft, you tap Send. **Handle it for me** shows the same five emails at every level, each marked **Sent as you** or **Waits for you**. Tapping there changes no setting. **Play again** replays the steps.\n- While the Executive is paused, a note at the top says nothing runs on its own, with a **Resume** link.\n- Someone who is not on the People list sees \"Only people on the team can see this.\"\n\n**Act as me:**\n\n- Who can use it: the owner. Team members can use it once the owner turns on **Let team members use it** (under **Advanced** on this tab). That switch shows only when the install allows it. Anyone else sees \"Act as me isn't available to you here.\"\n- Each person connects their own mailbox and turns it on for themselves. What it reads in your mail, the drafts it writes and your reply cards are yours alone. The owner sees only each team member's name, how many drafts they had written and sent in the last 30 days, and whether inbox replies are on. A conversation in which it read someone's mail can be opened only by that person.\n- **Your mailbox**: until it is connected, the card shows the command to run on a computer with a browser (one for Gmail and, where the install supports it, one for Outlook). Sign in as yourself, put the file it writes where the API reads it, then click **Check again**. Once connected it shows \"Connected to\" your address. It won't connect the Executive's own address as yours.\n- **What it writes as you**: \"Nothing goes out until you send it.\" Pick one:\n - **Off**: the Executive only writes as itself.\n - **When I ask**: ask in chat, \"reply to Dana as me: yes to the 5th\", and the draft waits in your Gmail or Outlook Drafts.\n - **Draft replies automatically**: it also writes a first reply to mail that needs you, and puts it on Home.\n- You can't move up from **Off** until your mailbox is connected. Moving down asks first, says what stops, and saves when you click **Move down**. Moving to **When I ask** stops inbox replies. Moving to **Off** stops everything it writes as you and turns **Read my calendar** off. Either one also stops Handle it for me if it was sending.\n- **Learn from my edits** (a checkbox once you are above **Off**): when you change a draft before sending, tick **Do it like this next time** and it learns how you write to that person. Nothing more is sent.\n- **Read my calendar**: a switch. On, it reads your own calendar when you ask about your day or week in chat, and offers your free slots when a reply needs a time. It also brings meeting invites from people you know to Home as cards (see **Meeting invites** below). The only change it makes to your calendar is answering an invite: when you tap **Accept** or **Decline**, or an accept on its own under Handle it for me. It stays off while **What it writes as you** is at **Off**. If your mailbox sign-in doesn't include your calendar, the card shows a command to run once to add it. A sign-in you made before invites could be answered still reads your calendar; run the same command again to let it answer invites.\n- **Suggested actions**: meeting invites and messages your mail calls for. **Always ask** brings each one to you as a card, every time. **In training** also brings each one as a card; tick **Do this on its own next time** before **Approve** and it does that kind, with those people, on its own from then on. **On** sends the message or invite on its own, no card; new contacts, anyone added in the last week, money, links and the topics that always wait still come to you, up to 10 a day.\n- **What it's learned**: what it learned from your edits (drafts) and your approvals (suggested actions). Each item says when, how many times it has been used since, and an example. **Remove** forgets it, and it asks you again.\n- **Advanced** (closed by default) holds **How I write**, **AI line on drafts you send** (shown only when the install adds an AI line to mail) and, for the owner, **Let team members use it**.\n\n**Asking in chat:**\n\n- Ask in the web app (signed in), in a direct message to the Executive on Slack or Discord, or in a private Telegram chat: \"reply to Dana as me: yes to the 5th.\"\n- It saves a draft in your own Drafts and shows a card, \"Drafted an email as you to Dana — in your Drafts\". Asking in chat never sends anything.\n- It does not write as you in a shared channel or thread, on Google Chat, from an email, from a scheduled job or in anyone else's conversation.\n- If it isn't sure about something, it asks you instead of guessing.\n- There is a daily limit on drafts written as one person (50 a day unless the install changes it).\n\n**Draft replies automatically:**\n\n- About every five minutes it looks at new mail in your inbox. For mail that needs a personal reply from you (a question, a request, a meeting to arrange, an introduction or a follow-up), it writes a first reply and puts it at the top of **Needs you** on Home.\n- It only looks at mail that arrives after you turn it on. It leaves out newsletters, notifications, mailing lists, automatic mail, mail you are not in To or Cc on, mail you've already answered and anything that doesn't need you. Mail you answer within ten minutes never gets a draft.\n- The first reply only acknowledges. It repeats only what you've already said in the thread, commits you to nothing and lists what's left for you to decide, each with a few short answers to tap. Tap one, or **Something else…** to type your own, and it rewrites the reply with your answer. For a time, with **Read my calendar** on, it offers your next free slots. For a document, it offers one from your documents to say you'll send it (it can't attach files). **Send** waits until you've answered, or until you change the words with **Edit**. Someone you've never written to gets a short holding reply.\n- Under the picker you see how it is doing (for example, that your mailbox needs connecting again) and when it last looked. Click **Check now** to look straight away.\n- **Also save inbox replies in my Gmail Drafts** (or Outlook): off by default, so replies wait on their cards only. Tick it to keep each reply in your Drafts too.\n- On each card on Home: **Send** asks you to confirm who it goes to, then **Send now**. In training, tick **Reply to <name> on its own next time** before **Send** and replies to that person go on their own from then on. **Edit** changes the words on the card. **Open in Gmail** opens it when it is in your Drafts. **Dismiss** removes the card.\n- Limits: at most 5 drafts a check and 20 a day unless the install changes it, 2 a day per sender (1 for a stranger), and never more than 25 cards open. A card closes when the draft is sent or deleted in your mailbox, when you reply yourself, or after 7 days.\n\n**Meeting invites (with Read my calendar on):**\n\n- An invite from someone you know (your team, a contact, or someone you've written to) becomes a card in **Needs you** on Home: the meeting, when it is, who invited you and anything on your calendar it clashes with. Only the busy times are shown, never what the other meetings are.\n- **Accept** or **Decline** answers it in your own calendar, and your calendar lets them know. **Dismiss** removes the card without answering.\n- Invites from people you don't know, from an address your mail service couldn't confirm, meetings that aren't on your calendar, ones you've already answered and ones that have started are left alone, as before.\n- If your sign-in can read your calendar but not answer invites, the card says so and shows the command to connect again under **Read my calendar**. Until then, answer it in your calendar.\n- A card closes by itself once the meeting starts, or after 7 days.\n\n**How I write (under Advanced):**\n\n- Shows your style as a few sentences, with where it came from (\"Learned from N of your sent emails\", or \"Set by you\") and whether it is locked.\n- **Describe it in your own words**: write how you write, the way you'd tell a new assistant (up to 2,000 characters). Buttons add common phrases, such as \"Short and to the point\" or \"No emojis\". Click **Write my style**; it shows the new style with new lines marked **New** and a sample reply. Click **Save** to keep it or **Change it** to edit your words. Nothing changes until you save.\n- **Learn from my sent mail** (or **Learn again from my sent mail**): reads your recent sent emails once and describes how you write. It needs your mailbox connected and is hidden while the style is locked.\n- **Fine-tune details** opens the fields: **Length** (short, medium, long), **Tone** (casual, neutral, formal), a **Greeting** **To your team**, **To your contacts** and **To anyone else** ({first} becomes their first name), **Sign-off**, **Habits** and **Never** (one per line), your **Signature** and **Examples of your writing**.\n- **Save changes** saves the fields. **Lock** stops it being relearned from your mail (you can still edit it); **Unlock** undoes that. **Reset** starts over. **Remove examples** drops the examples.\n- **Signature**: with Gmail, your signature is added to every draft. **Refresh from Gmail** picks up a change you made in Gmail, **Don't add my signature** stops adding it, and **Add my Gmail signature** brings it back. Outlook doesn't share signatures with apps, so Outlook drafts end with your sign-off.\n- **AI line on drafts you send**: a checkbox for whether drafts you approve and send end with the install's AI line. Off unless the install starts it on. A change applies to the next reply it writes.\n\n**Handle it for me:**\n\n- It sends from your own mailbox, on its own, some of the replies Act as me writes for your inbox, and some follow-ups. With **Read my calendar** on, it also accepts meeting invites from your team and contacts on its own when nothing on your calendar clashes. It never declines on its own: a clash, or an invite from someone it may not handle, still comes to you as a card.\n- It needs **Draft replies automatically** on the Act as me tab. Until then the card says so and offers **Turn on Draft replies automatically**, or **Connect your mailbox in Act as me** if your mailbox isn't connected.\n- Someone who can't have Act as me sees that Handle it for me isn't available to them.\n- **What it sends on its own**: **Off**, **In training** or **On**.\n - **Off**: every reply waits for you to send.\n - **In training**: every reply, follow-up and invite comes to you first. Tick **Reply to <name> on its own next time** (or **Follow up with them on its own next time**) on a card before **Send** and it handles that person on its own from then on. On an invite card, tick **Accept from <name> on its own next time** before **Accept** and their invites with no clash are accepted on their own from then on.\n - **On**: it sends what the step under **How much it sends** allows:\n - **Easy ones**: only short replies to people you know, when it's very sure. Follow-ups are written for you and wait on Home.\n - **People I know**: replies to people you know. Strangers, links and amounts wait for you. Follow-ups go to your team and contacts when they haven't answered a question of yours in a few days.\n - **Most mail**: also strangers and longer replies, and links or amounts when it's very sure. Follow-ups go to anyone you wrote to who hasn't answered a question of yours in a few days.\n - **Everything** (the owner only): it decides what to send as you. Replies with a link, the topics that always wait and your rules still hold it back.\n- **In training** and **On** need signed sign-ins on the server. Without them they are greyed out with \"Needs signed sign-ins on this server.\" Turning it off or moving down a step asks first and saves when you confirm.\n- Money, contracts, legal, hiring, the press and passwords always wait for you. It never writes to anyone the email didn't go to. A reply that names the Executive waits too.\n- **Your rules** (at **Everything**): replies matching one wait for you, on top of the company's rules. Pick **A person**, **A company**, **Words** or **An amount**, type the value and click **Add rule**. **Remove** deletes one.\n- **What it sent** (while it is on): \"Sent N replies on its own today\", then each reply and follow-up from the last week: who it went to, the subject, **Still yours to answer** for questions it left for you, and **Open in your mailbox**. An invite it accepted shows as one line, for example \"Accepted Dana's Pilot review, Wed 21 Oct, 14:30\", and counts toward the same daily limit.\n- **Who it's allowed to handle**: the people you ticked to handle on their own. **Remove** takes one off, and it asks you again.\n- **AI line on replies it sends** (under **Advanced**, when the install adds an AI line): on by default. Turning it off asks you to confirm with **Turn it off** or **Keep it on**.\n- Limits: 20 replies sent on its own a day unless the install changes it, and one a conversation. Past the limit, replies wait on cards.\n\n**Take the lead:**\n\n- The owner's alone. Anyone else sees \"Only the account owner can turn this on.\"\n- **Off**: when it looks over your day, it tells you what it would do, and you do it.\n- **In training**: everything it would do comes to you as a card on Home first. What you allow, it does on its own from then on.\n- **On**: it acts on what it finds while it looks over your day: it messages people, books meetings and starts workflows. Anything under **Always asks first** waits for a yes.\n- **In training** and **On** need signed sign-ins on the server.\n- **What it's learned**: the actions you ticked **on its own next time** on a card. **Remove** takes one off. Something you approved unchanged three times shows as a suggestion with **Allow**.\n- **Always asks first**: a switch for each: **Money**, **Contracts and legal**, **Hiring and people decisions**, **Deleting, cancelling or sharing**, **Someone new** and **Big sends** (company-wide or department-wide, or more than five people). These wait for you, or for whoever approves that area, with a card on Home. **Meetings asked for in chat** is the last row: meetings you or a teammate ask it to book (in a team, Operations must also act on its own). A meeting it thinks of itself always waits. While Take the lead is off, only the meetings row applies.\n- Department levels don't hold what it does here. The switches and rules do.\n- **Company rules**: anything matching one always waits for a yes, for the Executive and for everyone's sending as themselves. Add them the same way as **Your rules**.\n- **Pause** on **Settings → Your Executive** stops everything on this tab. Anything you tap **Send** or **Approve** on still goes.\n\n**Example prompts:**\n\n- \"Reply to Dana as me: yes to the 5th, and ask her to send the deck first.\"\n- \"Write to the Acme team as me and push our call to Thursday.\"\n- \"What's on my calendar tomorrow?\" (with **Read my calendar** on)\n",
"mermaid": null,
- "generated_at": "2026-10-19T17:00:00Z"
+ "generated_at": "2026-10-19T19:00:00Z"
}
diff --git a/packages/core/openexecutive/guide/prebuilt/today.json b/packages/core/openexecutive/guide/prebuilt/today.json
index 564f8e6f..65b29dee 100644
--- a/packages/core/openexecutive/guide/prebuilt/today.json
+++ b/packages/core/openexecutive/guide/prebuilt/today.json
@@ -1,7 +1,7 @@
{
"section_id": "today",
"title": "Today / Morning Brief",
- "markdown": "**What it is:** A single screen of *what needs you right now* — the proactive digest the Executive prepares so you're not the one chasing status. In the app it's **Home**, the screen the app opens on.\n\n**What it does:**\n\n- Opens with a greeting, one line summing up the day (click a part of it — *2 awaiting reply*, *1 department at risk* — to open that list), and an **Ask your Executive anything…** box that starts a chat. On a quiet day the line names one **Move today:** instead.\n- Puts what's waiting on your call up front under **Needs you**: the first card large, the next two below it, and **Show N more** for the rest.\n- Gathers everything else under **Everything else** as a row of count tiles — **Departments**, **People**, **Across the team** (waiting on someone else), **Under way**, **Handled**, **Monitoring**, and **Across your clients** when you look after client companies — shown only when they have something in them. Click a tile to open its full list in a side panel.\n- The **Departments** tile shows each department's goal health — on-track, at-risk, or off-track — with the at-risk goals called out.\n- The **People** tile lists people with open items, their reply counts, SLA status, and whether they're on leave.\n- In your first week, a **Your first week** card at the top asks for one goal with a date (**Set a goal** opens the add form on **Goals**) until you have one, lists up to two things the Executive found when it researched your company and industry during setup, and links to the **Watch list** with what it keeps watching for you. It goes away after seven days, or sooner once you have a goal and there's nothing to show.\n- **Right now**, above **Needs you**, is the Executive's read of the day, rewritten as things change: when it was updated, one line on what matters most, and the top points, each with the time it came in. Points that came in since you last looked get a green dot, with *N new since …* beside the title. **See the whole picture** opens all of it in a side panel: what's new, what's still open, the **Move today** line, what's next on your calendar and, under **Earlier today**, the morning brief you were sent. Tap a point there to talk it through.\n- If your latest morning brief, end-of-day digest or weekly review couldn't be sent to you, a line at the top says why and what to connect. It goes away once that's fixed.\n- When your morning brief or end-of-day digest left out lines that named people or figures the Executive couldn't match to your data, **Left out of your brief** under **Needs you** lists them for a day. **Hide** clears it.\n- With **Delegate → Act as me → What it writes as you** at **Draft replies automatically**, the replies the Executive wrote as you for mail that needs you come first in **Needs you**, marked **Reply waiting** (or **Follow-up waiting** when nobody answered an email you sent). Only you see them.\n- Actions the Executive suggested from your email (a meeting, a message to someone, a new contact) appear as cards in **Needs you**, each spelled out with a box to untick. **Approve** does the ticked ones (**Approve N** when you untick some), ticking **Do this on its own next time** first (shown while it is still learning) also lets it do that kind of action on its own from now on, and **Dismiss** drops the card. Only you see them.\n- A send or edit a team member asked for in chat that their department held waits as a card marked **Waiting on you**, with the reason and the exact details. **Approve** carries it out as shown; **Decline** drops it.\n- An item a team member asked the Executive to raise starts with **Raised by** and their name. It goes to a person or a department, never to the whole company. Team members can dismiss only items assigned to them; the owner can dismiss any item.\n- Under **Take the lead**, something the Executive wanted to do on its own that you haven't allowed yet comes as a card: **Approve** does it once (tick **Do this on its own next time** first and it does the same thing with the same person on its own from now on), **Edit** changes it first (tick **Do it like this next time** to keep your edit as an example and allow it), and **Decline** drops it.\n- Surfaces proposals and alerts you can click to open a chat thread with full context.\n\n**How to use:**\n\n1. Click **Home** in the sidebar (or the Open Executive logo). On a phone, **Home** is the first button in the bar at the bottom.\n2. Work **Needs you** from the top. Each card has one main button and **Discuss**; everything else is in the card's **⋯** menu:\n - **Approve** — accept the recommendation; the Executive carries it out right away. A line at the top of **Needs you** shows it working and then done, with a link to the chat where it did the work. If it didn't work, **Try again** is on that line. Usually the main button.\n - **Discuss** — open a chat with the context already filled in.\n - **Edit & approve** (in **⋯**) — reword the action first, then **Send approval**; your text is used exactly as written.\n - **Dismiss** (in **⋯**) — drop it and stay on Home. When the Executive thinks a card is stale, **Dismiss** is the main button instead.\n - **Snooze until …** (in **⋯**) — three hours from now (while that is still today), **tomorrow 9:00**, or **Monday 9:00** (not offered on a Sunday). The card leaves Home and comes back on its own then; *Snoozed until …* with **Undo** under **Needs you** brings it back now.\n - **Nudge *name*** — the main button when the best move is chasing someone for a reply; **Run *workflow*** when the best move is a workflow.\n - **Open *name*'s page** (in **⋯**) — the person the item is waiting on.\n - A **Monitoring** signal leads with **Discuss**; its **⋯** has **Dismiss signal**.\n3. Some cards are simpler: when a scheduled run didn't finish (a department check-in, or a workflow you set to run on a schedule), its card's main button is **Run again**, which runs it now and sends the result where it normally goes (**Open the run** in **⋯** shows what went wrong); a document card's main button is **Open document** (**Mark reviewed** is in its **⋯**, and **Open in app** when the document lives in another app), and a calendar-booking card books (or declines) the meeting directly when you click Approve or Dismiss. Only the person a booking was sent to for approval, or the owner, can approve or decline it.\n4. Keep it tidy from the **⋯** next to **Needs you**: **Dismiss N older than 7 days** clears stale items, and **Re-check relevance** asks the Executive to review every open item now.\n5. Open the **Departments** tile and click a department to ask for its status in chat.\n6. Work the replies waiting to be sent (they come first in **Needs you**). Each card shows who wrote (and *Address not verified* when the address couldn't be confirmed), **What they wrote** (click to open), **Your draft** with who it goes to, *Why it waited for you* when Handle it for me left it for you, **Decide before sending** (what the draft leaves for you to answer, with short answers to tap. Tap one, or **Something else…** to type your own, and the draft is rewritten with it; the new words are lightly marked. For a time it can offer free slots from your calendar, when Read my calendar is on, and for a document one from your documents to say you'll send. **Send** waits until each of these is answered, or until you change the words with **Edit**) and any warnings. The buttons:\n - **Send** asks once, naming who the reply goes to, then **Send now** sends it from your own mailbox (Gmail or Outlook). If the recipients changed or they wrote again since, it asks again, says what changed, and offers **Send anyway**.\n - **Reply to <name> on its own next time** (a tick shown while replies are still being learned): tick it before **Send** and replies to that person go on their own from now on while Handle it for me is on.\n - **Edit** changes the words right on the card; **Save** keeps them (and updates the draft in your mailbox when it is kept there too). When it is learning how you write, **Do it like this next time (if you changed it)** appears as you send.\n - **Open in Gmail** (or Outlook) opens the draft there, when it is kept in your Drafts.\n - **Dismiss** drops the card, and deletes the draft from your Drafts unless you changed it there.\n On a server, Send needs signed sign-ins; until they're set up, send from your mailbox. A card goes away on its own once you send or delete the draft in your mailbox, or reply yourself, and after 7 days.\n\n**Example:** in a Discuss thread, just say *\"go ahead\"* to approve the proposal or *\"drop it\"* to dismiss it — no need to go back to the card. (Calendar bookings still need the Approve button. When you asked for the meeting in a chat, its card is under that reply too.)\n\n**Just for yourself?** If you use Open Executive just for yourself (**Settings → Workspace → Personal**), Home leaves out the team parts: there are no Departments, People or Across the team tiles — everything that needs a decision is in **Needs you**. When a goal is slipping, the summary line at the top says how many goals are at risk; click it to open **Goals**. Instead, the tiles are **Due soon**, **Your projects** and **This week's review**, each opening its list in a side panel. **Your projects** lists the projects the Executive is tracking for you. Click **Done** when one is finished, or **Drop** to stop tracking it (it asks first, and removes the project from Pulse). **Due soon** lists what you've promised by a date and what others have asked of you, due in the next week — say *\"I'll send Northwind the proposal by Friday\"* in the web chat or your own Slack or Discord and it shows up here, and the Executive reminds you when it's due. Click **Done** once it's handled; **All open items** opens the full list. **Top three today**, right under **Needs you**, shows the three things to focus on today — the same three your morning brief opens with — each with a free slot in today's working hours when the Executive can read your calendar. **This week's review** shows your latest weekly review: when it ran and next week's top three. Click **Read the review** to see all of it.\n\nYour morning brief also opens with a **top three for today**, picked from what's overdue or due, goals that are slipping and the projects you're driving. When Google Workspace is connected and the Executive can read your calendar (it is your own account, or you shared your calendar with it), each of the three gets a free slot in today's working hours and the brief lists today's meetings; otherwise the three come without times. Every Friday afternoon (in your time zone) a **weekly review** arrives the same way: your goals graded by area, what's due or overdue, projects that went quiet, the week's decisions, a few older decisions to look back on, and next week's top three. Both also show up on Home (see above), so you see them even when no chat app or email is connected. When it asks how an older decision turned out, just tell the Executive in the web chat or your own Slack or Discord and it records the outcome against that decision.\n\n*Note: proposals are routed to the right person automatically based on who has authority over them.*",
+ "markdown": "**What it is:** A single screen of *what needs you right now* — the proactive digest the Executive prepares so you're not the one chasing status. In the app it's **Home**, the screen the app opens on.\n\n**What it does:**\n\n- Opens with a greeting, one line summing up the day (click a part of it — *2 awaiting reply*, *1 department at risk* — to open that list), and an **Ask your Executive anything…** box that starts a chat. On a quiet day the line names one **Move today:** instead.\n- Puts what's waiting on your call up front under **Needs you**: the first card large, the next two below it, and **Show N more** for the rest.\n- Gathers everything else under **Everything else** as a row of count tiles — **Departments**, **People**, **Across the team** (waiting on someone else), **Under way**, **Handled**, **Monitoring**, and **Across your clients** when you look after client companies — shown only when they have something in them. Click a tile to open its full list in a side panel.\n- The **Departments** tile shows each department's goal health — on-track, at-risk, or off-track — with the at-risk goals called out.\n- The **People** tile lists people with open items, their reply counts, SLA status, and whether they're on leave.\n- In your first week, a **Your first week** card at the top asks for one goal with a date (**Set a goal** opens the add form on **Goals**) until you have one, lists up to two things the Executive found when it researched your company and industry during setup, and links to the **Watch list** with what it keeps watching for you. It goes away after seven days, or sooner once you have a goal and there's nothing to show.\n- **Right now**, above **Needs you**, is the Executive's read of the day, rewritten as things change: when it was updated, one line on what matters most, and the top points, each with the time it came in. Points that came in since you last looked get a green dot, with *N new since …* beside the title. **See the whole picture** opens all of it in a side panel: what's new, what's still open, the **Move today** line, what's next on your calendar and, under **Earlier today**, the morning brief you were sent. Tap a point there to talk it through.\n- If your latest morning brief, end-of-day digest or weekly review couldn't be sent to you, a line at the top says why and what to connect. It goes away once that's fixed.\n- When your morning brief or end-of-day digest left out lines that named people or figures the Executive couldn't match to your data, **Left out of your brief** under **Needs you** lists them for a day. **Hide** clears it.\n- With **Delegate → Act as me → What it writes as you** at **Draft replies automatically**, the replies the Executive wrote as you for mail that needs you come first in **Needs you**, marked **Reply waiting** (or **Follow-up waiting** when nobody answered an email you sent). Only you see them.\n- With **Read my calendar** on, a meeting invite from someone you know appears as a card in **Needs you**, marked **Invite**: the meeting, when it is, who invited you and anything on your calendar it clashes with (only the times). **Accept** or **Decline** answers it in your own calendar, and your calendar lets them know; **Dismiss** removes the card without answering. While replies are still being learned, ticking **Accept from <name> on its own next time** before **Accept** lets it accept their invites on its own when nothing clashes. If your calendar sign-in can't answer invites yet, the card says to connect again under **Read my calendar** instead. Only you see them.\n- Actions the Executive suggested from your email (a meeting, a message to someone, a new contact) appear as cards in **Needs you**, each spelled out with a box to untick. **Approve** does the ticked ones (**Approve N** when you untick some), ticking **Do this on its own next time** first (shown while it is still learning) also lets it do that kind of action on its own from now on, and **Dismiss** drops the card. Only you see them.\n- A send or edit a team member asked for in chat that their department held waits as a card marked **Waiting on you**, with the reason and the exact details. **Approve** carries it out as shown; **Decline** drops it.\n- An item a team member asked the Executive to raise starts with **Raised by** and their name. It goes to a person or a department, never to the whole company. Team members can dismiss only items assigned to them; the owner can dismiss any item.\n- Under **Take the lead**, something the Executive wanted to do on its own that you haven't allowed yet comes as a card: **Approve** does it once (tick **Do this on its own next time** first and it does the same thing with the same person on its own from now on), **Edit** changes it first (tick **Do it like this next time** to keep your edit as an example and allow it), and **Decline** drops it.\n- Surfaces proposals and alerts you can click to open a chat thread with full context.\n\n**How to use:**\n\n1. Click **Home** in the sidebar (or the Open Executive logo). On a phone, **Home** is the first button in the bar at the bottom.\n2. Work **Needs you** from the top. Each card has one main button and **Discuss**; everything else is in the card's **⋯** menu:\n - **Approve** — accept the recommendation; the Executive carries it out right away. A line at the top of **Needs you** shows it working and then done, with a link to the chat where it did the work. If it didn't work, **Try again** is on that line. Usually the main button.\n - **Discuss** — open a chat with the context already filled in.\n - **Edit & approve** (in **⋯**) — reword the action first, then **Send approval**; your text is used exactly as written.\n - **Dismiss** (in **⋯**) — drop it and stay on Home. When the Executive thinks a card is stale, **Dismiss** is the main button instead.\n - **Snooze until …** (in **⋯**) — three hours from now (while that is still today), **tomorrow 9:00**, or **Monday 9:00** (not offered on a Sunday). The card leaves Home and comes back on its own then; *Snoozed until …* with **Undo** under **Needs you** brings it back now.\n - **Nudge *name*** — the main button when the best move is chasing someone for a reply; **Run *workflow*** when the best move is a workflow.\n - **Open *name*'s page** (in **⋯**) — the person the item is waiting on.\n - A **Monitoring** signal leads with **Discuss**; its **⋯** has **Dismiss signal**.\n3. Some cards are simpler: when a scheduled run didn't finish (a department check-in, or a workflow you set to run on a schedule), its card's main button is **Run again**, which runs it now and sends the result where it normally goes (**Open the run** in **⋯** shows what went wrong); a document card's main button is **Open document** (**Mark reviewed** is in its **⋯**, and **Open in app** when the document lives in another app), and a calendar-booking card books (or declines) the meeting directly when you click Approve or Dismiss. Only the person a booking was sent to for approval, or the owner, can approve or decline it.\n4. Keep it tidy from the **⋯** next to **Needs you**: **Dismiss N older than 7 days** clears stale items, and **Re-check relevance** asks the Executive to review every open item now.\n5. Open the **Departments** tile and click a department to ask for its status in chat.\n6. Work the replies waiting to be sent (they come first in **Needs you**). Each card shows who wrote (and *Address not verified* when the address couldn't be confirmed), **What they wrote** (click to open), **Your draft** with who it goes to, *Why it waited for you* when Handle it for me left it for you, **Decide before sending** (what the draft leaves for you to answer, with short answers to tap. Tap one, or **Something else…** to type your own, and the draft is rewritten with it; the new words are lightly marked. For a time it can offer free slots from your calendar, when Read my calendar is on, and for a document one from your documents to say you'll send. **Send** waits until each of these is answered, or until you change the words with **Edit**) and any warnings. The buttons:\n - **Send** asks once, naming who the reply goes to, then **Send now** sends it from your own mailbox (Gmail or Outlook). If the recipients changed or they wrote again since, it asks again, says what changed, and offers **Send anyway**.\n - **Reply to <name> on its own next time** (a tick shown while replies are still being learned): tick it before **Send** and replies to that person go on their own from now on while Handle it for me is on.\n - **Edit** changes the words right on the card; **Save** keeps them (and updates the draft in your mailbox when it is kept there too). When it is learning how you write, **Do it like this next time (if you changed it)** appears as you send.\n - **Open in Gmail** (or Outlook) opens the draft there, when it is kept in your Drafts.\n - **Dismiss** drops the card, and deletes the draft from your Drafts unless you changed it there.\n On a server, Send needs signed sign-ins; until they're set up, send from your mailbox. A card goes away on its own once you send or delete the draft in your mailbox, or reply yourself, and after 7 days.\n\n**Example:** in a Discuss thread, just say *\"go ahead\"* to approve the proposal or *\"drop it\"* to dismiss it — no need to go back to the card. (Calendar bookings still need the Approve button. When you asked for the meeting in a chat, its card is under that reply too.)\n\n**Just for yourself?** If you use Open Executive just for yourself (**Settings → Workspace → Personal**), Home leaves out the team parts: there are no Departments, People or Across the team tiles — everything that needs a decision is in **Needs you**. When a goal is slipping, the summary line at the top says how many goals are at risk; click it to open **Goals**. Instead, the tiles are **Due soon**, **Your projects** and **This week's review**, each opening its list in a side panel. **Your projects** lists the projects the Executive is tracking for you. Click **Done** when one is finished, or **Drop** to stop tracking it (it asks first, and removes the project from Pulse). **Due soon** lists what you've promised by a date and what others have asked of you, due in the next week — say *\"I'll send Northwind the proposal by Friday\"* in the web chat or your own Slack or Discord and it shows up here, and the Executive reminds you when it's due. Click **Done** once it's handled; **All open items** opens the full list. **Top three today**, right under **Needs you**, shows the three things to focus on today — the same three your morning brief opens with — each with a free slot in today's working hours when the Executive can read your calendar. **This week's review** shows your latest weekly review: when it ran and next week's top three. Click **Read the review** to see all of it.\n\nYour morning brief also opens with a **top three for today**, picked from what's overdue or due, goals that are slipping and the projects you're driving. When Google Workspace is connected and the Executive can read your calendar (it is your own account, or you shared your calendar with it), each of the three gets a free slot in today's working hours and the brief lists today's meetings; otherwise the three come without times. Every Friday afternoon (in your time zone) a **weekly review** arrives the same way: your goals graded by area, what's due or overdue, projects that went quiet, the week's decisions, a few older decisions to look back on, and next week's top three. Both also show up on Home (see above), so you see them even when no chat app or email is connected. When it asks how an older decision turned out, just tell the Executive in the web chat or your own Slack or Discord and it records the outcome against that decision.\n\n*Note: proposals are routed to the right person automatically based on who has authority over them.*",
"mermaid": null,
- "generated_at": "2026-10-19T17:00:00Z"
+ "generated_at": "2026-10-19T19:00:00Z"
}
diff --git a/packages/core/tests/unit/test_delegation_gmail.py b/packages/core/tests/unit/test_delegation_gmail.py
index ddd6138c..fa69b47d 100644
--- a/packages/core/tests/unit/test_delegation_gmail.py
+++ b/packages/core/tests/unit/test_delegation_gmail.py
@@ -28,6 +28,7 @@ from openexecutive.delegation.gmail import (
GmailCredential,
GmailError,
GmailNotConfigured,
+ MailMessage,
build_raw,
email_key,
gmail_link,
@@ -346,7 +347,10 @@ def test_the_only_send_is_an_existing_draft_by_its_id() -> None:
# Checks an id's shape (Gmail's and Outlook's differ); no call.
"valid_id",
# Read my calendar (delegation.calendar): read-only.
- "list_events", "calendar_granted",
+ "list_events", "calendar_granted", "calendar_write_granted", "find_invite",
+ # Answer a meeting invite as them (delegation.invites): their own
+ # attendee answer on one event, nothing else.
+ "answer_invite",
# A contact's newest mail, for their signature (people.contact_keeper): read-only.
"latest_from",
}
@@ -719,7 +723,8 @@ def test_a_refused_calendar_read_is_not_granted_not_a_reconnect() -> None:
def test_the_script_asks_for_the_calendar_only_with_the_flag() -> None:
script = _script()
payload = script.credential_payload(EMAIL, "r", "c", "s", scopes=[*script.SCOPES, script.CALENDAR_SCOPE])
- assert payload["scopes"][-1] == gm.SCOPE_CALENDAR
+ # calendar.events: reads, and answers invites (delegation.invites).
+ assert payload["scopes"][-1] == gm.SCOPE_CALENDAR_EVENTS
assert script.credential_payload(EMAIL, "r", "c", "s")["scopes"] == list(gm.SCOPES)
@@ -733,3 +738,111 @@ def test_each_recipient_keeps_the_name_it_was_written_with() -> None:
assert message.names == {
"[email protected]": "Shah, Priya", "[email protected]": "", "[email protected]": "Marco Diaz",
}
+
+
+# --------------------------------------------------------------------------- #
+# Meeting invites (delegation.invites)
+# --------------------------------------------------------------------------- #
+
+_ICS = (
+ "BEGIN:VCALENDAR\r\nMETHOD:REQUEST\r\nBEGIN:VTIMEZONE\r\nTZID:UTC\r\nEND:VTIMEZONE\r\n"
+ "BEGIN:VEVENT\r\nUID:abc123-very-long-uid-that-is-folded@\r\n google.com\r\nSUMMARY:Pilot review\r\n"
+ "END:VEVENT\r\nEND:VCALENDAR\r\n"
+)
+
+
+def test_an_invite_keeps_its_method_and_uid_and_nothing_else() -> None:
+ assert gm.ics_invite(_ICS) == ("REQUEST", "[email protected]")
+ assert gm.ics_invite("BEGIN:VCALENDAR\nMETHOD:CANCEL\nBEGIN:VEVENT\nUID:x1\nEND:VEVENT") == ("CANCEL", "x1")
+ assert gm.ics_invite("not a calendar") == ("", "")
+ invite = _message({"From": "[email protected]"}, plain="Invitation")
+ invite["payload"]["parts"].append({"mimeType": "text/calendar", "body": {"data": _b64(_ICS)}})
+ parsed = parse_message(invite)
+ assert (parsed.invite_method, parsed.invite_uid) == ("REQUEST", "[email protected]")
+
+
+def _invite_google(scope: str, *, items: list[dict[str, Any]] | None = None, event: dict[str, Any] | None = None,
+ status: int = 200) -> tuple[list[httpx.Request], DelegateGmail]:
+ seen: list[httpx.Request] = []
+
+ def handler(request: httpx.Request) -> httpx.Response:
+ seen.append(request)
+ if request.url.host == "oauth2.googleapis.com":
+ return httpx.Response(200, json={"access_token": "at", "expires_in": 3600, "scope": scope})
+ if status != 200:
+ return httpx.Response(status, json={"error": {"code": status, "errors": [{"reason": "forbidden"}]}})
+ if request.url.path.endswith("/events"):
+ return httpx.Response(200, json={"items": items or []})
+ return httpx.Response(200, json=event or {})
+
+ return seen, DelegateGmail(EMAIL, credential=_cred(), transport=httpx.MockTransport(handler))
+
+
+def test_an_invite_is_found_on_their_calendar_by_its_uid() -> None:
+ gm._TOKENS.clear()
+ item = {"id": "ev1", "summary": "Pilot review", "start": {"dateTime": "2026-10-14T16:00:00Z"},
+ "end": {"dateTime": "2026-10-14T16:30:00Z"}, "organizer": {"email": "[email protected]"},
+ "attendees": [{"email": EMAIL, "self": True, "responseStatus": "needsAction"}]}
+ seen, client = _invite_google(" ".join([*gm.SCOPES, gm.SCOPE_CALENDAR_EVENTS]), items=[item])
+ message = MailMessage(id="m1", thread_id="t1", calendar_invite=True, invite_method="REQUEST", invite_uid="u1@x")
+ event = asyncio.run(client.find_invite(message))
+ assert event is not None and (event.id, event.response) == ("ev1", "needs_action")
+ assert seen[-1].url.path == "/calendar/v3/calendars/primary/events" and seen[-1].url.params["iCalUID"] == "u1@x"
+ # A cancellation or someone's answer is never a request to answer.
+ cancelled = MailMessage(id="m2", thread_id="t1", calendar_invite=True, invite_method="CANCEL", invite_uid="u1@x")
+ assert asyncio.run(client.find_invite(cancelled)) is None
+
+
+def test_answering_changes_only_their_own_answer_and_tells_the_organizer() -> None:
+ gm._TOKENS.clear()
+ event = {"id": "ev1", "attendees": [
+ {"email": "[email protected]", "organizer": True, "responseStatus": "accepted"},
+ {"email": EMAIL, "self": True, "responseStatus": "needsAction"},
+ {"email": "[email protected]", "responseStatus": "tentative"},
+ ]}
+ seen, client = _invite_google(" ".join([*gm.SCOPES, gm.SCOPE_CALENDAR_EVENTS]), event=event)
+ asyncio.run(client.answer_invite("ev1", accept=False))
+ patch = next(r for r in seen if r.method == "PATCH")
+ assert patch.url.path == "/calendar/v3/calendars/primary/events/ev1" and patch.url.params["sendUpdates"] == "all"
+ body = json.loads(patch.content)
+ assert list(body) == ["attendees"]
+ assert [a["responseStatus"] for a in body["attendees"]] == ["accepted", "declined", "tentative"]
+ with pytest.raises(GmailError):
+ asyncio.run(client.answer_invite("ev1/../../other", accept=True))
+
+
+def test_answering_writes_against_the_event_it_read_and_reads_again_once_if_it_changed() -> None:
+ gm._TOKENS.clear()
+ reads = iter(["\"v1\"", "\"v2\""])
+ seen: list[httpx.Request] = []
+ scope = " ".join([*gm.SCOPES, gm.SCOPE_CALENDAR_EVENTS])
+
+ def handler(request: httpx.Request) -> httpx.Response:
+ seen.append(request)
+ if request.url.host == "oauth2.googleapis.com":
+ return httpx.Response(200, json={"access_token": "at", "expires_in": 3600, "scope": scope})
+ if request.method == "GET":
+ return httpx.Response(200, json={"id": "ev1", "etag": next(reads), "attendees": [
+ {"email": EMAIL, "self": True, "responseStatus": "needsAction"}]})
+ if request.headers.get("If-Match") == '"v1"':
+ return httpx.Response(412, json={"error": {"code": 412}})
+ return httpx.Response(200, json={})
+
+ client = DelegateGmail(EMAIL, credential=_cred(), transport=httpx.MockTransport(handler))
+ asyncio.run(client.answer_invite("ev1", accept=True))
+ patches = [r.headers.get("If-Match") for r in seen if r.method == "PATCH"]
+ assert patches == ['"v1"', '"v2"']
+
+
+def test_a_read_only_sign_in_reads_but_cannot_answer() -> None:
+ gm._TOKENS.clear()
+ seen, client = _invite_google(" ".join([*gm.SCOPES, gm.SCOPE_CALENDAR]))
+ assert asyncio.run(client.calendar_granted()) is True
+ assert asyncio.run(client.calendar_write_granted()) is False
+ with pytest.raises(gm.CalendarWriteNotGranted):
+ asyncio.run(client.answer_invite("ev1", accept=True))
+ assert all(r.url.host == "oauth2.googleapis.com" for r in seen)
+ gm._TOKENS.clear()
+ _seen, events_scope = _invite_google(" ".join([*gm.SCOPES, gm.SCOPE_CALENDAR_EVENTS]))
+ assert asyncio.run(events_scope.calendar_granted()) is True # calendar.events reads too
+ assert asyncio.run(events_scope.calendar_write_granted()) is True
diff --git a/packages/core/tests/unit/test_delegation_invites.py b/packages/core/tests/unit/test_delegation_invites.py
new file mode 100644
index 00000000..52cfb2f9
--- /dev/null
+++ b/packages/core/tests/unit/test_delegation_invites.py
@@ -0,0 +1,398 @@
+"""Meeting invites under Act as me (delegation/invites.py): an invite from
+someone the person knows becomes a card to accept or decline in their own
+calendar, Handle it for me accepts one on its own when nothing clashes, and
+everything else is skipped as before."""
+from __future__ import annotations
+
+import asyncio
+import json
+import sqlite3
+from datetime import UTC, datetime, timedelta
+from pathlib import Path
+from typing import Any
+
+import pytest
+from fastapi import FastAPI
+from fastapi.testclient import TestClient
+
+from openexecutive.api.routes import decisions as decisions_route
+from openexecutive.api.routes import delegation as route
+from openexecutive.delegation import calendar, handle_it, inbox, invites, training
+from openexecutive.delegation.gmail import CalendarEvent, CalendarWriteNotGranted, MailMessage
+from openexecutive.memory import decision_ledger as ledger
+
+from . import test_delegation_inbox as _inbox_tests
+from .test_delegation_inbox import DANA, NOW, OWNER, FakeInbox, _ledger, _msg, _scan
+
+db = _inbox_tests.db
+owner = _inbox_tests.owner
+models = _inbox_tests.models
+
+START = (NOW + timedelta(days=1)).replace(hour=14, minute=0)
+END = START + timedelta(minutes=30)
+
+
[email protected](autouse=True)
+def setup(monkeypatch: pytest.MonkeyPatch) -> None:
+ """Local login (the API can tie a tap or the switch to the person), and
+ the workspace in UTC."""
+ monkeypatch.setenv("OE_LOCAL_LOGIN", "1")
+ monkeypatch.delenv("OE_PUBLIC_DEPLOYMENT", raising=False)
+ monkeypatch.delenv("CALLER_ASSERTION_PUBLIC_KEYS", raising=False)
+ monkeypatch.setattr(invites, "_tz", lambda: UTC)
+ monkeypatch.setattr(invites, "_now", lambda: NOW)
+
+
+def person(owner: Any) -> Any:
+ calendar.set_enabled(owner.id, True, updated_by="test")
+ return owner
+
+
+class FakeCalendar(FakeInbox):
+ """The owner's mailbox and calendar: invites it finds, what's on the
+ calendar, and every answer it gave."""
+
+ def __init__(self) -> None:
+ super().__init__()
+ self.events: dict[str, CalendarEvent] = {}
+ self.busy: list[CalendarEvent] = []
+ self.answers: list[tuple[str, bool]] = []
+ self.write_granted: bool | None = True
+ self.answer_error: Exception | None = None
+
+ async def find_invite(self, message: MailMessage) -> CalendarEvent | None:
+ self.calls.append(f"find_invite:{message.id}")
+ return self.events.get(message.id)
+
+ async def list_events(self, start: datetime, end: datetime, *, max_results: int = 100) -> list[CalendarEvent]:
+ self.calls.append("list_events")
+ return list(self.busy)
+
+ async def calendar_write_granted(self) -> bool | None:
+ return self.write_granted
+
+ async def answer_invite(self, event_id: str, *, accept: bool) -> None:
+ if self.answer_error is not None:
+ raise self.answer_error
+ self.answers.append((event_id, accept))
+
+
+def _event(event_id: str = "ev1", *, title: str = "Pilot review", organizer: str = DANA,
+ start: datetime = START, end: datetime = END, response: str = "needs_action") -> CalendarEvent:
+ return CalendarEvent(
+ id=event_id, title=title, start=start.isoformat(), end=end.isoformat(),
+ organizer=f"Dana Park <{organizer}>", response=response,
+ )
+
+
+def _invite(mid: str = "i1", thread: str = "ti1", **kw: Any) -> MailMessage:
+ kw.setdefault("text", "Invitation: Pilot review")
+ return _msg(mid, thread, calendar_invite=True, auto_generated=True, **kw)
+
+
+def _mailbox(*messages: MailMessage, event: CalendarEvent | None = None) -> FakeCalendar:
+ mailbox = FakeCalendar()
+ mailbox.add(*(messages or (_invite(),)))
+ for m in messages or (_invite(),):
+ if event is not None or m.id == "i1":
+ mailbox.events[m.id] = event or _event()
+ return mailbox
+
+
+def _cards(person: Any) -> list[Any]:
+ return ledger.list_instances(invites.DECISION_CLASS, limit=50)
+
+
+# ── the card ──────────────────────────────────────────────────────────────────
+
+
+def test_read_my_calendar_off_skips_an_invite_as_before(db: Path, owner: Any, models: dict[str, Any]) -> None:
+ mailbox = _mailbox()
+ result = _scan(owner, mailbox)
+ assert result.invites == 0 and _ledger(db)["i1"] == ("skipped", "automatic")
+ assert not any(c.startswith("find_invite") for c in mailbox.calls)
+
+
+def test_an_invite_from_a_contact_becomes_a_card_with_no_model_call(
+ db: Path, person: Any, models: dict[str, Any]
+) -> None:
+ mailbox = _mailbox()
+ result = _scan(person, mailbox)
+ assert result.invites == 1 and result.drafted == 0
+ assert models["classified"] == [] and models["composed"] == [] # no model reads an invite
+ (card,) = _cards(person)
+ assert card.status == "proposed" and card.gate_mode == "propose" and card.approver_person_id == person.id
+ payload = json.loads(card.proposed_payload_json)
+ assert payload["private"] is True and payload["event_id"] == "ev1" and payload["title"] == "Pilot review"
+ assert payload["clashes"] == [] and payload["can_answer"] is True and "handle_it_reason" not in payload
+ (shown,) = invites.cards(person)
+ assert shown.when == "Thu 1 Oct, 14:00–14:30" and shown.from_email == DANA and shown.relation == "contact"
+ assert _ledger(db)["i1"] == (invites.CARDED, None)
+ assert mailbox.answers == [] # nothing answered until they tap
+
+
+def test_a_clash_shows_busy_times_only(person: Any, models: dict[str, Any]) -> None:
+ mailbox = _mailbox()
+ mailbox.busy = [
+ _event("other", title="Secret board prep", start=START - timedelta(minutes=15), end=START + timedelta(minutes=15)),
+ _event("ev1"), # the meeting itself
+ _event("free", title="Lunch", start=END, end=END + timedelta(hours=1)), # touching, not clashing
+ _event("no", title="Declined thing", response="declined"),
+ ]
+ _scan(person, mailbox)
+ (card,) = _cards(person)
+ assert json.loads(card.proposed_payload_json)["clashes"] == ["13:45–14:15"]
+ assert "Secret" not in card.proposed_payload_json
+
+
[email protected](("message", "event", "reason"), [
+ (_invite(sender="[email protected]", name="Pat"), _event(organizer="[email protected]"), "invite_stranger"),
+ (_invite(sender_authenticated=False), _event(), "invite_unverified"),
+ (_invite(), None, "invite_not_found"),
+ (_invite(), _event(organizer="[email protected]"), "invite_not_organizer"),
+ (_invite(), _event(response="accepted"), "invite_answered"),
+ (_invite(), _event(start=NOW - timedelta(hours=1), end=NOW), "invite_past"),
+ (_invite(to=["[email protected]"]), _event(), "not_addressed"),
+])
+def test_what_gets_no_card(
+ db: Path, person: Any, models: dict[str, Any], message: MailMessage, event: CalendarEvent | None, reason: str,
+) -> None:
+ mailbox = FakeCalendar()
+ mailbox.add(message)
+ if event is not None:
+ mailbox.events[message.id] = event
+ result = _scan(person, mailbox)
+ assert result.invites == 0 and _cards(person) == []
+ assert _ledger(db)[message.id] == ("skipped", reason)
+
+
+def test_one_card_per_invite_and_the_thread_waits(person: Any, models: dict[str, Any]) -> None:
+ mailbox = _mailbox()
+ _scan(person, mailbox)
+ mailbox.add(_invite("i2", "ti1", minutes_ago=20))
+ mailbox.events["i2"] = _event()
+ again = _scan(person, mailbox, now=NOW + timedelta(minutes=10))
+ assert again.invites == 0 and len(_cards(person)) == 1 and again.deferred == 1
+
+
+def test_a_card_closes_once_the_meeting_starts(db: Path, person: Any, models: dict[str, Any]) -> None:
+ mailbox = _mailbox()
+ _scan(person, mailbox)
+ later = _scan(person, mailbox, now=START + timedelta(minutes=1))
+ assert later.closed == 1 and _cards(person)[0].status == "closed_externally"
+ assert _ledger(db)["i1"][0] == "expired"
+
+
+# ── on its own ────────────────────────────────────────────────────────────────
+
+
+def _on(person: Any) -> None:
+ handle_it.set_(person.id, enabled=True, updated_by="test")
+
+
+def test_handle_it_accepts_with_no_clash_and_says_so(db: Path, person: Any, models: dict[str, Any]) -> None:
+ _on(person)
+ mailbox = _mailbox()
+ result = _scan(person, mailbox)
+ assert result.handled == 1 and mailbox.answers == [("ev1", True)]
+ (card,) = _cards(person)
+ assert card.status == "executed" and card.gate_mode == "auto_execute" and card.resolver_person_id is None
+ assert _ledger(db)["i1"] == (invites.ACCEPTED, "handled")
+ assert handle_it.sent_today(person.id, NOW) == 1 # the same daily limit as replies
+ (done,) = [h for h in handle_it.handled(person.id) if h.source == "invite"]
+ assert done.summary == "Accepted Dana's Pilot review, Thu 1 Oct, 14:00"
+ assert invites.cards(person) == []
+
+
+def test_handle_it_leaves_a_card_for_someone_they_have_only_written_to(
+ person: Any, models: dict[str, Any],
+) -> None:
+ """A sender known only from their Sent mail is no contact: an invite from
+ them waits on a tap, whatever the level."""
+ _on(person)
+ mailbox = _mailbox(_invite(sender=pat, name="Pat"), event=_event(organizer=pat))
+ mailbox.written_to.add(pat)
+ result = _scan(person, mailbox)
+ assert result.handled == 0 and mailbox.answers == []
+ (card,) = invites.cards(person)
+ assert card.relation == "correspondent" and card.status == "proposed"
+
+
[email protected](("arrange", "reason"), [
+ (lambda m: setattr(m, "busy", [_event("x", title="Standup")]), "clash"),
+ (lambda m: setattr(m, "write_granted", False), "calendar_write"),
+ (lambda m: m.events.__setitem__("i1", _event(title="Board pay review")), "sensitive"),
+])
+def test_handle_it_leaves_a_card_when_something_is_against_it(
+ person: Any, models: dict[str, Any], arrange: Any, reason: str,
+) -> None:
+ _on(person)
+ mailbox = _mailbox()
+ arrange(mailbox)
+ result = _scan(person, mailbox)
+ assert result.handled == 0 and mailbox.answers == []
+ (card,) = invites.cards(person)
+ assert card.waited_because == handle_it.REASONS[reason]
+ if reason == "calendar_write":
+ assert card.can_answer is False and "--calendar" in card.connect_command
+
+
+def test_it_never_declines_on_its_own_and_counts_the_daily_limit(
+ person: Any, models: dict[str, Any], monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ _on(person)
+ monkeypatch.setenv("DELEGATION_HANDLE_IT_MAX_SENDS_PER_DAY", "1")
+ handle_it.record_handled(person.id, "t-earlier", None, "s1", now=NOW - timedelta(hours=1))
+ mailbox = _mailbox()
+ _scan(person, mailbox)
+ (card,) = invites.cards(person)
+ assert card.waited_because == handle_it.REASONS["daily_limit"] and mailbox.answers == []
+
+
+def test_an_accept_that_fails_hands_the_card_back(person: Any, models: dict[str, Any]) -> None:
+ _on(person)
+ mailbox = _mailbox()
+ mailbox.answer_error = CalendarWriteNotGranted("read only")
+ result = _scan(person, mailbox)
+ assert result.handled == 0
+ (card,) = invites.cards(person)
+ assert card.status == "proposed" and card.can_answer is False
+
+
+def test_in_training_it_waits_until_they_tick_accept_next_time(person: Any, models: dict[str, Any]) -> None:
+ _on(person)
+ training.set_(person.id, {training.REPLIES: True}, updated_by="test")
+ mailbox = _mailbox()
+ _scan(person, mailbox)
+ (card,) = invites.cards(person)
+ assert card.can_allow is True and card.waited_because == handle_it.REASONS["invite_training"]
+ instance = ledger.get_decision_instance(card.decision_id)
+ from openexecutive.delegation.verified import ChatTap
+
+ assert asyncio.run(invites.answer(
+ instance, caller=ChatTap(OWNER), resolver=person.id, answer="accept", allow=True, mailbox=mailbox,
+ )) == "accepted"
+ allowed = training.allowed_inviter(person.id, DANA)
+ assert allowed is not None and allowed.label.startswith("Accept invites from Dana Park")
+ assert training.setting_of(allowed.key) == training.REPLIES
+ # The next invite from them goes on its own.
+ mailbox.add(_invite("i2", "ti2", minutes_ago=20))
+ mailbox.events["i2"] = _event("ev2", title="Pilot follow-up")
+ assert _scan(person, mailbox, now=NOW + timedelta(minutes=10)).handled == 1
+ assert mailbox.answers == [("ev1", True), ("ev2", True)]
+
+
+# ── answering on a tap (the routes) ───────────────────────────────────────────
+
+
+def client(monkeypatch: pytest.MonkeyPatch) -> TestClient:
+ app = FastAPI()
+ app.include_router(route.router)
+ app.include_router(decisions_route.router)
+ return TestClient(app)
+
+
+def _carded(person: Any, monkeypatch: pytest.MonkeyPatch) -> tuple[FakeCalendar, int]:
+ mailbox = _mailbox()
+ _scan(person, mailbox)
+ monkeypatch.setattr("openexecutive.delegation.gmail.gmail_for", lambda email: mailbox)
+ (card,) = invites.cards(person)
+ return mailbox, card.decision_id
+
+
+def test_the_route_lists_the_callers_invites(client: TestClient, person: Any, models: dict[str, Any],
+ monkeypatch: pytest.MonkeyPatch) -> None:
+ _carded(person, monkeypatch)
+ body = client.get("/delegation/invites", headers={"x-caller-email": OWNER}).json()
+ (card,) = body["cards"]
+ assert card["title"] == "Pilot review" and card["can_answer"] is True and card["clashes"] == []
+
+
+def test_decline_answers_in_their_calendar(
+ db: Path, client: TestClient, person: Any, models: dict[str, Any], monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ mailbox, card_id = _carded(person, monkeypatch)
+ resp = client.post(f"/decisions/{card_id}/approve", json={"edits": {"answer": "decline"}},
+ headers={"x-caller-email": OWNER})
+ assert resp.status_code == 200 and resp.json()["status"] == "approved_unchanged"
+ assert mailbox.answers == [("ev1", False)] and _ledger(db)["i1"] == (invites.DECLINED, "tapped")
+ again = client.post(f"/decisions/{card_id}/approve", json={}, headers={"x-caller-email": OWNER})
+ assert again.status_code == 409
+
+
+def test_only_their_own_tap_answers(
+ client: TestClient, person: Any, models: dict[str, Any], monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ from openexecutive.people import registry, store
+
+ store.upsert_person(full_name="Ben Teammate", email="[email protected]")
+ registry.invalidate()
+ mailbox, card_id = _carded(person, monkeypatch)
+ assert client.post(f"/decisions/{card_id}/approve", json={},
+ headers={"x-caller-email": "[email protected]"}).status_code == 404
+ monkeypatch.delenv("OE_LOCAL_LOGIN")
+ resp = client.post(f"/decisions/{card_id}/approve", json={}, headers={"x-caller-email": OWNER})
+ assert resp.status_code == 409 and resp.json()["detail"]["code"] == "caller_signing_required"
+ assert mailbox.answers == []
+
+
+def test_a_read_only_sign_in_says_to_connect_again(
+ client: TestClient, person: Any, models: dict[str, Any], monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ mailbox, card_id = _carded(person, monkeypatch)
+ mailbox.answer_error = CalendarWriteNotGranted("read only")
+ resp = client.post(f"/decisions/{card_id}/approve", json={}, headers={"x-caller-email": OWNER})
+ assert resp.status_code == 409 and resp.json()["detail"]["code"] == "calendar_write_needed"
+ (card,) = invites.cards(person)
+ assert card.status == "proposed" and card.can_answer is False # still there, to try after reconnecting
+
+
+def test_dismiss_answers_nothing(
+ db: Path, client: TestClient, person: Any, models: dict[str, Any], monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ mailbox, card_id = _carded(person, monkeypatch)
+ resp = client.post(f"/decisions/{card_id}/reject", json={}, headers={"x-caller-email": OWNER})
+ assert resp.status_code == 200 and mailbox.answers == []
+ assert _ledger(db)["i1"][0] == inbox.DISMISSED and invites.cards(person) == []
+
+
+# ── a dismissed card doesn't block a new one; a sent one does (reply cards too) ─
+
+
[email protected]("decision_class", [invites.DECISION_CLASS, inbox.DECISION_CLASS])
+def test_a_settled_card_under_the_key_doesnt_block_a_new_one(db: Path, decision_class: str) -> None:
+ key = f"{decision_class}:1:m1"
+ first = invites.create_once(decision_class, key, {"n": 1}, approver_person_id=1, gate_mode="propose")
+ assert invites.create_once(decision_class, key, {"n": 2}, approver_person_id=1, gate_mode="propose") == first
+ assert ledger.mark_resolved(first, ledger.STATUS_REJECTED)
+ second = invites.create_once(decision_class, key, {"n": 3}, approver_person_id=1, gate_mode="propose")
+ assert second != first and ledger.get_decision_instance(second).status == "proposed" # type: ignore[union-attr]
+ with sqlite3.connect(db) as conn:
+ keys = [r[0] for r in conn.execute("SELECT idempotency_key FROM decision_instances ORDER BY id")]
+ assert keys[0] == key and keys[1].startswith(f"{key}:")
+
+
[email protected]("decision_class", [invites.DECISION_CLASS, inbox.DECISION_CLASS])
[email protected]("status", ["executed", "approved_unchanged", "closed_externally"])
+def test_a_sent_or_settled_card_means_no_second_card(db: Path, decision_class: str, status: str) -> None:
+ key = f"{decision_class}:1:m1"
+ first = invites.create_once(decision_class, key, {"n": 1}, approver_person_id=1, gate_mode="propose")
+ assert first is not None and ledger.mark_resolved(first, status)
+ assert invites.create_once(decision_class, key, {"n": 2}, approver_person_id=1, gate_mode="propose") is None
+
+
+def test_today_says_what_it_accepted(monkeypatch: pytest.MonkeyPatch) -> None:
+ from openexecutive.api.routes import today
+ from openexecutive.delegation.handle_it import HandledReply
+
+ monkeypatch.setattr("openexecutive.api.routes.chat._resolve_caller_person_id", lambda request: 1)
+ monkeypatch.setattr(handle_it, "handled", lambda person_id: [HandledReply(
+ decision_id=9, sent_at=NOW.isoformat(), to_name="Dana Park", to_email=DANA, subject="Pilot review",
+ body="", open_questions=[], thread_id="ti1", source="invite",
+ summary="Accepted Dana's Pilot review, Thu 1 Oct, 14:00",
+ )])
+ (item,) = today._sent_as_caller(object()) # type: ignore[arg-type]
+ assert item.kind == "sent_as_you" and item.summary == "Accepted Dana's Pilot review, Thu 1 Oct, 14:00"
diff --git a/packages/core/tests/unit/test_delegation_outlook.py b/packages/core/tests/unit/test_delegation_outlook.py
index 1468bf74..4e29d6a7 100644
--- a/packages/core/tests/unit/test_delegation_outlook.py
+++ b/packages/core/tests/unit/test_delegation_outlook.py
@@ -800,7 +800,9 @@ def test_the_refresh_asks_for_the_calendar_only_when_it_was_granted(tmp_path: Pa
script.write_credential(tmp_path, EMAIL, payload)
with_calendar = load_credential(EMAIL, directory=tmp_path)
assert with_calendar is not None
- assert unquote(_refresh_form(with_calendar)["scope"]).endswith("https://graph.microsoft.com/Calendars.Read")
+ # --calendar asks for Calendars.ReadWrite now (it answers invites), and
+ # the refresh keeps asking for it.
+ assert unquote(_refresh_form(with_calendar)["scope"]).endswith("https://graph.microsoft.com/Calendars.ReadWrite")
_write(tmp_path)
mail_only = load_credential(EMAIL, directory=tmp_path)
assert mail_only is not None and "Calendars" not in unquote(_refresh_form(mail_only)["scope"])
@@ -916,3 +918,81 @@ def test_each_recipient_keeps_the_name_it_was_written_with() -> None:
raw = _msg("m1", toRecipients=[{"emailAddress": {"name": "Priya Shah", "address": "[email protected]"}}],
ccRecipients=[{"emailAddress": {"address": "[email protected]"}}])
assert ol.parse_message(raw, SENT_FOLDER, EMAIL).names == {"[email protected]": "Priya Shah", "[email protected]": ""}
+
+
+# --------------------------------------------------------------------------- #
+# Meeting invites (delegation.invites)
+# --------------------------------------------------------------------------- #
+
+
+def _invite_graph(scope: str, message: dict[str, Any] | None = None) -> tuple[list[httpx.Request], DelegateOutlook]:
+ seen: list[httpx.Request] = []
+
+ def handler(request: httpx.Request) -> httpx.Response:
+ seen.append(request)
+ if request.url.host == "login.microsoftonline.com":
+ return httpx.Response(200, json={"access_token": "at", "expires_in": 3600, "scope": scope})
+ if request.method == "POST":
+ return httpx.Response(202)
+ return httpx.Response(200, json=message or {})
+
+ cred = OutlookCredential(email=EMAIL, refresh_token="r1", client_id="cid", tenant="common")
+ return seen, DelegateOutlook(EMAIL, credential=cred, transport=httpx.MockTransport(handler))
+
+
+def test_an_outlook_invite_is_its_own_event() -> None:
+ from openexecutive.delegation.gmail import MailMessage
+
+ ol._TOKENS.clear()
+ message = {
+ "id": "m1", "meetingMessageType": "meetingRequest",
+ "event": {"id": "ev1", "subject": "Pilot review", "isAllDay": False,
+ "start": {"dateTime": "2026-10-14T16:00:00.0000000", "timeZone": "UTC"},
+ "end": {"dateTime": "2026-10-14T16:30:00.0000000", "timeZone": "UTC"},
+ "organizer": {"emailAddress": {"name": "Dana", "address": "[email protected]"}},
+ "responseStatus": {"response": "notResponded"}},
+ }
+ seen, client = _invite_graph(f"{_MAIL} https://graph.microsoft.com/Calendars.ReadWrite", message)
+ event = asyncio.run(client.find_invite(MailMessage(id="m1", thread_id="c1", calendar_invite=True)))
+ assert event is not None and (event.id, event.response) == ("ev1", "needs_action")
+ assert event.start == "2026-10-14T16:00:00+00:00"
+ call = seen[-1]
+ assert call.url.path == "/v1.0/me/messages/m1" and "eventMessage/event" in call.url.params["$expand"]
+ ol._TOKENS.clear()
+ _seen, cancelled = _invite_graph(_MAIL + " https://graph.microsoft.com/Calendars.ReadWrite",
+ {**message, "meetingMessageType": "meetingCancelled"})
+ assert asyncio.run(cancelled.find_invite(MailMessage(id="m1", thread_id="c1"))) is None
+
+
+def test_an_outlook_answer_is_graphs_accept_or_decline() -> None:
+ ol._TOKENS.clear()
+ seen, client = _invite_graph(f"{_MAIL} https://graph.microsoft.com/Calendars.ReadWrite")
+ assert asyncio.run(client.calendar_write_granted()) is True
+ asyncio.run(client.answer_invite("ev1", accept=True))
+ asyncio.run(client.answer_invite("ev1", accept=False))
+ posts = [r for r in seen if r.method == "POST" and r.url.host == "graph.microsoft.com"]
+ assert [r.url.path for r in posts] == ["/v1.0/me/events/ev1/accept", "/v1.0/me/events/ev1/decline"]
+ assert all(json.loads(r.content) == {"sendResponse": True} for r in posts)
+
+
+def test_an_outlook_read_only_sign_in_cannot_answer() -> None:
+ from openexecutive.delegation.gmail import CalendarWriteNotGranted
+
+ ol._TOKENS.clear()
+ seen, client = _invite_graph(f"{_MAIL} https://graph.microsoft.com/Calendars.Read")
+ assert asyncio.run(client.calendar_granted()) is True
+ assert asyncio.run(client.calendar_write_granted()) is False
+ with pytest.raises(CalendarWriteNotGranted):
+ asyncio.run(client.answer_invite("ev1", accept=True))
+ assert all(r.url.host == "login.microsoftonline.com" for r in seen)
+
+
+def test_an_older_read_only_credential_keeps_asking_for_read(tmp_path: Path) -> None:
+ script = _script()
+ payload = script.credential_payload(
+ EMAIL, "r1", "cid", "common", personal=False, graph_scopes=(*script.GRAPH_SCOPES, "Calendars.Read"),
+ )
+ script.write_credential(tmp_path, EMAIL, payload)
+ older = load_credential(EMAIL, directory=tmp_path)
+ assert older is not None
+ assert unquote(_refresh_form(older)["scope"]).endswith("https://graph.microsoft.com/Calendars.Read")
diff --git a/packages/ui/scripts/inviteCards.test.mjs b/packages/ui/scripts/inviteCards.test.mjs
new file mode 100644
index 00000000..aa3b6033
--- /dev/null
+++ b/packages/ui/scripts/inviteCards.test.mjs
@@ -0,0 +1,44 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+import {
+ answeredLine,
+ clashLine,
+ handledLine,
+ inviteNextTimeLabel,
+ inviterFirstName,
+} from "../src/lib/inviteCards.ts";
+
+const dana = { from_name: "Dana Park", from_email: "[email protected]" };
+
+test("the training tick names who invited you by first name", () => {
+ assert.equal(inviteNextTimeLabel(dana), "Accept from Dana on its own next time");
+ assert.equal(inviterFirstName({ from_name: " ", from_email: "[email protected]" }), "[email protected]");
+});
+
+test("clashLine shows busy times only, or says it couldn't look", () => {
+ assert.equal(clashLine({ ...dana, clashes: [], clash_checked: true }), "");
+ assert.equal(
+ clashLine({ ...dana, clashes: ["14:00–14:30"], clash_checked: true }),
+ "Clashes with something on your calendar: 14:00–14:30.",
+ );
+ assert.match(
+ clashLine({ ...dana, clashes: ["9:00–9:30", "10:00–11:00", "11:00–11:30", "12:00–13:00"], clash_checked: true }),
+ /other things on your calendar: 9:00–9:30, 10:00–11:00, 11:00–11:30 and 1 more\./,
+ );
+ assert.equal(clashLine({ ...dana, clashes: [], clash_checked: false }), "Couldn't check your calendar for clashes.");
+});
+
+test("answeredLine says what happened", () => {
+ assert.equal(answeredLine("accept", dana), "Accepted. Your calendar lets Dana know.");
+ assert.equal(answeredLine("decline", dana), "Declined. Your calendar lets Dana know.");
+});
+
+test("handledLine shows an accepted invite as its own line", () => {
+ assert.equal(
+ handledLine({ source: "invite", summary: "Accepted Dana's Pilot review, Wed 21 Oct, 14:30", to_name: "Dana Park", to_email: "", subject: "Pilot review" }),
+ "Accepted Dana's Pilot review, Wed 21 Oct, 14:30",
+ );
+ assert.equal(handledLine({ to_name: "Dana Park", to_email: "", subject: "Re: Pilot" }), "Replied to Dana Park: Re: Pilot");
+ assert.equal(handledLine({ source: "follow_up", to_name: "", to_email: "[email protected]", subject: "Pilot" }),
+ "Followed up with [email protected]: Pilot");
+});
diff --git a/packages/ui/src/components/Briefing.tsx b/packages/ui/src/components/Briefing.tsx
index f8fc4bde..64cc40c9 100644
--- a/packages/ui/src/components/Briefing.tsx
+++ b/packages/ui/src/components/Briefing.tsx
@@ -35,6 +35,7 @@ import type { SnoozeChoice } from "@/lib/snooze";
import InfoTip from "./InfoTip";
import HeldBack from "./briefing/HeldBack";
import { ACTION_CARDS_TIP, ActionCardItem, useActionCards } from "./ActionCards";
+import { INVITE_CARDS_TIP, InviteCardItem, useInviteCards } from "./InviteCards";
import { REPLIES_WAITING_TIP, ReplyCardItem, useReplyCards } from "./RepliesWaiting";
import Icon from "./Icon";
import {
@@ -404,6 +405,8 @@ export default function Briefing({ onContinue, showHeader = false, firstName, ba
const replies = useReplyCards();
// Actions it suggested from the caller's email, to approve (Act as me).
const actionCards = useActionCards();
+ // Meeting invites from people the caller knows, to accept or decline (Act as me).
+ const inviteCards = useInviteCards();
// Solo's own sections load on their own, so their tiles can count them.
const principalId = solo ? principalIdOf(today?.people ?? []) : null;
const projects = useActiveProjects(solo);
@@ -445,6 +448,7 @@ export default function Briefing({ onContinue, showHeader = false, firstName, ba
today.proposals.length === 0 &&
replies.cards.length === 0 &&
actionCards.cards.length === 0 &&
+ inviteCards.cards.length === 0 &&
activeDepts.every((d) => d.at_risk_count === 0 && d.off_track_count === 0 && d.awaiting_count === 0) &&
today.people.every((p) => p.awaiting_count === 0);
@@ -494,7 +498,8 @@ export default function Briefing({ onContinue, showHeader = false, firstName, ba
// The top three words a commitment as the owner's ("you").
const principalName =
(principalId != null && today?.people.find((p) => p.id === principalId)?.full_name) || "";
- const needsYouCount = mineProposals.length + replies.cards.length + actionCards.cards.length;
+ const needsYouCount =
+ mineProposals.length + replies.cards.length + inviteCards.cards.length + actionCards.cards.length;
const summary: SummaryPart[] = today
? briefingSummary({
needsYou: needsYouCount,
@@ -618,6 +623,12 @@ export default function Briefing({ onContinue, showHeader = false, firstName, ba
/>
),
})),
+ ...inviteCards.cards.map((card) => ({
+ key: `invite-${card.decision_id}`,
+ render: (emphasized: boolean) => (
+ <InviteCardItem card={card} onGone={inviteCards.gone} emphasized={emphasized} />
+ ),
+ })),
...actionCards.cards.map((card) => ({
key: `actions-${card.decision_id}`,
render: (emphasized: boolean) => (
@@ -818,6 +829,7 @@ export default function Briefing({ onContinue, showHeader = false, firstName, ba
{needsYouCount > 0 && <span className="ml-1.5 font-normal text-fg-muted">({needsYouCount})</span>}
</h2>
{replies.cards.length > 0 && <InfoTip align="left">{REPLIES_WAITING_TIP}</InfoTip>}
+ {inviteCards.cards.length > 0 && <InfoTip align="left">{INVITE_CARDS_TIP}</InfoTip>}
{actionCards.cards.length > 0 && <InfoTip align="left">{ACTION_CARDS_TIP}</InfoTip>}
<div className="ml-auto flex items-center gap-1">
{showNeedsYouMenu && <OverflowMenu size="sm" label="Needs you options" items={needsYouMenu} />}
diff --git a/packages/ui/src/components/InviteCards.tsx b/packages/ui/src/components/InviteCards.tsx
new file mode 100644
index 00000000..d7d4d7ae
--- /dev/null
+++ b/packages/ui/src/components/InviteCards.tsx
@@ -0,0 +1,175 @@
+"use client";
+
+import { useCallback, useEffect, useState } from "react";
+
+import Button from "@/components/ui/Button";
+import FeatureName from "@/components/FeatureName";
+import NextTimeTick from "@/components/NextTimeTick";
+import { answerInviteCard, dismissInviteCard, getInviteCards, type InviteCard } from "@/lib/api";
+import { answeredLine, clashLine, inviteNextTimeLabel } from "@/lib/inviteCards";
+import { relationLabel } from "@/lib/replyCards";
+import { formatRelativeTime } from "@/lib/relativeTime";
+
+// Home: meeting invites from people you know (Act as me, with Read my
+// calendar on), shown as cards in "Needs you" next to the reply cards: who
+// invited you, the meeting, when, and any clash with your calendar (times
+// only). Accept and Decline answer it in your own calendar; Dismiss leaves it
+// unanswered. GET /delegation/invites answers only the card's own person, so
+// nothing shows for anyone else, on a backend without it, and when nothing is
+// waiting.
+
+export function useInviteCards() {
+ const [cards, setCards] = useState<InviteCard[] | null>(null);
+
+ useEffect(() => {
+ const controller = new AbortController();
+ getInviteCards(controller.signal)
+ .then(setCards)
+ .catch(() => setCards([])); // no card is better than a broken one
+ return () => controller.abort();
+ }, []);
+
+ const gone = useCallback((decisionId: number) => {
+ setCards((prev) => (prev ?? []).filter((c) => c.decision_id !== decisionId));
+ }, []);
+
+ return { cards: cards ?? [], loaded: cards !== null, gone };
+}
+
+// What the invite cards are, for the Needs you header's tip.
+export const INVITE_CARDS_TIP =
+ "Meeting invites from people you know. Accept or Decline answers it in your own calendar, " +
+ "and your calendar lets them know. Only the busy times on your calendar are checked for clashes. " +
+ "Only you see these.";
+
+export function InviteCardItem({
+ card,
+ onGone,
+ emphasized = false,
+}: {
+ card: InviteCard;
+ emphasized?: boolean;
+ onGone: (id: number) => void;
+}) {
+ const [busy, setBusy] = useState<string | null>(null);
+ const [error, setError] = useState<string | null>(null);
+ const [done, setDone] = useState<"accept" | "decline" | null>(null);
+ const [nextTime, setNextTime] = useState(false);
+ const created = formatRelativeTime(card.created_at);
+ const relation = relationLabel(card.relation);
+ const clash = clashLine(card);
+
+ const answer = async (choice: "accept" | "decline") => {
+ setBusy(choice === "accept" ? "Accepting…" : "Declining…");
+ setError(null);
+ try {
+ await answerInviteCard(card.decision_id, choice, choice === "accept" && card.can_allow && nextTime);
+ setDone(choice);
+ } catch (err) {
+ setError(err instanceof Error ? err.message : "Couldn't answer that invite.");
+ } finally {
+ setBusy(null);
+ }
+ };
+
+ const dismiss = async () => {
+ setBusy("Dismissing…");
+ setError(null);
+ try {
+ await dismissInviteCard(card.decision_id);
+ onGone(card.decision_id);
+ } catch (err) {
+ setError(err instanceof Error ? err.message : "Couldn't dismiss that invite.");
+ setBusy(null);
+ }
+ };
+
+ return (
+ <article
+ className={`rounded-2xl border bg-surface-elevated p-4 sm:p-5 ${
+ emphasized ? "border-accent/60 ring-1 ring-accent/25 shadow-sm" : "border-line"
+ }`}
+ >
+ <div className="mb-2 flex flex-wrap items-center gap-2">
+ <span className="inline-flex items-center rounded-lg bg-surface-overlay px-2 py-0.5 text-[13px] font-medium text-fg-muted">
+ Invite
+ </span>
+ <FeatureName feature="act_as_me" className="text-[12px]" />
+ {created && <span className="text-sm text-fg-subtle tabular-nums">{created}</span>}
+ </div>
+ <div className="text-base sm:text-[17px] font-semibold leading-snug text-fg break-words">
+ {card.title || "A meeting"}
+ </div>
+ <p className="mt-1 text-sm text-fg break-words">
+ {card.when}
+ <span className="text-fg-muted">
+ {" · from "}
+ {card.from_name || card.from_email}
+ {relation ? ` (${relation})` : ""}
+ </span>
+ </p>
+ {clash && (
+ <p className={`mt-2 text-sm ${card.clash_checked ? "text-amber-700 dark:text-amber-300" : "text-fg-muted"}`}>
+ {clash}
+ </p>
+ )}
+ {card.waited_because && !done && <p className="mt-2 text-sm text-fg-muted">{card.waited_because}</p>}
+
+ {done ? (
+ <>
+ <p className="mt-3 text-sm text-emerald-700 dark:text-emerald-300">{answeredLine(done, card)}</p>
+ {done === "accept" && card.can_allow && nextTime && (
+ <p className="mt-1 text-sm text-fg-muted">From now on, their invites with no clash are accepted on their own.</p>
+ )}
+ <div className="mt-4 flex flex-wrap items-center gap-2">
+ <Button variant="secondary" onClick={() => onGone(card.decision_id)}>
+ Close
+ </Button>
+ </div>
+ </>
+ ) : card.can_answer ? (
+ <>
+ {card.can_allow && (
+ <NextTimeTick
+ className="mt-4"
+ checked={nextTime}
+ disabled={busy !== null}
+ onChange={setNextTime}
+ label={inviteNextTimeLabel(card)}
+ help="Only when nothing on your calendar clashes. You can undo this in Handle it for me."
+ />
+ )}
+ <div className="mt-4 flex flex-wrap items-center gap-2">
+ <Button variant="primary" onClick={() => void answer("accept")} disabled={busy !== null}>
+ {busy === "Accepting…" ? busy : "Accept"}
+ </Button>
+ <Button variant="secondary" onClick={() => void answer("decline")} disabled={busy !== null}>
+ {busy === "Declining…" ? busy : "Decline"}
+ </Button>
+ <Button variant="ghost" className="ml-auto" onClick={() => void dismiss()} disabled={busy !== null}>
+ Dismiss
+ </Button>
+ </div>
+ </>
+ ) : (
+ <>
+ <p className="mt-3 text-sm text-fg-muted">
+ Your calendar sign-in can read your calendar but not answer invites. Connect it again under Read my
+ calendar in Delegate → Act as me, then answer here. Until then, answer it in your calendar.
+ </p>
+ {card.connect_command && (
+ <code className="mt-2 block overflow-x-auto rounded-lg bg-surface px-2 py-1 text-[13px] text-fg-muted">
+ {card.connect_command}
+ </code>
+ )}
+ <div className="mt-4 flex flex-wrap items-center gap-2">
+ <Button variant="ghost" className="ml-auto" onClick={() => void dismiss()} disabled={busy !== null}>
+ Dismiss
+ </Button>
+ </div>
+ </>
+ )}
+ {error && <p className="mt-2 text-sm text-red-500">{error}</p>}
+ </article>
+ );
+}
diff --git a/packages/ui/src/components/settings/HandleItCard.tsx b/packages/ui/src/components/settings/HandleItCard.tsx
index 15315ea0..35f3e161 100644
--- a/packages/ui/src/components/settings/HandleItCard.tsx
+++ b/packages/ui/src/components/settings/HandleItCard.tsx
@@ -11,13 +11,15 @@ import {
type HandledReply,
type HandleIt,
} from "@/lib/api";
+import { handledLine } from "@/lib/inviteCards";
import { sentTodayLine } from "@/lib/reach";
import { formatAgo } from "@/lib/setupStatus";
// Handle it for me, its own tab under Delegate: replies the inbox watcher
// sends from your mailbox on its own. Plain code decides each one
// (delegation/handle_it.py). This tab holds What it sends on its own
-// (SendsCard) and what it sent in the last week (GET /delegation/handled).
+// (SendsCard) and what it sent in the last week (GET /delegation/handled),
+// meeting invites it accepted on its own included.
export type DelegationLoad = {
settings: DelegationSettings | null;
state: "loading" | "hidden" | "ready" | "error";
@@ -91,10 +93,8 @@ function HandleItSection({ handleIt }: { handleIt: HandleIt }) {
{handled.map((h) => (
<li key={h.decision_id} className="rounded-md border border-border px-3 py-2 text-sm">
<div className="flex flex-wrap items-baseline justify-between gap-2">
- <span className="min-w-0 font-medium">
- {h.source === "follow_up" ? "Followed up with" : "Replied to"} {h.to_name || h.to_email}:{" "}
- {h.subject}
- </span>
+ {/* A reply names who it went to; an accepted invite says so. */}
+ <span className="min-w-0 font-medium">{handledLine(h)}</span>
<span className="text-xs text-fg-muted">{formatAgo(h.sent_at)}</span>
</div>
{h.open_questions.length > 0 && (
diff --git a/packages/ui/src/lib/api.ts b/packages/ui/src/lib/api.ts
index f07fc6d4..2a6e7223 100644
--- a/packages/ui/src/lib/api.ts
+++ b/packages/ui/src/lib/api.ts
@@ -1992,8 +1992,11 @@ export interface HandledReply {
body: string;
open_questions: string[];
gmail_link: string;
- // "follow_up": a follow-up to your own unanswered email.
+ // "follow_up": a follow-up to your own unanswered email; "invite": a
+ // meeting invite it accepted on its own.
source?: string;
+ // One line for an invite: "Accepted Dana's Pilot review, Wed 21 Oct, 14:30".
+ summary?: string;
}
// One reply the inbox watcher drafted: a `delegation_reply` decision, yours
@@ -2574,6 +2577,65 @@ export async function approveActionCard(id: number, only: number[], allow = fals
}
}
+// A meeting invite from someone you know (Act as me, with Read my calendar
+// on), yours alone. Accept and Decline answer it in your own calendar
+// (POST /decisions/{id}/approve with edits.answer); Dismiss
+// (POST /decisions/{id}/reject) answers nothing.
+export interface InviteCard {
+ decision_id: number;
+ status: string;
+ created_at: string;
+ from_name: string;
+ from_email: string;
+ relation: string;
+ title: string;
+ // "Wed 21 Oct, 14:30–15:00", in your time zone.
+ when: string;
+ start: string;
+ end: string;
+ all_day: boolean;
+ // Busy times on your calendar that overlap it; times only.
+ clashes: string[];
+ clash_checked: boolean;
+ // false: your calendar sign-in can read but not answer invites yet.
+ can_answer: boolean;
+ // Replies in training: the "Accept from them on its own next time" tick.
+ can_allow: boolean;
+ // Why Handle it for me left it for you ("" when it was off).
+ waited_because: string;
+ connect_command: string;
+}
+
+// null when this viewer has none to see (403) or the backend predates them (404).
+export async function getInviteCards(signal?: AbortSignal): Promise<InviteCard[] | null> {
+ const res = await fetch(`${API_BASE}/delegation/invites`, { signal });
+ if (res.status === 403 || res.status === 404) return null;
+ if (!res.ok) throw await delegationError(res, "Couldn't load the invites waiting for you.");
+ const body = (await res.json()) as { cards: InviteCard[] };
+ return body.cards;
+}
+
+// Accept or decline an invite in your own calendar. `allow` (accept, Replies
+// in training): their invites are accepted on their own from now on.
+export async function answerInviteCard(id: number, answer: "accept" | "decline", allow = false): Promise<void> {
+ const res = await fetch(`${API_BASE}/decisions/${id}/approve`, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ edits: allow ? { answer, allow: true } : { answer } }),
+ });
+ if (!res.ok) throw await delegationError(res, "Couldn't answer that invite.");
+}
+
+export async function dismissInviteCard(id: number): Promise<void> {
+ const res = await fetch(`${API_BASE}/decisions/${id}/reject`, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ reason: "" }),
+ });
+ if (res.status === 404 || res.status === 409) return; // already gone or answered
+ if (!res.ok) throw await delegationError(res, "Couldn't dismiss that invite.");
+}
+
export async function dismissActionCard(id: number): Promise<void> {
const res = await fetch(`${API_BASE}/decisions/${id}/reject`, {
method: "POST",
diff --git a/packages/ui/src/lib/inviteCards.ts b/packages/ui/src/lib/inviteCards.ts
new file mode 100644
index 00000000..d6e32e0a
--- /dev/null
+++ b/packages/ui/src/lib/inviteCards.ts
@@ -0,0 +1,47 @@
+// Pure helpers for the meeting invite cards on Home (components/InviteCards.tsx):
+// an invite from someone you know, to accept or decline in your own calendar
+// (Act as me, with Read my calendar on). No React here so `npm test` can
+// exercise it directly (scripts/inviteCards.test.mjs).
+
+export interface InviteCardLike {
+ from_name: string;
+ from_email: string;
+ clashes: string[];
+ clash_checked: boolean;
+}
+
+/** Who invited you, by first name (their address when there's no name). */
+export function inviterFirstName(card: { from_name: string; from_email: string }): string {
+ return card.from_name.trim().split(/\s+/)[0] || card.from_email;
+}
+
+/** The training tick's words, as on a reply card. */
+export function inviteNextTimeLabel(card: { from_name: string; from_email: string }): string {
+ return `Accept from ${inviterFirstName(card)} on its own next time`;
+}
+
+/** What the card says about your calendar at that time: a clash (times
+ * only), that it couldn't look, or nothing when it's free. */
+export function clashLine(card: InviteCardLike): string {
+ if (!card.clash_checked) return "Couldn't check your calendar for clashes.";
+ if (card.clashes.length === 0) return "";
+ const times = card.clashes.slice(0, 3).join(", ");
+ const more = card.clashes.length > 3 ? ` and ${card.clashes.length - 3} more` : "";
+ return `Clashes with ${card.clashes.length === 1 ? "something" : "other things"} on your calendar: ${times}${more}.`;
+}
+
+/** The line once you answered. */
+export function answeredLine(answer: "accept" | "decline", card: { from_name: string; from_email: string }): string {
+ const who = inviterFirstName(card);
+ return answer === "accept"
+ ? `Accepted. Your calendar lets ${who} know.`
+ : `Declined. Your calendar lets ${who} know.`;
+}
+
+/** One line for something Handle it for me did (What it sent): an accepted
+ * invite says so; a reply names who it went to. */
+export function handledLine(h: { source?: string; summary?: string; to_name: string; to_email: string; subject: string }): string {
+ if (h.source === "invite" && h.summary) return h.summary;
+ const verb = h.source === "follow_up" ? "Followed up with" : "Replied to";
+ return `${verb} ${h.to_name || h.to_email}: ${h.subject}`;
+}
diff --git a/scripts/connect-own-gmail.py b/scripts/connect-own-gmail.py
index 5aa76f1b..a0374376 100644
--- a/scripts/connect-own-gmail.py
+++ b/scripts/connect-own-gmail.py
@@ -5,9 +5,12 @@ Act as me lets the Executive write drafts as you, in your own Gmail — never
from its own account, and never through the MCP gateway the model can reach.
This mints the credential it uses: a browser sign-in as you, asking only for
Gmail read + compose (drafts), and writes one file named from a hash of your
-address. With --calendar it also asks to read your calendar (read-only), for
-Read my calendar under Act as me; run it again with --calendar to add that
-to a sign-in you made without it.
+address. With --calendar it also asks for your calendar's events
+(calendar.events), for Read my calendar under Act as me: it reads your
+calendar, and answers a meeting invite as you when you tap Accept or Decline
+on its card (or accepts one on its own under Handle it for me). Run it again
+with --calendar to add that to a sign-in you made without it, or made with
+read-only calendar access before invites could be answered.
Run it where you can open a browser, with the Executive's Google OAuth client
exported (the same Desktop client scripts/mint-google-token.py uses):
@@ -38,7 +41,7 @@ SCOPES = [
"https://www.googleapis.com/auth/gmail.readonly",
"https://www.googleapis.com/auth/gmail.compose",
]
-CALENDAR_SCOPE = "https://www.googleapis.com/auth/calendar.readonly"
+CALENDAR_SCOPE = "https://www.googleapis.com/auth/calendar.events"
TOKEN_URI = "https://oauth2.googleapis.com/token"
PROFILE_URL = "https://gmail.googleapis.com/gmail/v1/users/me/profile"
CREDENTIAL_VERSION = 1
@@ -96,7 +99,7 @@ def _profile_email(access_token: str) -> str:
def main() -> int:
parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
parser.add_argument("--email", required=True, help="Your own Gmail address (as on your People entry)")
- parser.add_argument("--calendar", action="store_true", help="Also allow reading your calendar (Read my calendar)")
+ parser.add_argument("--calendar", action="store_true", help="Also allow your calendar: read it, and answer invites you accept or decline (Read my calendar)")
args = parser.parse_args()
scopes = [*SCOPES, CALENDAR_SCOPE] if args.calendar else SCOPES
email = args.email.strip().lower()
@@ -119,7 +122,7 @@ def main() -> int:
},
scopes=scopes,
)
- calendar = " and read-only access to your calendar" if args.calendar else ""
+ calendar = " and access to your calendar's events (read, and answer invites)" if args.calendar else ""
print(f"Opening a browser: sign in as {email} and allow read + draft access to Gmail{calendar}.")
creds = flow.run_local_server(port=0, prompt="consent", access_type="offline", login_hint=email)
if not creds.refresh_token:
diff --git a/scripts/connect-own-outlook.py b/scripts/connect-own-outlook.py
index 8e50dbe4..e27f5efa 100644
--- a/scripts/connect-own-outlook.py
+++ b/scripts/connect-own-outlook.py
@@ -9,12 +9,14 @@ type the code, from any browser), asking only for your profile and mail
(read, write drafts, and send the drafts you approve), and writes one file
named from a hash of your address. A person has one mailbox for Act as me:
this replaces a Gmail file for the same address. With --calendar it also
-asks to read your calendar (Calendars.Read), for Read my calendar.
+asks for your calendar (Calendars.ReadWrite), for Read my calendar: it reads
+your calendar, and answers a meeting invite as you when you tap Accept or
+Decline on its card (or accepts one on its own under Handle it for me).
It uses the Executive's own Entra app (the one the Microsoft 365 setup in
.env.example registers; "Allow public client flows" must be on). Its delegated
Microsoft Graph permissions must include User.Read, Mail.ReadWrite, Mail.Send
-and offline_access (and Calendars.Read for --calendar). A personal Microsoft account needs an app that accepts
+and offline_access (and Calendars.ReadWrite for --calendar). A personal Microsoft account needs an app that accepts
personal accounts, with MS365_MCP_TENANT_ID=common or consumers.
export MS365_MCP_CLIENT_ID=...
@@ -48,7 +50,7 @@ from typing import Any
LOGIN_BASE = "https://login.microsoftonline.com"
GRAPH_ME = "https://graph.microsoft.com/v1.0/me?$select=mail,userPrincipalName"
GRAPH_SCOPES = ("User.Read", "Mail.ReadWrite", "Mail.Send")
-CALENDAR_SCOPE = "Calendars.Read"
+CALENDAR_SCOPE = "Calendars.ReadWrite"
def scope_for(graph_scopes: tuple[str, ...]) -> str:
@@ -162,7 +164,7 @@ def _sign_in(tenant: str, client_id: str, scope: str = SCOPE) -> dict[str, Any]:
def main() -> int:
parser = argparse.ArgumentParser(description=(__doc__ or "").split("\n\n")[0])
parser.add_argument("--email", required=True, help="Your own Outlook address (as on your People entry)")
- parser.add_argument("--calendar", action="store_true", help="Also allow reading your calendar (Read my calendar)")
+ parser.add_argument("--calendar", action="store_true", help="Also allow your calendar: read it, and answer invites you accept or decline (Read my calendar)")
args = parser.parse_args()
graph_scopes = (*GRAPH_SCOPES, CALENDAR_SCOPE) if args.calendar else GRAPH_SCOPES
email = args.email.strip().lower()
@@ -176,7 +178,7 @@ def main() -> int:
if not TENANT_RE.fullmatch(tenant):
sys.exit("error: MS365_MCP_TENANT_ID must be a tenant id, common, organizations or consumers")
- calendar = ", and read-only access to your calendar" if args.calendar else ""
+ calendar = ", and your calendar (read it, and answer invites)" if args.calendar else ""
print(f"Sign in as {email} and allow read, draft and send access to your mail{calendar}.")
token = _sign_in(tenant, client_id, scope_for(graph_scopes))
refresh_token = str(token.get("refresh_token") or "")