Skip to content

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

feat(delegation): add What it may do and one dial for acting as you (#473)

Rufusc8eec039c1cb
diff --git a/packages/core/openexecutive/api/main.py b/packages/core/openexecutive/api/main.py
index 75b7a34b..c398fd91 100644
--- a/packages/core/openexecutive/api/main.py
+++ b/packages/core/openexecutive/api/main.py
@@ -38,6 +38,7 @@ from openexecutive.api.routes import (
health,
history,
knowledge,
+ may_do,
notifications,
onboarding,
people,
@@ -985,6 +986,7 @@ def create_app() -> FastAPI:
app.include_router(decisions.router, tags=["decisions"])
app.include_router(delegation.router, tags=["delegation"])
app.include_router(take_the_lead.router, tags=["take-the-lead"])
+ app.include_router(may_do.router, tags=["delegation"])
app.include_router(history.router, tags=["memories"])
app.include_router(audit.router, tags=["audit"])
app.include_router(departments.router, tags=["departments"])
diff --git a/packages/core/openexecutive/api/routes/delegation.py b/packages/core/openexecutive/api/routes/delegation.py
index cee9de49..f761b85a 100644
--- a/packages/core/openexecutive/api/routes/delegation.py
+++ b/packages/core/openexecutive/api/routes/delegation.py
@@ -27,6 +27,13 @@ Routes:
on and a calendar read that works (409
calendar_not_granted when their sign-in
lacks it, 503 when it can't be reached)
+ PUT /delegation/reach — {step}: How far it goes as you, one dial
+ over Act as me, the inbox watcher, Handle
+ it for me and its level, and Everything
+ (off, when_asked, inbox, careful,
+ balanced, bold, everything). Down turns
+ the higher switches off; up turns each on
+ through its own route and its checks
PUT /delegation/inbox — {enabled?, mailbox_drafts?}: "Draft
replies to my inbox"; turning it on needs
Act as me on and Gmail connected (409),
@@ -103,7 +110,7 @@ from __future__ import annotations
import asyncio
import logging
from dataclasses import asdict
-from typing import Any
+from typing import Any, Literal
from fastapi import APIRouter, HTTPException, Request
from pydantic import BaseModel, ConfigDict, Field
@@ -1130,6 +1137,82 @@ async def update_take_the_lead_as_you(request: Request, body: LeadUpdate) -> Del
return await _state(person)
+# How far it goes as you: one dial over Write drafts as me, Draft replies to
+# my inbox, Handle it for me and its level, and Everything (Take the lead as
+# you). Each step adds to the one before it.
+REACH_STEPS: tuple[str, ...] = ("off", "when_asked", "inbox", "careful", "balanced", "bold", "everything")
+_SENDING_FROM = REACH_STEPS.index("careful")
+
+
+class ReachUpdate(BaseModel):
+ model_config = ConfigDict(extra="forbid")
+
+ step: Literal["off", "when_asked", "inbox", "careful", "balanced", "bold", "everything"]
+
+
+def reach_of(person_id: int) -> str:
+ """Where ``person_id`` is on the dial, from the switches it sets."""
+ from openexecutive.delegation import handle_it, inbox, training
+
+ if not is_enabled(person_id):
+ return "off"
+ if not inbox.get_watch(person_id).enabled:
+ return "when_asked"
+ stored = handle_it.get(person_id)
+ if not stored.enabled:
+ return "inbox"
+ if not training.get(person_id).replies and handle_it.leading(person_id):
+ return "everything"
+ return stored.mode
+
+
[email protected]("/delegation/reach", response_model=DelegationOut)
+async def update_delegation_reach(request: Request, body: ReachUpdate) -> DelegationOut:
+ """Move the dial. Going down turns the higher switches off first, top
+ down, and needs no signed sign-in. Going up turns each one on in order
+ through its own route, so every check that switch makes still applies
+ (the mailbox connected, signed sign-ins, the owner alone for Everything,
+ not in training); the first one that refuses stops the move there, at a
+ step that is itself whole. Training is left as it is."""
+ from openexecutive.delegation import handle_it
+
+ person = _caller(request)
+ person_id = _person_id(person)
+ target = REACH_STEPS.index(body.step)
+ current = REACH_STEPS.index(reach_of(person_id))
+ if target == current:
+ return await _state(person)
+
+ # Down: highest first, so nothing is ever on above a switch that's off.
+ if target < REACH_STEPS.index("everything"):
+ _lead_off(person_id)
+ if target < _SENDING_FROM:
+ _set_handle_it(person_id, enabled=False, mode=None)
+ if target < REACH_STEPS.index("inbox"):
+ _set_inbox(person_id, False)
+ if target < REACH_STEPS.index("when_asked"):
+ return await update_delegation(request, DelegationUpdate(enabled=False))
+
+ # Up, or across the sending steps: each switch through its own route.
+ if not is_enabled(person_id):
+ await update_delegation(request, DelegationUpdate(enabled=True))
+ if target >= REACH_STEPS.index("inbox"):
+ from openexecutive.delegation import inbox
+
+ if not inbox.get_watch(person_id).enabled:
+ await update_delegation_inbox(request, InboxUpdate(enabled=True))
+ if target >= _SENDING_FROM:
+ mode = body.step if body.step in handle_it.MODES else None
+ stored = handle_it.get(person_id)
+ if stored.enabled and mode is not None and handle_it.MODES.index(mode) < handle_it.MODES.index(stored.mode):
+ # A lower level only holds more back: no signed sign-in needed.
+ _set_handle_it(person_id, enabled=None, mode=mode)
+ elif not stored.enabled or (mode is not None and mode != stored.mode):
+ await update_delegation_handle_it(request, HandleItUpdate(enabled=True, mode=mode))
+ if body.step == "everything":
+ await update_take_the_lead_as_you(request, LeadUpdate(enabled=True))
+ return await _state(person)
+
def _rules_out(person_id: int) -> LeadRulesOut:
from openexecutive.orchestrator import take_the_lead
diff --git a/packages/core/openexecutive/api/routes/may_do.py b/packages/core/openexecutive/api/routes/may_do.py
new file mode 100644
index 00000000..53a0c83d
--- /dev/null
+++ b/packages/core/openexecutive/api/routes/may_do.py
@@ -0,0 +1,111 @@
+"""Delegate → What it may do (``delegation.may_do``): read-only.
+
+ GET /what-it-may-do — for the signed-in caller: what goes out as them from
+ their own mailbox (when they may have Act as me),
+ what the Executive does on its own (the principal
+ only, as ``GET /take-the-lead``), and each
+ department's level (everyone on the team, as the
+ Departments page)
+
+Who: a team member on People, read through ``api/caller.py`` only. A request
+with no caller resolves to the principal only under local login, as on the
+Act as me routes; a contact or anyone not on People gets 403. Nothing here
+changes a setting or reads anyone's mail.
+"""
+from __future__ import annotations
+
+import logging
+from typing import Any
+
+from fastapi import APIRouter, HTTPException, Request
+from pydantic import BaseModel
+
+from openexecutive.api import caller as api_caller
+
+logger = logging.getLogger(__name__)
+
+router = APIRouter()
+
+
+class RowOut(BaseModel):
+ id: str
+ what: str
+ # goes | waits | always_waits | drafts | off
+ outcome: str
+ then: str
+ why: str
+ # act_as_me | handle_it | take_the_lead | pause | department:<slug> | ""
+ setting: str
+ items: list[str]
+
+
+class SectionOut(BaseModel):
+ # as_you | executive | departments
+ key: str
+ title: str
+ available: bool
+ unavailable: str
+ notes: list[str]
+ rows: list[RowOut]
+ footer: str
+ # How many rows go out (or act) without asking.
+ goes: int
+
+
+class MayDoOut(BaseModel):
+ paused: bool
+ sections: list[SectionOut]
+
+
+def _viewer(request: Request) -> Any:
+ from openexecutive.people.store import find_person_by_email, find_principal_person
+ from openexecutive.utils.deployment import is_local_login
+
+ who = api_caller.caller(request)
+ try:
+ if who.email:
+ person = find_person_by_email(who.email)
+ elif who.defaults_to_principal and is_local_login():
+ person = find_principal_person()
+ else:
+ raise HTTPException(status_code=403, detail="Sign in to see what it may do.")
+ except HTTPException:
+ raise
+ except Exception as exc:
+ logger.exception("may_do: caller lookup failed")
+ raise HTTPException(status_code=503, detail="Couldn't read the People list.") from exc
+ if person is None or person.id is None or person.archived or person.kind != "team":
+ raise HTTPException(status_code=403, detail="Only people on the team can see this.")
+ return person
+
+
[email protected]("/what-it-may-do", response_model=MayDoOut)
+def get_what_it_may_do(request: Request) -> MayDoOut:
+ from openexecutive.delegation import may_do
+ from openexecutive.delegation.settings import can_delegate
+
+ person = _viewer(request)
+ try:
+ found = may_do.summary(
+ person.id, can_have_it=can_delegate(person), is_principal=bool(person.is_principal),
+ )
+ except Exception as exc:
+ logger.exception("may_do: couldn't put the page together")
+ raise HTTPException(status_code=503, detail="Couldn't read the settings.") from exc
+ return MayDoOut(
+ paused=found.paused,
+ sections=[
+ SectionOut(
+ key=s.key, title=s.title, available=s.available, unavailable=s.unavailable, notes=list(s.notes),
+ footer=s.footer, goes=s.goes,
+ rows=[
+ RowOut(
+ id=r.id, what=r.what, outcome=r.outcome, then=r.then, why=r.why, setting=r.setting,
+ items=list(r.items),
+ )
+ for r in s.rows
+ ],
+ )
+ for s in found.sections
+ ],
+ )
diff --git a/packages/core/openexecutive/architecture/architecture-facts.yaml b/packages/core/openexecutive/architecture/architecture-facts.yaml
index 2dce16b4..5dd86e06 100644
--- a/packages/core/openexecutive/architecture/architecture-facts.yaml
+++ b/packages/core/openexecutive/architecture/architecture-facts.yaml
@@ -4823,7 +4823,7 @@ today:
explicit ids to `POST /alerts/bulk-ack` (never a server-side age sweep),
and "Re-check relevance" (`POST /alerts/review`); Monitoring gets the
same footer at 3 days; the ack body may carry `mute_topic`.
- ui_route: / (Next.js app router root) — the briefing is the default landing surface. `/today` still renders the same content as a standalone route (no sidebar shell) for bookmarks and the sidebar Briefing button. The chat lives at the same root behind a `mode` toggle — entering chat from "New chat" or by selecting a session swaps the main content; clicking the sidebar brandmark or the "Briefing" sidebar button returns to the briefing. Every signed-in route renders ONE sidebar component (`components/shell/AppSidebar.tsx`). The AppShell renders it for inner routes, and `/` (exempt from the shell for its own top bar and debug panel) renders the same component with in-page callbacks. On `/` its entries switch the page's in-memory mode; elsewhere they are links (`/?new=1`, `/?session=<id>`) that the home page applies on mount and then strips from the URL. `/?new=1&draft=<text>` (Playbooks "Try in chat") also seeds the new chat's input, capped at 2000 chars, WITHOUT auto-sending — unlike briefing handoffs, the text comes from a URL the user didn't type. The sidebar's "Recent" list is deliberately short — the 7 newest WEB chats only (channel sessions are recognised by their `slack:` / `telegram:` / `discord:` / `email:` / `google_chat:` session-id prefix, `lib/sessionChannel.ts`, since `sessions` has no channel column) — with an "All chats" link to `/chats`, the full history page with channel filter tabs, title search, date groups, a channel tag per row, and delete. The session list is held app-wide by `SessionsProvider` (root layout) over the unchanged `GET /sessions`, so the chat home refreshes it after each turn and every route sees the same list. A standalone "Pulse" link (→ `/memories`, the page titled "Pulse") is pinned directly beneath Briefing in the sidebar and the mobile bottom bar — an always-visible top-level destination rather than a Knowledge-group entry (the Knowledge group now lists "RAG" → `/knowledge`; Skills moved to the Playbooks tab of Workflows, `/jobs?tab=playbooks`), rendered from the shared `PULSE_NAV_ITEM` in `navConfig.ts`. In solo mode (read app-wide from `components/workspace/WorkspaceContext.tsx`'s WorkspaceProvider, mounted in the root layout next to ExecutiveStatusProvider, which reads team while loading or on error so a team install never flashes solo UI) `buildPrimaryNav({mode, roleKind})` swaps the Company group (Departments, People, Company profile) for "You" (Goals → `/goals`, People, and the profile — "Business profile" when the principal's role kind is owner, "Your work" for any other kind, an unset role, or one GET /workspace hides from a non-principal; `profileWording(mode, roleKind)` in navConfig.ts is the one rule, and the `/company-profile` breadcrumb, intro and section headings, the form wizard and the draft review follow it, copy only with no field renamed), `buildMobilePrimary(mode)` swaps People for Goals, and the briefing drops the Departments card, the People card, the "Across the team" lane (all action proposals land in "Needs you"), the people-awaiting, people-overdue and departments-at-risk pills and the quiet-day "Set up a check-in" link (a "N goals at risk" pill links to `/goals` instead), and shows a "Your projects" card of active initiatives (Done = PATCH status completed, Drop = DELETE after a confirm) where the Departments card was. `/goals` lists every goal from GET /departments grouped by area (a department row; areas with goals first, the rest offered as "Other areas") and adds, edits and deletes goals through the slug-scoped goal routes, sharing `components/goals/GoalEditor.tsx` with the department page. Team mode also lists Goals → `/goals` in the Company group (after Departments), and the page words it "department" there. The add-goal form asks only for the goal (`key_result`); the timeframe is a row of chips (This week … Ongoing, default This quarter) that fill the current period's label, target and current are optional, and there is no status picker (a new goal starts on_track). POST /departments/{slug}/goals matches it — only `key_result` is required, a blank `period_value` becomes the current period in the user's zone (`default_period_value`, the create_goal helper), `target` defaults to "", and PATCH rejects a blank `key_result` / `period_value`. Pulse hides "Department check-ins" and "Awaiting people" in solo. Settings has a Workspace card (mode with a confirm, "Your role" in solo — the principal's role kind, title, reports to, remit and measured on, saved with PUT /workspace —, time zone, and "Book meetings without asking", bound to GET/PUT `/decisions/classes/meeting_scheduling` and hidden when that returns 404). Team rendering is unchanged.
+ ui_route: / (Next.js app router root) — the briefing is the default landing surface. `/today` still renders the same content as a standalone route (no sidebar shell) for bookmarks and the sidebar Briefing button. The chat lives at the same root behind a `mode` toggle — entering chat from "New chat" or by selecting a session swaps the main content; clicking the sidebar brandmark or the "Briefing" sidebar button returns to the briefing. Every signed-in route renders ONE sidebar component (`components/shell/AppSidebar.tsx`). The AppShell renders it for inner routes, and `/` (exempt from the shell for its own top bar and debug panel) renders the same component with in-page callbacks. On `/` its entries switch the page's in-memory mode; elsewhere they are links (`/?new=1`, `/?session=<id>`) that the home page applies on mount and then strips from the URL. `/?new=1&draft=<text>` (Playbooks "Try in chat") also seeds the new chat's input, capped at 2000 chars, WITHOUT auto-sending — unlike briefing handoffs, the text comes from a URL the user didn't type. The sidebar's "Recent" list is deliberately short — the 7 newest WEB chats only (channel sessions are recognised by their `slack:` / `telegram:` / `discord:` / `email:` / `google_chat:` session-id prefix, `lib/sessionChannel.ts`, since `sessions` has no channel column) — with an "All chats" link to `/chats`, the full history page with channel filter tabs, title search, date groups, a channel tag per row, and delete. The session list is held app-wide by `SessionsProvider` (root layout) over the unchanged `GET /sessions`, so the chat home refreshes it after each turn and every route sees the same list. A standalone "Pulse" link (→ `/memories`, the page titled "Pulse") is pinned directly beneath Briefing in the sidebar and the mobile bottom bar — an always-visible top-level destination rather than a Knowledge-group entry (the Knowledge group now lists "RAG" → `/knowledge`; Skills moved to the Playbooks tab of Workflows, `/jobs?tab=playbooks`), rendered from the shared `PULSE_NAV_ITEM` in `navConfig.ts`. In solo mode (read app-wide from `components/workspace/WorkspaceContext.tsx`'s WorkspaceProvider, mounted in the root layout next to ExecutiveStatusProvider, which reads team while loading or on error so a team install never flashes solo UI) `buildPrimaryNav({mode, roleKind})` swaps the Company group (Departments, People, Company profile) for "You" (Goals → `/goals`, People, and the profile — "Business profile" when the principal's role kind is owner, "Your work" for any other kind, an unset role, or one GET /workspace hides from a non-principal; `profileWording(mode, roleKind)` in navConfig.ts is the one rule, and the `/company-profile` breadcrumb, intro and section headings, the form wizard and the draft review follow it, copy only with no field renamed), `buildMobilePrimary(mode)` swaps People for Goals, and the briefing drops the Departments card, the People card, the "Across the team" lane (all action proposals land in "Needs you"), the people-awaiting, people-overdue and departments-at-risk pills and the quiet-day "Set up a check-in" link (a "N goals at risk" pill links to `/goals` instead), and shows a "Your projects" card of active initiatives (Done = PATCH status completed, Drop = DELETE after a confirm) where the Departments card was. `/goals` lists every goal from GET /departments grouped by area (a department row; areas with goals first, the rest offered as "Other areas") and adds, edits and deletes goals through the slug-scoped goal routes, sharing `components/goals/GoalEditor.tsx` with the department page. Team mode also lists Goals → `/goals` in the Company group (after Departments), and the page words it "department" there. The add-goal form asks only for the goal (`key_result`); the timeframe is a row of chips (This week … Ongoing, default This quarter) that fill the current period's label, target and current are optional, and there is no status picker (a new goal starts on_track). POST /departments/{slug}/goals matches it — only `key_result` is required, a blank `period_value` becomes the current period in the user's zone (`default_period_value`, the create_goal helper), `target` defaults to "", and PATCH rejects a blank `key_result` / `period_value`. Pulse hides "Department check-ins" and "Awaiting people" in solo. Settings has a Workspace card (mode with a confirm, "Your role" in solo — the principal's role kind, title, reports to, remit and measured on, saved with PUT /workspace —, and time zone; the meeting_scheduling class mode, bound to GET/PUT `/decisions/classes/meeting_scheduling` and hidden when that returns 404, is now "Meetings asked for in chat" in Take the lead's Always asks first). Team rendering is unchanged.
briefing_first_landing: |
The root page (`packages/ui/src/app/page.tsx`) defaults to `mode="briefing"`
and renders `<Briefing>` (`packages/ui/src/components/Briefing.tsx`) in the
@@ -10403,6 +10403,37 @@ delegation:
(422 bad_mode) and GET /delegation/handled ({replies: [...]}, each with
source), see handle_it; DelegationOut.handle_it is {enabled, mode,
available, sent_today}; reply cards carry source ("follow_up" or "").
+ may_do: |
+ Delegate -> What it may do (delegation.may_do, GET /what-it-may-do) is
+ read-only: one row per thing that can go out without asking, its
+ outcome (goes, waits, always_waits, drafts, off) and the setting that
+ decides it. It reads the same settings the gates read, so it cannot say
+ something they don't do: As you from settings.is_enabled,
+ inbox.get_watch, handle_it.get / RULES / leading, training.get /
+ learned and the person's rules; As the Executive (principal only) from
+ take_the_lead.get, Lead.asks_first, the company's rules and the
+ meeting_scheduling class mode; Departments from the registry. Invariant:
+ a meeting Take the lead thinks of always waits, because both meeting
+ gates need someone on a verified surface in the turn; Always asks first
+ -> Meetings asked for in chat (meeting_scheduling's class mode: on is
+ propose, off is auto_execute) covers only meetings someone asks for in
+ chat (and in a team workspace also needs Operations on auto_execute). Department levels
+ never hold Take the lead's own actions; Always asks first and the
+ company's rules do. It writes nothing and reads no mail. 403 for a
+ contact, anyone not on People, or no caller outside local login.
+ reach: |
+ How far it goes as you (ReachCard, PUT /delegation/reach {step}) is one
+ dial over the Act as me switches: off, when_asked (Write drafts as me),
+ inbox (Draft replies to my inbox), careful / balanced / bold (Handle it
+ for me and its mode) and everything (Take the lead as you, owner only).
+ reach_of derives the step from the stored switches; nothing new is
+ stored, so every gate reads exactly what it read before. Down turns the
+ switches above the step off, highest first, so no switch is ever on
+ above one that's off; a lower sending mode is set directly and needs no
+ signed sign-in. Up calls each switch's own route in order, so the
+ mailbox, signed sign-ins, owner-only and not-in-training checks all
+ still apply, and the first refusal stops at a whole step. Training is
+ never changed by the dial.
surfaces: |
Settings → Act as me (ActAsMeCard): the Gmail status with the connect
command and Check again, the Write drafts as me switch, the Draft
@@ -10414,11 +10445,12 @@ delegation:
Refresh from Gmail and Don't add my signature — or Add my Gmail
signature — and each exemplar quoted, with Remove examples).
Settings → Your Executive (app/settings/executive; /settings/on-its-own
- redirects there): the pause, Take the lead and Book meetings without
- asking (moved from Workspace). Handle it for me (HandleItCard: the
- Off / Careful / Balanced / Bold / Take the lead dial, what each sends,
- sent today, the week's list) sits under the mailbox card on
- Settings → Act as me. Setup
+ redirects there): the pause. Take the lead (Delegate → Take the lead)
+ lists Always asks first even while it is off, ending in Meetings asked
+ for in chat (the meeting_scheduling class mode, moved from Workspace).
+ Handle it for me (Delegate → Handle it for me) is the How far it goes
+ as you dial, then What it sent (rules at Everything, sent today, the
+ week's list). Setup
status light your_gmail (amber while the inbox watcher is erroring,
rate-limited or has 25 cards waiting); the API protection light says
Send needs signed callers. The chat chip "Drafted an email as you
diff --git a/packages/core/openexecutive/architecture/prebuilt/api.json b/packages/core/openexecutive/architecture/prebuilt/api.json
index 8d88caf1..6f04b9b6 100644
--- a/packages/core/openexecutive/architecture/prebuilt/api.json
+++ b/packages/core/openexecutive/architecture/prebuilt/api.json
@@ -1,7 +1,7 @@
{
"section_id": "api",
"title": "API Reference",
- "markdown": "The FastAPI surface lives in `openexecutive.api.main`, which mounts one router per topic. A shared-secret middleware gates every request via an `x-api-key` header, except `/health` and the `/webhook/*` callbacks (which carry their own verification). With local login (`OE_LOCAL_LOGIN=1`, which only `make dev` sets, and only while neither Google nor SSO sign-in is set up) a second middleware answers 403 to any request whose raw `Host` is not `localhost`, `127.0.0.1` or `[::1]` (except a webhook that verifies its caller: Google Chat and Slack always, Telegram only with a `TELEGRAM_WEBHOOK_SECRET` Telegram can send), and to any write whose `Sec-Fetch-Site` is present and not `same-origin`/`none`. The UI signs that owner in with no password and this API usually has no secret, so without it a web page in the owner's browser could drive the API as the principal — by DNS-rebinding its own hostname to 127.0.0.1, or by posting a plain form from another site or localhost port. CORS is restricted to the UI origins in `BACKEND_ALLOWED_ORIGINS`, plus the `make dev` UI on `localhost:3000` only when `OE_PUBLIC_DEPLOYMENT` is unset, so a public instance never answers a localhost page with credentials. The gate is off when `BACKEND_SHARED_SECRET` is unset — intended for local development only — so any internet-reachable deployment sets `OE_PUBLIC_DEPLOYMENT`, and `create_app()` then refuses to boot without the secret rather than serving an unauthenticated API.\n\n**Who is calling** is read in one place, `api/caller.py`, which answers with a `Caller` kind and email; a test fails on any other read of an `x-caller-*` header. By default (`open`) it is the `x-caller-email` the UI proxy stamps from the sign-in, trusted because whoever holds the shared secret is trusted as the proxy, and a request with none runs as the principal. **Signed callers** remove that trust. With `CALLER_ASSERTION_PUBLIC_KEYS` set, the proxy signs every request with an Ed25519 key only the UI holds, and a third middleware checks the `x-caller-assertion` header:\n\n- **What it covers.** It is good for one method, the exact path and query, at most 120 seconds, and one use. The API keeps used ids in memory.\n- **What it names.** A `user`, by email, or the `operator`: local login, which runs as the principal.\n- **No caller header at all** is a `service`, for scripts or MCP clients holding only the secret. It is never the principal, not even on an install with no owner yet, so it can't save a first setup.\n- **Anything else is a 401.** That includes an `x-caller-email` without an assertion (`caller_assertion_required`), and a bad, expired, reused or mismatched assertion (`caller_assertion_invalid`).\n\nPublic keys that can't be read stop the boot, rather than fall back to trusting the header. `scripts/make-caller-keys.py` makes the pair, and `scripts/mint-caller-assertion.py` signs one request for curl. The API holds only public keys. Setup's API-protection check warns while a shared secret is set without them.\n\nEndpoints grouped by router:\n\n| Router | Key endpoints | Purpose |\n|---|---|---|\n| `chat` | `POST /chat`, `POST /chat/stop`, `POST /chat/add`, `POST /chat/background` | SSE stream of a live Executive turn, with a `: keepalive` comment every `CHAT_STREAM_KEEPALIVE_S` while the turn is quiet. `POST /chat/background` starts a new chat that the server answers to the end with nobody connected (a phone approving a card, then closing the app): it answers `202` with the new `session_id` once the same caller, access and quota checks as `/chat` pass, the turn saves itself as a `/chat` turn does, and one caller may have three running at once (`429` beyond that). `POST /chat/add` hands the running turn a message the person typed while it works; the turn takes it at its next step and the stream names it in a `message_added` event, and a second `POST /chat` on the same conversation waits for the first to finish. The request body optionally carries `page_context` (route, page title, guide section id, and a form descriptor with current values) — sent only by the Ask OE side panel so the Executive can explain the current page or propose form values. When the Executive calls its `propose_form_values` tool, the stream emits a `form_patch` event (`{type, form_id, fields, rationale, iteration}`) that the panel applies into the on-screen form as highlighted suggestions; the user reviews and saves through the form's normal submit path. Each round of tool calls also emits an `activity` event (`{type, label, tool, iteration}`) naming what is running — progress only, forwarded verbatim and never persisted with the message, unlike an `action_taken` chip. A `session_id` in the body must be a chat the caller may use (the same ownership rule as `sessions`). If it isn't, the turn runs in a fresh chat instead, so nothing is written into someone else's session and the reply looks the same as for an unknown id. An unknown namespaced id (`slack:…`, `telegram:…` and so on) is ignored and a fresh chat is started, because those ids belong to the channel adapters and claiming one first would make the caller its owner. The client mints a `client_turn_id` and sends it with the turn; `POST /chat/stop` takes that id and halts the turn mid-flight, so the button is live from the moment Send is pressed rather than only once the first SSE byte arrives. A stopped turn emits a `stopped` event and then the usual `done` over the same still-open stream — never an `error` — and whatever streamed so far is persisted and flagged. The endpoint returns 404 both for an unknown id and for another caller's turn, so it cannot be used to probe which turns are live. An optional `memory_text` (1–2000 chars) is what peer memory records as the caller's words instead of `message` — the briefing handoffs send it because their seed quotes the Executive's own card; `POST /chat/upload` derives it from the typed text and filenames. Since it never reaches the transcript, the `chat_turn` audit row keeps it beside `message`. After the reply — a stopped or timed-out one too, before the `stopped` / `error` / `done` frames — a turn that looked at anything sends one `sources` event, `{type, session_id, sources: [{kind, title, url}], unavailable: [area]}`: `kind` is `company`, `knowledge`, `notion`, `research`, `document` or `web`, `url` is only ever an http(s) link or, for an earlier document, `/artifacts/<id>`, at most 12 sources (6 from the web, pages the reply cites first), and `unavailable` names parts of the analysis (\"finance\") whose specialist failed or said nothing every time it was asked. It is persisted with the reply as `chat_messages.sources`. A request that carries `x-caller-email` marks its turn signed in (`Session.web_caller_signed_in`), which Act as me needs on a deployment without local login. |\n| `sessions` | `GET /sessions`, `GET /sessions/shared-with-me`, `GET\\|PATCH /sessions/{id}`, `GET /sessions/{id}/messages`, `DELETE /sessions/{id}`, `POST /sessions/{id}/messages/{message_id}/feedback`, `GET /sessions/{id}/followup`, `GET\\|PUT /sessions/{id}/shares`, `GET /sessions/{id}/export`, `POST /sessions/{id}/rewind` | List, read and delete saved chat sessions (assistant messages carry their row `id` and any `feedback`). The list is scoped to the caller, and each chat carries `preview`: its last message as one plain line, Markdown marks stripped and cut at a word near 120 characters, with `You:` before the person's own words. With `?q=` it is a search: the caller's own chats whose title or message text contains the words (case-insensitive, `LIKE` with wildcards escaped), each with `match_count` (messages that contain them; 0 for a title-only match) and `snippet` (the newest matching message, around the match, prefixed `You:` or `Executive:`). Scoped exactly like the list, so nobody else's conversation can match. The Chats page searches this way and opens a result with `?find=`, so the chat starts on that message and steps through the others. A chat-app conversation started with /new is left off the list until its first turn (`memory.conversations`). Every per-session route checks ownership, because session ids are guessable (`slack:dm:<user id>`, `telegram:<chat id>`): only the session's owner or the principal gets through, and a legacy row with no owner is the principal's alone. A teammate's own chat (a web chat, a DM, a private Telegram chat; not a channel or group conversation, `chat._shared_space`) is theirs alone, the principal included, as their mail with the Executive is. Anyone else gets the same 404 as for an unknown id, so the routes can't be used to find out which chats exist. The one other way in is having started the chat in this process (matched by Person id or verified email, so it survives the caller being added to the roster), which is how a caller the roster can't resolve keeps using their own chat. That record is in memory, so after a restart such an ownerless chat is refused for reads. The principal can continue someone else's ownerless chat without becoming its owner. Deleting a session also drops its in-memory copy, so a later turn naming that id starts fresh. The feedback route records 👍/👎 (`{\"feedback\": \"up\"|\"down\"|null}`) on one assistant reply; only the session's own caller or the principal may rate it. The rater is stored (`feedback_by_person_id`), and a 👎 on a reply to the rater's own message triggers a working-style pass for them (paced; see attunement). The chat stream's `done` event carries `message_id` for the persisted reply. The followup route returns `{\"suggestion\": string|null}` — one suggested next user message, written by the utility-fast model from the last few turns, that the chat composer shows as its greyed placeholder (Tab / → or the inline chip fills it in without sending). It is null unless the session ends on a persisted assistant reply, and null (uncached) when the model fails. Same ownership check as feedback; successful suggestions are cached in-process per (session, reply id). Messages from `GET /sessions/{id}/messages` carry each assistant reply's saved `sources` (the same shape as the chat stream's `sources` event, without `type`), so a reloaded chat shows them again. The owner (not the principal on someone else's chat; the principal for an ownerless one) also has the chat controls. `PATCH` takes `{title?, pinned?}`: a name they give is kept (`sessions.title_locked`, so the automatic title never replaces it) and a pinned chat lists first, newest pin first, with `pinned_at`. `PUT /sessions/{id}/shares {person_ids}` shares it, to read, with exactly those team members (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 readable by those it was shared with before. They get it from `GET /sessions/shared-with-me` (with `read_only`, `shared_by`, `shared_at`) and may read it, its messages (without the owner's ratings) and its export; every other route still treats them as anyone else, so they can't write in it, rate, rename, delete or redo it. `GET /sessions/{id}/export` returns the chat as a Markdown file (`memory.chat_export`: each message under its writer's People name or `Executive`, the reply's sources listed under it). `POST /sessions/{id}/rewind {last_message_id}` takes back the last turn for Try again and Edit: under the conversation's turn lock it deletes the last reply and the messages it answered, but only while that reply is still the chat's last row, and returns those messages' words (`{message}`), which the page sends again as an ordinary `/chat` turn through the usual gates. 409 while a turn is answering, for a stale reply id, and for a chat-app conversation (its reply also lives in Slack, Telegram or Discord); audited `session_rewound`. |\n| `today` | `GET /today`, `GET /today/activity`, `GET /today/activity/daily`, `GET /today/brief-delivery`, `GET /today/value`, `GET /today/top-three`, `GET /today/weekly-review` | Morning-brief aggregation, recent-action rail, Pulse heartbeat heatmap (per-day activity counts), and the owner's Your month tally (`GET /today/value?period=month|week&offset=N`: counted lines beside the period before plus the finished reports, owner only, 403 otherwise; see Today). `GET /today` carries the viewer's cached \"What's going on\" `narrative` with `narrative_generated_at` (when it was written) and `narrative_stale` (a fresher one is being written — the page re-polls; see Today). A proposal backed by a roster request carries `roster_request` (the new sender's server-derived details and held-message previews; the principal's only) and is answered through the `people` routes below. `brief-delivery` returns the latest morning brief or end-of-day digest that didn't reach the owner, as `{brief, at, problem, fix, readable}` in plain language (`readable` is false when it couldn't be written, so there is nothing to read), or null — null while briefs go out, once the cause is fixed, while the scheduler is off, and for anyone but the owner (`chat._caller_is_principal_or_unclaimed`); it carries no address or channel id. `top-three` and `weekly-review` feed the solo Briefing's own cards and answer only in solo mode and only to the principal (`workflows._caller_is_the_principal`: a principal match or no caller header, never an unclaimed roster); anyone else, and team mode, get null. `top-three` returns `{items: [{key, kind, text, why, slot}]}` — the morning brief's top three from the same code (`build_top_three(principal_due_soon())`), `slot` a free block like `10:00–11:00`, `\"\"` when none is left, null when no calendar was read — and is kept off `GET /today` because its calendar read may take up to 4 s. `weekly-review` returns the latest completed `weekly_review` run as `{run_id, completed_at, period, top_three, excerpt}` (next week's top three as plain text; `excerpt` when that list is empty), or null when none has completed. |\n| `people` | `GET\\|POST\\|PATCH /people`, `POST /people/{id}/archive`, `GET /people/requests`, `GET /people/requests/{id}`, `POST /people/requests/{id}/approve`, `POST /people/requests/{id}/decline`, `GET\\|POST /people/{id}/open-loops` (a `POST` tells the owner once and returns `notified`: `sent` with the channel, `held`, `not_reached` or `skipped`; see Attunement), `POST /open-loops/{loop_id}/close`, `GET /people/{id}/outreach`, `GET\\|PUT\\|DELETE /people/{id}/attunement` | Roster CRUD and scope lookups. Every `Person` carries `kind` (`team` / `contact`). `GET /people` lists team members only unless `?include_contacts=true` (the People page asks for both; the department-head and workflow pickers keep the default); `POST` / `PATCH` accept `kind`, and a principal contact is a 422 either way. They also take `email_aliases` (other addresses the person writes from, at most 10; on `PATCH` the full list replaces the current one, omitted leaves it): an alias matches their mail and may be emailed but never signs in; a malformed one is a 422, and an alias — or a new primary `email` — that is already someone else's address or alias is a 409. Every `POST` / `PATCH` then closes any pending roster request whose sender now matches someone and replays its held messages. Adding, editing and archiving (`POST`, `PATCH`, `/archive`) are the principal's only, or anyone's while no one is principal yet so a first setup can add its owner (`chat._caller_is_principal_or_unclaimed`, the check behind `PUT /workspace`; a request with no `x-caller-email`, such as the CLI or local login, counts as the principal). Anyone else, a person editing their own row included, gets 403 before the person lookup, so it can't probe which ids exist. Contacts are private to the principal (`caller_is_principal`: the signed-in email is the principal's, or no `x-caller-email`; stricter than the owner rule above, so while no one is principal nobody is): for anyone else `include_contacts` is ignored, a contact's id is a 404 on `GET /people/{id}` and open-loops (exactly as for a missing id; `PATCH` and archive are already a 403 for them), and creating a contact or turning someone into one is a 403, even on a first setup with no principal yet. `GET /people/me` returns `{person_id, is_principal}` so the UI offers contacts to the principal only. `GET /people/by-scope/{token}` never returns a contact. Archiving a person closes their open loops. The open-loop routes list what a person owes (soonest due first) and close one (`reason`: done / not_needed / cancelled) — both the principal's or the owner's only (403 otherwise, via `people.store.is_principal_or_self`). `POST /people/{id}/open-loops` `{task, due_date?}` assigns that person a task (201 with the loop; `due_date` is a local date, due 17:00 in the user's timezone, clamped to 60 days, default 2 days): any active team member may assign anyone on the team, 403 for anyone else; 409 for an archived person, a contact (as seen by the principal), a person at the open-loop cap, a duplicate or open loops turned off; 422 for an empty task. Nobody is messaged at assignment — the owner is chased once it is due. `/outreach` returns, per kind of proactive outreach over 30 days, `sent` / `replied` / `acted` / `ignored` / `pending` (voided DMs are excluded) — same access rule, checked before the person lookup so it can't probe which ids exist. `/attunement` reads, replaces (`rules`: up to 4 strings, or omitted to only set `locked`) or resets the person's working-style rules — same access rule, 404 for an archived person; `PUT` rejects a rule that is not purely about style with 422. Archiving a person also drops their working style and frees their aliases. The **roster-request** routes (declared before `/people/{person_id}`) are the principal's alone (`caller_is_principal`; anyone else gets 404, as for a missing id): `GET /people/requests?status=pending|approved|linked|declined|expired|superseded|all` lists up to 100 (`id`, `channel`, `channel_ref`, sanitised `display_name`, `profile_email`, `on_company_domain`, `suggested_kind`, `suggested_person_id` / `_name`, `status`, `resolved_person_id` / `_kind`, `message_count`, timestamps, `ack_sent`, and `previews` of the held messages while pending — shown to the principal, never to a model); `approve` takes either `link_person_id` (+ `replace_channel_id`) or `full_name` + `kind` (no default: 422 without both) + optional `role`; `decline` takes no body. An answered request is a 409, a chat id or address already on someone else is a 409; the held messages are replayed (or dropped) in the background. |\n| `departments` | `GET\\|POST\\|PATCH\\|DELETE /departments`, `.../goals` | Department state and per-department goals. `PATCH /departments/{slug}` also takes `watched_entities` (≤50 names, `[]` clears) — the entities the research watch policy may add watches for and route to this department. A `cadences` spec that does not parse is rejected with a 422 (empty means no cadence, i.e. the check-in is off); a changed `check_in` cancels the pending check-in and queues the next one on the new schedule. `GET` and `PATCH /departments/{slug}` return the department state plus `next_check_in_at` (ISO UTC of the pending check-in, `null` when it is off, the workspace is solo or none is queued); the list route does not carry it. A new `head_person_id` must be a team member: an unknown id and one of the principal's contacts get the same name-free 422 (`person_id N is not on the team.`), so the route — open to any signed-in user — never reveals that a contact exists; an unchanged head is not re-checked. `POST .../goals` requires only `key_result`: a missing or blank `period_value` is filled with the current period for `period_type` in the user's zone (the same label `create_goal` uses), and `target` defaults to empty. `PATCH .../goals/{id}` rejects a blank `key_result` or `period_value` with a 422; `target` may be cleared. |\n| `agents` | `GET /agents`, `GET /agents/models`, `GET /agents/models/options`, `GET /agents/presets`, `POST /agents/presets/{id}`, `PATCH /agents/{id}`, `POST /agents/{id}/test` | Specialist metadata and Council overrides. `/agents/models` is the flat model allowlist the PATCH validator uses; `/agents/models/options` returns the same ids in the same order, each tagged with `provider`, `provider_label`, `route` (`direct` / `openrouter` / `local`) and a display `label`, for the Council's Provider → Model picker. `AgentDetail` carries `instructions` (additional instructions, appended after `prompt`, which stays the built-in prompt or its replacement); `PATCH` and `/test` accept `instructions` (max 4,000 chars, blank clears it). `GET /agents/presets` lists the Fast, Balanced and Thorough quality presets (each with `available` and the resolved `model` for this install) plus `active` (null when the council is Custom), `base` and `custom_agents`; `POST /agents/presets/{id}` applies one by writing per-agent model and deep-reasoning overrides and returns the same shape (404 unknown preset, 409 when the install allows none of its models). Each `AgentMeta` carries `visibility` (`core` or `internal`) so the Council's simple view can list core agents first. |\n| `personas` | `GET\\|PUT\\|POST\\|DELETE /personas` | Executive persona definitions. |\n| `alerts` | `POST /alerts/{id}/approve`, `GET /alerts/approvals/{id}`, `POST /alerts/{id}/ack`, `POST /alerts/bulk-ack`, `POST /alerts/{id}/snooze`, `POST /alerts/{id}/reopen`, `POST /alerts/review` | Groom the briefing queue. `approve` (body `{edited_body?}`, 202) carries a proposal card out on the server and records who approved it and when (`alerts.approvals`, see Today): it queues the scheduled action a department-gated card held, or runs one Executive turn as the approver in a new chat (`session_id`). 409 for a card already approved or closed, a decision-backed card (approved at `/decisions`), a roster request or a drafted artifact; 403 unless the caller is the card's routed person or the principal (an unrouted card is the principal's); 429 when the caller already has three background turns running. `GET /alerts/approvals/{id}` reads one back (`running`, then `done` / `failed` with `outcome`) for its approver, the card's person or the principal (404 for anyone else). `snooze` (`until`, an ISO time up to 30 days ahead; `null` clears it, the Undo) hides an `unread` card until then by setting `snoozed_until` (409 on a closed card or a roster request); the TTL then counts from the snooze, so a card snoozed past its TTL still comes back. `ack` (`read`/`ack`/`dismissed`, optional `mute_topic`) also teaches a watch-sourced alert's watch (`trust_score`); `bulk-ack` takes explicit `alert_ids` and/or `older_than_days` + `category` (exempt sources skipped); `reopen` is the Undo for a `resolved` / `expired` / `dismissed` alert (never `ack` or an artifact / decision row; back to `unread` with every review stamp cleared and its TTL anchor refreshed, so it is live again even if older than its TTL); `review` runs the Executive's relevance review on demand (ignores the interval; still honours `ALERT_REVIEW_ENABLED`, the per-pass caps, the single-flight lock and per-alert idempotency) and returns the move counts. `bulk-ack` caps ids at 500, needs `older_than_days >= 1`, and applies watch feedback per row; `mute_topic` must be one of the alert's tags or a scoped `external:` / `department:` pattern. Alerts still surface only through the briefing (`/today` reads the live view) — there is no list, prefs, mutes, or live-stream endpoint. |\n| `artifacts` | `GET /artifacts`, `GET /artifacts/{id}`, `GET /artifacts/{id}/download?as=`, `POST /artifacts/{id}/archive`, `POST /artifacts/{id}/restore`, `DELETE /artifacts/{id}` | Browsable deliverables in any format — Markdown, HTML, Word, Excel, or a link into a connected app — with `format`, `downloads`, `external_url`, `supersedes_id` and, for an extension's kind of document, `collection` / `collection_label` on every summary (`orchestrator.extensions`; archive, restore and delete tell the collection first and answer 502 if it refuses). `download` renders the file (Word/Excel built at request time from the stored text; any Markdown artifact, workflow output included, can export `?as=docx`) and is always an attachment with `nosniff` and a sandbox CSP. Every route answers for the signed-in caller (`artifact_records.Viewer`): a drafted artifact is its owner's alone (`alerts.owner_person_id`, the person whose conversation published it; none = the principal's), a workflow output follows its run (`persistence.run_visible_to`), and anything the caller may not see is a 404 like a missing id, the principal included. `POST /alerts/{id}/ack` and `/reopen` answer 404 for someone else's drafted artifact the same way. |\n| `decisions` | `GET /decisions`, `POST /decisions/{id}/{approve,reject,cancel}`, `GET`/`PUT /decisions/classes/meeting_scheduling`, `GET /audit/reliability` | Approval-gated decision instances (e.g. calendar bookings). What approve/reject/cancel do is per class (`DECISION_CLASSES`, one `DecisionClassSpec` each; meeting booking books on approve and deletes on cancel; `delegation_reply`, an inbox reply card, is its approver's alone (`approver_only`) — hidden from everyone else, the principal included when it is a team member's — sends its Gmail draft on approve and, after a reject, deletes the draft unless it was edited; `department_action`, a team member's chat send or edit their department held (see Org), is the principal's and its approver's alone (`principal_and_approver`), makes that exact call on approve and audits `department_action_done` / `_failed` / `_declined`), and an instance of a class with no spec gets 409 instead of being carried out as another. Only the principal, or the person the decision went to for approval (`approver_person_id`), may approve, reject or cancel it. Anyone else gets 403, and a decision nobody was asked about, or one private to the principal, is the principal's alone. The resolver is recorded as `resolver_person_id`, and a reject that loses the race to another answer is a 409. `GET /audit/reliability` is the principal's alone (403 otherwise), because it counts private decisions too. A proposed booking is surfaced on the briefing as a companion alert; approve/reject/cancel here also clear that alert. An approval whose caller resolves to the principal runs the booking inside `grant_contact_egress()`, so a meeting the principal proposed with a contact can be created. Such a booking's payload is marked `private`: it is proposed to the principal, left out of anyone else's `GET /decisions`, and a 404 for them on `GET /decisions/{id}` and every action route. Reviewed in the briefing — there is no separate proposals page. The class routes read and set how meetings are handled: both return `{decision_class: \"meeting_scheduling\", mode: \"propose\" \\| \"auto_execute\"}` (default `propose`); the `PUT` body is `{mode}`, principal-only (403 otherwise, open before a principal exists — but then only `propose` can be set: `auto_execute` is a 409 until a non-archived principal is on the roster), 422 on any other mode, and a change writes a `decision_class_mode_changed` audit row. In solo mode the class mode decides a booking, and `auto_execute` applies only to a turn the principal started on a verified surface — any other turn gets a proposal. |\n| `delegation` | `GET`/`PUT /delegation`, `GET`/`PUT`/`DELETE /delegation/voice`, `POST /delegation/voice/learn`, `POST /delegation/voice/describe`, `POST /delegation/voice/signature`, `PUT /delegation/inbox`, `POST /delegation/inbox/check`, `GET /delegation/replies`, `PUT /delegation/replies/{id}/text`, `GET /delegation/actions`, `PUT /delegation/handle-it`, `PUT /delegation/disclosure`, `PUT /delegation/training`, `DELETE /delegation/learned/{id}`, `GET /delegation/handled`, `PUT /delegation/team` | Act as me — the **caller's own** delegation only; nobody sets it for anyone else. It answers the principal, and a team member once the owner lets them; anyone else gets 403 `not_available_yet`. `GET /delegation` returns `{enabled, gmail: {status, message, email, connect_command, outlook_connect_command, provider}, inbox: {enabled, status, message, watch_since, last_poll_at, checking}, handle_it: {enabled, mode, available, sent_today, lead, lead_available}, training: {replies, follow_ups, actions, drafts, learned}, disclosure: {enabled, handle_it, approved_sends, line}, team}`, where `team` is the owner's switch for the principal while `DELEGATION_TEAM_MEMBERS` allows it — `{enabled, members: [{person_id, name, enabled, inbox, drafts_30d, sent_30d}]}`, counts only — and `null` otherwise. `PUT /delegation/handle-it` takes `{enabled?, mode?}` (`mode` is `careful`, `balanced` or `bold`; anything else is a 422 `bad_mode`) from a caller the API knows is that person — 403 `not_yours`, 409 `caller_signing_required` with only the shared secret — and turning it on needs Act as me and Draft replies to my inbox on (409 `act_as_me_off` / `inbox_off`); `GET /delegation/handled` returns `{replies: [{decision_id, sent_at, to_name, to_email, subject, body, open_questions, gmail_link, source}]}`, the caller's replies and follow-ups (`source` `follow_up`) sent on its own in the last 7 days; a card on `GET /delegation/replies` carries `source` the same way, `can_allow` while Replies (Follow-ups, on a follow-up) is in training, and `learns_style` while Drafts is. `PUT /delegation/disclosure` takes `{handle_it?, approved_sends?}` (any other field is a 422), the caller's own switches for the AI line on replies sent as them (`disclosure.enabled` is the install's `AI_DISCLOSURE`); turning one on needs no signed sign-in, turning one off does (409 `caller_signing_required`), and a change is audited as `delegation_disclosure_changed`. `PUT /delegation/training` takes `{replies?, follow_ups?, actions?, drafts?}` (any other field is a 422) and returns the `GET /delegation` shape; putting Replies or Follow-ups in, or Suggested actions out, needs no signed sign-in, anything else does (409 `caller_signing_required`), and putting Replies or Follow-ups in turns Take the lead as you off (`PUT /delegation/take-the-lead` on answers 409 `in_training` while they are). `training.learned` is `[{id, label, setting, example, uses, created_at}]`, what the caller allowed or kept in training (`setting` `replies`, `follow_ups`, `actions` or `drafts`; the kept example, or \"\"); `DELETE /delegation/learned/{id}` removes one of the caller's own (404 for anyone else's). `PUT /delegation/team` takes `{enabled}` from the principal alone (403 `principal_only`; 409 `not_available` when the install doesn't allow it). The Gmail `status` is `connected`, `not_configured`, `needs_reconnect`, `mismatch`, `no_email`, `shared_mailbox` or `error`, checked live with Google on each call. `PUT` takes `{enabled}` (any other field is a 422); turning it on needs the caller's own Gmail connected, otherwise a 409 whose code says why (`gmail_not_connected`, `gmail_needs_reconnect`, `gmail_mismatch`, `no_email`, `shared_mailbox`, `gmail_error`). The voice routes show, learn (from the caller's sent mail, one pass at a time — a 409 `in_progress`, `locked`, `too_soon`, `not_enough_mail`, `no_profile` or `changed` when it was locked or edited while learning, or a Gmail code), write it from the caller's own description (`POST /delegation/voice/describe` with `{description}`: one model call applies their words to the profile they have and returns it with a short `sample_reply`, saving nothing, so they review it and save it with `PUT`; a 409 `empty`, `too_long`, `in_progress`, `too_many` past 10 an hour or `no_profile`; no mailbox needed), edit and lock, and reset \"How I write\": a typed field that fails validation is a 422 `invalid_voice` listing each `rejected` field, and `clear_exemplars` / `clear_signature` drop those. `POST /delegation/voice/signature` reads the signature from the caller's Gmail settings again and changes nothing else (a locked profile stays locked), with the same Gmail codes as learning: a 409 when their mailbox isn't connected, it refuses the sign-in or the check itself fails (`gmail_error`), and a 502 `gmail_error` when reading the signature fails. On an Outlook mailbox it is a 409 `signature_unavailable`, since Outlook gives apps no signature to read, and the stored one is left alone. A caller `can_delegate` refuses — anyone but the principal, for now — gets 403 `not_available_yet`, which hides the Settings card. A request with no `x-caller-email` is a 403 `sign_in_required` unless the API runs under local login — a header-less call is not a sign-in (the caller is read through `api/caller.py`, as on every principal-only route). `PUT /delegation/inbox` takes `{enabled}` and turns **Draft replies to my inbox** on or off, returning the same shape as `GET /delegation`: on needs Act as me on (409 `act_as_me_off`) and the mailbox connected (the Gmail codes above, which keep their names for an Outlook mailbox too), and turning Act as me off turns it off too. `POST /delegation/inbox/check` starts a scan now in the background and answers 202 with the `inbox` state (409 `inbox_off` or `in_progress`). `GET /delegation/replies` returns `{cards: [...]}`, the caller's open reply cards from the database alone (no Gmail call): the decision id, the sender's name, address, relation and whether it was verified, the subject, when it arrived, what they wrote, the draft's recipients, subject and body, `open_questions`, `flags` and a Gmail link built from a fixed prefix. **Send** is `POST /decisions/{id}/approve`: it sends the card's draft exactly as it is in Gmail, after checking again that the caller is its owner — which on a server needs signed callers (409 `caller_signing_required` otherwise) — that both switches are on (`inbox_off`), no client slot is active (`client_slot`), the Gmail is connected (the Gmail codes), the draft is still there and unanswered (`draft_gone`, `you_replied`) and its recipients are allowed (`no_recipients`, `too_many_recipients`, `executive_recipient`, `not_from_you`). Recipients that changed, or a newer message in the thread, answer 409 `{code: \"confirm\", message, reasons, recipients}`; approving again with `edits: {recipients: <the list shown>, thread_moved_on: true}` is the second yes. **Send + allow** adds `edits.allow: true`: 422 `cant_allow` unless Replies (Follow-ups, on a follow-up card) is in training, 409 `learned_full` when their list is full, both before anything is sent; `edits.example: true` keeps a draft edited in the mailbox as how they write to that person while Drafts is in training. A draft edited in Gmail between those checks and the send is not sent (`draft_changed`). A double tap sends once (`already_handled`); Gmail refusing answers 429 `rate_limited` or 502 `gmail_error` with nothing sent, and a send Gmail didn't confirm answers 502 `send_unconfirmed` and is settled by the next inbox scan. Dismiss is `POST /decisions/{id}/reject`. `GET /delegation/actions` returns `{cards: [...]}`, the caller's own approval cards (`delegation_actions`): the decision id, when it was made, a one-line `why`, and each action's `index`, `kind` (`invite`, `message`, `add_contact`), `summary` and `text` (a message as it will be sent, or a meeting's description). **Approve** is `POST /decisions/{id}/approve` with `edits: {only: [indexes]}` (and `allow: true` for Approve + allow while Suggested actions is in training: 422 `cant_allow` otherwise or when nothing on it can be allowed, 409 `learned_full`; a card carries `can_allow`); it needs the card's own person signed in (403 `not_yours`, 409 `caller_signing_required`), Act as me on (409 `act_as_me_off`) and a card under a week old (409 `expired`), runs once (409 `already_handled`), and returns the decision with `final_payload_json.results`: per action `done`, `waiting` (sent to whoever approves meetings), `failed` with why, or `skipped`. Every change writes a private audit row. |\n| `history` | `GET /memories/history` (`?q=`), `PUT /memories/history/settings`, `PATCH`/`DELETE /memories/history/{id}`, `POST /memories/history/{id}/forget-conversation` | Always in the loop: the **caller's own** notes and switches only, resolved as for Act as me (a signed-in person on the roster, or the principal under local login; otherwise 403 `sign_in_required` / `not_on_roster`). `GET` returns `{notes, reply_notes, retention_days, effective_retention_days, company_retention_days, retention_choices, can_keep_notes, can_note_replies, can_set_company_retention, share_work_style, can_share_work_style}` (`can_keep_notes`: a team member on the People list may turn notes on; `can_note_replies`: they can use Act as me, so email replies are noted too; `share_work_style`: their own \"Share my work style with the team\" switch, `can_share_work_style`: a team member in a team workspace). `PUT` turns notes on only for someone who may keep them, and `share_work_style` on only for someone who may share it (403 `not_available` for either; turning either off always works), takes a person's retention only when shorter than the company's (422 `invalid_setting`), and the company retention only from the principal (403 `principal_only`). `PATCH` pins or corrects a note; `DELETE` forgets it; `forget-conversation` is \"Don't remember this\". A note that isn't the caller's is 404. Every change is audited privately to its person. |\n| `notifications` | `GET /notifications/settings`, `PUT /notifications/settings` | Settings → Notifications: the **caller's own** settings only, resolved as for the notes (a signed-in person on the People list, or the principal under local login; otherwise 403 `sign_in_required` / `not_on_roster`). `GET` returns `{quiet_hours: {enabled, start, end, days}, delivery, urgent_through, timezone, effective_timezone, held_count, gets_briefs, updated_at}` — `days` is `every_day` or `weekdays`, `delivery` `instant` or `digest`, `timezone` the zone they chose (`\"\"` for the workspace's), `held_count` how many messages wait for their quiet hours or brief (counted, never listed), `gets_briefs` whether they are the principal. `PUT` takes `{quiet_hours, delivery, urgent_through, timezone}` and replaces them (extra fields, equal start and end, a bad time or an unknown zone → 422); switching `digest` → `instant` makes what waited for the brief go now. Audited as `notification_settings_changed`. See Org. |\n| `audit` | `GET /audit/logs`, `GET /audit/logs/{id}`, `GET /audit/sessions/{id}`, `GET /audit/usage`, `POST /audit/log` | Durable audit trail of side effects. `/audit/sessions/{id}` adds a per-session token cost summary; `/audit/usage` aggregates token usage and OpenRouter cost across all sessions (totals, by day, by model, and by source — the part of the system that made the calls — including server-side web-search counts), plus `scripts`: how many `run_script` scripts ran (and worked, and in workflows), the tool calls they made, their time, and `turns_avoided` — an upper bound on the model turns those calls would otherwise have needed (each call past a script's first) — and `python_jobs`: how many Python jobs ran (and worked, ran a kept Custom tool, took a chat attachment), their time, CPU, largest peak memory and bytes in and out, and the tokens and charge of the turns that ran one. The Token usage page shows it as a Scripts section. Rows private to the principal (`private_to_principal`: a turn about their private mail, or a row naming one of their contacts on their own turn) are theirs alone: for any other caller, resolved as for `/alerts`, the usage totals leave them out. Once a principal is on the roster, anyone else reads only their own rows (a teammate's own turns, their Act as me work) in the list, by id and in a session, and the principal reads those as actions only — what was done, when and in whose conversation, with the text, details and `full` left out, and no text search over them; any other row's id is a 404, and a session shows only the rows the caller reads. |\n| `architecture` | `GET /architecture/sections`, `.../sections/{id}` | This documentation surface. |\n| `guide` | `GET /guide/sections`, `.../sections/{id}` | Plain-language user-guide content surface — mirrors `architecture` (static, version-controlled files; no LLM on the serving path). |\n| `health` | `GET /health`, `GET /health/honcho` | Liveness probes. Only `/health` is unauthenticated; `/health/honcho` sits behind the gate like everything else, because the exemption is an exact-path set. `/health` also carries `google_tools_missing`, the pinned Google tools startup priming could not find: `[]` once it has checked and they are all there, a list of names when a workspace-mcp rename or the configured services and tool tier left one out, and `null` for no answer — Google Workspace is not configured, or the probe has not finished or it failed. Only `[]` asserts they are present. It also carries `gateway`, the MCP gateway's state from its supervisor (`orchestrator.gateway_boot`): `state` is `off` (MCP not enabled), `no_servers` (enabled, the config names none), `starting` (an attempt is running), `up` or `down` (every attempt so far failed; `next_retry_at` is the next one), with `attempts`, `up_since` and `email_poller` (whether the poller that rides on the gateway runs); the failure's own text stays out, since the route is open to anyone, and goes to the log and the owner's notice on Home. A hosted instance whose gateway never came up used to answer `ok` here with no email going out or in. Only `[]` asserts the tools are present, so a probe that died cannot read as healthy; Setup status says which of the three `null` means. |\n| `version` | `GET /version` | The running version, the latest release on GitHub and `update_available`, for Settings → About. The GitHub answer is cached 6h, only a semver `tag_name` is used and the release link is built from it; `UPDATE_CHECK_ENABLED=false` skips the call and still returns the running version. No in-app updater: upgrading is host-side (`docs/deployment.md#upgrading`). |\n| `setup_status` | `GET /setup/status` | Settings → Setup status: one light per part of the install — AI model, company setup, owner, the Executive's address, API protection, Gmail, your own mailbox (Act as me), Slack, Discord, Telegram, Google Chat, the scheduler, the daily brief (when and where it goes) and Honcho — as `{checked_at, checks: [{id, label, state, summary, fix, link, last_activity}]}`, where `state` is `ok`, `warn`, `error` or `off` (optional and not set up), `fix` says what to do in plain language, `link` is an in-app page that helps (`/people`, `/onboard`) and `last_activity` is the channel's latest `integration_inbound` audit time. It tests live, with at most one free read-only call per service, each bounded to 5 s: Anthropic `models.list` (so an organisation key missing `ANTHROPIC_WORKSPACE_ID` shows up), Slack `auth.test`, Telegram `getMe` and `getWebhookInfo`, Discord `users/@me` only while the bot is still connecting, and — once the owner's own Gmail credential exists — Google's token refresh and Gmail `users/me/profile`. It also reads the listeners the lifespan leaves on `app.state` (Slack's socket, the Discord bot and its task, the MCP gateway), the scheduler heartbeat and the pause switch. When `google_workspace` is configured, the lifespan also starts `MCPGateway.prime_pinned_tools()` in the background (held on `app.state.mcp_prime_task`, cancelled at shutdown), so the pinned Google tools named in the prompt are callable without a search. With `DRIVE_SYNC_ENABLED` the lifespan also bootstraps the `drive_sync_scan` heartbeat beside Notion's (see Scheduler); the Drive folder sync has no HTTP route, only the `openexecutive sync-drive` / `purge-drive` CLI. With `CONFLUENCE_SYNC_ENABLED` it bootstraps the `confluence_sync_scan` heartbeat the same way; that sync is run by hand with `openexecutive sync-confluence` / `purge-confluence`. Sample values copied from `.env.example` are named as such without being sent anywhere. No token reaches a response or a log line: probes report a status code, a service's short error code or an exception's class name. Requests within 5 s of a run get that run's answer and concurrent requests share one run (kept per app on `app.state`), so the button can't become a stream of calls to those services. Gated like every other route; the UI adds a sign-in light of its own, from its own settings. |\n| `documents` | `POST\\|GET\\|DELETE /documents`, `GET /documents/{filename}`, `GET /documents/sources`, `POST /documents/sources/{drive\\|onedrive\\|notion}/sync`, `GET /documents/{drive\\|onedrive\\|notion}`, `GET /documents/{drive\\|onedrive\\|notion}/{id}` | Upload, list, view extracted text, and delete indexed company docs. `GET /documents` rows carry `source: \"upload\"` and the `domain` the upload was indexed under. The connected-source routes back the knowledge page's single Company documents list: `/documents/sources` gives each source's `{id, label, enabled, syncing, last_run, last_error, interval_minutes, file_count}`; `/documents/drive`, `/documents/onedrive` and `/documents/notion` list synced files from the sync state (`{enabled, last_run, last_error, files: [{id, name, url, modified_at, synced_at, indexed}]}`; a Drive row also carries `unreadable_reason`, why a file with `indexed: false` has no text — e.g. a scan OCR could not read — or null); `/documents/{drive\\|onedrive\\|notion}/{id}` returns the stored text (a OneDrive id is `<drive id>:<item id>`) for an id on record (the path comes from the state, never the caller). They are read-only — a synced file is removed where it lives. `POST …/sync` starts one tick of the same sync the scheduler runs as a background task (202); 409 when the source is not connected or a tick is already running (every sync holds a per-process run lock, so a manual run never overlaps the heartbeat; the route also keeps its own started task per source and re-checks just before starting one, so two simultaneous requests start one tick, not two), 429 with `Retry-After` within 60 s of the last successful run or of the end of the last tick in this process, failed ones included, so a failing or slow source can't be re-run back-to-back. The page's text view never loads images from synced content (a remote image would be a read beacon for whoever edits the shared folder). Upload is keyed on the filename, so re-uploading a document replaces its chunks rather than duplicating them, and `DELETE` removes the rows as well as the file. `domain` must be one of the nine specialist domains (including `sales`) or `general`; anything else is a 400 rather than a 200 that indexes where no specialist can retrieve. A scanned PDF is converted (`knowledge.pdf_reader`) before it is indexed and in the text view, as are scanned PDFs in `POST /chat/upload` and the client / onboarding intake uploads. The upload is streamed to disk 1 MB at a time and refused with a 413 once it passes 50 MB, and the file is parsed in a short-lived child process (see the RAG section), so a large document does not stay in the API process's memory. A Word or Excel file that cannot be parsed, or whose parse runs out of time, is a 422 with a readable reason. When every parser is busy, the response is a 503 with `Retry-After`. |\n| `executive` | `GET /executive/status`, `POST /executive/pause`, `POST /executive/resume` | Operator pause switch for all autonomous work (scheduler, Gmail poller, workflow resumer); inbound chat and DMs stay live. Status returns `{paused, paused_at, paused_by, reason, held_actions, can_resume}` — `held_actions` counts due `pending` rows that fire on resume. `pause` takes an optional `reason` (≤200 chars) and is idempotent (re-pausing keeps the original start and reason); `paused_by` is the UI proxy's `x-caller-email`, else `api`. Behind the shared-secret middleware — not `SCHEDULED_ADMIN_TOKEN`, which the UI cannot send. Any caller may pause; `resume` is principal-only (`is_principal_or_self`, 403 otherwise; open while no principal is rostered; a header-less caller resolves to the principal as in `chat`), and status carries `can_resume` for the viewer so the UI hides Resume from everyone else. |\n| `workspace` | `GET /workspace`, `PUT /workspace` | Solo/team mode, the user's time zone and the principal's role (`memory.workspace_settings`). Both return `{mode, timezone, effective_timezone, role_kind, role_title, reports_to, remit, measured_on, company_domains, company_domains_custom}` — `timezone` is what the user set (null when unset), `effective_timezone` the zone in effect (`timezone`, else `USER_TIMEZONE`, else UTC), and each role field is null until set. `PUT` is a partial update: only the fields sent change; `mode` is `solo` or `team` (not null), `timezone` an IANA zone, or null/blank to clear it; `role_kind` is `owner`, `in_house`, `independent` or `other`, and `role_title` / `reports_to` / `remit` / `measured_on` are free text (trimmed, at most 120 / 120 / 500 / 300 characters), each null or blank to clear it; an unknown zone, a bad mode or role kind, an over-long role field or an unknown field is a 422 and changes nothing. Switching to solo cancels every pending department check-in, switching to team re-schedules them, and a new zone re-times the pending briefs and reflection; a role change has no side effects (the next turn reads it). `company_domains` is the company's own email domains (a teammate matches by local part on them — see Org): `GET` returns the ones in effect (the stored list, or the domain of the principal's primary address, with `company_domains_custom` false) only to the same caller the role is shown to, `[]` for anyone else; `PUT` takes a list (at most 10 plain domain names, never a free-mail provider's — 422 otherwise, the value never quoted) or null / `[]` to go back to deriving them, and a change is audited with the new list. Each change writes a `workspace_settings_changed` audit row (a role change adds `details.role_fields_changed`, the names of the fields that changed — never their text). The role is the principal's: `GET` returns it only to a caller `PUT` would accept and reads it as nulls for anyone else. `PUT` is the principal's alone (`is_principal_or_self`, 403 otherwise; a header-less caller resolves to the principal as in `chat`) and open while no principal is rostered, so first-run setup can pick a mode. Both work before onboarding — unlike `company-profile`, nothing here needs a profile. |\n| `scheduled` | `GET\\|DELETE` scheduled actions (`?status=…&order=asc\\|desc`) | Pending and fired scheduled actions; `order` flips the `run_at` sort (asc=soonest-first for the upcoming queue, desc=most-recent-first for terminal-status history). `DELETE /scheduled/{id}` cancels a `pending` row (409 otherwise). Like pause it only stops work, so any signed-in user may — the UI proxy's `x-caller-email` is trusted when the request also carries the `BACKEND_SHARED_SECRET` `x-api-key` — as may a matching `X-Admin-Token` (`SCHEDULED_ADMIN_TOKEN`) or a loopback caller with no token set; otherwise 401 (token set) or 503. Audited as `scheduled_action_cancelled`. |\n| `watchlist` | `GET\\|POST\\|PATCH\\|DELETE /watchlist`, `POST /watchlist/{slug}/approve`, `POST /watchlist/{slug}/decline` | External-monitoring watchlist + signals. Rows carry `origin` (`manual` \\| `executive` \\| `research` \\| `research_proposed`); `approve` turns a research suggestion (`research_proposed`, `dry_run`) into a live watch, `decline` `{reason: not_relevant \\| too_noisy \\| wrong_source}` removes it and records the decline (or, for `too_noisy`, keeps it live at a high floor), both 409 unless the row is a pending suggestion; `DELETE ?reason=` on a research-origin row records the decline too. |\n| `workflows` | `GET /workflows`, `POST /workflows/{name}/runs`, `GET\\|POST\\|PUT\\|DELETE /workflows/custom`, `GET\\|DELETE /workflows/custom/{name}/targets`, `POST /workflows/runs/{run_id}/decision`, `POST /workflows/runs/{run_id}/rerun`, `GET /workflows/tools/search?q=`, `GET /workflows/tools/describe?names=` | Workflow catalog, run management, and user-created (dynamic) workflow CRUD. `rerun` queues a failed scheduled run (a department check-in, a saved workflow on a cadence) once more, due now (see Scheduler); the principal may, and for a saved workflow the person it delivers to; 409 for a run that did not fail, one started from `/jobs` (\"Start this one again from its page\") or one already queued again. Custom definitions come back with a server-managed `owner_person_id` (the creator — the web caller on `POST`, set on insert only; a client-sent value is ignored), who is asked to approve a workflow's first write to a new target. `GET /workflows/custom/{name}/targets` lists the targets its tool steps may write to without asking and `DELETE …/targets?value=` forgets one. `POST /workflows/{name}/runs` is a 403 (\"Only the principal can run this workflow.\"), audited, before any run row exists, when the workflow is one only the principal may start in the workspace's mode (`weekly_review` always, `morning_brief` in solo) and the caller is not the principal. A request with no `x-caller-email` counts as the principal; with no principal on the roster, no signed-in caller does. This governs starting a run only. A run started by hand (this endpoint, or `run_workflow` / research in chat) records its starter as `owner_person_id` and is theirs alone: `GET /workflows/runs` lists the team's (scheduled, no owner) runs plus the caller's own and the ones waiting on them, and `GET` / `DELETE /workflows/runs/{run_id}` and `POST /workflows/runs/{run_id}/decision` are a 404 for anyone else's, the principal included. A signed-in email that is on nobody's People entry cannot start one (403), and a run whose starter can't be read is refused (503); its steps read and draft documents as the starter only. `POST /workflows/runs/{run_id}/decision` with `{decision: \"approve\"|\"reject\"}` answers a run awaiting a yes/no sign-off from the web app — 403 unless the caller is the person it waits on or the principal, 409 if it isn't awaiting or needs a written reply — through the same `apply_resolution` a chat reply uses. Custom create/update also rejects (422) any action-step tool that does not resolve, and so does `POST /workflows/custom/{name}/activate` when turning a workflow **on** — that click is the approval for a tool workflow chat saved switched off (turning off is never checked). Turning on a workflow with action steps requires the body `{is_active: true, definition}` carrying the definition the user reviewed; if the stored one differs (ignoring `is_active` and timestamps) it returns 409, and the switch itself is a compare-and-set on the validated revision (`dynamic_store.activate_if_unchanged`, keyed on `updated_at`), so a save that lands while the tool check awaits the gateway — even from another process — is a 409 too, so only what was shown gets switched on. `GET /workflows/custom` lists inactive definitions too; `GET /workflows/{name}` 404s for them. The two `tools` endpoints return `{tools: [{name, description, read_only, source}]}` for the advanced editor's tool picker and the review card; `read_only` is true only when the name says it reads (a label, not a control). The run stream adds a `progress` event (`step_id`, `summary`) while an action step uses tools. Each catalog entry (`WorkflowMeta`) carries `is_custom`, `background` (true for the system-run built-ins the UI files under “System”) and `quick` (true for a Quick workflow, one per playbook nothing else follows, named `quick_<playbook>`). The run endpoint streams SSE; its `awaiting_human` event carries `delivery` (`self` \\| `sent` \\| `suppressed` \\| `alerted` \\| `failed`) alongside `person_id` / `question` / `awaiting_until`, because the outbound guard or an unreachable approver means the question may never have been asked — a client must not render “waiting on them” for those. A paused run ends the stream with neither `done` nor `error`, so that `awaiting_human` frame carries `terminal: true` to say so explicitly, plus `resumable` — whether the run continues by itself once answered or stops at the gate. `GET /workflows/runs/{run_id}` returns the run row with the resume payload replaced by a small `resume_progress` summary (`gate_step_id`, `completed_step_ids`, or `null`): the payload holds every completed step's full text, and the run-detail page polls this endpoint while a run is unfinished. |\n| `knowledge` | `/knowledge/builtin`, `/external`, `/search` | MBA knowledge base and external sources. `/search` is the introspection parallel of `retriever.retrieve` and mirrors its filters — including the `general` catch-all on the company collection — so the panel cannot report a specialist seeing nothing that it does retrieve in chat. It accepts `general` in `domain_filter` for the same reason. `/search` applies the same review gate as `retrieve()` — withheld (pending or rejected) built-in, external and failure rows are dropped, so the panel never advertises knowledge the Executive cannot use; it degrades to unfiltered rather than failing if review state is unreadable. `POST /knowledge/builtin` refuses a name already held by shipped content, and `POST|DELETE /knowledge/failures` now register and deregister for review — without that a user-authored failure case study had no review row, so no SME decision could block it. |\n| `skills` | `/skills`, `/skills/search`, `/skills/{name}/restore` | Skill registry (the UI's **Playbooks**) CRUD and search. `PUT` on a built-in saves a company customization that shadows it; `DELETE` returns `{name, outcome}` — `deleted`, `reverted` (customization removed, built-in back) or `hidden` (built-in hidden for this company); `restore` un-hides; `GET /skills?include_hidden=true` lists hidden built-ins. List and detail carry `used_by` — `[{name, title, is_custom}]` of the workflows that follow the playbook (switched-off custom ones included) (`WorkflowMeta.playbooks` is the other direction). |\n| `evals` | `/evals/scenarios`, `/evals/runs` | Eval scenarios and run results. `POST /evals/runs` is a 403 when a workflow scenario names a workflow that only the principal may start in the mode it runs in (the weekly review; the morning brief in solo) and the caller is not the principal — the Jobs page's rule for starting a run; stored results are read under the existing `/evals/runs` rules. |\n| `memories` | `/memories/{decisions,initiatives,advice}`, `GET /memories/facts`, `POST /memories/facts/{fact_id}/{retire,approve,decline}`, `GET /memories/facts/approval`, `PUT /memories/facts/approval/{person_id}`, `GET /memories/people`, `GET /memories/people/{person_id}/conclusions` | Episodic-memory record management; the standing facts the Pulse Corrections tab reads (`{facts: [...], can_retire, retirable_ids, can_review}`; each fact carries `recorded_by_role` / `recorded_by_name`; `?include_inactive=` default true, honoured for the principal only; anyone else gets the active rows plus their own `proposed` ones, with the provenance (`session_id`, `turn_id`, `recorded_by_person_id`, `retired_reason`, and `source_quote` except on their own facts) blanked, never retired, replaced or declined text; `?limit=` 1–500) and their retire (the principal any fact, a teammate only one they recorded that the principal has not approved — else 403; the audit row names the teammate; 404 for an unknown or `profile` row, 409 when no longer active; writes a private `fact_retired` audit row); approve / decline a teammate's `proposed` fact (principal only, else 403; 409 when it is not proposed; private `fact_reviewed` row); and the per-teammate \"needs my approval\" switch (on by default; `GET` lists `[{person_id, full_name, needs_approval}]` for every active team member but the principal, `true` for anyone not yet set; `PUT` takes `{needs_approval}`, 404 for anyone else; both principal only; private `fact_approval_changed` row); plus the read-only peer-memory overview the Pulse People tab reads (`{status: ok|disabled|error, people: [...], conclusion_total}`; `?recent=` 1–50, default 5) and one person's full conclusion list, paged newest first (`{status, person_id, items, page, size, total, has_more}`; `?page=` ≥1, `?size=` 1–100, default 50; 404 when the person has no peer). Peer memory is each person's own: the overview holds only the caller's entry (none for a caller off the roster; `conclusion_total` counts only theirs), the principal included, and `/conclusions` for anyone but the caller is a 404. |\n| `review` | `/review/items`, `/review/stats`, `/review/trusted-defaults`, `POST /review/curate`, `POST /review/bulk-approve` | Knowledge review queue and annotations. Shipped knowledge registers as a trusted default (`approved` with a NULL `reviewed_at`), so the queue starts empty; `curate` (`{domain, action: start|stop}`, domain required) opts one domain in or out, and `trusted-defaults` returns domain → unreviewed count. `bulk-approve` takes a non-empty `domain`, `item_ids` (max 500) or `all_pending: true`, and 400s with no selector; it returns `{approved_count, item_ids}`. |\n| `onboarding` | `/onboard/interview/understand`, `/onboard/interview/start`, `/onboard/interview/message`, `/onboard/interview/draft`, `/onboard/interview/{id}`, `/onboard/interview/commit` | Conversational company setup. The `onboarding_interviewer` agent asks clarifying questions, then emits a draft profile + people + departments. **Nothing is persisted until `POST /onboard/interview/commit`** — the interview itself never writes. `start` is multipart (description + optional deck/one-pager uploads). `commit` answers 403 when the draft would make a different person the owner and the caller is not the current owner (setup demotes the old principal, and any signed-in user can open it). It also takes an optional `owner_email` — the principal's sign-in email, which the review screen pre-fills from the signed-in user — checked before anything is written (422 if it is malformed, already another person's, or would replace the principal's existing email — setup only fills in a missing one; 403 if the caller is not the owner and it is not the address they signed in with, since the roster is the sign-in allow-list) and saved on the principal's People row, so the owner's chats resolve to them from the first turn. |\n| `workflow_designer` | `POST /workflows/designer/start`, `POST /workflows/designer/edit`, `POST /workflows/designer/message`, `POST /workflows/designer/draft`, `GET /workflows/designer/{session_id}` | The conversational New workflow wizard, and editing a saved workflow by conversation. `/edit` (`{name}`) opens a session on a saved custom workflow with no model call: the stored definition is the starting draft, and every response then carries `editing` (its name) and `original` (the stored definition as the session opened on it); drafts keep that name and its on/off state whatever the model writes (404 for an unknown workflow). The UI saves one with `POST /workflows/custom/{name}/save-edit` (`{session_id, definition}`): the server saves the session's own draft, never a client-sent body, and only when it equals the `definition` the user reviewed (a later message is a 409, so the click saves only what was shown); it re-validates it, keeps the stored on/off state, and writes only if the stored workflow is still the version the conversation opened on — otherwise 409, as it is for a session about another workflow or one with nothing drafted yet. It sits under `/workflows/custom` so anything that limits writes to custom workflows covers it too. The `workflow_designer` agent asks clarifying questions (`phase: \"question\"`, with `hint` and up to four suggested `options`), then returns `phase: \"draft\"` with `draft.definition` (exactly the body `POST /workflows/custom` takes), `summary`, and `assumptions`; every response carries the `transcript`. **Nothing is persisted here** — sessions are in memory, and the UI saves through `POST /workflows/custom`. Errors are fixed strings (422 over the 8,000-char message cap or the transcript cap, 404 for an expired session, 409 while another turn on the same session is still running, 502/504 for model failure or timeout). Mounted ahead of the `workflows` router. |\n| `python_jobs` | `GET /python-jobs/{job_id}/{name}` | A result file a Python job (`run_python_job`) wrote, the principal's alone (403 otherwise), served as a download (`Content-Disposition: attachment`, `Content-Security-Policy: sandbox`, `nosniff`, `Cache-Control: no-store`); 404 for a bad id or name or a file past its 7 days. |\n| `saved_tools` | `GET /saved-tools`, `GET\\|PUT /saved-tools/{name}`, `POST /saved-tools/{name}/rollback` | The scripts the Executive saved as tools (Settings → Advanced → Saved tools), the owner's alone (403 otherwise). The list gives each tool's name, description, on/off, current version, `kind` (`script` or `python`, a kept Python job) and the tools it calls, plus whether `SAVED_TOOLS_ENABLED` is on; the detail adds the script, every version and the last 20 runs. `PUT {enabled?, workflows?, version?}` turns one on or off (off also turns it off for workflows, so turning it back on never re-arms unattended runs), and turns the named `version` — the one the owner looked at, never whatever is current by then — on for workflows (or workflows off); a Python tool never turns on for workflows (409) — turning workflows on lets more run unattended, so it needs a request tied to the owner (signed sign-ins or local login, as Take the lead's switches do; 409 otherwise); `rollback {version}` makes that version the one that runs. Both are audited as `saved_tool_changed`. The Executive saves tools itself through `run_script`; there is no create route. |\n| `onboarding` (fallback) | `/onboard/start`, `/onboard/answer`, `/onboard/status/{id}` | The original 12-step form wizard, kept as a fallback (UI at `/onboard?mode=form`) and used by the `openexecutive onboard` CLI. Its final answer saves the profile and adds people with their emails and a principal, so once there is an owner only they can send it (403, and the session rolls back so the owner can still finish it). `/onboard/start` reads the workspace mode once for the session: solo skips the Team Size, Team Members and Fractional Executives steps. Each status response's `current_step` / `total_steps` count only the steps that session asks, and `optional` says whether the current step can be skipped. |\n| `company-profile` | `GET\\|PATCH /company-profile` | Structured company profile. |\n| `alerts` (private cards) | `POST /alerts/{id}/ack`, `/reopen`, `/alerts/bulk-ack` | An alert tagged `private:principal` (see Today) is a 404 on ack and reopen for anyone but the principal, and their bulk sweep skips it. A roster-request card (source `roster_request`) is a 409 on `ack` even for the principal — it is answered at `/people/requests/{id}`, since acking would leave the sender waiting with nothing to show it — and, as an exempt source, `bulk-ack` and `reopen` skip it. |\n| `auth` | `GET /auth/allowed-emails` | Non-archived **team members** with an email, offered to the UI's sign-in gate — a contact is never on it, so adding a client to reach them by email no longer lets them sign in. The gate takes the **union** of this roster and its own `ALLOWED_EMAILS` env list, so env entries always work (and are checked first, short-circuiting the fetch) and roster entries are additive — a roster change can never revoke a configured operator. With local login (`make dev` with Google sign-in not set up — the UI then listens on 127.0.0.1 only) the UI signs in without an email, sends no `x-caller-email`, and the backend resolves the caller to the principal, as it does for the CLI. |\n| `fixtures` | `/fixtures`, `/fixtures/{name}/load` | Demo-company fixture load/reset/snapshot. `POST /fixtures/reset` leaves no departments, like a new install (`departments_seeded` is always 0). |\n| `clients` | `/clients`, `/clients/generate`, `/clients/cockpit`, `/clients/save`, `/clients/{slug}/activate` | Client-company slots — multi-client mode for fractional use; create from current/blank/AI-generated intake draft (pasted notes and/or file attachments, multipart on `/clients/generate`), save-back switching, engagement metadata (PATCH), cross-client cockpit, delete. See the Client Companies section. |\n| webhooks | `POST /webhook/telegram`, `POST /webhook/google-chat`, `POST /webhook/slack` | Inbound integration callbacks (self-verified). `/webhook/slack` answers 503 unless `SLACK_SIGNING_SECRET` is set. |\n| MCP server | `POST\\|GET /mcp` | Open Executive exposed as an MCP server (Streamable-HTTP). Not a router — a mounted FastMCP sub-app. Same shared-secret gate (`x-api-key`); exposes company context as resources and the specialist council as tools. See the MCP Server section. |\n\n**Take the lead** (`api/routes/take_the_lead.py`): `GET /take-the-lead` returns the As the Executive switch, its six Ask first switches (`{kind, label, hint, on}`, the hint a plain line on what each one catches), the company's rules, whether this server can tie a change to the owner (`available`), and whether the Executive is paused. `PUT /take-the-lead` takes `{enabled?, ask_first?}`, and `POST /take-the-lead/rules` / `DELETE /take-the-lead/rules/{id}` add or remove a company rule (`{kind: person|domain|words|amount, value}`, 422 on a bad one). All four are the principal's alone (403). Anything that lets more happen on its own (turning it on, turning an Ask first off, removing a rule) needs a caller the API can tie to them (`delegation.verified.caller_refusal`, else 409). `GET /today/activity` adds `took_the_lead` rows (what Take the lead did, named, not quoted) and, for the caller alone, `sent_as_you` rows for what Handle it for me sent as them. Under `/delegation`: `PUT /delegation/take-the-lead {enabled}` is Take the lead as you (the owner's only for now; turning it on turns Handle it for me on), and `GET|POST /delegation/take-the-lead/rules` and `DELETE …/rules/{id}` manage the caller's own rules. `HandleItOut` gains `lead` and `lead_available`. A `take_the_lead_action` decision is approved or rejected through the existing `/decisions/{id}/approve|reject`. Training: the response also carries `training` (In training: everything waits unless allowed), `learned` (`{id, label, feature, example, uses, created_at}`: what it was allowed, the edit kept as an example by field) and `suggested` (`{key, label, approvals}`); `PUT` takes `training?` too, and leaving training while on needs the same provable owner as turning it on. `POST /take-the-lead/learned {key}` allows a current suggestion (404 for anything else; provable owner), `DELETE /take-the-lead/learned/{id}` makes it ask first again. `learned` also lists the owner's own Act as me senders (`feature` `act_as_me`), never anyone else's, and Remove works on those too. On a `take_the_lead_action` card, `POST /decisions/{id}/approve` takes `edits.input` (the card's editable fields, 422 for any other; the principal's alone, 403 for an area approver) and `edits.allow: true` (a training card only, 422 otherwise; the principal from a provable request, 403 otherwise), finishing `approved_with_edit` when a field changed.",
+ "markdown": "The FastAPI surface lives in `openexecutive.api.main`, which mounts one router per topic. A shared-secret middleware gates every request via an `x-api-key` header, except `/health` and the `/webhook/*` callbacks (which carry their own verification). With local login (`OE_LOCAL_LOGIN=1`, which only `make dev` sets, and only while neither Google nor SSO sign-in is set up) a second middleware answers 403 to any request whose raw `Host` is not `localhost`, `127.0.0.1` or `[::1]` (except a webhook that verifies its caller: Google Chat and Slack always, Telegram only with a `TELEGRAM_WEBHOOK_SECRET` Telegram can send), and to any write whose `Sec-Fetch-Site` is present and not `same-origin`/`none`. The UI signs that owner in with no password and this API usually has no secret, so without it a web page in the owner's browser could drive the API as the principal — by DNS-rebinding its own hostname to 127.0.0.1, or by posting a plain form from another site or localhost port. CORS is restricted to the UI origins in `BACKEND_ALLOWED_ORIGINS`, plus the `make dev` UI on `localhost:3000` only when `OE_PUBLIC_DEPLOYMENT` is unset, so a public instance never answers a localhost page with credentials. The gate is off when `BACKEND_SHARED_SECRET` is unset — intended for local development only — so any internet-reachable deployment sets `OE_PUBLIC_DEPLOYMENT`, and `create_app()` then refuses to boot without the secret rather than serving an unauthenticated API.\n\n**Who is calling** is read in one place, `api/caller.py`, which answers with a `Caller` kind and email; a test fails on any other read of an `x-caller-*` header. By default (`open`) it is the `x-caller-email` the UI proxy stamps from the sign-in, trusted because whoever holds the shared secret is trusted as the proxy, and a request with none runs as the principal. **Signed callers** remove that trust. With `CALLER_ASSERTION_PUBLIC_KEYS` set, the proxy signs every request with an Ed25519 key only the UI holds, and a third middleware checks the `x-caller-assertion` header:\n\n- **What it covers.** It is good for one method, the exact path and query, at most 120 seconds, and one use. The API keeps used ids in memory.\n- **What it names.** A `user`, by email, or the `operator`: local login, which runs as the principal.\n- **No caller header at all** is a `service`, for scripts or MCP clients holding only the secret. It is never the principal, not even on an install with no owner yet, so it can't save a first setup.\n- **Anything else is a 401.** That includes an `x-caller-email` without an assertion (`caller_assertion_required`), and a bad, expired, reused or mismatched assertion (`caller_assertion_invalid`).\n\nPublic keys that can't be read stop the boot, rather than fall back to trusting the header. `scripts/make-caller-keys.py` makes the pair, and `scripts/mint-caller-assertion.py` signs one request for curl. The API holds only public keys. Setup's API-protection check warns while a shared secret is set without them.\n\nEndpoints grouped by router:\n\n| Router | Key endpoints | Purpose |\n|---|---|---|\n| `chat` | `POST /chat`, `POST /chat/stop`, `POST /chat/add`, `POST /chat/background` | SSE stream of a live Executive turn, with a `: keepalive` comment every `CHAT_STREAM_KEEPALIVE_S` while the turn is quiet. `POST /chat/background` starts a new chat that the server answers to the end with nobody connected (a phone approving a card, then closing the app): it answers `202` with the new `session_id` once the same caller, access and quota checks as `/chat` pass, the turn saves itself as a `/chat` turn does, and one caller may have three running at once (`429` beyond that). `POST /chat/add` hands the running turn a message the person typed while it works; the turn takes it at its next step and the stream names it in a `message_added` event, and a second `POST /chat` on the same conversation waits for the first to finish. The request body optionally carries `page_context` (route, page title, guide section id, and a form descriptor with current values) — sent only by the Ask OE side panel so the Executive can explain the current page or propose form values. When the Executive calls its `propose_form_values` tool, the stream emits a `form_patch` event (`{type, form_id, fields, rationale, iteration}`) that the panel applies into the on-screen form as highlighted suggestions; the user reviews and saves through the form's normal submit path. Each round of tool calls also emits an `activity` event (`{type, label, tool, iteration}`) naming what is running — progress only, forwarded verbatim and never persisted with the message, unlike an `action_taken` chip. A `session_id` in the body must be a chat the caller may use (the same ownership rule as `sessions`). If it isn't, the turn runs in a fresh chat instead, so nothing is written into someone else's session and the reply looks the same as for an unknown id. An unknown namespaced id (`slack:…`, `telegram:…` and so on) is ignored and a fresh chat is started, because those ids belong to the channel adapters and claiming one first would make the caller its owner. The client mints a `client_turn_id` and sends it with the turn; `POST /chat/stop` takes that id and halts the turn mid-flight, so the button is live from the moment Send is pressed rather than only once the first SSE byte arrives. A stopped turn emits a `stopped` event and then the usual `done` over the same still-open stream — never an `error` — and whatever streamed so far is persisted and flagged. The endpoint returns 404 both for an unknown id and for another caller's turn, so it cannot be used to probe which turns are live. An optional `memory_text` (1–2000 chars) is what peer memory records as the caller's words instead of `message` — the briefing handoffs send it because their seed quotes the Executive's own card; `POST /chat/upload` derives it from the typed text and filenames. Since it never reaches the transcript, the `chat_turn` audit row keeps it beside `message`. After the reply — a stopped or timed-out one too, before the `stopped` / `error` / `done` frames — a turn that looked at anything sends one `sources` event, `{type, session_id, sources: [{kind, title, url}], unavailable: [area]}`: `kind` is `company`, `knowledge`, `notion`, `research`, `document` or `web`, `url` is only ever an http(s) link or, for an earlier document, `/artifacts/<id>`, at most 12 sources (6 from the web, pages the reply cites first), and `unavailable` names parts of the analysis (\"finance\") whose specialist failed or said nothing every time it was asked. It is persisted with the reply as `chat_messages.sources`. A request that carries `x-caller-email` marks its turn signed in (`Session.web_caller_signed_in`), which Act as me needs on a deployment without local login. |\n| `sessions` | `GET /sessions`, `GET /sessions/shared-with-me`, `GET\\|PATCH /sessions/{id}`, `GET /sessions/{id}/messages`, `DELETE /sessions/{id}`, `POST /sessions/{id}/messages/{message_id}/feedback`, `GET /sessions/{id}/followup`, `GET\\|PUT /sessions/{id}/shares`, `GET /sessions/{id}/export`, `POST /sessions/{id}/rewind` | List, read and delete saved chat sessions (assistant messages carry their row `id` and any `feedback`). The list is scoped to the caller, and each chat carries `preview`: its last message as one plain line, Markdown marks stripped and cut at a word near 120 characters, with `You:` before the person's own words. With `?q=` it is a search: the caller's own chats whose title or message text contains the words (case-insensitive, `LIKE` with wildcards escaped), each with `match_count` (messages that contain them; 0 for a title-only match) and `snippet` (the newest matching message, around the match, prefixed `You:` or `Executive:`). Scoped exactly like the list, so nobody else's conversation can match. The Chats page searches this way and opens a result with `?find=`, so the chat starts on that message and steps through the others. A chat-app conversation started with /new is left off the list until its first turn (`memory.conversations`). Every per-session route checks ownership, because session ids are guessable (`slack:dm:<user id>`, `telegram:<chat id>`): only the session's owner or the principal gets through, and a legacy row with no owner is the principal's alone. A teammate's own chat (a web chat, a DM, a private Telegram chat; not a channel or group conversation, `chat._shared_space`) is theirs alone, the principal included, as their mail with the Executive is. Anyone else gets the same 404 as for an unknown id, so the routes can't be used to find out which chats exist. The one other way in is having started the chat in this process (matched by Person id or verified email, so it survives the caller being added to the roster), which is how a caller the roster can't resolve keeps using their own chat. That record is in memory, so after a restart such an ownerless chat is refused for reads. The principal can continue someone else's ownerless chat without becoming its owner. Deleting a session also drops its in-memory copy, so a later turn naming that id starts fresh. The feedback route records 👍/👎 (`{\"feedback\": \"up\"|\"down\"|null}`) on one assistant reply; only the session's own caller or the principal may rate it. The rater is stored (`feedback_by_person_id`), and a 👎 on a reply to the rater's own message triggers a working-style pass for them (paced; see attunement). The chat stream's `done` event carries `message_id` for the persisted reply. The followup route returns `{\"suggestion\": string|null}` — one suggested next user message, written by the utility-fast model from the last few turns, that the chat composer shows as its greyed placeholder (Tab / → or the inline chip fills it in without sending). It is null unless the session ends on a persisted assistant reply, and null (uncached) when the model fails. Same ownership check as feedback; successful suggestions are cached in-process per (session, reply id). Messages from `GET /sessions/{id}/messages` carry each assistant reply's saved `sources` (the same shape as the chat stream's `sources` event, without `type`), so a reloaded chat shows them again. The owner (not the principal on someone else's chat; the principal for an ownerless one) also has the chat controls. `PATCH` takes `{title?, pinned?}`: a name they give is kept (`sessions.title_locked`, so the automatic title never replaces it) and a pinned chat lists first, newest pin first, with `pinned_at`. `PUT /sessions/{id}/shares {person_ids}` shares it, to read, with exactly those team members (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 readable by those it was shared with before. They get it from `GET /sessions/shared-with-me` (with `read_only`, `shared_by`, `shared_at`) and may read it, its messages (without the owner's ratings) and its export; every other route still treats them as anyone else, so they can't write in it, rate, rename, delete or redo it. `GET /sessions/{id}/export` returns the chat as a Markdown file (`memory.chat_export`: each message under its writer's People name or `Executive`, the reply's sources listed under it). `POST /sessions/{id}/rewind {last_message_id}` takes back the last turn for Try again and Edit: under the conversation's turn lock it deletes the last reply and the messages it answered, but only while that reply is still the chat's last row, and returns those messages' words (`{message}`), which the page sends again as an ordinary `/chat` turn through the usual gates. 409 while a turn is answering, for a stale reply id, and for a chat-app conversation (its reply also lives in Slack, Telegram or Discord); audited `session_rewound`. |\n| `today` | `GET /today`, `GET /today/activity`, `GET /today/activity/daily`, `GET /today/brief-delivery`, `GET /today/value`, `GET /today/top-three`, `GET /today/weekly-review` | Morning-brief aggregation, recent-action rail, Pulse heartbeat heatmap (per-day activity counts), and the owner's Your month tally (`GET /today/value?period=month|week&offset=N`: counted lines beside the period before plus the finished reports, owner only, 403 otherwise; see Today). `GET /today` carries the viewer's cached \"What's going on\" `narrative` with `narrative_generated_at` (when it was written) and `narrative_stale` (a fresher one is being written — the page re-polls; see Today). A proposal backed by a roster request carries `roster_request` (the new sender's server-derived details and held-message previews; the principal's only) and is answered through the `people` routes below. `brief-delivery` returns the latest morning brief or end-of-day digest that didn't reach the owner, as `{brief, at, problem, fix, readable}` in plain language (`readable` is false when it couldn't be written, so there is nothing to read), or null — null while briefs go out, once the cause is fixed, while the scheduler is off, and for anyone but the owner (`chat._caller_is_principal_or_unclaimed`); it carries no address or channel id. `top-three` and `weekly-review` feed the solo Briefing's own cards and answer only in solo mode and only to the principal (`workflows._caller_is_the_principal`: a principal match or no caller header, never an unclaimed roster); anyone else, and team mode, get null. `top-three` returns `{items: [{key, kind, text, why, slot}]}` — the morning brief's top three from the same code (`build_top_three(principal_due_soon())`), `slot` a free block like `10:00–11:00`, `\"\"` when none is left, null when no calendar was read — and is kept off `GET /today` because its calendar read may take up to 4 s. `weekly-review` returns the latest completed `weekly_review` run as `{run_id, completed_at, period, top_three, excerpt}` (next week's top three as plain text; `excerpt` when that list is empty), or null when none has completed. |\n| `people` | `GET\\|POST\\|PATCH /people`, `POST /people/{id}/archive`, `GET /people/requests`, `GET /people/requests/{id}`, `POST /people/requests/{id}/approve`, `POST /people/requests/{id}/decline`, `GET\\|POST /people/{id}/open-loops` (a `POST` tells the owner once and returns `notified`: `sent` with the channel, `held`, `not_reached` or `skipped`; see Attunement), `POST /open-loops/{loop_id}/close`, `GET /people/{id}/outreach`, `GET\\|PUT\\|DELETE /people/{id}/attunement` | Roster CRUD and scope lookups. Every `Person` carries `kind` (`team` / `contact`). `GET /people` lists team members only unless `?include_contacts=true` (the People page asks for both; the department-head and workflow pickers keep the default); `POST` / `PATCH` accept `kind`, and a principal contact is a 422 either way. They also take `email_aliases` (other addresses the person writes from, at most 10; on `PATCH` the full list replaces the current one, omitted leaves it): an alias matches their mail and may be emailed but never signs in; a malformed one is a 422, and an alias — or a new primary `email` — that is already someone else's address or alias is a 409. Every `POST` / `PATCH` then closes any pending roster request whose sender now matches someone and replays its held messages. Adding, editing and archiving (`POST`, `PATCH`, `/archive`) are the principal's only, or anyone's while no one is principal yet so a first setup can add its owner (`chat._caller_is_principal_or_unclaimed`, the check behind `PUT /workspace`; a request with no `x-caller-email`, such as the CLI or local login, counts as the principal). Anyone else, a person editing their own row included, gets 403 before the person lookup, so it can't probe which ids exist. Contacts are private to the principal (`caller_is_principal`: the signed-in email is the principal's, or no `x-caller-email`; stricter than the owner rule above, so while no one is principal nobody is): for anyone else `include_contacts` is ignored, a contact's id is a 404 on `GET /people/{id}` and open-loops (exactly as for a missing id; `PATCH` and archive are already a 403 for them), and creating a contact or turning someone into one is a 403, even on a first setup with no principal yet. `GET /people/me` returns `{person_id, is_principal}` so the UI offers contacts to the principal only. `GET /people/by-scope/{token}` never returns a contact. Archiving a person closes their open loops. The open-loop routes list what a person owes (soonest due first) and close one (`reason`: done / not_needed / cancelled) — both the principal's or the owner's only (403 otherwise, via `people.store.is_principal_or_self`). `POST /people/{id}/open-loops` `{task, due_date?}` assigns that person a task (201 with the loop; `due_date` is a local date, due 17:00 in the user's timezone, clamped to 60 days, default 2 days): any active team member may assign anyone on the team, 403 for anyone else; 409 for an archived person, a contact (as seen by the principal), a person at the open-loop cap, a duplicate or open loops turned off; 422 for an empty task. Nobody is messaged at assignment — the owner is chased once it is due. `/outreach` returns, per kind of proactive outreach over 30 days, `sent` / `replied` / `acted` / `ignored` / `pending` (voided DMs are excluded) — same access rule, checked before the person lookup so it can't probe which ids exist. `/attunement` reads, replaces (`rules`: up to 4 strings, or omitted to only set `locked`) or resets the person's working-style rules — same access rule, 404 for an archived person; `PUT` rejects a rule that is not purely about style with 422. Archiving a person also drops their working style and frees their aliases. The **roster-request** routes (declared before `/people/{person_id}`) are the principal's alone (`caller_is_principal`; anyone else gets 404, as for a missing id): `GET /people/requests?status=pending|approved|linked|declined|expired|superseded|all` lists up to 100 (`id`, `channel`, `channel_ref`, sanitised `display_name`, `profile_email`, `on_company_domain`, `suggested_kind`, `suggested_person_id` / `_name`, `status`, `resolved_person_id` / `_kind`, `message_count`, timestamps, `ack_sent`, and `previews` of the held messages while pending — shown to the principal, never to a model); `approve` takes either `link_person_id` (+ `replace_channel_id`) or `full_name` + `kind` (no default: 422 without both) + optional `role`; `decline` takes no body. An answered request is a 409, a chat id or address already on someone else is a 409; the held messages are replayed (or dropped) in the background. |\n| `departments` | `GET\\|POST\\|PATCH\\|DELETE /departments`, `.../goals` | Department state and per-department goals. `PATCH /departments/{slug}` also takes `watched_entities` (≤50 names, `[]` clears) — the entities the research watch policy may add watches for and route to this department. A `cadences` spec that does not parse is rejected with a 422 (empty means no cadence, i.e. the check-in is off); a changed `check_in` cancels the pending check-in and queues the next one on the new schedule. `GET` and `PATCH /departments/{slug}` return the department state plus `next_check_in_at` (ISO UTC of the pending check-in, `null` when it is off, the workspace is solo or none is queued); the list route does not carry it. A new `head_person_id` must be a team member: an unknown id and one of the principal's contacts get the same name-free 422 (`person_id N is not on the team.`), so the route — open to any signed-in user — never reveals that a contact exists; an unchanged head is not re-checked. `POST .../goals` requires only `key_result`: a missing or blank `period_value` is filled with the current period for `period_type` in the user's zone (the same label `create_goal` uses), and `target` defaults to empty. `PATCH .../goals/{id}` rejects a blank `key_result` or `period_value` with a 422; `target` may be cleared. |\n| `agents` | `GET /agents`, `GET /agents/models`, `GET /agents/models/options`, `GET /agents/presets`, `POST /agents/presets/{id}`, `PATCH /agents/{id}`, `POST /agents/{id}/test` | Specialist metadata and Council overrides. `/agents/models` is the flat model allowlist the PATCH validator uses; `/agents/models/options` returns the same ids in the same order, each tagged with `provider`, `provider_label`, `route` (`direct` / `openrouter` / `local`) and a display `label`, for the Council's Provider → Model picker. `AgentDetail` carries `instructions` (additional instructions, appended after `prompt`, which stays the built-in prompt or its replacement); `PATCH` and `/test` accept `instructions` (max 4,000 chars, blank clears it). `GET /agents/presets` lists the Fast, Balanced and Thorough quality presets (each with `available` and the resolved `model` for this install) plus `active` (null when the council is Custom), `base` and `custom_agents`; `POST /agents/presets/{id}` applies one by writing per-agent model and deep-reasoning overrides and returns the same shape (404 unknown preset, 409 when the install allows none of its models). Each `AgentMeta` carries `visibility` (`core` or `internal`) so the Council's simple view can list core agents first. |\n| `personas` | `GET\\|PUT\\|POST\\|DELETE /personas` | Executive persona definitions. |\n| `alerts` | `POST /alerts/{id}/approve`, `GET /alerts/approvals/{id}`, `POST /alerts/{id}/ack`, `POST /alerts/bulk-ack`, `POST /alerts/{id}/snooze`, `POST /alerts/{id}/reopen`, `POST /alerts/review` | Groom the briefing queue. `approve` (body `{edited_body?}`, 202) carries a proposal card out on the server and records who approved it and when (`alerts.approvals`, see Today): it queues the scheduled action a department-gated card held, or runs one Executive turn as the approver in a new chat (`session_id`). 409 for a card already approved or closed, a decision-backed card (approved at `/decisions`), a roster request or a drafted artifact; 403 unless the caller is the card's routed person or the principal (an unrouted card is the principal's); 429 when the caller already has three background turns running. `GET /alerts/approvals/{id}` reads one back (`running`, then `done` / `failed` with `outcome`) for its approver, the card's person or the principal (404 for anyone else). `snooze` (`until`, an ISO time up to 30 days ahead; `null` clears it, the Undo) hides an `unread` card until then by setting `snoozed_until` (409 on a closed card or a roster request); the TTL then counts from the snooze, so a card snoozed past its TTL still comes back. `ack` (`read`/`ack`/`dismissed`, optional `mute_topic`) also teaches a watch-sourced alert's watch (`trust_score`); `bulk-ack` takes explicit `alert_ids` and/or `older_than_days` + `category` (exempt sources skipped); `reopen` is the Undo for a `resolved` / `expired` / `dismissed` alert (never `ack` or an artifact / decision row; back to `unread` with every review stamp cleared and its TTL anchor refreshed, so it is live again even if older than its TTL); `review` runs the Executive's relevance review on demand (ignores the interval; still honours `ALERT_REVIEW_ENABLED`, the per-pass caps, the single-flight lock and per-alert idempotency) and returns the move counts. `bulk-ack` caps ids at 500, needs `older_than_days >= 1`, and applies watch feedback per row; `mute_topic` must be one of the alert's tags or a scoped `external:` / `department:` pattern. Alerts still surface only through the briefing (`/today` reads the live view) — there is no list, prefs, mutes, or live-stream endpoint. |\n| `artifacts` | `GET /artifacts`, `GET /artifacts/{id}`, `GET /artifacts/{id}/download?as=`, `POST /artifacts/{id}/archive`, `POST /artifacts/{id}/restore`, `DELETE /artifacts/{id}` | Browsable deliverables in any format — Markdown, HTML, Word, Excel, or a link into a connected app — with `format`, `downloads`, `external_url`, `supersedes_id` and, for an extension's kind of document, `collection` / `collection_label` on every summary (`orchestrator.extensions`; archive, restore and delete tell the collection first and answer 502 if it refuses). `download` renders the file (Word/Excel built at request time from the stored text; any Markdown artifact, workflow output included, can export `?as=docx`) and is always an attachment with `nosniff` and a sandbox CSP. Every route answers for the signed-in caller (`artifact_records.Viewer`): a drafted artifact is its owner's alone (`alerts.owner_person_id`, the person whose conversation published it; none = the principal's), a workflow output follows its run (`persistence.run_visible_to`), and anything the caller may not see is a 404 like a missing id, the principal included. `POST /alerts/{id}/ack` and `/reopen` answer 404 for someone else's drafted artifact the same way. |\n| `decisions` | `GET /decisions`, `POST /decisions/{id}/{approve,reject,cancel}`, `GET`/`PUT /decisions/classes/meeting_scheduling`, `GET /audit/reliability` | Approval-gated decision instances (e.g. calendar bookings). What approve/reject/cancel do is per class (`DECISION_CLASSES`, one `DecisionClassSpec` each; meeting booking books on approve and deletes on cancel; `delegation_reply`, an inbox reply card, is its approver's alone (`approver_only`) — hidden from everyone else, the principal included when it is a team member's — sends its Gmail draft on approve and, after a reject, deletes the draft unless it was edited; `department_action`, a team member's chat send or edit their department held (see Org), is the principal's and its approver's alone (`principal_and_approver`), makes that exact call on approve and audits `department_action_done` / `_failed` / `_declined`), and an instance of a class with no spec gets 409 instead of being carried out as another. Only the principal, or the person the decision went to for approval (`approver_person_id`), may approve, reject or cancel it. Anyone else gets 403, and a decision nobody was asked about, or one private to the principal, is the principal's alone. The resolver is recorded as `resolver_person_id`, and a reject that loses the race to another answer is a 409. `GET /audit/reliability` is the principal's alone (403 otherwise), because it counts private decisions too. A proposed booking is surfaced on the briefing as a companion alert; approve/reject/cancel here also clear that alert. An approval whose caller resolves to the principal runs the booking inside `grant_contact_egress()`, so a meeting the principal proposed with a contact can be created. Such a booking's payload is marked `private`: it is proposed to the principal, left out of anyone else's `GET /decisions`, and a 404 for them on `GET /decisions/{id}` and every action route. Reviewed in the briefing — there is no separate proposals page. The class routes read and set how meetings are handled: both return `{decision_class: \"meeting_scheduling\", mode: \"propose\" \\| \"auto_execute\"}` (default `propose`); the `PUT` body is `{mode}`, principal-only (403 otherwise, open before a principal exists — but then only `propose` can be set: `auto_execute` is a 409 until a non-archived principal is on the roster), 422 on any other mode, and a change writes a `decision_class_mode_changed` audit row. In solo mode the class mode decides a booking, and `auto_execute` applies only to a turn the principal started on a verified surface — any other turn gets a proposal. |\n| `delegation` | `GET`/`PUT /delegation`, `GET`/`PUT`/`DELETE /delegation/voice`, `POST /delegation/voice/learn`, `POST /delegation/voice/describe`, `POST /delegation/voice/signature`, `PUT /delegation/inbox`, `POST /delegation/inbox/check`, `GET /delegation/replies`, `PUT /delegation/replies/{id}/text`, `GET /delegation/actions`, `PUT /delegation/handle-it`, `PUT /delegation/disclosure`, `PUT /delegation/training`, `DELETE /delegation/learned/{id}`, `GET /delegation/handled`, `PUT /delegation/team` | Act as me — the **caller's own** delegation only; nobody sets it for anyone else. It answers the principal, and a team member once the owner lets them; anyone else gets 403 `not_available_yet`. `GET /delegation` returns `{enabled, gmail: {status, message, email, connect_command, outlook_connect_command, provider}, inbox: {enabled, status, message, watch_since, last_poll_at, checking}, handle_it: {enabled, mode, available, sent_today, lead, lead_available}, training: {replies, follow_ups, actions, drafts, learned}, disclosure: {enabled, handle_it, approved_sends, line}, team}`, where `team` is the owner's switch for the principal while `DELEGATION_TEAM_MEMBERS` allows it — `{enabled, members: [{person_id, name, enabled, inbox, drafts_30d, sent_30d}]}`, counts only — and `null` otherwise. `PUT /delegation/handle-it` takes `{enabled?, mode?}` (`mode` is `careful`, `balanced` or `bold`; anything else is a 422 `bad_mode`) from a caller the API knows is that person — 403 `not_yours`, 409 `caller_signing_required` with only the shared secret — and turning it on needs Act as me and Draft replies to my inbox on (409 `act_as_me_off` / `inbox_off`); `GET /delegation/handled` returns `{replies: [{decision_id, sent_at, to_name, to_email, subject, body, open_questions, gmail_link, source}]}`, the caller's replies and follow-ups (`source` `follow_up`) sent on its own in the last 7 days; a card on `GET /delegation/replies` carries `source` the same way, `can_allow` while Replies (Follow-ups, on a follow-up) is in training, and `learns_style` while Drafts is. `PUT /delegation/disclosure` takes `{handle_it?, approved_sends?}` (any other field is a 422), the caller's own switches for the AI line on replies sent as them (`disclosure.enabled` is the install's `AI_DISCLOSURE`); turning one on needs no signed sign-in, turning one off does (409 `caller_signing_required`), and a change is audited as `delegation_disclosure_changed`. `PUT /delegation/training` takes `{replies?, follow_ups?, actions?, drafts?}` (any other field is a 422) and returns the `GET /delegation` shape; putting Replies or Follow-ups in, or Suggested actions out, needs no signed sign-in, anything else does (409 `caller_signing_required`), and putting Replies or Follow-ups in turns Take the lead as you off (`PUT /delegation/take-the-lead` on answers 409 `in_training` while they are). `training.learned` is `[{id, label, setting, example, uses, created_at}]`, what the caller allowed or kept in training (`setting` `replies`, `follow_ups`, `actions` or `drafts`; the kept example, or \"\"); `DELETE /delegation/learned/{id}` removes one of the caller's own (404 for anyone else's). `PUT /delegation/team` takes `{enabled}` from the principal alone (403 `principal_only`; 409 `not_available` when the install doesn't allow it). The Gmail `status` is `connected`, `not_configured`, `needs_reconnect`, `mismatch`, `no_email`, `shared_mailbox` or `error`, checked live with Google on each call. `PUT` takes `{enabled}` (any other field is a 422); turning it on needs the caller's own Gmail connected, otherwise a 409 whose code says why (`gmail_not_connected`, `gmail_needs_reconnect`, `gmail_mismatch`, `no_email`, `shared_mailbox`, `gmail_error`). The voice routes show, learn (from the caller's sent mail, one pass at a time — a 409 `in_progress`, `locked`, `too_soon`, `not_enough_mail`, `no_profile` or `changed` when it was locked or edited while learning, or a Gmail code), write it from the caller's own description (`POST /delegation/voice/describe` with `{description}`: one model call applies their words to the profile they have and returns it with a short `sample_reply`, saving nothing, so they review it and save it with `PUT`; a 409 `empty`, `too_long`, `in_progress`, `too_many` past 10 an hour or `no_profile`; no mailbox needed), edit and lock, and reset \"How I write\": a typed field that fails validation is a 422 `invalid_voice` listing each `rejected` field, and `clear_exemplars` / `clear_signature` drop those. `POST /delegation/voice/signature` reads the signature from the caller's Gmail settings again and changes nothing else (a locked profile stays locked), with the same Gmail codes as learning: a 409 when their mailbox isn't connected, it refuses the sign-in or the check itself fails (`gmail_error`), and a 502 `gmail_error` when reading the signature fails. On an Outlook mailbox it is a 409 `signature_unavailable`, since Outlook gives apps no signature to read, and the stored one is left alone. A caller `can_delegate` refuses — anyone but the principal, for now — gets 403 `not_available_yet`, which hides the Settings card. A request with no `x-caller-email` is a 403 `sign_in_required` unless the API runs under local login — a header-less call is not a sign-in (the caller is read through `api/caller.py`, as on every principal-only route). `PUT /delegation/inbox` takes `{enabled}` and turns **Draft replies to my inbox** on or off, returning the same shape as `GET /delegation`: on needs Act as me on (409 `act_as_me_off`) and the mailbox connected (the Gmail codes above, which keep their names for an Outlook mailbox too), and turning Act as me off turns it off too. `POST /delegation/inbox/check` starts a scan now in the background and answers 202 with the `inbox` state (409 `inbox_off` or `in_progress`). `GET /delegation/replies` returns `{cards: [...]}`, the caller's open reply cards from the database alone (no Gmail call): the decision id, the sender's name, address, relation and whether it was verified, the subject, when it arrived, what they wrote, the draft's recipients, subject and body, `open_questions`, `flags` and a Gmail link built from a fixed prefix. **Send** is `POST /decisions/{id}/approve`: it sends the card's draft exactly as it is in Gmail, after checking again that the caller is its owner — which on a server needs signed callers (409 `caller_signing_required` otherwise) — that both switches are on (`inbox_off`), no client slot is active (`client_slot`), the Gmail is connected (the Gmail codes), the draft is still there and unanswered (`draft_gone`, `you_replied`) and its recipients are allowed (`no_recipients`, `too_many_recipients`, `executive_recipient`, `not_from_you`). Recipients that changed, or a newer message in the thread, answer 409 `{code: \"confirm\", message, reasons, recipients}`; approving again with `edits: {recipients: <the list shown>, thread_moved_on: true}` is the second yes. **Send + allow** adds `edits.allow: true`: 422 `cant_allow` unless Replies (Follow-ups, on a follow-up card) is in training, 409 `learned_full` when their list is full, both before anything is sent; `edits.example: true` keeps a draft edited in the mailbox as how they write to that person while Drafts is in training. A draft edited in Gmail between those checks and the send is not sent (`draft_changed`). A double tap sends once (`already_handled`); Gmail refusing answers 429 `rate_limited` or 502 `gmail_error` with nothing sent, and a send Gmail didn't confirm answers 502 `send_unconfirmed` and is settled by the next inbox scan. Dismiss is `POST /decisions/{id}/reject`. `GET /delegation/actions` returns `{cards: [...]}`, the caller's own approval cards (`delegation_actions`): the decision id, when it was made, a one-line `why`, and each action's `index`, `kind` (`invite`, `message`, `add_contact`), `summary` and `text` (a message as it will be sent, or a meeting's description). **Approve** is `POST /decisions/{id}/approve` with `edits: {only: [indexes]}` (and `allow: true` for Approve + allow while Suggested actions is in training: 422 `cant_allow` otherwise or when nothing on it can be allowed, 409 `learned_full`; a card carries `can_allow`); it needs the card's own person signed in (403 `not_yours`, 409 `caller_signing_required`), Act as me on (409 `act_as_me_off`) and a card under a week old (409 `expired`), runs once (409 `already_handled`), and returns the decision with `final_payload_json.results`: per action `done`, `waiting` (sent to whoever approves meetings), `failed` with why, or `skipped`. Every change writes a private audit row. |\n| `history` | `GET /memories/history` (`?q=`), `PUT /memories/history/settings`, `PATCH`/`DELETE /memories/history/{id}`, `POST /memories/history/{id}/forget-conversation` | Always in the loop: the **caller's own** notes and switches only, resolved as for Act as me (a signed-in person on the roster, or the principal under local login; otherwise 403 `sign_in_required` / `not_on_roster`). `GET` returns `{notes, reply_notes, retention_days, effective_retention_days, company_retention_days, retention_choices, can_keep_notes, can_note_replies, can_set_company_retention, share_work_style, can_share_work_style}` (`can_keep_notes`: a team member on the People list may turn notes on; `can_note_replies`: they can use Act as me, so email replies are noted too; `share_work_style`: their own \"Share my work style with the team\" switch, `can_share_work_style`: a team member in a team workspace). `PUT` turns notes on only for someone who may keep them, and `share_work_style` on only for someone who may share it (403 `not_available` for either; turning either off always works), takes a person's retention only when shorter than the company's (422 `invalid_setting`), and the company retention only from the principal (403 `principal_only`). `PATCH` pins or corrects a note; `DELETE` forgets it; `forget-conversation` is \"Don't remember this\". A note that isn't the caller's is 404. Every change is audited privately to its person. |\n| `notifications` | `GET /notifications/settings`, `PUT /notifications/settings` | Settings → Notifications: the **caller's own** settings only, resolved as for the notes (a signed-in person on the People list, or the principal under local login; otherwise 403 `sign_in_required` / `not_on_roster`). `GET` returns `{quiet_hours: {enabled, start, end, days}, delivery, urgent_through, timezone, effective_timezone, held_count, gets_briefs, updated_at}` — `days` is `every_day` or `weekdays`, `delivery` `instant` or `digest`, `timezone` the zone they chose (`\"\"` for the workspace's), `held_count` how many messages wait for their quiet hours or brief (counted, never listed), `gets_briefs` whether they are the principal. `PUT` takes `{quiet_hours, delivery, urgent_through, timezone}` and replaces them (extra fields, equal start and end, a bad time or an unknown zone → 422); switching `digest` → `instant` makes what waited for the brief go now. Audited as `notification_settings_changed`. See Org. |\n| `audit` | `GET /audit/logs`, `GET /audit/logs/{id}`, `GET /audit/sessions/{id}`, `GET /audit/usage`, `POST /audit/log` | Durable audit trail of side effects. `/audit/sessions/{id}` adds a per-session token cost summary; `/audit/usage` aggregates token usage and OpenRouter cost across all sessions (totals, by day, by model, and by source — the part of the system that made the calls — including server-side web-search counts), plus `scripts`: how many `run_script` scripts ran (and worked, and in workflows), the tool calls they made, their time, and `turns_avoided` — an upper bound on the model turns those calls would otherwise have needed (each call past a script's first) — and `python_jobs`: how many Python jobs ran (and worked, ran a kept Custom tool, took a chat attachment), their time, CPU, largest peak memory and bytes in and out, and the tokens and charge of the turns that ran one. The Token usage page shows it as a Scripts section. Rows private to the principal (`private_to_principal`: a turn about their private mail, or a row naming one of their contacts on their own turn) are theirs alone: for any other caller, resolved as for `/alerts`, the usage totals leave them out. Once a principal is on the roster, anyone else reads only their own rows (a teammate's own turns, their Act as me work) in the list, by id and in a session, and the principal reads those as actions only — what was done, when and in whose conversation, with the text, details and `full` left out, and no text search over them; any other row's id is a 404, and a session shows only the rows the caller reads. |\n| `architecture` | `GET /architecture/sections`, `.../sections/{id}` | This documentation surface. |\n| `guide` | `GET /guide/sections`, `.../sections/{id}` | Plain-language user-guide content surface — mirrors `architecture` (static, version-controlled files; no LLM on the serving path). |\n| `health` | `GET /health`, `GET /health/honcho` | Liveness probes. Only `/health` is unauthenticated; `/health/honcho` sits behind the gate like everything else, because the exemption is an exact-path set. `/health` also carries `google_tools_missing`, the pinned Google tools startup priming could not find: `[]` once it has checked and they are all there, a list of names when a workspace-mcp rename or the configured services and tool tier left one out, and `null` for no answer — Google Workspace is not configured, or the probe has not finished or it failed. Only `[]` asserts they are present. It also carries `gateway`, the MCP gateway's state from its supervisor (`orchestrator.gateway_boot`): `state` is `off` (MCP not enabled), `no_servers` (enabled, the config names none), `starting` (an attempt is running), `up` or `down` (every attempt so far failed; `next_retry_at` is the next one), with `attempts`, `up_since` and `email_poller` (whether the poller that rides on the gateway runs); the failure's own text stays out, since the route is open to anyone, and goes to the log and the owner's notice on Home. A hosted instance whose gateway never came up used to answer `ok` here with no email going out or in. Only `[]` asserts the tools are present, so a probe that died cannot read as healthy; Setup status says which of the three `null` means. |\n| `version` | `GET /version` | The running version, the latest release on GitHub and `update_available`, for Settings → About. The GitHub answer is cached 6h, only a semver `tag_name` is used and the release link is built from it; `UPDATE_CHECK_ENABLED=false` skips the call and still returns the running version. No in-app updater: upgrading is host-side (`docs/deployment.md#upgrading`). |\n| `setup_status` | `GET /setup/status` | Settings → Setup status: one light per part of the install — AI model, company setup, owner, the Executive's address, API protection, Gmail, your own mailbox (Act as me), Slack, Discord, Telegram, Google Chat, the scheduler, the daily brief (when and where it goes) and Honcho — as `{checked_at, checks: [{id, label, state, summary, fix, link, last_activity}]}`, where `state` is `ok`, `warn`, `error` or `off` (optional and not set up), `fix` says what to do in plain language, `link` is an in-app page that helps (`/people`, `/onboard`) and `last_activity` is the channel's latest `integration_inbound` audit time. It tests live, with at most one free read-only call per service, each bounded to 5 s: Anthropic `models.list` (so an organisation key missing `ANTHROPIC_WORKSPACE_ID` shows up), Slack `auth.test`, Telegram `getMe` and `getWebhookInfo`, Discord `users/@me` only while the bot is still connecting, and — once the owner's own Gmail credential exists — Google's token refresh and Gmail `users/me/profile`. It also reads the listeners the lifespan leaves on `app.state` (Slack's socket, the Discord bot and its task, the MCP gateway), the scheduler heartbeat and the pause switch. When `google_workspace` is configured, the lifespan also starts `MCPGateway.prime_pinned_tools()` in the background (held on `app.state.mcp_prime_task`, cancelled at shutdown), so the pinned Google tools named in the prompt are callable without a search. With `DRIVE_SYNC_ENABLED` the lifespan also bootstraps the `drive_sync_scan` heartbeat beside Notion's (see Scheduler); the Drive folder sync has no HTTP route, only the `openexecutive sync-drive` / `purge-drive` CLI. With `CONFLUENCE_SYNC_ENABLED` it bootstraps the `confluence_sync_scan` heartbeat the same way; that sync is run by hand with `openexecutive sync-confluence` / `purge-confluence`. Sample values copied from `.env.example` are named as such without being sent anywhere. No token reaches a response or a log line: probes report a status code, a service's short error code or an exception's class name. Requests within 5 s of a run get that run's answer and concurrent requests share one run (kept per app on `app.state`), so the button can't become a stream of calls to those services. Gated like every other route; the UI adds a sign-in light of its own, from its own settings. |\n| `documents` | `POST\\|GET\\|DELETE /documents`, `GET /documents/{filename}`, `GET /documents/sources`, `POST /documents/sources/{drive\\|onedrive\\|notion}/sync`, `GET /documents/{drive\\|onedrive\\|notion}`, `GET /documents/{drive\\|onedrive\\|notion}/{id}` | Upload, list, view extracted text, and delete indexed company docs. `GET /documents` rows carry `source: \"upload\"` and the `domain` the upload was indexed under. The connected-source routes back the knowledge page's single Company documents list: `/documents/sources` gives each source's `{id, label, enabled, syncing, last_run, last_error, interval_minutes, file_count}`; `/documents/drive`, `/documents/onedrive` and `/documents/notion` list synced files from the sync state (`{enabled, last_run, last_error, files: [{id, name, url, modified_at, synced_at, indexed}]}`; a Drive row also carries `unreadable_reason`, why a file with `indexed: false` has no text — e.g. a scan OCR could not read — or null); `/documents/{drive\\|onedrive\\|notion}/{id}` returns the stored text (a OneDrive id is `<drive id>:<item id>`) for an id on record (the path comes from the state, never the caller). They are read-only — a synced file is removed where it lives. `POST …/sync` starts one tick of the same sync the scheduler runs as a background task (202); 409 when the source is not connected or a tick is already running (every sync holds a per-process run lock, so a manual run never overlaps the heartbeat; the route also keeps its own started task per source and re-checks just before starting one, so two simultaneous requests start one tick, not two), 429 with `Retry-After` within 60 s of the last successful run or of the end of the last tick in this process, failed ones included, so a failing or slow source can't be re-run back-to-back. The page's text view never loads images from synced content (a remote image would be a read beacon for whoever edits the shared folder). Upload is keyed on the filename, so re-uploading a document replaces its chunks rather than duplicating them, and `DELETE` removes the rows as well as the file. `domain` must be one of the nine specialist domains (including `sales`) or `general`; anything else is a 400 rather than a 200 that indexes where no specialist can retrieve. A scanned PDF is converted (`knowledge.pdf_reader`) before it is indexed and in the text view, as are scanned PDFs in `POST /chat/upload` and the client / onboarding intake uploads. The upload is streamed to disk 1 MB at a time and refused with a 413 once it passes 50 MB, and the file is parsed in a short-lived child process (see the RAG section), so a large document does not stay in the API process's memory. A Word or Excel file that cannot be parsed, or whose parse runs out of time, is a 422 with a readable reason. When every parser is busy, the response is a 503 with `Retry-After`. |\n| `executive` | `GET /executive/status`, `POST /executive/pause`, `POST /executive/resume` | Operator pause switch for all autonomous work (scheduler, Gmail poller, workflow resumer); inbound chat and DMs stay live. Status returns `{paused, paused_at, paused_by, reason, held_actions, can_resume}` — `held_actions` counts due `pending` rows that fire on resume. `pause` takes an optional `reason` (≤200 chars) and is idempotent (re-pausing keeps the original start and reason); `paused_by` is the UI proxy's `x-caller-email`, else `api`. Behind the shared-secret middleware — not `SCHEDULED_ADMIN_TOKEN`, which the UI cannot send. Any caller may pause; `resume` is principal-only (`is_principal_or_self`, 403 otherwise; open while no principal is rostered; a header-less caller resolves to the principal as in `chat`), and status carries `can_resume` for the viewer so the UI hides Resume from everyone else. |\n| `workspace` | `GET /workspace`, `PUT /workspace` | Solo/team mode, the user's time zone and the principal's role (`memory.workspace_settings`). Both return `{mode, timezone, effective_timezone, role_kind, role_title, reports_to, remit, measured_on, company_domains, company_domains_custom}` — `timezone` is what the user set (null when unset), `effective_timezone` the zone in effect (`timezone`, else `USER_TIMEZONE`, else UTC), and each role field is null until set. `PUT` is a partial update: only the fields sent change; `mode` is `solo` or `team` (not null), `timezone` an IANA zone, or null/blank to clear it; `role_kind` is `owner`, `in_house`, `independent` or `other`, and `role_title` / `reports_to` / `remit` / `measured_on` are free text (trimmed, at most 120 / 120 / 500 / 300 characters), each null or blank to clear it; an unknown zone, a bad mode or role kind, an over-long role field or an unknown field is a 422 and changes nothing. Switching to solo cancels every pending department check-in, switching to team re-schedules them, and a new zone re-times the pending briefs and reflection; a role change has no side effects (the next turn reads it). `company_domains` is the company's own email domains (a teammate matches by local part on them — see Org): `GET` returns the ones in effect (the stored list, or the domain of the principal's primary address, with `company_domains_custom` false) only to the same caller the role is shown to, `[]` for anyone else; `PUT` takes a list (at most 10 plain domain names, never a free-mail provider's — 422 otherwise, the value never quoted) or null / `[]` to go back to deriving them, and a change is audited with the new list. Each change writes a `workspace_settings_changed` audit row (a role change adds `details.role_fields_changed`, the names of the fields that changed — never their text). The role is the principal's: `GET` returns it only to a caller `PUT` would accept and reads it as nulls for anyone else. `PUT` is the principal's alone (`is_principal_or_self`, 403 otherwise; a header-less caller resolves to the principal as in `chat`) and open while no principal is rostered, so first-run setup can pick a mode. Both work before onboarding — unlike `company-profile`, nothing here needs a profile. |\n| `scheduled` | `GET\\|DELETE` scheduled actions (`?status=…&order=asc\\|desc`) | Pending and fired scheduled actions; `order` flips the `run_at` sort (asc=soonest-first for the upcoming queue, desc=most-recent-first for terminal-status history). `DELETE /scheduled/{id}` cancels a `pending` row (409 otherwise). Like pause it only stops work, so any signed-in user may — the UI proxy's `x-caller-email` is trusted when the request also carries the `BACKEND_SHARED_SECRET` `x-api-key` — as may a matching `X-Admin-Token` (`SCHEDULED_ADMIN_TOKEN`) or a loopback caller with no token set; otherwise 401 (token set) or 503. Audited as `scheduled_action_cancelled`. |\n| `watchlist` | `GET\\|POST\\|PATCH\\|DELETE /watchlist`, `POST /watchlist/{slug}/approve`, `POST /watchlist/{slug}/decline` | External-monitoring watchlist + signals. Rows carry `origin` (`manual` \\| `executive` \\| `research` \\| `research_proposed`); `approve` turns a research suggestion (`research_proposed`, `dry_run`) into a live watch, `decline` `{reason: not_relevant \\| too_noisy \\| wrong_source}` removes it and records the decline (or, for `too_noisy`, keeps it live at a high floor), both 409 unless the row is a pending suggestion; `DELETE ?reason=` on a research-origin row records the decline too. |\n| `workflows` | `GET /workflows`, `POST /workflows/{name}/runs`, `GET\\|POST\\|PUT\\|DELETE /workflows/custom`, `GET\\|DELETE /workflows/custom/{name}/targets`, `POST /workflows/runs/{run_id}/decision`, `POST /workflows/runs/{run_id}/rerun`, `GET /workflows/tools/search?q=`, `GET /workflows/tools/describe?names=` | Workflow catalog, run management, and user-created (dynamic) workflow CRUD. `rerun` queues a failed scheduled run (a department check-in, a saved workflow on a cadence) once more, due now (see Scheduler); the principal may, and for a saved workflow the person it delivers to; 409 for a run that did not fail, one started from `/jobs` (\"Start this one again from its page\") or one already queued again. Custom definitions come back with a server-managed `owner_person_id` (the creator — the web caller on `POST`, set on insert only; a client-sent value is ignored), who is asked to approve a workflow's first write to a new target. `GET /workflows/custom/{name}/targets` lists the targets its tool steps may write to without asking and `DELETE …/targets?value=` forgets one. `POST /workflows/{name}/runs` is a 403 (\"Only the principal can run this workflow.\"), audited, before any run row exists, when the workflow is one only the principal may start in the workspace's mode (`weekly_review` always, `morning_brief` in solo) and the caller is not the principal. A request with no `x-caller-email` counts as the principal; with no principal on the roster, no signed-in caller does. This governs starting a run only. A run started by hand (this endpoint, or `run_workflow` / research in chat) records its starter as `owner_person_id` and is theirs alone: `GET /workflows/runs` lists the team's (scheduled, no owner) runs plus the caller's own and the ones waiting on them, and `GET` / `DELETE /workflows/runs/{run_id}` and `POST /workflows/runs/{run_id}/decision` are a 404 for anyone else's, the principal included. A signed-in email that is on nobody's People entry cannot start one (403), and a run whose starter can't be read is refused (503); its steps read and draft documents as the starter only. `POST /workflows/runs/{run_id}/decision` with `{decision: \"approve\"|\"reject\"}` answers a run awaiting a yes/no sign-off from the web app — 403 unless the caller is the person it waits on or the principal, 409 if it isn't awaiting or needs a written reply — through the same `apply_resolution` a chat reply uses. Custom create/update also rejects (422) any action-step tool that does not resolve, and so does `POST /workflows/custom/{name}/activate` when turning a workflow **on** — that click is the approval for a tool workflow chat saved switched off (turning off is never checked). Turning on a workflow with action steps requires the body `{is_active: true, definition}` carrying the definition the user reviewed; if the stored one differs (ignoring `is_active` and timestamps) it returns 409, and the switch itself is a compare-and-set on the validated revision (`dynamic_store.activate_if_unchanged`, keyed on `updated_at`), so a save that lands while the tool check awaits the gateway — even from another process — is a 409 too, so only what was shown gets switched on. `GET /workflows/custom` lists inactive definitions too; `GET /workflows/{name}` 404s for them. The two `tools` endpoints return `{tools: [{name, description, read_only, source}]}` for the advanced editor's tool picker and the review card; `read_only` is true only when the name says it reads (a label, not a control). The run stream adds a `progress` event (`step_id`, `summary`) while an action step uses tools. Each catalog entry (`WorkflowMeta`) carries `is_custom`, `background` (true for the system-run built-ins the UI files under “System”) and `quick` (true for a Quick workflow, one per playbook nothing else follows, named `quick_<playbook>`). The run endpoint streams SSE; its `awaiting_human` event carries `delivery` (`self` \\| `sent` \\| `suppressed` \\| `alerted` \\| `failed`) alongside `person_id` / `question` / `awaiting_until`, because the outbound guard or an unreachable approver means the question may never have been asked — a client must not render “waiting on them” for those. A paused run ends the stream with neither `done` nor `error`, so that `awaiting_human` frame carries `terminal: true` to say so explicitly, plus `resumable` — whether the run continues by itself once answered or stops at the gate. `GET /workflows/runs/{run_id}` returns the run row with the resume payload replaced by a small `resume_progress` summary (`gate_step_id`, `completed_step_ids`, or `null`): the payload holds every completed step's full text, and the run-detail page polls this endpoint while a run is unfinished. |\n| `knowledge` | `/knowledge/builtin`, `/external`, `/search` | MBA knowledge base and external sources. `/search` is the introspection parallel of `retriever.retrieve` and mirrors its filters — including the `general` catch-all on the company collection — so the panel cannot report a specialist seeing nothing that it does retrieve in chat. It accepts `general` in `domain_filter` for the same reason. `/search` applies the same review gate as `retrieve()` — withheld (pending or rejected) built-in, external and failure rows are dropped, so the panel never advertises knowledge the Executive cannot use; it degrades to unfiltered rather than failing if review state is unreadable. `POST /knowledge/builtin` refuses a name already held by shipped content, and `POST|DELETE /knowledge/failures` now register and deregister for review — without that a user-authored failure case study had no review row, so no SME decision could block it. |\n| `skills` | `/skills`, `/skills/search`, `/skills/{name}/restore` | Skill registry (the UI's **Playbooks**) CRUD and search. `PUT` on a built-in saves a company customization that shadows it; `DELETE` returns `{name, outcome}` — `deleted`, `reverted` (customization removed, built-in back) or `hidden` (built-in hidden for this company); `restore` un-hides; `GET /skills?include_hidden=true` lists hidden built-ins. List and detail carry `used_by` — `[{name, title, is_custom}]` of the workflows that follow the playbook (switched-off custom ones included) (`WorkflowMeta.playbooks` is the other direction). |\n| `evals` | `/evals/scenarios`, `/evals/runs` | Eval scenarios and run results. `POST /evals/runs` is a 403 when a workflow scenario names a workflow that only the principal may start in the mode it runs in (the weekly review; the morning brief in solo) and the caller is not the principal — the Jobs page's rule for starting a run; stored results are read under the existing `/evals/runs` rules. |\n| `memories` | `/memories/{decisions,initiatives,advice}`, `GET /memories/facts`, `POST /memories/facts/{fact_id}/{retire,approve,decline}`, `GET /memories/facts/approval`, `PUT /memories/facts/approval/{person_id}`, `GET /memories/people`, `GET /memories/people/{person_id}/conclusions` | Episodic-memory record management; the standing facts the Pulse Corrections tab reads (`{facts: [...], can_retire, retirable_ids, can_review}`; each fact carries `recorded_by_role` / `recorded_by_name`; `?include_inactive=` default true, honoured for the principal only; anyone else gets the active rows plus their own `proposed` ones, with the provenance (`session_id`, `turn_id`, `recorded_by_person_id`, `retired_reason`, and `source_quote` except on their own facts) blanked, never retired, replaced or declined text; `?limit=` 1–500) and their retire (the principal any fact, a teammate only one they recorded that the principal has not approved — else 403; the audit row names the teammate; 404 for an unknown or `profile` row, 409 when no longer active; writes a private `fact_retired` audit row); approve / decline a teammate's `proposed` fact (principal only, else 403; 409 when it is not proposed; private `fact_reviewed` row); and the per-teammate \"needs my approval\" switch (on by default; `GET` lists `[{person_id, full_name, needs_approval}]` for every active team member but the principal, `true` for anyone not yet set; `PUT` takes `{needs_approval}`, 404 for anyone else; both principal only; private `fact_approval_changed` row); plus the read-only peer-memory overview the Pulse People tab reads (`{status: ok|disabled|error, people: [...], conclusion_total}`; `?recent=` 1–50, default 5) and one person's full conclusion list, paged newest first (`{status, person_id, items, page, size, total, has_more}`; `?page=` ≥1, `?size=` 1–100, default 50; 404 when the person has no peer). Peer memory is each person's own: the overview holds only the caller's entry (none for a caller off the roster; `conclusion_total` counts only theirs), the principal included, and `/conclusions` for anyone but the caller is a 404. |\n| `review` | `/review/items`, `/review/stats`, `/review/trusted-defaults`, `POST /review/curate`, `POST /review/bulk-approve` | Knowledge review queue and annotations. Shipped knowledge registers as a trusted default (`approved` with a NULL `reviewed_at`), so the queue starts empty; `curate` (`{domain, action: start|stop}`, domain required) opts one domain in or out, and `trusted-defaults` returns domain → unreviewed count. `bulk-approve` takes a non-empty `domain`, `item_ids` (max 500) or `all_pending: true`, and 400s with no selector; it returns `{approved_count, item_ids}`. |\n| `onboarding` | `/onboard/interview/understand`, `/onboard/interview/start`, `/onboard/interview/message`, `/onboard/interview/draft`, `/onboard/interview/{id}`, `/onboard/interview/commit` | Conversational company setup. The `onboarding_interviewer` agent asks clarifying questions, then emits a draft profile + people + departments. **Nothing is persisted until `POST /onboard/interview/commit`** — the interview itself never writes. `start` is multipart (description + optional deck/one-pager uploads). `commit` answers 403 when the draft would make a different person the owner and the caller is not the current owner (setup demotes the old principal, and any signed-in user can open it). It also takes an optional `owner_email` — the principal's sign-in email, which the review screen pre-fills from the signed-in user — checked before anything is written (422 if it is malformed, already another person's, or would replace the principal's existing email — setup only fills in a missing one; 403 if the caller is not the owner and it is not the address they signed in with, since the roster is the sign-in allow-list) and saved on the principal's People row, so the owner's chats resolve to them from the first turn. |\n| `workflow_designer` | `POST /workflows/designer/start`, `POST /workflows/designer/edit`, `POST /workflows/designer/message`, `POST /workflows/designer/draft`, `GET /workflows/designer/{session_id}` | The conversational New workflow wizard, and editing a saved workflow by conversation. `/edit` (`{name}`) opens a session on a saved custom workflow with no model call: the stored definition is the starting draft, and every response then carries `editing` (its name) and `original` (the stored definition as the session opened on it); drafts keep that name and its on/off state whatever the model writes (404 for an unknown workflow). The UI saves one with `POST /workflows/custom/{name}/save-edit` (`{session_id, definition}`): the server saves the session's own draft, never a client-sent body, and only when it equals the `definition` the user reviewed (a later message is a 409, so the click saves only what was shown); it re-validates it, keeps the stored on/off state, and writes only if the stored workflow is still the version the conversation opened on — otherwise 409, as it is for a session about another workflow or one with nothing drafted yet. It sits under `/workflows/custom` so anything that limits writes to custom workflows covers it too. The `workflow_designer` agent asks clarifying questions (`phase: \"question\"`, with `hint` and up to four suggested `options`), then returns `phase: \"draft\"` with `draft.definition` (exactly the body `POST /workflows/custom` takes), `summary`, and `assumptions`; every response carries the `transcript`. **Nothing is persisted here** — sessions are in memory, and the UI saves through `POST /workflows/custom`. Errors are fixed strings (422 over the 8,000-char message cap or the transcript cap, 404 for an expired session, 409 while another turn on the same session is still running, 502/504 for model failure or timeout). Mounted ahead of the `workflows` router. |\n| `python_jobs` | `GET /python-jobs/{job_id}/{name}` | A result file a Python job (`run_python_job`) wrote, the principal's alone (403 otherwise), served as a download (`Content-Disposition: attachment`, `Content-Security-Policy: sandbox`, `nosniff`, `Cache-Control: no-store`); 404 for a bad id or name or a file past its 7 days. |\n| `saved_tools` | `GET /saved-tools`, `GET\\|PUT /saved-tools/{name}`, `POST /saved-tools/{name}/rollback` | The scripts the Executive saved as tools (Settings → Advanced → Saved tools), the owner's alone (403 otherwise). The list gives each tool's name, description, on/off, current version, `kind` (`script` or `python`, a kept Python job) and the tools it calls, plus whether `SAVED_TOOLS_ENABLED` is on; the detail adds the script, every version and the last 20 runs. `PUT {enabled?, workflows?, version?}` turns one on or off (off also turns it off for workflows, so turning it back on never re-arms unattended runs), and turns the named `version` — the one the owner looked at, never whatever is current by then — on for workflows (or workflows off); a Python tool never turns on for workflows (409) — turning workflows on lets more run unattended, so it needs a request tied to the owner (signed sign-ins or local login, as Take the lead's switches do; 409 otherwise); `rollback {version}` makes that version the one that runs. Both are audited as `saved_tool_changed`. The Executive saves tools itself through `run_script`; there is no create route. |\n| `onboarding` (fallback) | `/onboard/start`, `/onboard/answer`, `/onboard/status/{id}` | The original 12-step form wizard, kept as a fallback (UI at `/onboard?mode=form`) and used by the `openexecutive onboard` CLI. Its final answer saves the profile and adds people with their emails and a principal, so once there is an owner only they can send it (403, and the session rolls back so the owner can still finish it). `/onboard/start` reads the workspace mode once for the session: solo skips the Team Size, Team Members and Fractional Executives steps. Each status response's `current_step` / `total_steps` count only the steps that session asks, and `optional` says whether the current step can be skipped. |\n| `company-profile` | `GET\\|PATCH /company-profile` | Structured company profile. |\n| `alerts` (private cards) | `POST /alerts/{id}/ack`, `/reopen`, `/alerts/bulk-ack` | An alert tagged `private:principal` (see Today) is a 404 on ack and reopen for anyone but the principal, and their bulk sweep skips it. A roster-request card (source `roster_request`) is a 409 on `ack` even for the principal — it is answered at `/people/requests/{id}`, since acking would leave the sender waiting with nothing to show it — and, as an exempt source, `bulk-ack` and `reopen` skip it. |\n| `auth` | `GET /auth/allowed-emails` | Non-archived **team members** with an email, offered to the UI's sign-in gate — a contact is never on it, so adding a client to reach them by email no longer lets them sign in. The gate takes the **union** of this roster and its own `ALLOWED_EMAILS` env list, so env entries always work (and are checked first, short-circuiting the fetch) and roster entries are additive — a roster change can never revoke a configured operator. With local login (`make dev` with Google sign-in not set up — the UI then listens on 127.0.0.1 only) the UI signs in without an email, sends no `x-caller-email`, and the backend resolves the caller to the principal, as it does for the CLI. |\n| `fixtures` | `/fixtures`, `/fixtures/{name}/load` | Demo-company fixture load/reset/snapshot. `POST /fixtures/reset` leaves no departments, like a new install (`departments_seeded` is always 0). |\n| `clients` | `/clients`, `/clients/generate`, `/clients/cockpit`, `/clients/save`, `/clients/{slug}/activate` | Client-company slots — multi-client mode for fractional use; create from current/blank/AI-generated intake draft (pasted notes and/or file attachments, multipart on `/clients/generate`), save-back switching, engagement metadata (PATCH), cross-client cockpit, delete. See the Client Companies section. |\n| webhooks | `POST /webhook/telegram`, `POST /webhook/google-chat`, `POST /webhook/slack` | Inbound integration callbacks (self-verified). `/webhook/slack` answers 503 unless `SLACK_SIGNING_SECRET` is set. |\n| MCP server | `POST\\|GET /mcp` | Open Executive exposed as an MCP server (Streamable-HTTP). Not a router — a mounted FastMCP sub-app. Same shared-secret gate (`x-api-key`); exposes company context as resources and the specialist council as tools. See the MCP Server section. |\n\n**What it may do** (`api/routes/may_do.py`): `GET /what-it-may-do` is read-only. It returns `{paused, sections}`, three sections in order (`as_you`, `executive`, `departments`), each `{key, title, available, unavailable, notes, rows, footer, goes}`, and each row `{id, what, outcome, then, why, setting, items}`: `outcome` is `goes`, `waits`, `always_waits`, `drafts` or `off`, and `setting` names where to change it (`act_as_me`, `handle_it`, `take_the_lead`, `pause`, `department:<slug>`, or empty). `as_you` is the caller's own (`available` false, with why, when they can't have Act as me); `executive` is the principal's alone (`available` false for anyone else); `departments` is everyone's. Any team member on People may call it; a contact, someone not on People, or a request with no caller outside local login gets 403. See Delegation → What it may do.\n\n**How far it goes as you** (`api/routes/delegation.py`): `PUT /delegation/reach` takes `{step}`, one of `off`, `when_asked`, `inbox`, `careful`, `balanced`, `bold`, `everything`, and answers the caller's delegation state as `GET /delegation` does. Going down turns the switches above the step off, highest first; going up runs each switch's own route in order (`PUT /delegation`, `PUT /delegation/inbox`, `PUT /delegation/handle-it`, `PUT /delegation/take-the-lead`), so the first refusal (409 `gmail_not_connected`, a signed sign-in missing, `in_training`, 403 for Everything when not the owner) stops it at a whole step. See Delegation → How far it goes as you.\n\n**Take the lead** (`api/routes/take_the_lead.py`): `GET /take-the-lead` returns the As the Executive switch, its six Ask first switches (`{kind, label, hint, on}`, the hint a plain line on what each one catches), the company's rules, whether this server can tie a change to the owner (`available`), and whether the Executive is paused. `PUT /take-the-lead` takes `{enabled?, ask_first?}`, and `POST /take-the-lead/rules` / `DELETE /take-the-lead/rules/{id}` add or remove a company rule (`{kind: person|domain|words|amount, value}`, 422 on a bad one). All four are the principal's alone (403). Anything that lets more happen on its own (turning it on, turning an Ask first off, removing a rule) needs a caller the API can tie to them (`delegation.verified.caller_refusal`, else 409). `GET /today/activity` adds `took_the_lead` rows (what Take the lead did, named, not quoted) and, for the caller alone, `sent_as_you` rows for what Handle it for me sent as them. Under `/delegation`: `PUT /delegation/take-the-lead {enabled}` is Take the lead as you (the owner's only for now; turning it on turns Handle it for me on), and `GET|POST /delegation/take-the-lead/rules` and `DELETE …/rules/{id}` manage the caller's own rules. `HandleItOut` gains `lead` and `lead_available`. A `take_the_lead_action` decision is approved or rejected through the existing `/decisions/{id}/approve|reject`. Training: the response also carries `training` (In training: everything waits unless allowed), `learned` (`{id, label, feature, example, uses, created_at}`: what it was allowed, the edit kept as an example by field) and `suggested` (`{key, label, approvals}`); `PUT` takes `training?` too, and leaving training while on needs the same provable owner as turning it on. `POST /take-the-lead/learned {key}` allows a current suggestion (404 for anything else; provable owner), `DELETE /take-the-lead/learned/{id}` makes it ask first again. `learned` also lists the owner's own Act as me senders (`feature` `act_as_me`), never anyone else's, and Remove works on those too. On a `take_the_lead_action` card, `POST /decisions/{id}/approve` takes `edits.input` (the card's editable fields, 422 for any other; the principal's alone, 403 for an area approver) and `edits.allow: true` (a training card only, 422 otherwise; the principal from a provable request, 403 otherwise), finishing `approved_with_edit` when a field changed.",
"mermaid": null,
"generated_at": "2026-10-14T14:31:35Z"
}
diff --git a/packages/core/openexecutive/architecture/prebuilt/delegation.json b/packages/core/openexecutive/architecture/prebuilt/delegation.json
index 76e8ba96..da71814f 100644
--- a/packages/core/openexecutive/architecture/prebuilt/delegation.json
+++ b/packages/core/openexecutive/architecture/prebuilt/delegation.json
@@ -1,7 +1,7 @@
{
"section_id": "delegation",
"title": "Act as Me (Delegation)",
- "markdown": "The **delegation** module (`openexecutive.delegation`) is **Act as me**: the one place the Executive writes *as* a person instead of as itself. Everywhere else it has its own Google account and bots and signs as itself. Here — when the person asks, or, with a second switch, for mail in their inbox that needs them — it writes an email in their voice and saves it as a **draft in their own mailbox** — Gmail or Outlook — for them to review and send. The one thing it ever sends is one of those inbox drafts, exactly as it is in their mailbox: when the person taps **Send** on its card, or, with a third switch, **Handle it for me**, on its own when plain-code rules allow it (below); chat never sends. The principal can turn it on for themselves, and so can each team member once the owner lets them. It is off by default, and off changes nothing: the prompts, tool lists and prompt caches are byte-identical to an install without it.\n\n## Who can have it, and when it is offered\n\n`delegation.settings.can_delegate(person)` is the single rule for who may turn it on: the principal (a non-archived team member flagged `is_principal`), and any other non-archived team member — never a contact — once team members may have it (`team_members_enabled`). That takes two things: the install allows it (`DELEGATION_TEAM_MEMBERS`, default off, which offers the owner the switch) and the owner turned on **Let team members use it** (`PUT /delegation/team`, principal only, one row in `delegation_team`). Turning the owner's switch off takes it away from every team member from their next message, and their inbox watchers stop at their next check; their own switches, drafts and cards are kept. Everything is keyed by `person_id`. A person turns it on for themselves (`PUT /delegation`); nobody turns it on for anyone else. The setting is one row per person in `delegation_settings`, and a missing, unreadable or zero row all mean off.\n\nAt the start of every chat turn (`Executive.stream_chat` and the committee path) `pin_turn_delegation(session, speaker_text)` runs next to the workspace-mode pin and records a `TurnDelegation` on the session. `ghostwrite_email` is **offered** only when all of these hold:\n\n- the speaker may have it and turned it on — read fresh every turn, so turning it off applies from the next message;\n- the speaker is on a surface that verified it is them — the principal through `people_tools.is_principal_on_verified_surface`, a team member through `teammate_on_verified_surface` (the web app signed in, their own Slack or Discord, never an email turn) — and a web turn also carried a signed-in caller (`Session.web_caller_signed_in`, set from `x-caller-email`) or runs under local login — a request with no caller header is not a sign-in and never gets it (whoever holds the shared secret is trusted as the UI proxy that stamps that header, as on every principal-only route);\n- the conversation is private to the speaker: the web chat, a Slack or Discord DM, or a verified private Telegram chat — never a shared channel or thread, where the draft's preview or the matching threads would be posted for everyone and other people's messages sit in the model's context;\n- the turn is neither unattended (the scheduler's proactive run) nor private to the principal (the email poller's turns), so inbound text can never reach it. The MCP server, workflows, reflection and research never carry it at all.\n\nThe mailbox connection is deliberately **not** part of the offer: the handler checks it on every call and says how to fix it, so the cached tool prefix never flips when a token lapses. The pin lives in a context variable for the turn's task as well as on the session, so two turns running at once on one session (a second browser tab) each read their own. It also carries the speaker's own words for the turn (a new email may go to an address they just typed — the turn's message joins the history only once the turn ends), a per-turn draft count, and `touched_mail` (see Privacy). `own_words` reads those words back for every own-words check (addresses here, facts and task assignments elsewhere): it first removes the hydrated `<outbound_reply_context>` backstory by its exact, anchored shape, so a look-alike closing tag quoted inside it cannot pass the rest off as the speaker's, then drops other adapter tag blocks, and returns nothing for a message carrying an attachment.\n\n## The tool: `ghostwrite_email`\n\nIt lives in its own registry (`orchestrator.delegation_tools.DELEGATION_TOOLS` / `DELEGATION_TOOL_HANDLERS`), **never** `_ALL_SKILL_TOOLS`, so no other toolkit can carry it. On a turn it is offered to, the agent loop adds it to the pool *before* the sort and builds that turn's handler map from both registries; on any other turn a call to it is an unknown tool. The handler re-checks the pin and the surface anyway, then:\n\n1. **Caps** — at most 5 drafts per turn, and `DELEGATION_MAX_DRAFTS_PER_DAY` (default 50, at most 1000) per person per UTC day, shared with the inbox watcher (`delegation.caps`). It is counted from `delegation_drafts`, one row of ids per draft saved from either place, with a count kept in the process as a floor in case a row was lost. Each slot is taken before the first await — a round's tool calls run concurrently, so otherwise every call in it would pass the caps before any counted — and handed back if nothing was drafted. If the rows can't be read it refuses rather than guess.\n2. **Marks the turn** — sets `TurnDelegation.touched_mail` *before* its first read of the mailbox.\n3. **Checks the mailbox** — `gmail_status` asks Google or Microsoft whose mailbox the credential opens and compares it with the person's People email, on every call: a roster email can change, and a client slot swaps the roster.\n4. **Finds the thread** — by `thread_id` (checked against the mailbox's own id shape), or a Gmail-style search (`find`; on Outlook, words, `from:`, `to:`, `cc:`, `subject:` and `newer_than:` are kept and other Gmail operators dropped). Several matches return `{status: \"choose\", candidates}` (subject, sender and date — no message text) and draft nothing; none returns `not_found`.\n5. **Sets the recipients in code**, never from the model. A reply goes to the last inbound message's `From` — never its `Reply-To` (a different one is flagged `reply_to_ignored`) — with the thread's other recipients only on `reply_all`. A new email or a forward may go to any well-formed address: it is only a draft, waiting in their own mailbox, where they see who it is to before they send it. An address that is neither on the roster (contacts only when `contacts_reachable_now()`) nor typed by the speaker this turn comes back in `not_in_people`, and the Executive names it for them to check (`delegation_tools.not_in_people`). Mailing-list mail, a thread they replied to last and a reply-all trimmed to 10 recipients are flagged. An address inside a block an adapter added to their message (the backstory hydrated into a DM) is not one they typed, and when the message carries an attachment — a document's inlined text, or a note naming the file — none of its addresses count as typed: neither has an end mark, and a filename is chosen by whoever sent the file, so such an address is named back to check.\n6. **Writes it** (the ghostwriter, below) and saves it with the mailbox client's `create_draft` (Gmail: threaded with `In-Reply-To`, `References` (whole message ids: when the chain is too long for one header the oldest after the thread's first go, never the parent) and `threadId`, and stamped `X-OE-Ghostwritten`; Outlook: Graph's `createReply` on the message it answers, then the text and recipients, and a named property marking it).\n\nThe result is `{status: \"drafted\", draft_id, gmail_link, to, cc, subject, preview, flags, open_questions, note}`, plus `not_in_people` and `check_address` when a recipient needs checking. The link (`gmail.mailbox_link`) is built server-side from a fixed prefix — the thread in Gmail, the draft itself in Outlook on the web — and the note tells the model the preview is the person's draft, to be treated as data. The chat shows an action chip — \"Drafted an email as you to … — in your Drafts\" — that opens it, and only a link under `MAILBOX_LINK_PREFIXES` is ever linked. A sincere \"are you an AI?\" in the thread comes back as an open question for the person to answer themselves.\n\n## Reading their mailbox\n\nFive read-only 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## 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, `intent` becoming the short note above it (the ghostwriter writes only the note; the forwarded email's subject, someone else's words, is never put in the intent). Recipients follow the new-email rule (`_new_recipients`: the roster, or addresses the speaker typed this turn). Gmail's draft quotes a forward header and the original's own words under the note and attaches the original's files, up to 10 and 20 MB (`FORWARD_MAX_FILES`, `FORWARD_MAX_BYTES`; any left off are flagged `attachments_left_off`); Outlook uses Graph's `createForward`, which keeps the original and its files, with the note as its comment and the body never patched. It is still only a draft.\n\n`remind_me(text, when)` (`orchestrator.reminder_tools`) rides with the same tools and checks, but opens no mailbox, so it never marks or locks a turn (`MAILBOX_TOOL_NAMES` are the ones that do). It stores the text once cleaned — one line, anything a chat app could turn into a link (a URL of any scheme, an address, a domain-like word, a host and port, an IP address) replaced with \"[link]\", at most 300 characters — with its time (stored in UTC) in `delegation_reminders` (5 a turn, 25 waiting, a year ahead, refused when the person has no channel). When it is due the scheduler sends that text to the person alone, as \"Reminder you set on <date>: …\", running nothing (see Scheduler); the Slack and Discord DMs it may go by turn link previews off. The chat chip shows the text as it will be sent. A reminder that comes due in the person's quiet hours or leave (when `OUTBOUND_RESPECT_QUIET_HOURS` is on) waits unclaimed and goes once they end, rather than being suppressed and lost. It is allowed after mail is read and in later turns of that conversation: it reaches only the speaker, as plain text. `schedule_followup`, which runs a turn with tools and is listed to everyone, stays refused there.\n\n## Approval cards\n\nA turn that read someone's mail may not message anyone, invite anyone or change the roster (see the lockdown above), yet what the mail asks for is often right. `propose_actions` (`orchestrator.action_card_tools`) leaves the speaker a card instead: up to five actions, each spelled out exactly as it will happen, done only when they tap Approve. It rides with the other Act as me tools and checks (`_writer`), opens no mailbox, and is allowed after mail is read because it does nothing on the turn.\n\n- **Kinds.** `invite` (a meeting with people on the roster), `message` (a direct message to someone on the roster, as written) and `add_contact` (a new contact; the principal's cards only, since contacts are theirs). A team member's card can't name a contact. Each action is checked when the card is made (`delegation.action_cards.check`) and again when it is carried out, so an archived person or a time that has passed fails that action alone.\n- **Whose.** A card is a `delegation_actions` decision for the speaker, `approver_only` like a reply card: only they see it (`GET /delegation/actions`) or resolve it, a team member's answers 404 to the principal too, and it is never an alert. The same actions still waiting are that card, not a new one. 3 cards a turn, 25 waiting, dropped after 7 days.\n- **Approve.** In the chat, under the reply that left it (the `propose_actions` chip carries the card's `decision_id`, and `ChatActionCards` shows the card while it waits), and on the Briefing's Needs you list, with a box per action. Approve (`POST /decisions/{id}/approve`, `edits.only`) needs the card's person signed in (`verified.caller_refusal`) with Act as me on; the card is claimed first so it runs once, then each ticked action runs as stored with no model call, in an unattended session (the principal's with contact egress) under `rows_for_person`, so every audit row it writes is theirs and nothing reaches the team's activity rail: `message_person` (a direct message or nothing; never its Briefing-alert fallback, which more people read), `create_calendar_event`, or a contact row. Approving also needs the person still allowed Act as me (`can_delegate`) and switched on. An invite is booked straight away when the person approving is the one the meeting gate would ask (`calendar_tools.approved_by`), and otherwise goes to that approver as usual, so a card never widens anyone's authority. Per-action results (`done`, `waiting`, `failed`, `skipped`) are kept on the decision and shown on the card. Dismiss rejects it and does nothing else. With Suggested actions in training the card adds Approve + allow, and a card of actions all allowed is carried out on its own (see In training above).\n- **Channels.** A card can come from any surface Act as me runs on; it is approved in the web app, since the chat apps have no buttons here.\n\n## The ghostwriter\n\n`delegation.ghostwriter.compose` writes the text. The Executive decides *what* to say (`intent`); this call decides *how* the person would say it, and it is deliberately small:\n\n- a constant `GHOSTWRITER_PROMPT` plus the person's voice block as the system prompt;\n- the thread (each message cut to its sender's own words, every line scrubbed, all labelled alike), then the writer's own earlier words in it (`<writer_said>`, from their sent mail only), the intent and the recipients' names in the user turn — no company profile, memory or roster;\n- with Always in the loop on, `<writer_noted>`: what the writer's own notes say they told these same people in earlier Act as me replies (`memory.history_drafts.notes_for_draft`: only notes from mail **every** recipient of the new draft was on, so nothing told to one person reaches another; chat notes name no recipient and never qualify; at most 8, newest first, the person's own words or their correction, with dates). The prompt's rule 6 makes it a consistency check, never content: a draft that contradicts it is still written as the intent says, and the conflict becomes an open question on the card, which only the writer sees. Both the chat tool and the inbox watcher pass it;\n- **no tools** but the forced `compose_reply` return, so text in the thread can ask for anything and there is nothing to do it with.\n\nIt is not a Council agent — the Council's edit routes have no principal check — and runs on `DELEGATION_COMPOSER_MODEL` (default: the default model), logged as `ghostwriter` usage. `lint` then runs in code on what comes back: a link or an email address survives only if it appears in the intent, the signature or the recipients, so a link planted in the thread is removed and flagged; the Executive's own name is flagged; and the body is capped, cut at a paragraph, line or word break in its last fifth. A draft with nothing left after that is refused. The signature from the person's Gmail settings (or the one already stored, for Outlook) is appended.\n\n## How I write\n\n`delegation.voice` learns how a person writes *their own* email (`attunement.style` learns how the Executive should write *to* someone). `POST /delegation/voice/learn` reads up to 40 recent sent messages, keeps only what they wrote (quoted replies stripped with the email poller's `sender_new_text`), skips automatic mail, every thread chat drafted into, and every sent message that began as a draft written for them (`delegation_drafts.sent_message_id`), and makes one forced-tool call (`record_voice_profile`). Code validates every field before it is stored:\n\n- greetings per audience (their team, their contacts, anyone else), a sign-off of at most two lines, and a usual length and tone (a backslash-n the model wrote instead of a line break is read as one, keeping the first lines that fit, which also repairs a profile stored before that rule);\n- up to 8 habits and 6 things to avoid, through the same deny-list as working-style rules — no actions, links, handles, amounts, tool names or names of people;\n- up to 3 short exemplars, each checked to be verbatim from a sample, with addresses and phone numbers masked — and none while a client slot is active, so one client's mail never lands in another's state.\n\nThe signature comes from Gmail's `sendAs` settings, not the model (Outlook gives apps no way to read one, so a learn keeps the stored signature and `POST /delegation/voice/signature` answers 409 `signature_unavailable` rather than clearing it), as plain text with its lines kept (`gmail.html_to_text`: a `<br>` always ends a line, and a block tag, opening or closing, ends one when it has text, so Gmail's layout of a first line followed by one `<div>` per line comes out line by line). `POST /delegation/voice/signature` reads it again without relearning: nothing else changes and a locked profile stays locked, so it picks up a changed Gmail signature and undoes **Don't add my signature**. A person can also describe their style in their own words: `POST /delegation/voice/describe` applies the description to the profile they have through the same forced tool (a separate system prompt, no exemplars) and the same validation, keeps their signature and writing examples, and returns the result with a short sample reply for them to review. It saves nothing and needs no mailbox; Save stores it as an ordinary edit. The person can edit the profile, lock it (a locked profile is never relearned) and reset it, and every change is kept in `delegation_voice_history`. One learn runs at a time per person, and a lock or an edit made while it runs wins: the learned profile is dropped (`changed`).\n\n## Draft replies to my inbox\n\nA second switch under Act as me, **Draft replies to my inbox** (`delegation.inbox`), has the Executive watch the person's own inbox and write a first reply to mail that needs them. The reply waits on a private card on Today; nothing is sent until they tap **Send** (below). Where the reply lives is the person's choice, **Also save replies in my Gmail Drafts** (`mailbox_drafts`, off by default): off, it lives on the card alone (`delegation.card_drafts`: the card keeps the draft's recipients, subject and thread headers as `draft_spec`, and Send makes the mailbox draft from exactly that just before the send-time checks, taking it back out if they refuse), so their Drafts folder doesn't fill with replies they may never send; on, it is also saved in their Drafts as before. The switch is one row per person in `delegation_inbox_watch`. Turning it on needs Act as me on and their mailbox connected, and sets `watch_since` to now every time, so it never drafts for mail that arrived before; turning Act as me off turns it off too. Off means no mailbox call and no row written, with one exception: a send the person started that the mailbox never confirmed is still followed through until it is settled.\n\n### When it looks\n\nA throttled hook in the scheduler tick (`_maybe_scan_inbox`, after the pause, company-profile and rotation gates) checks each person whose switch is on every `DELEGATION_INBOX_POLL_MINUTES` (default 5). It is not a scheduled action, because those are listed on `/scheduled` for everyone and anyone may cancel them. One scan task runs at a time, one scan per person, and none while a client slot is active. **Check now** on the Settings card runs the same scan. Every row a scan writes is private and the person's own (`audit.rows_for_person`: a team member's rows are hidden from the principal too, see Privacy), and the process log carries counts and codes, never an address or a line of mail. The scan never marks mail read or changes a label.\n\n### What it drafts for\n\nA scan first settles the open cards (below), and stops with `backlog_full` once 25 are waiting, counting the ones it makes. It then lists the inbox since `watch_since` (`inbox_message_ids`) — not chats, not mail from the person, and not the promotions, social, updates or forums tabs (on Outlook: the Focused inbox only) — up to 100 messages, and takes the newest message of each thread that still needs a look, at most 10: settled threads and threads with an open card are passed over first, so a burst of mail, or a pause for a limit or a back-off, never hides older threads for good. `delegation_inbox_messages` is its durable cursor: one row per message (`UNIQUE(person_id, message_id)`) with what happened to it, the reason, how many tries it took, and the draft and card ids. It stores a hash of the sender's address, never the address. A message is skipped, with the reason recorded, when:\n\n- it came before `watch_since`, or more than three days ago;\n- it is from the person or one of their send-as addresses, from the Executive, or one of this module's own drafts;\n- it is automatic — `Auto-Submitted`, a bulk or auto-reply `Precedence`, a bounce, a calendar invite or a no-reply sender — or from a mailing list, or in a Gmail tab, spam or trash;\n- the person is not in To or Cc, or it has more than 10 recipients;\n- the person replied last, or a draft already sits in the thread.\n\nThree kinds are left unrecorded, so a later scan looks again: mail under 10 minutes old (mail the person answers straight away never gets a card), mail in a thread whose card is still open, and mail a daily limit holds back.\n\n### Deciding, then writing\n\nTwo model calls, and code decides between them. The classifier (`delegation.inbox_classifier`) is one forced-tool call, `classify_email`, returning whether the email needs a personal reply, what kind it is and how sure it is. It sees a few one-lined header lines and the sender's own new words (at most 3000 characters, every line scrubbed) inside one `<email>` block marked as data, and it has no other tools, context or memory, so an email can ask for anything and there is nothing to do it with. A reply is drafted only for a question, a request, scheduling, an introduction or a follow-up, and only when the confidence clears a bar that rises the less the sender is known: 0.6 for their team or a contact (the principal's contacts count only for the principal: a team member's mail is weighed by the team and their own sent mail), 0.7 for someone they have written to before (`has_written_to`, a search of their sent mail), 0.85 for a stranger. Pitches, notes of thanks, FYIs, notifications, newsletters and phishing get nothing, and so does any failure. An email that also went to other people is drafted for only when the person is in To and it asks them themselves: the classifier is told their name, whether they are in To or Cc and how many others it went to, and lists the names the email greets or asks by name (`asked_names`). Code matches those against the person's name, whole name parts only (\"Alexis\" never counts for \"Alex\", and a nickname misses, which means no draft), so mail that greets someone else (\"Good morning, Brennan, could you sign ...\") is never theirs, whatever the model makes of it as a whole. When it names nobody, the model's `asked_of_them` decides, false for a question to the group at large. One that only copies them is never drafted for. Either is recorded `not_needed` with the reason `asks_someone_else`. It runs on `DELEGATION_CLASSIFIER_MODEL`, else the routing model. A sender whose address Gmail couldn't authenticate is handled as a stranger whatever the roster says — anyone can put a colleague's or a client's address in From — so they get the stranger's bar, a holding reply and the stranger limits; the card still says who they claim to be, and that the address isn't verified.\n\nThe reply is written by the same ghostwriter, in the person's voice, but from a fixed intent the module builds rather than words the person typed. Because the intent lets it restate the person's own earlier words, which words are theirs is never written inside the thread, where a sender could imitate any marker with a look-alike: every message there is labelled alike, and the person's own words come in a separate `<writer_said>` block after the thread, taken only from mail their own mailbox sent. Nothing inside the thread can close the thread block or open another. The intent: acknowledge the sender; say again only what the person's *own* earlier messages in the thread already said; commit to nothing new — no yes or no, date, time, price, fact or promise — and say they will get back to them; and put every question it could not answer from their words in **open questions**. A stranger always gets a short holding reply. The lint still strips any link or address that isn't the person's own. The reply goes to the sender (never `Reply-To`) and, on a group email, to everyone else it went to as Cc (reply to all, never the person's own addresses or the Executive); a stranger's holding reply goes to the sender alone. The card says when others were on the email, and its `draft_to` lists everyone, which Send checks.\n\nThe order: record the message, classify, reserve a slot in the shared daily limit, write, save the draft in Gmail (from the alias the mail went to, when it went to one) and store its id, then create the card (idempotent on the message) and mark it drafted. Nothing that fails along the way loses the message. A failure that may pass — the classifier or the writer failing, Gmail refusing the draft, a card that couldn't be made (its draft is deleted first, so no draft is left without a card), any other error with that one message — leaves it for a later scan (`retry`), and it is given up on only after three tries; one message's trouble never holds up the rest. A daily limit reached while it was being read leaves it for later without counting as a try.\n\n### The reply cards\n\nA card is a `delegation_reply` decision whose class is **its approver's alone** (`DecisionClassSpec.approver_only`): only the person it was drafted for sees or resolves it on any decisions route — a team member's card answers 404 to the principal too — and it is never an alert: alerts feed chat turns, which would put other people's mail into memory. It carries the sender with who they are to the person and whether Gmail could verify the address (SPF/DKIM/DMARC, through `fact_confirmation.headers_authenticated`), the subject, what they wrote, the draft, the open questions and its warnings. `GET /delegation/replies` lists the open ones from the database alone, so Today never waits on Google.\n\n- **Send** approves the card, which sends its draft exactly as it is in their mailbox (see *Send on your tap*). **Edit** changes the reply's words right on the card (`PUT /delegation/replies/{id}/text`, `card_drafts.edit`): only its own person, from a caller the API can tie to them (as for Send), never while it is being sent on its own; a reply in their Drafts is rewritten there too (`update_draft_text`, every header kept), and only while it is still the version the card last saw, so a change made in the mailbox is never overwritten. A card edit counts as edited (`approved_with_edit`, and **Do it like this next time** keeps it). **Open in Gmail** (or **Open in Outlook**), shown only when the reply is in their Drafts, opens it there.\n- **Dismiss** rejects the card; the class's after-reject step then deletes the draft if nobody edited it — its message id is still the one it was saved with, since Gmail gives an edited draft a new one, and the Outlook client makes a draft's message id `<id>.<changeKey>` so an edit there changes it too — and keeps it otherwise. What happened is recorded even when Gmail fails.\n- Each scan first **settles** what Gmail already settled: a draft sent from Gmail, a draft deleted there, a reply the person wrote themselves, a thread that is gone, or a card left for 7 days (its draft stays in Gmail). Each is a compare-and-set close with the reason. A newer message from someone else flags the card instead. A card being sent at that moment is left alone.\n\n### Send on your tap\n\n`delegation.reply_send` is the only thing in Act as me that sends, and all it can send is the draft on a card, by its id: `DelegateGmail.send_draft` posts `{\"id\": …}` to Gmail's `drafts.send`, and `DelegateOutlook.send_draft` posts an empty body to that draft's Graph `send`, and nothing else, so no text, recipient or header is ever passed. It has two doors: `send_approved_reply`, reached only from `POST /decisions/{id}/approve` — a class only the card's own person may resolve — and `send_on_its_own`, reached only from the inbox watcher under Handle it for me (below). AST tests pin both call sites, so no model, chat turn, workflow, scheduled job or MCP call can. A tap is checked like this: At send time it checks everything again:\n\n1. **Who is asking.** The caller is the card's person and the API knows it: signed callers are on and the request carries that person's signed assertion (or the operator's, under local login), or the API runs for local login and answers this computer only. Anything else is a 409 `caller_signing_required` — with only the shared secret, whoever holds it could send as the owner — so on a server Send needs signed sign-ins.\n2. **The switches.** Act as me and Draft replies to my inbox are on, and no client slot is active.\n3. **The mailbox.** Their mailbox is connected.\n4. **The draft.** It still exists, in the same thread, and they haven't replied there themselves since; otherwise the card closes.\n5. **Who it goes to.** To, Cc and Bcc hold between 1 and 10 addresses, never the Executive's own, and it is from one of their own addresses.\n6. **What changed.** Recipients that differ from the card's, or a newer message from someone else, need a second yes: the first tap gets a 409 `confirm` naming the recipients and the reason, and the person approves again with what they were shown.\n\nThen it claims the card (`claim_for_execution`, proposed → executing, a compare-and-set, so a double tap sends once) and reads the draft once more: `drafts.send` sends whatever the draft is when Gmail gets the request, so if it was edited since the checks read it — in another tab, by a delegate — nothing is sent and the card comes back (`draft_changed`). Then it sends, and records the result: `approved_with_edit` when the draft was edited in Gmail, the sent message's id, the draft row's `sent_message_id`, and a private `delegation_reply_sent` row. A refusal that proves nothing went — a 4xx, a lapsed sign-in, a rate limit, a draft already gone — hands the card back. A failure that leaves it unclear — a timeout, a 5xx — leaves it `executing` and says to check the Sent folder, and the next scans ask Gmail: their message in the thread means it was sent; anything else is judged on the second scan that sees it: the draft still there and nothing sent means it was not (Gmail deletes a draft it sends), and the card comes back, flagged; the draft gone and nothing sent means it was deleted. Nothing is ever retried on its own. Sending is the person's own act, so it works while the Executive is paused.\n\n### Limits and failures\n\nAt most 5 drafts a scan; `DELEGATION_INBOX_MAX_DRAFTS_PER_DAY` (default 20) a day, inside the shared `DELEGATION_MAX_DRAFTS_PER_DAY` it shares with chat; 200 classifications, 2 drafts per sender (1 for a stranger) and 10 for strangers in all per day; and never more than 25 open cards. A lapsed Gmail sign-in sets the status and is looked at again every 30 minutes; a rate limit, an error reaching Gmail or a crash backs off from 5 minutes, doubling up to 2 hours. Neither turns the switch off: the Settings card shows the status in plain words.\n\n## Handle it for me\n\nA third switch under Act as me, **Handle it for me** (`delegation.handle_it`), lets the inbox watcher send some of its replies itself instead of leaving them on a card. It is one row per person in `delegation_handle_it` (`enabled`, `mode`); no row means off. One setting says how much goes without them, the way quality does on the Agent Council (`handle_it.RULES`): **Easy ones** (`careful`) sends only replies to people they know (someone on their team, a contact or someone they have written to) of at most 400 characters when the classifier is at least 0.9 sure; **People I know** (`balanced`), where it starts, sends replies to people they know up to 1200 characters at 0.8; **Most mail** (`bold`) also answers strangers, up to 2000 characters, and lets a link or an amount through when the classifier is at least 0.9 sure. Everything else waits on a card as before, so turning it on never drafts less. A table from before the setting gets the `mode` column on its next open (`schema._add_handle_it_mode`): someone who had strangers set to send keeps that as Bold, everyone else gets Balanced. Only the person turns it on (`PUT /delegation/handle-it`), from a session the API knows is theirs: the same rule Send uses (`delegation.verified.caller_refusal`), so with only the shared secret it answers 409 `caller_signing_required`. Turning it on needs Act as me and Draft replies to my inbox on, and turning the inbox watcher off (or Act as me, which turns it off) turns it off too.\n\n**In training** (`delegation.training`). Like someone new, each Act as me job can be put in training on its own, from that job's card on the Act as me page, the way Take the lead has it: **Write drafts as me** and **Handle it for me** each pick Off / In training / On (Handle it's In training is Replies in training, with a *Train follow-ups too* box for Follow-ups), and **Suggested actions** picks Always ask / In training; one *What it's learned* list sits at the bottom, each item named by its job (`PUT /delegation/training`, one row per person and setting in `delegation_training`, absent means not in training). In training it asks first and learns who and how from what the person approves; what it learns is a `take_the_lead_allowed` row (feature `act_as_me`, the person's id), theirs alone.\n\n- **Replies.** Every reply waits on its card (`handle_it_reason` `training`) whatever the dial says, and a reply card adds **Send + allow**: it sends that reply on the person's own tap, exactly as Send does, then allows replies to that sender (key `act_as_me|person:<id>|reply|<address>`). While Handle it for me is on, a reply to an allowed sender goes on its own under the dial's limits (a stranger they allowed included) and every check above (the topics that always wait, links and amounts, new recipients, once a thread a day, the daily limit); it's checked again at send time, so a sender removed since waits. Take the lead as you lifts nothing in training: putting Replies or Follow-ups in training turns it off, and it can't be turned on while they are (409 `in_training`).\n- **Follow-ups.** Every follow-up waits (`follow_up_training`); Send + allow on a follow-up card allows follow-ups to exactly the people it went to (`…|follow_up|<sorted addresses>`), whoever they are, under every other follow-up check.\n- **Suggested actions.** An action card (below) adds **Approve + allow**: it does the actions on the tap, then allows each one that happened (a message to that person, `…|message|person:<id>`; a meeting with exactly those people, the person left out, `…|invite|people:<ids>`). A new contact is never allowed. A card proposed later whose every action is allowed is carried out at once, with no tap (`action_cards.run_on_its_own`, `gate_mode` `auto_execute`, status `executed`), only if plain code finds nothing against it (`on_its_own_refusal`): still in training, Act as me on, a server that ties the switch to the person, nothing sensitive, no link or amount, a message of at most 1200 characters, and at most 10 actions carried out this way a day (checked one card at a time); anything refused is handed back to wait on its card as before. An invite carried out this way is never booked as approved by the person: the meeting gate decides as for any meeting nobody tapped, so a time taken from someone's mail can't land on a calendar unasked. The tool result and chip say what was done. The message text in such an action is model-written from the mail and goes without anyone reading it; the allowance covers who and what kind, not the words, which is why sensitive topics, links, amounts and long messages are held back.\n- **Drafts.** Nothing is sent. When the person changes a reply's draft in their mailbox before tapping Send (plain or + allow) and ticks **Do it like this next time**, what they sent is kept (its new text, quoted replies dropped, at most 1000 characters, `…|style|<address>`), and the ghostwriter gets it in its user turn as `<writer_example>` when it next writes to that person, from the inbox, a follow-up or a chat draft to that one person: style only, never its facts, and nothing in it can open or close a tag.\n\nSend + allow and Approve + allow are refused before anything is done unless their setting is in training (422 `cant_allow`) and the person's list has room (409 `learned_full`, at most 200 a person); allowing failing afterwards never undoes the send. Putting Replies or Follow-ups in, or Suggested actions out, of training only holds more back and works without signed sign-ins; anything else needs a caller the API knows is that person. What it learned is the person's alone: listed on `GET /delegation` (`training.learned`, each with its `setting`), removed with `DELETE /delegation/learned/{id}`, and for the owner also in Take the lead's \"What it's learned\" list; it never reaches anyone else's list or Take the lead's prompts. A dial left on In training by an older version (mode `training`) moves to People I know with Replies and Follow-ups in training (`schema._move_training_off_the_dial`).\n\n**No model decides whether a reply goes.** The watcher's two model calls are unchanged and tool-less, so text in an email can at most change the verdict and the draft. After the draft is written, `handle_it.refusal` — plain code — decides, and anything it refuses becomes the usual card with the reason kept on it (`handle_it_reason`). It refuses when:\n\n- it's off, or the sender is a stranger and the setting isn't Bold, or on a server signed sign-ins are off (`signing_ok`: signed callers, or local login);\n- Gmail couldn't authenticate the sender, whatever the roster says;\n- the email isn't a question, request, scheduling, introduction or follow-up, or the classifier was less sure than the setting needs (0.9 on Easy ones, 0.8 otherwise);\n- the reply goes to anyone the email didn't already go to (its From, To and Cc, less the person's own and the Executive's addresses), leaves out the sender, or goes to more than 10;\n- the email's subject, the sender's new words, or the reply touch money, contracts, legal, hiring, pay, layoffs, the board, investors, mergers, the press, health, or credentials and secrets (passwords, logins, tokens, API keys); or the reply carries an amount, a percentage or a link (a scheme, `www.`, a bare host with a path such as `bit.ly/…`, or a bare host on a common top-level domain) unless it's Bold and at least 0.9 sure, or runs over the setting's length (400, 1200 or 2000 characters);\n- the draft carries any flag but *others on the thread* or *Executive on the thread* (they asked if it's an AI, recipients were trimmed, …);\n- it already sent one in this thread in the last day, or the person's last message in the thread was itself sent on its own (no auto-reply ping-pong);\n- the day's limit is reached (`DELEGATION_HANDLE_IT_MAX_SENDS_PER_DAY`, default 20, within the watcher's drafts limit), or it can't be counted. Any error in the rules counts as a refusal.\n\nA reply the rules allow gets a card with `gate_mode` `auto_execute`, and the watcher sends it at once through `reply_send.send_on_its_own`, the second and last door into the send path (an AST test pins both callers: the approve route and the watcher). It runs the same send-time checks as a tap — switches, mailbox, draft, recipients, the claim and the last re-read — with no caller, and adds its own: the card must be `auto_execute`, Handle it for me still on with the setting still allowing that sender (or, for a follow-up, that recipient), signing still on, the once-a-thread-a-day rule and the daily limit counted again, and the draft untouched since it was saved (an edit in Gmail means the person has taken it over: `draft_changed`, the card waits for them). Every refusal hands the card back to the person (`decision_ledger.hand_back`, a compare-and-set to `propose`), with the reason kept on it when there are words for it, and a failure never stops the scan. Every card it left for the person says why on Today (`waited_because` on `GET /delegation/replies`). A reply sent on its own finishes as `executed` (not approved), is recorded in `delegation_handled` (for the per-thread and daily rules) and writes a private `delegation_reply_handled` row; an unconfirmed one is settled by the reconciler the same way. No History note is taken from it, since notes come only from the person's own words. It runs inside the watcher's scan, so it stops while the Executive is paused.\n\n**Follow-ups as you** (`delegation.follow_ups`). While Handle it for me is on, the watcher's scan also looks at the person's own sent mail, at most once an hour (`LOOK_EVERY`), for an email of theirs that asked something (a question mark in their own words), is 3 to 10 days old, went to at most 10 people other than the Executive, and is still the last message in its thread. Plain code picks it; each gets one follow-up ever (its `delegation_inbox_messages` row), at most two a look, within the drafts limit. The ghostwriter, tool-less as always, writes a short nudge in their voice from the thread, saved as a draft in that thread to exactly the people the email went to. `handle_it.follow_up_refusal` — plain code — decides whether it goes: by the setting it never goes on Easy ones, goes to their team and contacts on People I know and to anyone they wrote to on Most mail (`follow_up_refused` otherwise: `follow_up_level`); it also refuses on any change of recipients, a sensitive topic, an amount or a link, more than 600 characters, a flag, and the same per-thread and daily counts as replies. It goes through `send_on_its_own` on an ordinary `delegation_reply` card marked `source: follow_up`, which rechecks the setting for that recipient. A refused one waits on Today as **Follow-up waiting**, and closes by itself (its untouched draft deleted) when anyone answers in the thread first.\n\n**What it sent** is the person's alone: `GET /delegation/handled` lists the last 7 days (who, subject, the reply, the questions it left them and a link to the thread in their mailbox), and the Settings card shows it under the switch with how many went today.\n\n### Take the lead as you\n\nOn Settings → Act as me, Handle it for me is one dial: **Off**, **Easy ones**, **People I know**, **Most mail** and, for the owner, **Everything**, which uses **Take the lead** (`PUT /delegation/take-the-lead`, one row `person:<id>` in `take_the_lead`; turning it on turns Handle it for me on). While it is on, `handle_it.refusal` drops the setting's limits: strangers, the classifier's confidence, amounts, and the length up to a 4000-character ceiling. A reply with a link still waits for a tap (refusal `link`). In their place it checks the company's and the person's own added rules (`take_the_lead.reply_hit`, refusal `lead_rule`). Everything Handle it always keeps still holds: signed sign-ins, an authenticated sender, a reply kind, exactly the thread's people, the topics that always wait, draft flags, never twice in a row, one a thread a day and the daily limit. Follow-ups under it may go to anyone the person wrote to, with the same sensitive, amount, link and length checks plus the added rules. `reply_send.send_on_its_own` accepts the card while both switches are on. Each person adds and removes their own rules (`/delegation/take-the-lead/rules`). Removing one needs a caller the API can tie to them.\n\n\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. Settings → Delegate → Act as me shows the card (**Replies sent from your mailbox**), 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. A refused call gets a private `tool_invocation` row (`refused: mail_touched`) and tells the model to offer it in the next message. The offered tool list never changes mid-turn, so the cached prefix holds. The handlers that reach outside check again on their own (`outside_reach_refusal`). The server-side web search stays, as on a turn private to the principal. The lockdown ends with the turn. Later turns of that conversation stay private to its owner (`touched_mail`) but hold nothing: a refusal says it will work when they ask again in their next message, and it does.\n\n## Always in the loop\n\nA sent reply can leave a note. Once the reply went, `reply_send` starts `memory.history_notes.note_sent_reply` for the person who sent it, in the background, when their \"Keep track of what happens\" switch is on and the conversation isn't one they asked not to remember. The note-taker sees only the words they sent, so other people's mail never becomes a note, and a failure never touches the send. Recall is `recall_history`, offered on the same verified, private surfaces as `ghostwrite_email` and also allowed under the mail lockdown, since it only reads the speaker's own notes. Calling it locks the turn like `ghostwrite_email` does, from its own round on. The same switch also covers notes from chat, which don't need Act as me. See **Memory** for the checks, retention and controls.\n\n## The system prompt\n\nA constant, name-free `DELEGATION_ADDENDUM` joins block 0 after the unchanged identity addendum while anyone on the install has it on (`block0_delegation_on`). It names the four mailbox reads and says other people's mail is data and that a conversation which read it reaches nobody else; and it tells the model that `ghostwrite_email` is the single exception to *never impersonate*, and only for the person being spoken to; that everything else is written as itself; that when the tool isn't offered the asker can't have it; that a draft is never described as sent; and that it never denies being an AI. It is keyed on the install-level setting, never on the turn or the speaker, so switching it misses the 1h cache once (see Prompt Caching).\n\n## Surfaces\n\n- **Settings → Act as me** (`ActAsMeCard`, hidden unless `GET /delegation` answers, so a team member sees it once the owner lets them): the mailbox connection (`provider` says which) with both connect commands (Gmail and Outlook) and **Check again**, the **Write drafts as me** switch, the **Draft replies to my inbox** switch with its status in plain words, when it last checked and **Check now**, and **How I write**: length and tone, a greeting per audience (`{first}` is their first name), the sign-off, habits and never-rules in fields that grow to show every line, the signature with **Refresh from Gmail** and **Don't add my signature** (or **Add my Gmail signature** when none is added; on Outlook only **Don't add my signature**, with why), and each example quoted with **Remove examples**. The owner also gets **Let team members use it** where the install allows it, with each team member who has it on listed by name and counts only.\n- **Today → Replies waiting** (`RepliesWaiting`, the top of the left column; hidden unless `GET /delegation/replies` answers with cards): each card shows who wrote and who they are to you, whether their address was verified, the subject, **They wrote** as plain text, your draft, **Decide before sending** (the open questions) and its warnings, with **Send** (a confirm naming who it goes to, and a second one when that or the thread changed), **Edit** (a text box on the card with Save and Cancel), **Open in Gmail** or **Open in Outlook** when the reply is in their Drafts, and **Dismiss**.\n- **Setup status**: a **Your own mailbox (Act as me)** light (`your_gmail`), amber while the inbox watcher can't reach the mailbox, is being rate-limited or has 25 replies waiting.\n- **Settings → Your Executive** (`app/settings/executive`, where `/settings/on-its-own` lands): the pause, **Take the lead** and **Book meetings without asking** (as the Executive). **Handle it for me** (the Off / Easy ones / People I know / Most mail / Everything dial, what each sends, how many went today and what it sent this week, as you) sits under the mailbox card on **Settings → Act as me**.\n- **API**: `GET`/`PUT /delegation`, `GET`/`PUT`/`DELETE /delegation/voice`, `POST /delegation/voice/learn`, `POST /delegation/voice/describe`, `POST /delegation/voice/signature`, `PUT /delegation/inbox` (`{enabled?, mailbox_drafts?}`), `POST /delegation/inbox/check`, `GET /delegation/replies`, `PUT /delegation/replies/{id}/text`, `PUT /delegation/handle-it`, `PUT /delegation/training`, `DELETE /delegation/learned/{id}` and `GET /delegation/handled` — the caller's own delegation only — and `PUT /delegation/team`, the owner's switch (see API Reference). Send is `POST /decisions/{id}/approve`; Dismiss is `POST /decisions/{id}/reject`.\n- **Evals**: a scenario's `delegation:` block runs the turn against an in-memory mailbox (`evals.mailbox.ScenarioMailbox`) and hands the saved drafts to the judge (`delegation_001`–`003`). A `type: inbox` scenario runs the watcher's two model calls on one thread: whether it drafts must match the scenario, and a draft is judged on saying nothing the person hadn't, copying no link or address, and listing every open question (`delegation_inbox_001`–`007`; the last checks a draft never claims anything was sent).\n\nActing within rules the person sets and standing in for them are later, separate changes, each behind its own switch, off by default.",
+ "markdown": "The **delegation** module (`openexecutive.delegation`) is **Act as me**: the one place the Executive writes *as* a person instead of as itself. Everywhere else it has its own Google account and bots and signs as itself. Here — when the person asks, or, with a second switch, for mail in their inbox that needs them — it writes an email in their voice and saves it as a **draft in their own mailbox** — Gmail or Outlook — for them to review and send. The one thing it ever sends is one of those inbox drafts, exactly as it is in their mailbox: when the person taps **Send** on its card, or, with a third switch, **Handle it for me**, on its own when plain-code rules allow it (below); chat never sends. The principal can turn it on for themselves, and so can each team member once the owner lets them. It is off by default, and off changes nothing: the prompts, tool lists and prompt caches are byte-identical to an install without it.\n\n## Who can have it, and when it is offered\n\n`delegation.settings.can_delegate(person)` is the single rule for who may turn it on: the principal (a non-archived team member flagged `is_principal`), and any other non-archived team member — never a contact — once team members may have it (`team_members_enabled`). That takes two things: the install allows it (`DELEGATION_TEAM_MEMBERS`, default off, which offers the owner the switch) and the owner turned on **Let team members use it** (`PUT /delegation/team`, principal only, one row in `delegation_team`). Turning the owner's switch off takes it away from every team member from their next message, and their inbox watchers stop at their next check; their own switches, drafts and cards are kept. Everything is keyed by `person_id`. A person turns it on for themselves (`PUT /delegation`); nobody turns it on for anyone else. The setting is one row per person in `delegation_settings`, and a missing, unreadable or zero row all mean off.\n\nAt the start of every chat turn (`Executive.stream_chat` and the committee path) `pin_turn_delegation(session, speaker_text)` runs next to the workspace-mode pin and records a `TurnDelegation` on the session. `ghostwrite_email` is **offered** only when all of these hold:\n\n- the speaker may have it and turned it on — read fresh every turn, so turning it off applies from the next message;\n- the speaker is on a surface that verified it is them — the principal through `people_tools.is_principal_on_verified_surface`, a team member through `teammate_on_verified_surface` (the web app signed in, their own Slack or Discord, never an email turn) — and a web turn also carried a signed-in caller (`Session.web_caller_signed_in`, set from `x-caller-email`) or runs under local login — a request with no caller header is not a sign-in and never gets it (whoever holds the shared secret is trusted as the UI proxy that stamps that header, as on every principal-only route);\n- the conversation is private to the speaker: the web chat, a Slack or Discord DM, or a verified private Telegram chat — never a shared channel or thread, where the draft's preview or the matching threads would be posted for everyone and other people's messages sit in the model's context;\n- the turn is neither unattended (the scheduler's proactive run) nor private to the principal (the email poller's turns), so inbound text can never reach it. The MCP server, workflows, reflection and research never carry it at all.\n\nThe mailbox connection is deliberately **not** part of the offer: the handler checks it on every call and says how to fix it, so the cached tool prefix never flips when a token lapses. The pin lives in a context variable for the turn's task as well as on the session, so two turns running at once on one session (a second browser tab) each read their own. It also carries the speaker's own words for the turn (a new email may go to an address they just typed — the turn's message joins the history only once the turn ends), a per-turn draft count, and `touched_mail` (see Privacy). `own_words` reads those words back for every own-words check (addresses here, facts and task assignments elsewhere): it first removes the hydrated `<outbound_reply_context>` backstory by its exact, anchored shape, so a look-alike closing tag quoted inside it cannot pass the rest off as the speaker's, then drops other adapter tag blocks, and returns nothing for a message carrying an attachment.\n\n## The tool: `ghostwrite_email`\n\nIt lives in its own registry (`orchestrator.delegation_tools.DELEGATION_TOOLS` / `DELEGATION_TOOL_HANDLERS`), **never** `_ALL_SKILL_TOOLS`, so no other toolkit can carry it. On a turn it is offered to, the agent loop adds it to the pool *before* the sort and builds that turn's handler map from both registries; on any other turn a call to it is an unknown tool. The handler re-checks the pin and the surface anyway, then:\n\n1. **Caps** — at most 5 drafts per turn, and `DELEGATION_MAX_DRAFTS_PER_DAY` (default 50, at most 1000) per person per UTC day, shared with the inbox watcher (`delegation.caps`). It is counted from `delegation_drafts`, one row of ids per draft saved from either place, with a count kept in the process as a floor in case a row was lost. Each slot is taken before the first await — a round's tool calls run concurrently, so otherwise every call in it would pass the caps before any counted — and handed back if nothing was drafted. If the rows can't be read it refuses rather than guess.\n2. **Marks the turn** — sets `TurnDelegation.touched_mail` *before* its first read of the mailbox.\n3. **Checks the mailbox** — `gmail_status` asks Google or Microsoft whose mailbox the credential opens and compares it with the person's People email, on every call: a roster email can change, and a client slot swaps the roster.\n4. **Finds the thread** — by `thread_id` (checked against the mailbox's own id shape), or a Gmail-style search (`find`; on Outlook, words, `from:`, `to:`, `cc:`, `subject:` and `newer_than:` are kept and other Gmail operators dropped). Several matches return `{status: \"choose\", candidates}` (subject, sender and date — no message text) and draft nothing; none returns `not_found`.\n5. **Sets the recipients in code**, never from the model. A reply goes to the last inbound message's `From` — never its `Reply-To` (a different one is flagged `reply_to_ignored`) — with the thread's other recipients only on `reply_all`. A new email or a forward may go to any well-formed address: it is only a draft, waiting in their own mailbox, where they see who it is to before they send it. An address that is neither on the roster (contacts only when `contacts_reachable_now()`) nor typed by the speaker this turn comes back in `not_in_people`, and the Executive names it for them to check (`delegation_tools.not_in_people`). Mailing-list mail, a thread they replied to last and a reply-all trimmed to 10 recipients are flagged. An address inside a block an adapter added to their message (the backstory hydrated into a DM) is not one they typed, and when the message carries an attachment — a document's inlined text, or a note naming the file — none of its addresses count as typed: neither has an end mark, and a filename is chosen by whoever sent the file, so such an address is named back to check.\n6. **Writes it** (the ghostwriter, below) and saves it with the mailbox client's `create_draft` (Gmail: threaded with `In-Reply-To`, `References` (whole message ids: when the chain is too long for one header the oldest after the thread's first go, never the parent) and `threadId`, and stamped `X-OE-Ghostwritten`; Outlook: Graph's `createReply` on the message it answers, then the text and recipients, and a named property marking it).\n\nThe result is `{status: \"drafted\", draft_id, gmail_link, to, cc, subject, preview, flags, open_questions, note}`, plus `not_in_people` and `check_address` when a recipient needs checking. The link (`gmail.mailbox_link`) is built server-side from a fixed prefix — the thread in Gmail, the draft itself in Outlook on the web — and the note tells the model the preview is the person's draft, to be treated as data. The chat shows an action chip — \"Drafted an email as you to … — in your Drafts\" — that opens it, and only a link under `MAILBOX_LINK_PREFIXES` is ever linked. A sincere \"are you an AI?\" in the thread comes back as an open question for the person to answer themselves.\n\n## Reading their mailbox\n\nFive read-only 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## 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, `intent` becoming the short note above it (the ghostwriter writes only the note; the forwarded email's subject, someone else's words, is never put in the intent). Recipients follow the new-email rule (`_new_recipients`: the roster, or addresses the speaker typed this turn). Gmail's draft quotes a forward header and the original's own words under the note and attaches the original's files, up to 10 and 20 MB (`FORWARD_MAX_FILES`, `FORWARD_MAX_BYTES`; any left off are flagged `attachments_left_off`); Outlook uses Graph's `createForward`, which keeps the original and its files, with the note as its comment and the body never patched. It is still only a draft.\n\n`remind_me(text, when)` (`orchestrator.reminder_tools`) rides with the same tools and checks, but opens no mailbox, so it never marks or locks a turn (`MAILBOX_TOOL_NAMES` are the ones that do). It stores the text once cleaned — one line, anything a chat app could turn into a link (a URL of any scheme, an address, a domain-like word, a host and port, an IP address) replaced with \"[link]\", at most 300 characters — with its time (stored in UTC) in `delegation_reminders` (5 a turn, 25 waiting, a year ahead, refused when the person has no channel). When it is due the scheduler sends that text to the person alone, as \"Reminder you set on <date>: …\", running nothing (see Scheduler); the Slack and Discord DMs it may go by turn link previews off. The chat chip shows the text as it will be sent. A reminder that comes due in the person's quiet hours or leave (when `OUTBOUND_RESPECT_QUIET_HOURS` is on) waits unclaimed and goes once they end, rather than being suppressed and lost. It is allowed after mail is read and in later turns of that conversation: it reaches only the speaker, as plain text. `schedule_followup`, which runs a turn with tools and is listed to everyone, stays refused there.\n\n## Approval cards\n\nA turn that read someone's mail may not message anyone, invite anyone or change the roster (see the lockdown above), yet what the mail asks for is often right. `propose_actions` (`orchestrator.action_card_tools`) leaves the speaker a card instead: up to five actions, each spelled out exactly as it will happen, done only when they tap Approve. It rides with the other Act as me tools and checks (`_writer`), opens no mailbox, and is allowed after mail is read because it does nothing on the turn.\n\n- **Kinds.** `invite` (a meeting with people on the roster), `message` (a direct message to someone on the roster, as written) and `add_contact` (a new contact; the principal's cards only, since contacts are theirs). A team member's card can't name a contact. Each action is checked when the card is made (`delegation.action_cards.check`) and again when it is carried out, so an archived person or a time that has passed fails that action alone.\n- **Whose.** A card is a `delegation_actions` decision for the speaker, `approver_only` like a reply card: only they see it (`GET /delegation/actions`) or resolve it, a team member's answers 404 to the principal too, and it is never an alert. The same actions still waiting are that card, not a new one. 3 cards a turn, 25 waiting, dropped after 7 days.\n- **Approve.** In the chat, under the reply that left it (the `propose_actions` chip carries the card's `decision_id`, and `ChatActionCards` shows the card while it waits), and on the Briefing's Needs you list, with a box per action. Approve (`POST /decisions/{id}/approve`, `edits.only`) needs the card's person signed in (`verified.caller_refusal`) with Act as me on; the card is claimed first so it runs once, then each ticked action runs as stored with no model call, in an unattended session (the principal's with contact egress) under `rows_for_person`, so every audit row it writes is theirs and nothing reaches the team's activity rail: `message_person` (a direct message or nothing; never its Briefing-alert fallback, which more people read), `create_calendar_event`, or a contact row. Approving also needs the person still allowed Act as me (`can_delegate`) and switched on. An invite is booked straight away when the person approving is the one the meeting gate would ask (`calendar_tools.approved_by`), and otherwise goes to that approver as usual, so a card never widens anyone's authority. Per-action results (`done`, `waiting`, `failed`, `skipped`) are kept on the decision and shown on the card. Dismiss rejects it and does nothing else. With Suggested actions in training the card adds Approve + allow, and a card of actions all allowed is carried out on its own (see In training above).\n- **Channels.** A card can come from any surface Act as me runs on; it is approved in the web app, since the chat apps have no buttons here.\n\n## The ghostwriter\n\n`delegation.ghostwriter.compose` writes the text. The Executive decides *what* to say (`intent`); this call decides *how* the person would say it, and it is deliberately small:\n\n- a constant `GHOSTWRITER_PROMPT` plus the person's voice block as the system prompt;\n- the thread (each message cut to its sender's own words, every line scrubbed, all labelled alike), then the writer's own earlier words in it (`<writer_said>`, from their sent mail only), the intent and the recipients' names in the user turn — no company profile, memory or roster;\n- with Always in the loop on, `<writer_noted>`: what the writer's own notes say they told these same people in earlier Act as me replies (`memory.history_drafts.notes_for_draft`: only notes from mail **every** recipient of the new draft was on, so nothing told to one person reaches another; chat notes name no recipient and never qualify; at most 8, newest first, the person's own words or their correction, with dates). The prompt's rule 6 makes it a consistency check, never content: a draft that contradicts it is still written as the intent says, and the conflict becomes an open question on the card, which only the writer sees. Both the chat tool and the inbox watcher pass it;\n- **no tools** but the forced `compose_reply` return, so text in the thread can ask for anything and there is nothing to do it with.\n\nIt is not a Council agent — the Council's edit routes have no principal check — and runs on `DELEGATION_COMPOSER_MODEL` (default: the default model), logged as `ghostwriter` usage. `lint` then runs in code on what comes back: a link or an email address survives only if it appears in the intent, the signature or the recipients, so a link planted in the thread is removed and flagged; the Executive's own name is flagged; and the body is capped, cut at a paragraph, line or word break in its last fifth. A draft with nothing left after that is refused. The signature from the person's Gmail settings (or the one already stored, for Outlook) is appended.\n\n## How I write\n\n`delegation.voice` learns how a person writes *their own* email (`attunement.style` learns how the Executive should write *to* someone). `POST /delegation/voice/learn` reads up to 40 recent sent messages, keeps only what they wrote (quoted replies stripped with the email poller's `sender_new_text`), skips automatic mail, every thread chat drafted into, and every sent message that began as a draft written for them (`delegation_drafts.sent_message_id`), and makes one forced-tool call (`record_voice_profile`). Code validates every field before it is stored:\n\n- greetings per audience (their team, their contacts, anyone else), a sign-off of at most two lines, and a usual length and tone (a backslash-n the model wrote instead of a line break is read as one, keeping the first lines that fit, which also repairs a profile stored before that rule);\n- up to 8 habits and 6 things to avoid, through the same deny-list as working-style rules — no actions, links, handles, amounts, tool names or names of people;\n- up to 3 short exemplars, each checked to be verbatim from a sample, with addresses and phone numbers masked — and none while a client slot is active, so one client's mail never lands in another's state.\n\nThe signature comes from Gmail's `sendAs` settings, not the model (Outlook gives apps no way to read one, so a learn keeps the stored signature and `POST /delegation/voice/signature` answers 409 `signature_unavailable` rather than clearing it), as plain text with its lines kept (`gmail.html_to_text`: a `<br>` always ends a line, and a block tag, opening or closing, ends one when it has text, so Gmail's layout of a first line followed by one `<div>` per line comes out line by line). `POST /delegation/voice/signature` reads it again without relearning: nothing else changes and a locked profile stays locked, so it picks up a changed Gmail signature and undoes **Don't add my signature**. A person can also describe their style in their own words: `POST /delegation/voice/describe` applies the description to the profile they have through the same forced tool (a separate system prompt, no exemplars) and the same validation, keeps their signature and writing examples, and returns the result with a short sample reply for them to review. It saves nothing and needs no mailbox; Save stores it as an ordinary edit. The person can edit the profile, lock it (a locked profile is never relearned) and reset it, and every change is kept in `delegation_voice_history`. One learn runs at a time per person, and a lock or an edit made while it runs wins: the learned profile is dropped (`changed`).\n\n## Draft replies to my inbox\n\nA second switch under Act as me, **Draft replies to my inbox** (`delegation.inbox`), has the Executive watch the person's own inbox and write a first reply to mail that needs them. The reply waits on a private card on Today; nothing is sent until they tap **Send** (below). Where the reply lives is the person's choice, **Also save replies in my Gmail Drafts** (`mailbox_drafts`, off by default): off, it lives on the card alone (`delegation.card_drafts`: the card keeps the draft's recipients, subject and thread headers as `draft_spec`, and Send makes the mailbox draft from exactly that just before the send-time checks, taking it back out if they refuse), so their Drafts folder doesn't fill with replies they may never send; on, it is also saved in their Drafts as before. The switch is one row per person in `delegation_inbox_watch`. Turning it on needs Act as me on and their mailbox connected, and sets `watch_since` to now every time, so it never drafts for mail that arrived before; turning Act as me off turns it off too. Off means no mailbox call and no row written, with one exception: a send the person started that the mailbox never confirmed is still followed through until it is settled.\n\n### When it looks\n\nA throttled hook in the scheduler tick (`_maybe_scan_inbox`, after the pause, company-profile and rotation gates) checks each person whose switch is on every `DELEGATION_INBOX_POLL_MINUTES` (default 5). It is not a scheduled action, because those are listed on `/scheduled` for everyone and anyone may cancel them. One scan task runs at a time, one scan per person, and none while a client slot is active. **Check now** on the Settings card runs the same scan. Every row a scan writes is private and the person's own (`audit.rows_for_person`: a team member's rows are hidden from the principal too, see Privacy), and the process log carries counts and codes, never an address or a line of mail. The scan never marks mail read or changes a label.\n\n### What it drafts for\n\nA scan first settles the open cards (below), and stops with `backlog_full` once 25 are waiting, counting the ones it makes. It then lists the inbox since `watch_since` (`inbox_message_ids`) — not chats, not mail from the person, and not the promotions, social, updates or forums tabs (on Outlook: the Focused inbox only) — up to 100 messages, and takes the newest message of each thread that still needs a look, at most 10: settled threads and threads with an open card are passed over first, so a burst of mail, or a pause for a limit or a back-off, never hides older threads for good. `delegation_inbox_messages` is its durable cursor: one row per message (`UNIQUE(person_id, message_id)`) with what happened to it, the reason, how many tries it took, and the draft and card ids. It stores a hash of the sender's address, never the address. A message is skipped, with the reason recorded, when:\n\n- it came before `watch_since`, or more than three days ago;\n- it is from the person or one of their send-as addresses, from the Executive, or one of this module's own drafts;\n- it is automatic — `Auto-Submitted`, a bulk or auto-reply `Precedence`, a bounce, a calendar invite or a no-reply sender — or from a mailing list, or in a Gmail tab, spam or trash;\n- the person is not in To or Cc, or it has more than 10 recipients;\n- the person replied last, or a draft already sits in the thread.\n\nThree kinds are left unrecorded, so a later scan looks again: mail under 10 minutes old (mail the person answers straight away never gets a card), mail in a thread whose card is still open, and mail a daily limit holds back.\n\n### Deciding, then writing\n\nTwo model calls, and code decides between them. The classifier (`delegation.inbox_classifier`) is one forced-tool call, `classify_email`, returning whether the email needs a personal reply, what kind it is and how sure it is. It sees a few one-lined header lines and the sender's own new words (at most 3000 characters, every line scrubbed) inside one `<email>` block marked as data, and it has no other tools, context or memory, so an email can ask for anything and there is nothing to do it with. A reply is drafted only for a question, a request, scheduling, an introduction or a follow-up, and only when the confidence clears a bar that rises the less the sender is known: 0.6 for their team or a contact (the principal's contacts count only for the principal: a team member's mail is weighed by the team and their own sent mail), 0.7 for someone they have written to before (`has_written_to`, a search of their sent mail), 0.85 for a stranger. Pitches, notes of thanks, FYIs, notifications, newsletters and phishing get nothing, and so does any failure. An email that also went to other people is drafted for only when the person is in To and it asks them themselves: the classifier is told their name, whether they are in To or Cc and how many others it went to, and lists the names the email greets or asks by name (`asked_names`). Code matches those against the person's name, whole name parts only (\"Alexis\" never counts for \"Alex\", and a nickname misses, which means no draft), so mail that greets someone else (\"Good morning, Brennan, could you sign ...\") is never theirs, whatever the model makes of it as a whole. When it names nobody, the model's `asked_of_them` decides, false for a question to the group at large. One that only copies them is never drafted for. Either is recorded `not_needed` with the reason `asks_someone_else`. It runs on `DELEGATION_CLASSIFIER_MODEL`, else the routing model. A sender whose address Gmail couldn't authenticate is handled as a stranger whatever the roster says — anyone can put a colleague's or a client's address in From — so they get the stranger's bar, a holding reply and the stranger limits; the card still says who they claim to be, and that the address isn't verified.\n\nThe reply is written by the same ghostwriter, in the person's voice, but from a fixed intent the module builds rather than words the person typed. Because the intent lets it restate the person's own earlier words, which words are theirs is never written inside the thread, where a sender could imitate any marker with a look-alike: every message there is labelled alike, and the person's own words come in a separate `<writer_said>` block after the thread, taken only from mail their own mailbox sent. Nothing inside the thread can close the thread block or open another. The intent: acknowledge the sender; say again only what the person's *own* earlier messages in the thread already said; commit to nothing new — no yes or no, date, time, price, fact or promise — and say they will get back to them; and put every question it could not answer from their words in **open questions**. A stranger always gets a short holding reply. The lint still strips any link or address that isn't the person's own. The reply goes to the sender (never `Reply-To`) and, on a group email, to everyone else it went to as Cc (reply to all, never the person's own addresses or the Executive); a stranger's holding reply goes to the sender alone. The card says when others were on the email, and its `draft_to` lists everyone, which Send checks.\n\nThe order: record the message, classify, reserve a slot in the shared daily limit, write, save the draft in Gmail (from the alias the mail went to, when it went to one) and store its id, then create the card (idempotent on the message) and mark it drafted. Nothing that fails along the way loses the message. A failure that may pass — the classifier or the writer failing, Gmail refusing the draft, a card that couldn't be made (its draft is deleted first, so no draft is left without a card), any other error with that one message — leaves it for a later scan (`retry`), and it is given up on only after three tries; one message's trouble never holds up the rest. A daily limit reached while it was being read leaves it for later without counting as a try.\n\n### The reply cards\n\nA card is a `delegation_reply` decision whose class is **its approver's alone** (`DecisionClassSpec.approver_only`): only the person it was drafted for sees or resolves it on any decisions route — a team member's card answers 404 to the principal too — and it is never an alert: alerts feed chat turns, which would put other people's mail into memory. It carries the sender with who they are to the person and whether Gmail could verify the address (SPF/DKIM/DMARC, through `fact_confirmation.headers_authenticated`), the subject, what they wrote, the draft, the open questions and its warnings. `GET /delegation/replies` lists the open ones from the database alone, so Today never waits on Google.\n\n- **Send** approves the card, which sends its draft exactly as it is in their mailbox (see *Send on your tap*). **Edit** changes the reply's words right on the card (`PUT /delegation/replies/{id}/text`, `card_drafts.edit`): only its own person, from a caller the API can tie to them (as for Send), never while it is being sent on its own; a reply in their Drafts is rewritten there too (`update_draft_text`, every header kept), and only while it is still the version the card last saw, so a change made in the mailbox is never overwritten. A card edit counts as edited (`approved_with_edit`, and **Do it like this next time** keeps it). **Open in Gmail** (or **Open in Outlook**), shown only when the reply is in their Drafts, opens it there.\n- **Dismiss** rejects the card; the class's after-reject step then deletes the draft if nobody edited it — its message id is still the one it was saved with, since Gmail gives an edited draft a new one, and the Outlook client makes a draft's message id `<id>.<changeKey>` so an edit there changes it too — and keeps it otherwise. What happened is recorded even when Gmail fails.\n- Each scan first **settles** what Gmail already settled: a draft sent from Gmail, a draft deleted there, a reply the person wrote themselves, a thread that is gone, or a card left for 7 days (its draft stays in Gmail). Each is a compare-and-set close with the reason. A newer message from someone else flags the card instead. A card being sent at that moment is left alone.\n\n### Send on your tap\n\n`delegation.reply_send` is the only thing in Act as me that sends, and all it can send is the draft on a card, by its id: `DelegateGmail.send_draft` posts `{\"id\": …}` to Gmail's `drafts.send`, and `DelegateOutlook.send_draft` posts an empty body to that draft's Graph `send`, and nothing else, so no text, recipient or header is ever passed. It has two doors: `send_approved_reply`, reached only from `POST /decisions/{id}/approve` — a class only the card's own person may resolve — and `send_on_its_own`, reached only from the inbox watcher under Handle it for me (below). AST tests pin both call sites, so no model, chat turn, workflow, scheduled job or MCP call can. A tap is checked like this: At send time it checks everything again:\n\n1. **Who is asking.** The caller is the card's person and the API knows it: signed callers are on and the request carries that person's signed assertion (or the operator's, under local login), or the API runs for local login and answers this computer only. Anything else is a 409 `caller_signing_required` — with only the shared secret, whoever holds it could send as the owner — so on a server Send needs signed sign-ins.\n2. **The switches.** Act as me and Draft replies to my inbox are on, and no client slot is active.\n3. **The mailbox.** Their mailbox is connected.\n4. **The draft.** It still exists, in the same thread, and they haven't replied there themselves since; otherwise the card closes.\n5. **Who it goes to.** To, Cc and Bcc hold between 1 and 10 addresses, never the Executive's own, and it is from one of their own addresses.\n6. **What changed.** Recipients that differ from the card's, or a newer message from someone else, need a second yes: the first tap gets a 409 `confirm` naming the recipients and the reason, and the person approves again with what they were shown.\n\nThen it claims the card (`claim_for_execution`, proposed → executing, a compare-and-set, so a double tap sends once) and reads the draft once more: `drafts.send` sends whatever the draft is when Gmail gets the request, so if it was edited since the checks read it — in another tab, by a delegate — nothing is sent and the card comes back (`draft_changed`). Then it sends, and records the result: `approved_with_edit` when the draft was edited in Gmail, the sent message's id, the draft row's `sent_message_id`, and a private `delegation_reply_sent` row. A refusal that proves nothing went — a 4xx, a lapsed sign-in, a rate limit, a draft already gone — hands the card back. A failure that leaves it unclear — a timeout, a 5xx — leaves it `executing` and says to check the Sent folder, and the next scans ask Gmail: their message in the thread means it was sent; anything else is judged on the second scan that sees it: the draft still there and nothing sent means it was not (Gmail deletes a draft it sends), and the card comes back, flagged; the draft gone and nothing sent means it was deleted. Nothing is ever retried on its own. Sending is the person's own act, so it works while the Executive is paused.\n\n### Limits and failures\n\nAt most 5 drafts a scan; `DELEGATION_INBOX_MAX_DRAFTS_PER_DAY` (default 20) a day, inside the shared `DELEGATION_MAX_DRAFTS_PER_DAY` it shares with chat; 200 classifications, 2 drafts per sender (1 for a stranger) and 10 for strangers in all per day; and never more than 25 open cards. A lapsed Gmail sign-in sets the status and is looked at again every 30 minutes; a rate limit, an error reaching Gmail or a crash backs off from 5 minutes, doubling up to 2 hours. Neither turns the switch off: the Settings card shows the status in plain words.\n\n## Handle it for me\n\nA third switch under Act as me, **Handle it for me** (`delegation.handle_it`), lets the inbox watcher send some of its replies itself instead of leaving them on a card. It is one row per person in `delegation_handle_it` (`enabled`, `mode`); no row means off. One setting says how much goes without them, the way quality does on the Agent Council (`handle_it.RULES`): **Easy ones** (`careful`) sends only replies to people they know (someone on their team, a contact or someone they have written to) of at most 400 characters when the classifier is at least 0.9 sure; **People I know** (`balanced`), where it starts, sends replies to people they know up to 1200 characters at 0.8; **Most mail** (`bold`) also answers strangers, up to 2000 characters, and lets a link or an amount through when the classifier is at least 0.9 sure. Everything else waits on a card as before, so turning it on never drafts less. A table from before the setting gets the `mode` column on its next open (`schema._add_handle_it_mode`): someone who had strangers set to send keeps that as Bold, everyone else gets Balanced. Only the person turns it on (`PUT /delegation/handle-it`), from a session the API knows is theirs: the same rule Send uses (`delegation.verified.caller_refusal`), so with only the shared secret it answers 409 `caller_signing_required`. Turning it on needs Act as me and Draft replies to my inbox on, and turning the inbox watcher off (or Act as me, which turns it off) turns it off too.\n\n**In training** (`delegation.training`). Like someone new, each Act as me job can be put in training on its own, from that job's card on the Act as me page, the way Take the lead has it: **Write drafts as me** and **Handle it for me** each pick Off / In training / On (Handle it's In training is Replies in training, with a *Train follow-ups too* box for Follow-ups), and **Suggested actions** picks Always ask / In training; one *What it's learned* list sits at the bottom, each item named by its job (`PUT /delegation/training`, one row per person and setting in `delegation_training`, absent means not in training). In training it asks first and learns who and how from what the person approves; what it learns is a `take_the_lead_allowed` row (feature `act_as_me`, the person's id), theirs alone.\n\n- **Replies.** Every reply waits on its card (`handle_it_reason` `training`) whatever the dial says, and a reply card adds **Send + allow**: it sends that reply on the person's own tap, exactly as Send does, then allows replies to that sender (key `act_as_me|person:<id>|reply|<address>`). While Handle it for me is on, a reply to an allowed sender goes on its own under the dial's limits (a stranger they allowed included) and every check above (the topics that always wait, links and amounts, new recipients, once a thread a day, the daily limit); it's checked again at send time, so a sender removed since waits. Take the lead as you lifts nothing in training: putting Replies or Follow-ups in training turns it off, and it can't be turned on while they are (409 `in_training`).\n- **Follow-ups.** Every follow-up waits (`follow_up_training`); Send + allow on a follow-up card allows follow-ups to exactly the people it went to (`…|follow_up|<sorted addresses>`), whoever they are, under every other follow-up check.\n- **Suggested actions.** An action card (below) adds **Approve + allow**: it does the actions on the tap, then allows each one that happened (a message to that person, `…|message|person:<id>`; a meeting with exactly those people, the person left out, `…|invite|people:<ids>`). A new contact is never allowed. A card proposed later whose every action is allowed is carried out at once, with no tap (`action_cards.run_on_its_own`, `gate_mode` `auto_execute`, status `executed`), only if plain code finds nothing against it (`on_its_own_refusal`): still in training, Act as me on, a server that ties the switch to the person, nothing sensitive, no link or amount, a message of at most 1200 characters, and at most 10 actions carried out this way a day (checked one card at a time); anything refused is handed back to wait on its card as before. An invite carried out this way is never booked as approved by the person: the meeting gate decides as for any meeting nobody tapped, so a time taken from someone's mail can't land on a calendar unasked. The tool result and chip say what was done. The message text in such an action is model-written from the mail and goes without anyone reading it; the allowance covers who and what kind, not the words, which is why sensitive topics, links, amounts and long messages are held back.\n- **Drafts.** Nothing is sent. When the person changes a reply's draft in their mailbox before tapping Send (plain or + allow) and ticks **Do it like this next time**, what they sent is kept (its new text, quoted replies dropped, at most 1000 characters, `…|style|<address>`), and the ghostwriter gets it in its user turn as `<writer_example>` when it next writes to that person, from the inbox, a follow-up or a chat draft to that one person: style only, never its facts, and nothing in it can open or close a tag.\n\nSend + allow and Approve + allow are refused before anything is done unless their setting is in training (422 `cant_allow`) and the person's list has room (409 `learned_full`, at most 200 a person); allowing failing afterwards never undoes the send. Putting Replies or Follow-ups in, or Suggested actions out, of training only holds more back and works without signed sign-ins; anything else needs a caller the API knows is that person. What it learned is the person's alone: listed on `GET /delegation` (`training.learned`, each with its `setting`), removed with `DELETE /delegation/learned/{id}`, and for the owner also in Take the lead's \"What it's learned\" list; it never reaches anyone else's list or Take the lead's prompts. A dial left on In training by an older version (mode `training`) moves to People I know with Replies and Follow-ups in training (`schema._move_training_off_the_dial`).\n\n**No model decides whether a reply goes.** The watcher's two model calls are unchanged and tool-less, so text in an email can at most change the verdict and the draft. After the draft is written, `handle_it.refusal` — plain code — decides, and anything it refuses becomes the usual card with the reason kept on it (`handle_it_reason`). It refuses when:\n\n- it's off, or the sender is a stranger and the setting isn't Bold, or on a server signed sign-ins are off (`signing_ok`: signed callers, or local login);\n- Gmail couldn't authenticate the sender, whatever the roster says;\n- the email isn't a question, request, scheduling, introduction or follow-up, or the classifier was less sure than the setting needs (0.9 on Easy ones, 0.8 otherwise);\n- the reply goes to anyone the email didn't already go to (its From, To and Cc, less the person's own and the Executive's addresses), leaves out the sender, or goes to more than 10;\n- the email's subject, the sender's new words, or the reply touch money, contracts, legal, hiring, pay, layoffs, the board, investors, mergers, the press, health, or credentials and secrets (passwords, logins, tokens, API keys); or the reply carries an amount, a percentage or a link (a scheme, `www.`, a bare host with a path such as `bit.ly/…`, or a bare host on a common top-level domain) unless it's Bold and at least 0.9 sure, or runs over the setting's length (400, 1200 or 2000 characters);\n- the draft carries any flag but *others on the thread* or *Executive on the thread* (they asked if it's an AI, recipients were trimmed, …);\n- it already sent one in this thread in the last day, or the person's last message in the thread was itself sent on its own (no auto-reply ping-pong);\n- the day's limit is reached (`DELEGATION_HANDLE_IT_MAX_SENDS_PER_DAY`, default 20, within the watcher's drafts limit), or it can't be counted. Any error in the rules counts as a refusal.\n\nA reply the rules allow gets a card with `gate_mode` `auto_execute`, and the watcher sends it at once through `reply_send.send_on_its_own`, the second and last door into the send path (an AST test pins both callers: the approve route and the watcher). It runs the same send-time checks as a tap — switches, mailbox, draft, recipients, the claim and the last re-read — with no caller, and adds its own: the card must be `auto_execute`, Handle it for me still on with the setting still allowing that sender (or, for a follow-up, that recipient), signing still on, the once-a-thread-a-day rule and the daily limit counted again, and the draft untouched since it was saved (an edit in Gmail means the person has taken it over: `draft_changed`, the card waits for them). Every refusal hands the card back to the person (`decision_ledger.hand_back`, a compare-and-set to `propose`), with the reason kept on it when there are words for it, and a failure never stops the scan. Every card it left for the person says why on Today (`waited_because` on `GET /delegation/replies`). A reply sent on its own finishes as `executed` (not approved), is recorded in `delegation_handled` (for the per-thread and daily rules) and writes a private `delegation_reply_handled` row; an unconfirmed one is settled by the reconciler the same way. No History note is taken from it, since notes come only from the person's own words. It runs inside the watcher's scan, so it stops while the Executive is paused.\n\n**Follow-ups as you** (`delegation.follow_ups`). While Handle it for me is on, the watcher's scan also looks at the person's own sent mail, at most once an hour (`LOOK_EVERY`), for an email of theirs that asked something (a question mark in their own words), is 3 to 10 days old, went to at most 10 people other than the Executive, and is still the last message in its thread. Plain code picks it; each gets one follow-up ever (its `delegation_inbox_messages` row), at most two a look, within the drafts limit. The ghostwriter, tool-less as always, writes a short nudge in their voice from the thread, saved as a draft in that thread to exactly the people the email went to. `handle_it.follow_up_refusal` — plain code — decides whether it goes: by the setting it never goes on Easy ones, goes to their team and contacts on People I know and to anyone they wrote to on Most mail (`follow_up_refused` otherwise: `follow_up_level`); it also refuses on any change of recipients, a sensitive topic, an amount or a link, more than 600 characters, a flag, and the same per-thread and daily counts as replies. It goes through `send_on_its_own` on an ordinary `delegation_reply` card marked `source: follow_up`, which rechecks the setting for that recipient. A refused one waits on Today as **Follow-up waiting**, and closes by itself (its untouched draft deleted) when anyone answers in the thread first.\n\n**What it sent** is the person's alone: `GET /delegation/handled` lists the last 7 days (who, subject, the reply, the questions it left them and a link to the thread in their mailbox), and the Settings card shows it under the switch with how many went today.\n\n### Take the lead as you\n\nOn Settings → Act as me, Handle it for me is one dial: **Off**, **Easy ones**, **People I know**, **Most mail** and, for the owner, **Everything**, which uses **Take the lead** (`PUT /delegation/take-the-lead`, one row `person:<id>` in `take_the_lead`; turning it on turns Handle it for me on). While it is on, `handle_it.refusal` drops the setting's limits: strangers, the classifier's confidence, amounts, and the length up to a 4000-character ceiling. A reply with a link still waits for a tap (refusal `link`). In their place it checks the company's and the person's own added rules (`take_the_lead.reply_hit`, refusal `lead_rule`). Everything Handle it always keeps still holds: signed sign-ins, an authenticated sender, a reply kind, exactly the thread's people, the topics that always wait, draft flags, never twice in a row, one a thread a day and the daily limit. Follow-ups under it may go to anyone the person wrote to, with the same sensitive, amount, link and length checks plus the added rules. `reply_send.send_on_its_own` accepts the card while both switches are on. Each person adds and removes their own rules (`/delegation/take-the-lead/rules`). Removing one needs a caller the API can tie to them.\n\n\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. Settings → Delegate → Act as me shows the card (**Replies sent from your mailbox**), 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. 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 may do\n\n**Delegate → What it may do** (`delegation.may_do`, `GET /what-it-may-do`) is read-only: one row per thing that can go out without asking, what happens to it (goes out, waits for someone, always waits, drafts only, off) and which setting decides it, with a link there. It is the first Delegate tab, and `/delegate` opens on it. 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 dial (`ReachCard`, on both the Act as me and Handle it for me tabs) replaces the switches that used to turn each other off out of sight. 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). The first three are grouped as \"Writes as you, never sends\"; the rest as \"Handle it for me sends as you\". `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. **In training** (Replies and Follow-ups together, with **Train follow-ups too** to split them) sits under the dial at the sending steps, and **Learn from my edits** (drafts training) beside it; the dial never 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**, the **How far it goes as you** dial (below), the **Your inbox** status card while the inbox watcher is on (its status in plain words, when it last checked and **Check now**), and **How I write**: length and tone, a greeting per audience (`{first}` is their first name), the sign-off, habits and never-rules in fields that grow to show every line, the signature with **Refresh from Gmail** and **Don't add my signature** (or **Add my Gmail signature** when none is added; on Outlook only **Don't add my signature**, with why), and each example quoted with **Remove examples**. The owner also gets **Let team members use it** where the install allows it, with each team member who has it on listed by name and counts only.\n- **Today → Replies waiting** (`RepliesWaiting`, the top of the left column; hidden unless `GET /delegation/replies` answers with cards): each card shows who wrote and who they are to you, whether their address was verified, the subject, **They wrote** as plain text, your draft, **Decide before sending** (the open questions) and its warnings, with **Send** (a confirm naming who it goes to, and a second one when that or the thread changed), **Edit** (a text box on the card with Save and Cancel), **Open in Gmail** or **Open in Outlook** when the reply is in their Drafts, and **Dismiss**.\n- **Setup status**: a **Your own mailbox (Act as me)** light (`your_gmail`), amber while the inbox watcher can't reach the mailbox, is being rate-limited or has 25 replies waiting.\n- **Delegate** (main menu): **What it may do** (above, where `/delegate` lands), **Act as me** (where `/settings/act-as-me` lands), **Handle it for me** (the same dial, then **What it sent**: your rules at Everything, 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.",
"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-14T13:07:16Z"
+ "generated_at": "2026-10-14T00:00:00Z"
}
diff --git a/packages/core/openexecutive/delegation/may_do.py b/packages/core/openexecutive/delegation/may_do.py
new file mode 100644
index 00000000..f3a56fb7
--- /dev/null
+++ b/packages/core/openexecutive/delegation/may_do.py
@@ -0,0 +1,565 @@
+"""What it may do: everything that goes out without asking, and why.
+
+Delegate → What it may do is read-only. It answers one question for the
+person looking at it: what will the Executive send or change without asking
+anyone, who does it go out as, and which setting allows it. Every answer is
+read from the same code the gates use, so the page can't say something the
+gates don't do:
+
+- **As you** (the caller's own, ``can_delegate``): Write drafts as me
+ (``settings.is_enabled``), Draft replies to my inbox (``inbox.get_watch``),
+ Handle it for me and its level (``handle_it.get``, ``handle_it.RULES``),
+ Everything (``handle_it.leading``, Take the lead as you), what each
+ setting has in training and what it has learned (``training``), and the
+ person's own rules (``take_the_lead.list_rules``). The checks in
+ ``handle_it.refusal`` and ``follow_up_refusal`` are the source of each row.
+- **As the Executive** (the principal's alone, as ``GET /take-the-lead``
+ is): the switch and its training (``take_the_lead.get``), each Ask first
+ kind (``Lead.asks_first``), the company's rules, and meetings. A meeting the
+ Executive books on its own always waits: both meeting gates need someone on
+ a verified surface in the turn (``calendar_tools._asked_on_a_verified_surface``,
+ ``_solo_meeting_gate``), and an unattended run never is.
+- **Departments**: each department's authority level (``departments.registry``),
+ and what that level covers (``departments.authority.gate_action``'s
+ callers: department-scoped scheduled work, check-ins, alert review, team
+ members' chat sends in ``orchestrator.department_gate`` and, in a team
+ workspace, a meeting someone asks for in chat). Not what the Executive does
+ under Take the lead: its gate reads no department.
+
+The page also says when one setting rides on another (``notes``), when the
+Executive is paused (``scheduler.pause``), and when nothing can be sent as
+anyone because this server can't tie a switch to a person
+(``handle_it.signing_ok``).
+
+Nothing here writes, and nothing here reads anyone's mail.
+"""
+from __future__ import annotations
+
+import logging
+from dataclasses import dataclass, field
+from typing import Literal
+
+logger = logging.getLogger(__name__)
+
+Outcome = Literal["goes", "waits", "always_waits", "drafts", "off"]
+
+# Where each row's setting lives: the UI turns these into links.
+SETTING_ACT_AS_ME = "act_as_me"
+SETTING_HANDLE_IT = "handle_it"
+SETTING_TAKE_THE_LEAD = "take_the_lead"
+SETTING_PAUSE = "pause"
+SETTING_NONE = ""
+_DEPARTMENT_PREFIX = "department:"
+
+SECTION_AS_YOU = "as_you"
+SECTION_EXECUTIVE = "executive"
+SECTION_DEPARTMENTS = "departments"
+
+# Handle it's levels, by the names on its card (``HandleItCard.tsx``).
+LEVEL_NAMES: dict[str, str] = {
+ "careful": "Easy ones",
+ "balanced": "People I know",
+ "bold": "Most mail",
+ "lead": "Everything",
+}
+
+# The words for each department level, as the department page shows them.
+DEPARTMENT_LEVEL_NAMES: dict[str, str] = {
+ "auto_execute": "Acts on its own",
+ "propose_only": "Proposes, you approve",
+ "escalate": "Escalates to a person",
+}
+
+
+def department_setting(slug: str) -> str:
+ return f"{_DEPARTMENT_PREFIX}{slug}"
+
+
+@dataclass(frozen=True)
+class Row:
+ """One thing that can go out, what happens to it, and why."""
+
+ id: str
+ what: str
+ outcome: Outcome
+ # The outcome in a few words: "Goes out", "Waits for you".
+ then: str
+ # Which setting decides it, in a sentence.
+ why: str
+ # Where that setting lives (``SETTING_*``, or ``department:<slug>``).
+ setting: str = SETTING_NONE
+ # Things the row lists: the rules that hold it, say.
+ items: tuple[str, ...] = ()
+
+
+@dataclass(frozen=True)
+class Section:
+ key: str
+ title: str
+ rows: list[Row] = field(default_factory=list)
+ # Sentences shown above the rows: one setting riding on another, a
+ # switch that is off for everyone here.
+ notes: list[str] = field(default_factory=list)
+ # A sentence shown under the rows.
+ footer: str = ""
+ # False when the viewer can't see this section; ``unavailable`` says why.
+ available: bool = True
+ unavailable: str = ""
+
+ @property
+ def goes(self) -> int:
+ """How many of its rows go out (or act) without asking."""
+ return sum(1 for r in self.rows if r.outcome == "goes")
+
+
+@dataclass(frozen=True)
+class MayDo:
+ paused: bool
+ sections: list[Section]
+
+
+# --------------------------------------------------------------------------- #
+# As you
+# --------------------------------------------------------------------------- #
+
+_SENSITIVE_WORDS = "money, contracts, legal, hiring, pay, the board, the press, health or passwords"
+
+
+def _plural(n: int, one: str, many: str | None = None) -> str:
+ return f"{n} {one if n == 1 else (many or one + 's')}"
+
+
+def as_you(person_id: int, *, can_have_it: bool, signing: bool, is_principal: bool = False) -> Section:
+ """What goes out as ``person_id``, from their own mailbox. The company's
+ rules are named only to the principal, as ``GET /take-the-lead`` does;
+ anyone else is told only how many there are."""
+ from openexecutive.delegation import handle_it, inbox, training
+ from openexecutive.delegation.settings import is_enabled
+ from openexecutive.orchestrator import take_the_lead
+
+ title = "As you, from your own mailbox"
+ if not can_have_it:
+ return Section(
+ SECTION_AS_YOU, title, available=False,
+ unavailable="Act as me isn't available to you here. The owner of this Open Executive can turn it on "
+ "for team members.",
+ )
+
+ drafts_on = is_enabled(person_id)
+ watching = drafts_on and inbox.get_watch(person_id).enabled
+ settings = handle_it.get(person_id)
+ handling = watching and settings.enabled
+ trained = training.get(person_id)
+ learned = training.learned(person_id)
+ allowed: dict[str, int] = {}
+ for a in learned:
+ setting = training.setting_of(a.key)
+ allowed[setting] = allowed.get(setting, 0) + 1
+ replies_trained = handling and trained.replies
+ follow_ups_trained = handling and trained.follow_ups
+ lead = handling and not trained.replies and handle_it.leading(person_id)
+ follow_lead = handling and not trained.follow_ups and handle_it.leading(person_id)
+ rules = handle_it.RULES.get(settings.mode, handle_it.RULES[handle_it.DEFAULT_MODE])
+ level = LEVEL_NAMES["lead" if lead else settings.mode]
+ sends = handling and signing
+
+ rows: list[Row] = []
+ notes: list[str] = []
+
+ # Emails it writes when asked in chat: always a draft.
+ rows.append(Row(
+ "chat_drafts", "Emails you ask it to write in chat",
+ "drafts" if drafts_on else "off",
+ "Drafts only" if drafts_on else "Off",
+ "Write drafts as me is on. They wait in your Drafts; it never sends them."
+ if drafts_on else "Write drafts as me is off: it only ever writes as itself.",
+ SETTING_ACT_AS_ME,
+ ))
+
+ def reply_row(row_id: str, what: str, stranger: bool) -> Row:
+ if not watching:
+ why = (
+ "Draft replies to my inbox is off." if drafts_on
+ else "Write drafts as me is off, and the inbox replies need it."
+ )
+ return Row(row_id, what, "off", "Off", why, SETTING_ACT_AS_ME)
+ if not settings.enabled:
+ return Row(
+ row_id, what, "waits", "Waits for you",
+ "Draft replies to my inbox puts each one on a card. Handle it for me is off, so you tap Send.",
+ SETTING_HANDLE_IT,
+ )
+ if not signing:
+ return Row(
+ row_id, what, "waits", "Waits for you",
+ "This server can't tie the switch to you (signed sign-ins are off), so nothing is sent as you.",
+ SETTING_HANDLE_IT,
+ )
+ if replies_trained:
+ n = allowed.get(training.REPLIES, 0)
+ return Row(
+ row_id, what, "waits", "Waits for you",
+ "Handle it for me is in training. Only replies to the "
+ + (_plural(n, "sender") + " you allowed with Send + allow" if n else "senders you allow with Send + allow")
+ + " go on their own.",
+ SETTING_HANDLE_IT,
+ )
+ if lead:
+ return Row(
+ row_id, what, "goes", "Goes out",
+ "Handle it for me is set to Everything: it decides, within the limits below.",
+ SETTING_HANDLE_IT,
+ )
+ if stranger and not rules.strangers:
+ return Row(
+ row_id, what, "waits", "Waits for you",
+ f"Handle it for me is set to {level}. Most mail or Everything would send these.",
+ SETTING_HANDLE_IT,
+ )
+ if settings.mode == handle_it.MODE_CAREFUL:
+ why = f"Handle it for me is set to {level}: only short ones, when it's very sure."
+ else:
+ why = f"Handle it for me is set to {level}, when it's sure the email needs only a simple reply."
+ return Row(row_id, what, "goes", "Goes out", why, SETTING_HANDLE_IT)
+
+ rows.append(reply_row("replies_known", "Replies to people you know", stranger=False))
+ rows.append(reply_row("replies_strangers", "Replies to people you don't know yet", stranger=True))
+
+ # Follow-ups on their own unanswered emails.
+ what = "Follow-ups on your emails that went unanswered"
+ if not handling:
+ rows.append(Row(
+ "follow_ups", what, "off" if not watching else "waits",
+ "Off" if not watching else "Waits for you",
+ "Draft replies to my inbox is off." if not watching
+ else "Handle it for me is off, so a follow-up waits for you to send it.",
+ SETTING_HANDLE_IT if watching else SETTING_ACT_AS_ME,
+ ))
+ elif not signing:
+ rows.append(Row(
+ "follow_ups", what, "waits", "Waits for you",
+ "Signed sign-ins are off on this server, so nothing is sent as you.", SETTING_HANDLE_IT,
+ ))
+ elif follow_ups_trained:
+ n = allowed.get(training.FOLLOW_UPS, 0)
+ rows.append(Row(
+ "follow_ups", what, "waits", "Waits for you",
+ "Follow-ups are in training. Only follow-ups to "
+ + (_plural(n, "group") + " of people you allowed" if n else "people you allow with Send + allow")
+ + " go on their own.",
+ SETTING_HANDLE_IT,
+ ))
+ elif follow_lead:
+ rows.append(Row(
+ "follow_ups", what, "goes", "Goes out",
+ "Handle it for me is set to Everything.", SETTING_HANDLE_IT,
+ ))
+ elif not rules.follow_up_to:
+ rows.append(Row(
+ "follow_ups", what, "waits", "Waits for you",
+ f"Handle it for me is set to {level}: it writes them and you send them.", SETTING_HANDLE_IT,
+ ))
+ else:
+ who = "your team, your contacts and anyone you've written to" if "correspondent" in rules.follow_up_to \
+ else "your team and your contacts"
+ rows.append(Row(
+ "follow_ups", what, "goes", "Goes out",
+ f"Handle it for me is set to {level}: follow-ups to {who}.", SETTING_HANDLE_IT,
+ ))
+
+ # Links and amounts.
+ if sends and not replies_trained:
+ if lead:
+ rows.append(Row(
+ "links", "A reply with a link in it", "waits", "Waits for you",
+ "Always at Everything: sent as you, a link is the shape a phishing email takes.",
+ SETTING_HANDLE_IT,
+ ))
+ elif rules.details_confidence is not None:
+ rows.append(Row(
+ "links", "A reply with a link or an amount in it", "goes", "Goes out",
+ f"Handle it for me is set to {level}, when it's very sure.", SETTING_HANDLE_IT,
+ ))
+ else:
+ rows.append(Row(
+ "links", "A reply with a link or an amount in it", "waits", "Waits for you",
+ f"Handle it for me is set to {level}. Most mail sends these when it's very sure.",
+ SETTING_HANDLE_IT,
+ ))
+
+ # The topics that always wait.
+ if sends:
+ rows.append(Row(
+ "sensitive", f"Anything about {_SENSITIVE_WORDS}", "always_waits", "Always waits",
+ "Can't be turned off. It also never writes to anyone the email didn't go to.",
+ ))
+
+ # Their own rules, which hold only at Everything.
+ if lead or follow_lead:
+ try:
+ own = take_the_lead.list_rules([take_the_lead.person_scope(person_id)])
+ company = take_the_lead.list_rules([take_the_lead.SCOPE_COMPANY])
+ except Exception:
+ logger.warning("may_do: couldn't read the rules", exc_info=True)
+ own, company = [], []
+ if own or company:
+ shown = [*own, *company] if is_principal else own
+ why = "Your rules and your company's always hold at Everything."
+ if company and not is_principal:
+ why += f" Your company has {_plural(len(company), 'rule')}; the owner can see them."
+ rows.append(Row(
+ "rules", "Replies matching your rules or your company's", "always_waits", "Waits for you",
+ why, SETTING_HANDLE_IT,
+ items=tuple(_rule_label(r.kind, r.value) for r in shown),
+ ))
+
+ # Messages and meetings it suggests from their mail.
+ if drafts_on:
+ if trained.actions:
+ n = allowed.get(training.ACTIONS, 0)
+ why = (
+ "Suggested actions are in training. "
+ + (f"The {_plural(n, 'kind')} you allowed with Approve + allow happen on their own."
+ if n else "What you allow with Approve + allow happens on its own next time.")
+ )
+ rows.append(Row(
+ "actions", "Messages and meetings it suggests from your mail",
+ "goes" if n and signing else "waits", "Goes out when allowed" if n and signing else "Waits for you",
+ why, SETTING_ACT_AS_ME,
+ ))
+ else:
+ rows.append(Row(
+ "actions", "Messages and meetings it suggests from your mail", "waits", "Waits for you",
+ "Suggested actions are set to Always ask.", SETTING_ACT_AS_ME,
+ ))
+
+ if lead or follow_lead:
+ notes.append(
+ "Handle it for me is set to Everything, which uses Take the lead as you. It rides on Draft replies "
+ "to my inbox and Write drafts as me: turning either off, or putting Handle it for me in training, "
+ "turns Everything off too."
+ )
+ elif handling:
+ notes.append(
+ "Handle it for me rides on Draft replies to my inbox and Write drafts as me: turning either off "
+ "turns Handle it for me off too."
+ )
+ if handling and not signing:
+ notes.append(
+ "Signed sign-ins are off on this server, so nothing is sent as you until they're on."
+ )
+
+ footer = ""
+ if sends:
+ try:
+ from openexecutive.config import get_settings
+
+ cap = int(get_settings().delegation_handle_it_max_sends_per_day)
+ footer = f"At most {_plural(cap, 'reply', 'replies')} a day go out on their own, and one a conversation."
+ except Exception:
+ footer = ""
+ return Section(SECTION_AS_YOU, title, rows=rows, notes=notes, footer=footer)
+
+
+def _rule_label(kind: str, value: str) -> str:
+ from openexecutive.orchestrator import take_the_lead
+
+ if kind == take_the_lead.RULE_DOMAIN:
+ return f"Anyone at {value}"
+ if kind == take_the_lead.RULE_WORDS:
+ return f"Words: {value}"
+ if kind == take_the_lead.RULE_AMOUNT:
+ return f"Amounts of {value} or more"
+ return value
+
+
+# --------------------------------------------------------------------------- #
+# As the Executive
+# --------------------------------------------------------------------------- #
+
+
+def as_the_executive(*, is_principal: bool) -> Section:
+ """What the Executive does in its own name, under Take the lead."""
+ from openexecutive.orchestrator import take_the_lead
+
+ title = "As the Executive, on its own"
+ if not is_principal:
+ return Section(
+ SECTION_EXECUTIVE, title, available=False,
+ unavailable="Only the account owner sees what the Executive does on its own.",
+ )
+ lead = take_the_lead.get(take_the_lead.SCOPE_EXECUTIVE)
+ try:
+ rules = take_the_lead.list_rules([take_the_lead.SCOPE_COMPANY])
+ learned = take_the_lead.list_allowed(feature=take_the_lead.FEATURE)
+ except Exception:
+ logger.warning("may_do: couldn't read Take the lead's rules", exc_info=True)
+ rules, learned = [], []
+
+ rows: list[Row] = []
+ if not lead.enabled:
+ rows.append(Row(
+ "lead", "Messages, bookings and workflows it thinks of on its own", "off", "Off",
+ "Take the lead is off. When it looks over your day it tells you what it would do, and you do it.",
+ SETTING_TAKE_THE_LEAD,
+ ))
+ return Section(SECTION_EXECUTIVE, title, rows=rows)
+
+ if lead.training:
+ n = len(learned)
+ rows.append(Row(
+ "lead", "Messages, bookings and workflows it thinks of on its own",
+ "goes" if n else "waits", "Goes out when allowed" if n else "Waits for you",
+ "Take the lead is in training: everything comes to you first. "
+ + (f"The {_plural(n, 'thing')} you allowed happen on their own." if n
+ else "Approve + allow on a card lets that action happen on its own next time."),
+ SETTING_TAKE_THE_LEAD,
+ ))
+ else:
+ rows.append(Row(
+ "lead", "Messages to your team, and workflows it starts", "goes", "Goes out",
+ "Take the lead is on. Each step a workflow sends is checked again.", SETTING_TAKE_THE_LEAD,
+ ))
+
+ rows.append(Row(
+ "to_you", "Messages only to you", "goes", "Goes out",
+ "Always: you are who it would ask.", SETTING_NONE,
+ ))
+
+ for kind in take_the_lead.KINDS:
+ label = take_the_lead.KIND_LABELS[kind]
+ hint = take_the_lead.KIND_HINTS[kind]
+ if lead.asks_first(kind):
+ rows.append(Row(
+ f"kind:{kind}", hint, "waits", "Waits for its approver",
+ f"Always asks first: {label}. It goes to whoever approves that area on People, else you.",
+ SETTING_TAKE_THE_LEAD,
+ ))
+ elif lead.training:
+ rows.append(Row(
+ f"kind:{kind}", hint, "waits", "Waits unless allowed",
+ f"Always asks first: {label} is off, and Take the lead is in training.", SETTING_TAKE_THE_LEAD,
+ ))
+ else:
+ rows.append(Row(
+ f"kind:{kind}", hint, "goes", "Goes out",
+ f"Always asks first: {label} is off.", SETTING_TAKE_THE_LEAD,
+ ))
+
+ rows.append(Row(
+ "meetings", "Booking a meeting it thought of", "always_waits", "Waits for its approver",
+ "Always. Always asks first: Meetings asked for in chat covers only meetings someone asks for in chat, "
+ "and it never cancels a meeting on its own.",
+ SETTING_TAKE_THE_LEAD,
+ ))
+
+ if rules:
+ rows.append(Row(
+ "rules", "Anything matching your company's rules", "always_waits", "Waits for you",
+ "Company rules always hold.", SETTING_TAKE_THE_LEAD,
+ items=tuple(_rule_label(r.kind, r.value) for r in rules),
+ ))
+
+ rows.append(_meetings_in_chat())
+ return Section(
+ SECTION_EXECUTIVE, title, rows=rows,
+ footer="Department levels don't hold what it does here. Always asks first and the company's rules do.",
+ )
+
+
+def _meetings_in_chat() -> Row:
+ """A meeting someone on the team asks for in chat: the class mode, and in
+ a team workspace the Operations department's level as well
+ (``calendar_tools.handle_create_calendar_event``)."""
+ from openexecutive.memory.decision_ledger import get_class_mode
+ from openexecutive.memory.workspace_settings import get_workspace
+
+ what = "A meeting you or a teammate ask it to book in chat"
+ try:
+ class_mode = get_class_mode("meeting_scheduling")
+ except Exception:
+ class_mode = "propose"
+ if class_mode != "auto_execute":
+ return Row(
+ "meetings_chat", what, "waits", "Waits for its approver",
+ "Always asks first: Meetings asked for in chat is on.", SETTING_TAKE_THE_LEAD,
+ )
+ if get_workspace().mode == "solo":
+ return Row(
+ "meetings_chat", what, "goes", "Books it",
+ "Always asks first: Meetings asked for in chat is off, so when you ask, it books.", SETTING_TAKE_THE_LEAD,
+ )
+ from openexecutive.departments import registry as dept_registry
+
+ ops = dept_registry.get_state("operations")
+ level = str(ops.config.authority_level) if ops is not None else "propose_only"
+ if level == "auto_execute":
+ return Row(
+ "meetings_chat", what, "goes", "Books it",
+ "Meetings asked for in chat is off in Always asks first, and Operations acts on its own.", department_setting("operations"),
+ )
+ return Row(
+ "meetings_chat", what, "waits", "Waits for its approver",
+ "Meetings asked for in chat is off in Always asks first, but Operations isn't set to Acts on its own.",
+ department_setting("operations"),
+ )
+
+
+# --------------------------------------------------------------------------- #
+# Departments
+# --------------------------------------------------------------------------- #
+
+
+def departments() -> Section:
+ from openexecutive.departments import registry as dept_registry
+ from openexecutive.memory.workspace_settings import get_workspace
+
+ title = "For each department"
+ try:
+ states = dept_registry.list_states()
+ except Exception:
+ logger.warning("may_do: couldn't read the departments", exc_info=True)
+ states = []
+ rows: list[Row] = []
+ for state in states:
+ level = str(state.config.authority_level)
+ outcome: Outcome = "goes" if level == "auto_execute" else "waits"
+ then = {
+ "auto_execute": "Acts on its own",
+ "propose_only": "Waits for its approver",
+ "escalate": "Waits, marked urgent",
+ }.get(level, "Waits for its approver")
+ rows.append(Row(
+ f"department:{state.config.slug}", state.config.title, outcome, then,
+ f"Set to {DEPARTMENT_LEVEL_NAMES.get(level, level)}.", department_setting(state.config.slug),
+ ))
+ solo = get_workspace().mode == "solo"
+ footer = (
+ "A level covers that department's scheduled messages and alerts"
+ + (". Check-ins don't run in a personal workspace" if solo else ", its check-ins, and what its team members ask for in chat")
+ + ". It doesn't cover what the Executive does on its own under Take the lead."
+ )
+ return Section(SECTION_DEPARTMENTS, title, rows=rows, footer=footer)
+
+
+# --------------------------------------------------------------------------- #
+# All of it
+# --------------------------------------------------------------------------- #
+
+
+def summary(person_id: int | None, *, can_have_it: bool, is_principal: bool) -> MayDo:
+ """The whole page for one viewer."""
+ from openexecutive.delegation.handle_it import signing_ok
+ from openexecutive.scheduler.pause import is_paused
+
+ try:
+ paused = is_paused()
+ except Exception:
+ paused = True
+ signing = signing_ok()
+ you = (
+ as_you(person_id, can_have_it=can_have_it, signing=signing, is_principal=is_principal)
+ if person_id is not None
+ else as_you(0, can_have_it=False, signing=signing)
+ )
+ return MayDo(paused=paused, sections=[you, as_the_executive(is_principal=is_principal), departments()])
diff --git a/packages/core/openexecutive/guide/prebuilt/departments.json b/packages/core/openexecutive/guide/prebuilt/departments.json
index 9c6c072a..465db644 100644
--- a/packages/core/openexecutive/guide/prebuilt/departments.json
+++ b/packages/core/openexecutive/guide/prebuilt/departments.json
@@ -1,7 +1,7 @@
{
"section_id": "departments",
"title": "Departments",
- "markdown": "**What it is:** The org units the Executive works through. Each department has goals, an authority level, a head, and a specialist agent behind it.\n\n**What it does:**\n\n- View every department with its goal count and health (on-track / at-risk / off-track).\n- Create departments and give them a mission, goals, budget, and headcount.\n- Set the **authority level** — act automatically, propose for approval, or always escalate.\n- Wire up a head person and team channels (Slack, Discord, Telegram).\n\n**How to use:**\n\n1. Open **Company** in the sidebar, pick the **Departments** tab, and click **Add department**. Enter a **Name** (and, optionally, a mission) and click **Create**. New departments start at *Proposes, you approve*.\n2. Open the department and click **Edit settings**. The settings open in a side panel, split into tabs (**Charter**, **How it acts**, **Numbers**, **Channels**, **Watched**):\n - **Department head** — the person who owns it.\n - **Authority level** — **Acts on its own**, **Proposes, you approve**, or **Escalates to a human**.\n - **Recurring check-in** — when the department reviews its goals: **Daily** (pick a time), **Weekly** (pick a day and a time) or **Off**. New departments check in weekly, on Monday at 09:00; times are UTC. The department page shows when the next check-in is due, and a change takes effect straight away.\n - **Headcount** and **Budget (USD)**.\n - **Team channels** — a Slack channel ID, Discord channel ID or Telegram chat ID. Leave them blank and messages go to the department head by DM.\n - **Watched entities** — one per line.\n\n Then click **Save settings**.\n3. Click **Add goal**: pick a timeframe (week, month, quarter, year, or ongoing), enter the **Key result** and **Target** (and current progress if you know it), set a status, and click **Add goal**. Each goal's **⋯** menu has **Edit goal** and **Delete goal**.\n4. Keep goals current by just telling the Executive what happened — it updates the matching goal and records why.\n5. Set a new goal the same way: tell the Executive the target, and it adds the goal under the right department (or area), creating that department if you don't have one yet. Only the owner can do this, from the web app or their own Slack or Discord — a teammate, or an email, can't. It adds one goal for each target you actually give it (at most 8 per department this way) — ask it to \"set up some goals\" and it asks you which ones.\n\n**Examples from chat:** *\"We closed 40% of the Q3 ARR target.\"* · *\"We lost the Acme deal.\"* · *\"New Sales goal: 20 paying customers by December 31.\"* · *\"Make Sarah the head of Marketing.\"*\n\n**Goals page:** the **Goals** tab of **Company** (of **You** when you use Open Executive just for yourself) lists every goal in one place, grouped by department — called an **area** when it's just you. Each goal shows its status, timeframe, target and where it stands now, with **Edit goal** and **Delete goal** in its **⋯** menu. Click **Add goal**, pick the department (or **Area**) it belongs to, and fill it in as above; ones with no goals yet are listed at the bottom so you can start one there.\n\n**Just for yourself?** In that mode department check-ins are paused and **Company** becomes **You**, with **Goals** and no **Departments** tab. The departments are still there — open `/departments` to rename an area or change its settings.\n\n*Note: the authority level is what decides whether the Executive acts on its own or asks first within that department's scope.*",
+ "markdown": "**What it is:** The org units the Executive works through. Each department has goals, an authority level, a head, and a specialist agent behind it.\n\n**What it does:**\n\n- View every department with its goal count and health (on-track / at-risk / off-track).\n- Create departments and give them a mission, goals, budget, and headcount.\n- Set the **authority level** — act automatically, propose for approval, or always escalate.\n- Wire up a head person and team channels (Slack, Discord, Telegram).\n\n**How to use:**\n\n1. Open **Company** in the sidebar, pick the **Departments** tab, and click **Add department**. Enter a **Name** (and, optionally, a mission) and click **Create**. New departments start at *Proposes, you approve*.\n2. Open the department and click **Edit settings**. The settings open in a side panel, split into tabs (**Charter**, **How it acts**, **Numbers**, **Channels**, **Watched**):\n - **Department head** — the person who owns it.\n - **Authority level** — **Acts on its own**, **Proposes, you approve**, or **Escalates to a person**.\n - **Recurring check-in** — when the department reviews its goals: **Daily** (pick a time), **Weekly** (pick a day and a time) or **Off**. New departments check in weekly, on Monday at 09:00; times are UTC. The department page shows when the next check-in is due, and a change takes effect straight away.\n - **Headcount** and **Budget (USD)**.\n - **Team channels** — a Slack channel ID, Discord channel ID or Telegram chat ID. Leave them blank and messages go to the department head by DM.\n - **Watched entities** — one per line.\n\n Then click **Save settings**.\n3. Click **Add goal**: pick a timeframe (week, month, quarter, year, or ongoing), enter the **Key result** and **Target** (and current progress if you know it), set a status, and click **Add goal**. Each goal's **⋯** menu has **Edit goal** and **Delete goal**.\n4. Keep goals current by just telling the Executive what happened — it updates the matching goal and records why.\n5. Set a new goal the same way: tell the Executive the target, and it adds the goal under the right department (or area), creating that department if you don't have one yet. Only the owner can do this, from the web app or their own Slack or Discord — a teammate, or an email, can't. It adds one goal for each target you actually give it (at most 8 per department this way) — ask it to \"set up some goals\" and it asks you which ones.\n\n**Examples from chat:** *\"We closed 40% of the Q3 ARR target.\"* · *\"We lost the Acme deal.\"* · *\"New Sales goal: 20 paying customers by December 31.\"* · *\"Make Sarah the head of Marketing.\"*\n\n**Goals page:** the **Goals** tab of **Company** (of **You** when you use Open Executive just for yourself) lists every goal in one place, grouped by department — called an **area** when it's just you. Each goal shows its status, timeframe, target and where it stands now, with **Edit goal** and **Delete goal** in its **⋯** menu. Click **Add goal**, pick the department (or **Area**) it belongs to, and fill it in as above; ones with no goals yet are listed at the bottom so you can start one there.\n\n**Just for yourself?** In that mode department check-ins are paused and **Company** becomes **You**, with **Goals** and no **Departments** tab. The departments are still there — open `/departments` to rename an area or change its settings.\n\n*Note: the authority level is what decides whether the Executive acts on its own or asks first within that department's scope.*",
"mermaid": null,
"generated_at": "2026-10-03T12:00:00Z"
}
diff --git a/packages/core/openexecutive/guide/prebuilt/settings.json b/packages/core/openexecutive/guide/prebuilt/settings.json
index eb8a3cd8..1b57b7c3 100644
--- a/packages/core/openexecutive/guide/prebuilt/settings.json
+++ b/packages/core/openexecutive/guide/prebuilt/settings.json
@@ -1,7 +1,7 @@
{
"section_id": "settings",
"title": "Settings & Advanced",
- "markdown": "**What it is:** The settings that live outside the day-to-day nav: whether the Executive is running and how it sounds, who Open Executive is for, letting it write email as you, and the admin and power-user tools.\n\n**What it does:**\n\n- Opens on a page of tiles, one per settings page — **Your Executive**, **Workspace**, **Advanced** and **About**. Each tile says what's on its page and, where it can, how things stand now (running or paused, the voice, just you or your team, a newer version). Click a tile to open its page; the **Settings** link at the top of each page takes you back. Old links to a section (such as `/settings#workspace`) land on the matching page. **Act as me**, **Handle it for me** and **Take the lead** are not in Settings: they are the three tabs of **Delegate** in the main menu.\n- **Your Executive** shows whether the Executive is **running** or **paused**, with one button: **Pause…** opens the pause form; while it is paused, who paused it, the held count and **Resume** stay in view. Below it, **Voice** picks the voice the Executive answers you in.\n- **Workspace** holds, one card each: whether Open Executive is personal or for your team, your role when it's just you, your time zone, and whether the Executive books meetings without asking. **Company email domains** sits under **Advanced** at the bottom.\n- **Act as me** (a tab of **Delegate** in the main menu) lets you have the Executive write email drafts as you, in your own voice, from your own Gmail — when you ask, and, if you turn it on, for mail in your inbox that needs you, which you can send from Home with one tap. Your mailbox and the two switches are up front; **How I write** (and, for the owner, **Let team members use it**) sit under **Advanced** at the bottom.\n- **Advanced** lists the pages that open their own screen, grouped by what you'd use them for: **Check & diagnose** (Setup status, Audit log, Token usage), **Configure** (Agent Council, Company Simulator, Client Companies) and **Learn** (User Guide, Architecture).\n- **About** shows the version this install runs, and whether a newer one is out.\n\n**How to use:**\n\n1. Click **Settings** at the bottom of the sidebar. (On a phone, open the menu with the button at the top left; Settings is at its bottom.)\n2. Click a tile to open that page.\n3. On **Advanced**, click a row to open that page:\n - **Setup status** — check that every part of your setup is working, and see what to do about anything that isn't.\n - **Agent Council** — change a specialist's model or prompt, or the Executive's voice.\n - **Audit log** — find out what the Executive did, and why.\n - **Token usage** — see what you're spending and where.\n - **User Guide** — this guide.\n - **Architecture** — the technical reference for how the system is built.\n - **Company Simulator** — try the Executive on a test company.\n - **Client Companies** — switch between clients if you do fractional work.\n\n**Checking your setup:**\n\n- Open **Settings → Advanced → Setup status**. Each part of your setup gets a light: green is working, amber needs attention, red isn't working, grey isn't set up (and is optional).\n- It tests things for real: the AI key, and each chat app's token, with a quick call that sends nothing. It also checks the Executive's email address, the company setup, the daily schedule, when and where your daily brief goes, and whether anyone on your team list can reach each chat app.\n- Anything that isn't green says what to do in plain words, with a button when the fix is on another page. After you change a setting and restart the app, click **Check again**.\n\n**Workspace:**\n\n- **Using Open Executive** — **Personal** or **Team**. You pick this when you first set up; change it here. Switching asks you to confirm and says what changes:\n - **Personal** pauses department check-ins and renames **Company** in the sidebar to **You**, with **Goals** (grouped by area), **People** and your profile — there is no Departments tab. Nothing is deleted — your departments stay, as the areas your goals are grouped by.\n - **Team** brings back **Company** with its **Departments** tab and their daily check-ins, and the People and Departments tiles on Home.\n- **Your role** (just you) — which describes you best (**Owner / founder**, **Executive inside an organisation**, **Independent or fractional**, or **Other**), your title, who you report to, what you're responsible for and what you're measured on. Every field is optional; click **Save role** after editing. The Executive uses it to fit its advice to your job — a VP gets help making the case to their boss, an owner gets help with a call that's theirs alone to make. It stays saved if you switch to your team.\n- **Time zone** — when your morning brief, end-of-day digest and reflection arrive, and how the Executive reads \"tomorrow at 9\". It suggests the zone your browser is in; **Follow server default** uses the server's setting.\n- **Book meetings without asking** — when on, the Executive books meetings on your calendar on its own; when off, each booking waits for your approval on Home. (Shown only when your install supports it.)\n- **Company email domains** (under **Advanced**, principal only) — mail from these domains matches a teammate by the part before the @, and a new address there is filled in as a teammate when someone writes in. It follows your own address unless you set it here.\n- Only the principal can change the mode, role and time zone. A persona you customised in Council stays in place in either mode.\n\n**Act as me (Delegate → Act as me):**\n\n- Normally the Executive writes only as itself, from its own email account. **Act as me** lets it write an email *as you*: ask in chat — \"reply to Dana as me: yes to the 5th\" — and it saves a draft in **your own Gmail Drafts** for you to read, change and send. Asking in chat never sends anything, and everything else it writes stays in its own name.\n- The owner sees this page, and so does each team member once the owner turns on **Let team members use it** under **Advanced** at the bottom of it (shown only where your install allows it). Each team member connects their own Gmail and turns it on for themselves. What it reads in their mail, the drafts it writes and their **Replies waiting** are theirs alone: the owner sees only who uses it and how many drafts and sends it made, and a conversation in which it read someone's mail can be opened only by that person. Turning the owner's switch off takes it away from the team from their next message. It works when you ask in the web app, in a direct message to the Executive on Slack or Discord, or in a verified private Telegram chat — never in a shared channel or thread, from an email, a scheduled job or anyone else's conversation.\n- **Your Gmail** — connect your own Gmail first. The page shows the command to run on a computer with a browser; sign in as yourself, put the file it writes where your install reads it, then click **Check again**. It won't connect the Executive's own address as yours.\n- **Write drafts as me** — the switch. It stays off until your Gmail is connected, and turning it off applies from your next message.\n- **Draft replies to my inbox** — a second switch, once **Write drafts as me** is on. Every few minutes the Executive looks at new mail in your inbox, and 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 in your Gmail Drafts and puts it at the top of **Needs you** on Home. Nothing is sent until you tap **Send** there. It only looks at mail that arrives after you turn it on, and leaves out newsletters, notifications, mailing lists, mail you've already answered and anything that doesn't need you; mail you answer within ten minutes never gets a draft. 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. Someone you've never written to gets a short holding reply. The line under the switch says how it's doing (for example, that your Gmail needs connecting again) and when it last looked; click **Check now** to look straight away. Turning **Write drafts as me** off turns this off too.\n- **How I write** (under **Advanced**) — click **Learn from my sent mail** and it reads your recent sent emails once and describes how you write (click **Edit how I write** to open the fields): your usual **Length** and **Tone**, a **Greeting** for your team, your contacts and anyone else ({first} stands for their first name), your **Sign-off**, your **Habits**, what you **Never** do, and a few **Examples of your writing** that set the tone. Change any of them and click **Save changes**; **Lock** stops it being relearned from your mail (you can still edit it); **Reset** starts over; **Remove examples** drops the examples. Your Gmail signature is added to every draft: **Refresh from Gmail** picks up a change you made to it in Gmail, **Don't add my signature** stops adding it, and **Add my Gmail signature** brings it back.\n- In chat you get a card, \"Drafted an email as you to …\", that opens the draft in Gmail. If the Executive isn't sure about something, it asks you instead of guessing.\n\n**Setting up just for yourself:**\n\n- The first time you set up, Open Executive asks who it is for — **Personal** or **Team** — before anything else, and saves your time zone from the browser. Re-running setup later skips this; change the mode here instead. Either way you can add teammates later from **People**.\n- **Personal** is for anyone who uses Open Executive just for themselves, whatever their role: your own business, a team you lead inside an organisation, or clients you advise as an independent or fractional executive.\n- Choosing **Personal** then asks **What's your role?** — the same fields as **Your role** above. Fill in what you like, or click **Skip for now**.\n- Just for yourself, the setup conversation asks about your work rather than your team, following the role you gave: an owner about what you offer, your customers, pricing, cash and runway; an executive inside an organisation about that organisation (it becomes your company profile), what you're responsible for, who you report to and what you're measured on; an independent about your practice and clients. Everyone is asked about their goals. On **Here's what I understood** there is a single **You** card (your name and role) next to **Your sign-in email**, instead of the team and department lists.\n- The step-by-step form skips the team size, team members and fractional executives steps.\n- In the sidebar, **You** takes the place of **Company** and holds **Goals**, **People** and your profile: **Business profile** if you own the business, **Your work** for any other role (or none). The profile page follows the same choice: for any other role it is worded around the organisation you work in (**Where You Work** in place of Company Basics). Either way departments are listed there as **Areas**, and your title, who you report to and what you're responsible for stay under **Your role** above.\n\n**Pausing the Executive:**\n\n- Open **Settings → Your Executive** (or **Pause or resume the Executive** in the account menu — the **⋯** next to your name at the bottom of the sidebar) and click **Pause…**. Add a reason if you like, and click **Pause Executive**.\n- While paused, the Executive starts nothing on its own: no briefs, nudges, monitoring, inbox processing or workflow timers. An amber banner appears on every page.\n- Chat and direct messages (Slack, Telegram, Discord, Google Chat) still get answers.\n- Nothing is lost. Work that falls due during the pause waits, and runs when you click **Resume**. The switch shows how many actions are waiting.\n- Anyone who can sign in can pause the Executive, but only the principal can resume it.\n\n*Tip: if you're looking for a feature that isn't in the sidebar, it's probably under **Settings → Advanced**. This guide is also in the account menu (the **⋯** next to your name at the bottom of the sidebar), with **Pause or resume the Executive** and, when you signed in with an account, **Sign out**.*",
+ "markdown": "**What it is:** The settings that live outside the day-to-day nav: whether the Executive is running and how it sounds, who Open Executive is for, letting it write email as you, and the admin and power-user tools.\n\n**What it does:**\n\n- Opens on a page of tiles, one per settings page — **Your Executive**, **Workspace**, **Advanced** and **About**. Each tile says what's on its page and, where it can, how things stand now (running or paused, the voice, just you or your team, a newer version). Click a tile to open its page; the **Settings** link at the top of each page takes you back. Old links to a section (such as `/settings#workspace`) land on the matching page. **Act as me**, **Handle it for me** and **Take the lead** are not in Settings: they are tabs of **Delegate** in the main menu, after **What it may do**, which lists everything that goes out without asking you and the setting that allows it.\n- **Your Executive** shows whether the Executive is **running** or **paused**, with one button: **Pause…** opens the pause form; while it is paused, who paused it, the held count and **Resume** stay in view. Below it, **Voice** picks the voice the Executive answers you in.\n- **Workspace** holds, one card each: whether Open Executive is personal or for your team, your role when it's just you, and your time zone. **Company email domains** sits under **Advanced** at the bottom.\n- **Act as me** (a tab of **Delegate** in the main menu) lets you have the Executive write email drafts as you, in your own voice, from your own Gmail — when you ask, and, if you turn it on, for mail in your inbox that needs you, which you can send from Home with one tap. Your mailbox and **How far it goes as you** are up front; **How I write** (and, for the owner, **Let team members use it**) sit under **Advanced** at the bottom.\n- **Advanced** lists the pages that open their own screen, grouped by what you'd use them for: **Check & diagnose** (Setup status, Audit log, Token usage), **Configure** (Agent Council, Company Simulator, Client Companies) and **Learn** (User Guide, Architecture).\n- **About** shows the version this install runs, and whether a newer one is out.\n\n**How to use:**\n\n1. Click **Settings** at the bottom of the sidebar. (On a phone, open the menu with the button at the top left; Settings is at its bottom.)\n2. Click a tile to open that page.\n3. On **Advanced**, click a row to open that page:\n - **Setup status** — check that every part of your setup is working, and see what to do about anything that isn't.\n - **Agent Council** — change a specialist's model or prompt, or the Executive's voice.\n - **Audit log** — find out what the Executive did, and why.\n - **Token usage** — see what you're spending and where.\n - **User Guide** — this guide.\n - **Architecture** — the technical reference for how the system is built.\n - **Company Simulator** — try the Executive on a test company.\n - **Client Companies** — switch between clients if you do fractional work.\n\n**Checking your setup:**\n\n- Open **Settings → Advanced → Setup status**. Each part of your setup gets a light: green is working, amber needs attention, red isn't working, grey isn't set up (and is optional).\n- It tests things for real: the AI key, and each chat app's token, with a quick call that sends nothing. It also checks the Executive's email address, the company setup, the daily schedule, when and where your daily brief goes, and whether anyone on your team list can reach each chat app.\n- Anything that isn't green says what to do in plain words, with a button when the fix is on another page. After you change a setting and restart the app, click **Check again**.\n\n**Workspace:**\n\n- **Using Open Executive** — **Personal** or **Team**. You pick this when you first set up; change it here. Switching asks you to confirm and says what changes:\n - **Personal** pauses department check-ins and renames **Company** in the sidebar to **You**, with **Goals** (grouped by area), **People** and your profile — there is no Departments tab. Nothing is deleted — your departments stay, as the areas your goals are grouped by.\n - **Team** brings back **Company** with its **Departments** tab and their daily check-ins, and the People and Departments tiles on Home.\n- **Your role** (just you) — which describes you best (**Owner / founder**, **Executive inside an organisation**, **Independent or fractional**, or **Other**), your title, who you report to, what you're responsible for and what you're measured on. Every field is optional; click **Save role** after editing. The Executive uses it to fit its advice to your job — a VP gets help making the case to their boss, an owner gets help with a call that's theirs alone to make. It stays saved if you switch to your team.\n- **Time zone** — when your morning brief, end-of-day digest and reflection arrive, and how the Executive reads \"tomorrow at 9\". It suggests the zone your browser is in; **Follow server default** uses the server's setting.\n- **Company email domains** (under **Advanced**, principal only) — mail from these domains matches a teammate by the part before the @, and a new address there is filled in as a teammate when someone writes in. It follows your own address unless you set it here.\n- Only the principal can change the mode, role and time zone. A persona you customised in Council stays in place in either mode.\n\n**Act as me (Delegate → Act as me):**\n\n- Normally the Executive writes only as itself, from its own email account. **Act as me** lets it write an email *as you*: ask in chat — \"reply to Dana as me: yes to the 5th\" — and it saves a draft in **your own Gmail Drafts** for you to read, change and send. Asking in chat never sends anything, and everything else it writes stays in its own name.\n- The owner sees this page, and so does each team member once the owner turns on **Let team members use it** under **Advanced** at the bottom of it (shown only where your install allows it). Each team member connects their own Gmail and turns it on for themselves. What it reads in their mail, the drafts it writes and their **Replies waiting** are theirs alone: the owner sees only who uses it and how many drafts and sends it made, and a conversation in which it read someone's mail can be opened only by that person. Turning the owner's switch off takes it away from the team from their next message. It works when you ask in the web app, in a direct message to the Executive on Slack or Discord, or in a verified private Telegram chat — never in a shared channel or thread, from an email, a scheduled job or anyone else's conversation.\n- **Your Gmail** — connect your own Gmail first. The page shows the command to run on a computer with a browser; sign in as yourself, put the file it writes where your install reads it, then click **Check again**. It won't connect the Executive's own address as yours.\n- **How far it goes as you** — one setting for everything it writes or sends as you, from **Off** up. Each step adds to the one above it, and it stays at **Off** until your Gmail is connected. **Writes as you, never sends**: **Drafts when I ask** writes a draft when you ask in chat; **Drafts for my inbox** also writes replies to your inbox (below). **Handle it for me sends as you**: **Easy ones**, **People I know** and **Most mail** let it send some replies and follow-ups itself, and the owner also gets **Everything**. Moving down asks first and says what stops. At a sending step, **In training** has every reply come to you first.\n- **Drafts for my inbox** — every few minutes the Executive looks at new mail in your inbox, and 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 in your Gmail Drafts and puts it at the top of **Needs you** on Home. Nothing is sent until you tap **Send** there. It only looks at mail that arrives after you turn it on, and leaves out newsletters, notifications, mailing lists, mail you've already answered and anything that doesn't need you; mail you answer within ten minutes never gets a draft. 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. Someone you've never written to gets a short holding reply. While it's on, **Your inbox** says how it's doing (for example, that your Gmail needs connecting again) and when it last looked; click **Check now** to look straight away. Moving to **Off** also turns **Read my calendar** off.\n- **How I write** (under **Advanced**) — click **Learn from my sent mail** and it reads your recent sent emails once and describes how you write (click **Edit how I write** to open the fields): your usual **Length** and **Tone**, a **Greeting** for your team, your contacts and anyone else ({first} stands for their first name), your **Sign-off**, your **Habits**, what you **Never** do, and a few **Examples of your writing** that set the tone. Change any of them and click **Save changes**; **Lock** stops it being relearned from your mail (you can still edit it); **Reset** starts over; **Remove examples** drops the examples. Your Gmail signature is added to every draft: **Refresh from Gmail** picks up a change you made to it in Gmail, **Don't add my signature** stops adding it, and **Add my Gmail signature** brings it back.\n- In chat you get a card, \"Drafted an email as you to …\", that opens the draft in Gmail. If the Executive isn't sure about something, it asks you instead of guessing.\n\n**Setting up just for yourself:**\n\n- The first time you set up, Open Executive asks who it is for — **Personal** or **Team** — before anything else, and saves your time zone from the browser. Re-running setup later skips this; change the mode here instead. Either way you can add teammates later from **People**.\n- **Personal** is for anyone who uses Open Executive just for themselves, whatever their role: your own business, a team you lead inside an organisation, or clients you advise as an independent or fractional executive.\n- Choosing **Personal** then asks **What's your role?** — the same fields as **Your role** above. Fill in what you like, or click **Skip for now**.\n- Just for yourself, the setup conversation asks about your work rather than your team, following the role you gave: an owner about what you offer, your customers, pricing, cash and runway; an executive inside an organisation about that organisation (it becomes your company profile), what you're responsible for, who you report to and what you're measured on; an independent about your practice and clients. Everyone is asked about their goals. On **Here's what I understood** there is a single **You** card (your name and role) next to **Your sign-in email**, instead of the team and department lists.\n- The step-by-step form skips the team size, team members and fractional executives steps.\n- In the sidebar, **You** takes the place of **Company** and holds **Goals**, **People** and your profile: **Business profile** if you own the business, **Your work** for any other role (or none). The profile page follows the same choice: for any other role it is worded around the organisation you work in (**Where You Work** in place of Company Basics). Either way departments are listed there as **Areas**, and your title, who you report to and what you're responsible for stay under **Your role** above.\n\n**Pausing the Executive:**\n\n- Open **Settings → Your Executive** (or **Pause or resume the Executive** in the account menu — the **⋯** next to your name at the bottom of the sidebar) and click **Pause…**. Add a reason if you like, and click **Pause Executive**.\n- While paused, the Executive starts nothing on its own: no briefs, nudges, monitoring, inbox processing or workflow timers. An amber banner appears on every page.\n- Chat and direct messages (Slack, Telegram, Discord, Google Chat) still get answers.\n- Nothing is lost. Work that falls due during the pause waits, and runs when you click **Resume**. The switch shows how many actions are waiting.\n- Anyone who can sign in can pause the Executive, but only the principal can resume it.\n\n*Tip: if you're looking for a feature that isn't in the sidebar, it's probably under **Settings → Advanced**. This guide is also in the account menu (the **⋯** next to your name at the bottom of the sidebar), with **Pause or resume the Executive** and, when you signed in with an account, **Sign out**.*",
"mermaid": null,
"generated_at": "2026-10-03T12:00:00Z"
}
diff --git a/packages/core/openexecutive/guide/prebuilt/today.json b/packages/core/openexecutive/guide/prebuilt/today.json
index 4b9c5963..600c6cbe 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.\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), **In flight**, **Handled overnight**, **Monitoring** — 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- **Read today's brief** (next to **Needs you**) opens the written brief — what's going on across the company — in a side panel.\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 → Draft replies to my inbox** on, the replies the Executive wrote in your Gmail Drafts for mail that needs you come first in **Needs you**. Only you see them.\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 **⋯**) — later today, tomorrow at 9:00 or Monday at 9:00. The card leaves Home and comes back on its own then; **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.\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 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 whether Gmail could confirm their address), what they wrote, your draft, and **Decide before sending** — what the draft leaves for you to answer. **Send** asks you once, naming who the reply goes to, then sends the draft from your Gmail exactly as it is there. If you changed who it goes to in Gmail, or they wrote again since, it asks a second time and says what changed. To change the wording, choose **Edit in Gmail** in the card's **⋯**, edit the draft there, then Send here or from Gmail. **Dismiss** (also in **⋯**) deletes the draft, unless you've already edited it in Gmail. On a server, Send needs signed sign-ins; until they're set up, send from Gmail. A card goes away on its own once you send or delete the draft in Gmail, or reply yourself, and after a week.\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.)\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.\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), **In flight**, **Handled overnight**, **Monitoring** — 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- **Read today's brief** (next to **Needs you**) opens the written brief — what's going on across the company — in a side panel.\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 → How far it goes as you** at **Drafts for my inbox** or above, the replies the Executive wrote in your Gmail Drafts for mail that needs you come first in **Needs you**. Only you see them.\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 **⋯**) — later today, tomorrow at 9:00 or Monday at 9:00. The card leaves Home and comes back on its own then; **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.\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 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 whether Gmail could confirm their address), what they wrote, your draft, and **Decide before sending** — what the draft leaves for you to answer. **Send** asks you once, naming who the reply goes to, then sends the draft from your Gmail exactly as it is there. If you changed who it goes to in Gmail, or they wrote again since, it asks a second time and says what changed. To change the wording, choose **Edit in Gmail** in the card's **⋯**, edit the draft there, then Send here or from Gmail. **Dismiss** (also in **⋯**) deletes the draft, unless you've already edited it in Gmail. On a server, Send needs signed sign-ins; until they're set up, send from Gmail. A card goes away on its own once you send or delete the draft in Gmail, or reply yourself, and after a week.\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.)\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-13T20:51:09Z"
}
diff --git a/packages/core/tests/unit/test_delegation_route.py b/packages/core/tests/unit/test_delegation_route.py
index 484e618a..c305812b 100644
--- a/packages/core/tests/unit/test_delegation_route.py
+++ b/packages/core/tests/unit/test_delegation_route.py
@@ -440,3 +440,104 @@ def test_read_my_calendar_turns_on_only_once_the_calendar_opens(
# Off never needs the calendar.
box.outcome = CalendarNotGranted("no")
assert client.put("/delegation/calendar", json={"enabled": False}, headers=OWNER).status_code == 200
+
+
+# ── How far it goes as you (PUT /delegation/reach) ────────────────────────────
+
+
+def _reach(client: TestClient, step: str) -> Any:
+ return client.put("/delegation/reach", json={"step": step}, headers=OWNER)
+
+
+def signed(monkeypatch: pytest.MonkeyPatch) -> None:
+ """Sending on its own needs a caller the API can tie to the person."""
+ monkeypatch.setenv("OE_LOCAL_LOGIN", "1")
+
+
+def test_the_dial_climbs_one_switch_at_a_time(
+ client: TestClient, ids: dict[str, int], gmail: dict[str, str], signed: None
+) -> None:
+ from openexecutive.delegation import handle_it, inbox
+
+ pid = ids["principal"]
+ gmail["status"] = "connected"
+ assert route.reach_of(pid) == "off"
+ assert _reach(client, "inbox").status_code == 200
+ assert is_enabled(pid) and inbox.get_watch(pid).enabled and not handle_it.get(pid).enabled
+ assert route.reach_of(pid) == "inbox"
+ _reach(client, "bold")
+ assert handle_it.get(pid).enabled and handle_it.get(pid).mode == "bold"
+ _reach(client, "everything")
+ assert route.reach_of(pid) == "everything"
+ # Across the sending steps: Everything goes, the level stays the one picked.
+ _reach(client, "careful")
+ assert route.reach_of(pid) == "careful" and not handle_it.leading(pid)
+
+
+def test_moving_down_turns_everything_above_off(
+ client: TestClient, ids: dict[str, int], gmail: dict[str, str], signed: None
+) -> None:
+ from openexecutive.delegation import handle_it, inbox
+
+ pid = ids["principal"]
+ gmail["status"] = "connected"
+ _reach(client, "everything")
+ assert _reach(client, "when_asked").status_code == 200
+ assert is_enabled(pid) and not inbox.get_watch(pid).enabled
+ assert not handle_it.get(pid).enabled and not handle_it.leading(pid)
+ _reach(client, "off")
+ assert route.reach_of(pid) == "off" and not is_enabled(pid)
+
+
+def test_without_a_mailbox_the_dial_stays_off(client: TestClient, ids: dict[str, int], gmail: dict[str, str]) -> None:
+ resp = _reach(client, "inbox")
+ assert resp.status_code == 409 and resp.json()["detail"]["code"] == "gmail_not_connected"
+ assert route.reach_of(ids["principal"]) == "off"
+
+
+def test_sending_needs_a_signed_sign_in_but_holding_back_doesnt(
+ client: TestClient, ids: dict[str, int], gmail: dict[str, str], monkeypatch: pytest.MonkeyPatch
+) -> None:
+ from openexecutive.delegation import handle_it
+
+ pid = ids["principal"]
+ gmail["status"] = "connected"
+ monkeypatch.setenv("OE_LOCAL_LOGIN", "1")
+ _reach(client, "bold")
+ monkeypatch.delenv("OE_LOCAL_LOGIN")
+ # Without signed sign-ins it can't go higher...
+ assert _reach(client, "everything").status_code == 409
+ assert route.reach_of(pid) == "bold"
+ # ...but a lower level, or no sending at all, is always possible.
+ assert _reach(client, "careful").status_code == 200 and handle_it.get(pid).mode == "careful"
+ assert _reach(client, "inbox").status_code == 200 and route.reach_of(pid) == "inbox"
+
+
+def test_everything_is_the_owners_and_not_in_training(
+ client: TestClient, ids: dict[str, int], gmail: dict[str, str], signed: None, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ from openexecutive.delegation import training
+
+ gmail["status"] = "connected"
+ _reach(client, "balanced")
+ training.set_(ids["principal"], {training.REPLIES: True}, updated_by="t")
+ resp = _reach(client, "everything")
+ assert resp.status_code == 409 and resp.json()["detail"]["code"] == "in_training"
+ assert route.reach_of(ids["principal"]) == "balanced"
+
+
+def test_training_set_before_sending_holds_once_it_sends(
+ client: TestClient, ids: dict[str, int], gmail: dict[str, str], signed: None
+) -> None:
+ from openexecutive.delegation import handle_it, training
+
+ pid = ids["principal"]
+ gmail["status"] = "connected"
+ _reach(client, "inbox")
+ resp = client.put("/delegation/training", json={"replies": True, "follow_ups": True}, headers=OWNER)
+ assert resp.status_code == 200
+ _reach(client, "careful")
+ assert handle_it.get(pid).enabled
+ t = training.get(pid)
+ assert t.replies and t.follow_ups
diff --git a/packages/core/tests/unit/test_may_do.py b/packages/core/tests/unit/test_may_do.py
new file mode 100644
index 00000000..a881fce6
--- /dev/null
+++ b/packages/core/tests/unit/test_may_do.py
@@ -0,0 +1,281 @@
+"""What it may do (delegation/may_do.py, GET /what-it-may-do): one read-only
+answer to what goes out without asking, read from the gates' own settings."""
+from __future__ import annotations
+
+from collections.abc import Iterator
+from pathlib import Path
+from typing import Any
+
+import pytest
+from fastapi import FastAPI
+from fastapi.testclient import TestClient
+
+from openexecutive.api.routes import may_do as route
+from openexecutive.delegation import handle_it, inbox, may_do, training
+from openexecutive.delegation.settings import set_enabled
+from openexecutive.memory import decision_ledger as ledger
+from openexecutive.memory import episodic
+from openexecutive.orchestrator import take_the_lead as ttl
+from openexecutive.people import registry as people_registry
+from openexecutive.people import store as people_store
+
+OWNER = {"x-caller-email": "[email protected]"}
+TEAMMATE = {"x-caller-email": "[email protected]"}
+CONTACT = {"x-caller-email": "[email protected]"}
+
+
[email protected](autouse=True)
+def db(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Iterator[Path]:
+ path = tmp_path / "episodic.db"
+ monkeypatch.setattr(episodic, "DB_PATH", path)
+ monkeypatch.setattr(people_store, "DB_PATH", path)
+ episodic.initialize_db(path)
+ people_store.initialize_db(path)
+ for var in ("OE_LOCAL_LOGIN", "OE_PUBLIC_DEPLOYMENT", "CALLER_ASSERTION_PUBLIC_KEYS"):
+ monkeypatch.delenv(var, raising=False)
+ # Sending as someone needs the API to tie a switch to them.
+ monkeypatch.setattr(handle_it, "signing_ok", lambda: True)
+ monkeypatch.setattr("openexecutive.scheduler.pause.is_paused", lambda: False)
+ monkeypatch.setattr("openexecutive.departments.registry.list_states", lambda **_: [])
+ monkeypatch.setattr("openexecutive.departments.registry.get_state", lambda slug: None)
+ people_registry.invalidate()
+ yield path
+ people_registry.invalidate()
+
+
+def ids() -> dict[str, int]:
+ principal = people_store.upsert_person(full_name="Olivia Owner", is_principal=True, email="[email protected]")
+ teammate = people_store.upsert_person(full_name="Ben Teammate", email="[email protected]")
+ people_store.upsert_person(full_name="Dana Park", email="[email protected]", kind="contact")
+ people_registry.invalidate()
+ return {"principal": principal, "teammate": teammate}
+
+
+def _handling(pid: int, mode: str = "balanced") -> None:
+ set_enabled(pid, True, updated_by="t")
+ inbox.set_watch(pid, True, updated_by="t")
+ handle_it.set_(pid, enabled=True, mode=mode, updated_by="t")
+ training.set_(pid, {training.REPLIES: False, training.FOLLOW_UPS: False}, updated_by="t")
+
+
+def _rows(section: may_do.Section) -> dict[str, may_do.Row]:
+ return {r.id: r for r in section.rows}
+
+
+def _you(pid: int, *, principal: bool = True) -> may_do.Section:
+ return may_do.as_you(pid, can_have_it=True, signing=True, is_principal=principal)
+
+
+# ── as you ────────────────────────────────────────────────────────────────────
+
+
+def test_with_everything_off_nothing_goes_out_as_you(ids: dict[str, int]) -> None:
+ section = _you(ids["principal"])
+ rows = _rows(section)
+ assert section.goes == 0
+ assert rows["chat_drafts"].outcome == "off"
+ assert rows["replies_known"].outcome == "off" and "Write drafts as me is off" in rows["replies_known"].why
+ assert "actions" not in rows and "sensitive" not in rows
+ assert section.notes == []
+
+
+def test_drafts_and_the_inbox_without_handle_it_wait_for_a_tap(ids: dict[str, int]) -> None:
+ pid = ids["principal"]
+ set_enabled(pid, True, updated_by="t")
+ inbox.set_watch(pid, True, updated_by="t")
+ rows = _rows(_you(pid))
+ assert rows["chat_drafts"].outcome == "drafts"
+ assert rows["replies_known"].outcome == "waits" and "Handle it for me is off" in rows["replies_known"].why
+ assert rows["follow_ups"].outcome == "waits"
+ assert rows["actions"].outcome == "waits"
+
+
[email protected](("mode", "known", "strangers", "follow_ups", "links"), [
+ ("careful", "goes", "waits", "waits", "waits"),
+ ("balanced", "goes", "waits", "goes", "waits"),
+ ("bold", "goes", "goes", "goes", "goes"),
+])
+def test_each_level_matches_its_rules(
+ ids: dict[str, int], mode: str, known: str, strangers: str, follow_ups: str, links: str
+) -> None:
+ pid = ids["principal"]
+ _handling(pid, mode)
+ rules = handle_it.RULES[mode]
+ # The rows follow the rules the refusals check, not a copy of them.
+ assert (strangers == "goes") is rules.strangers
+ assert (follow_ups == "goes") is bool(rules.follow_up_to)
+ assert (links == "goes") is (rules.details_confidence is not None)
+ section = _you(pid)
+ rows = _rows(section)
+ assert rows["replies_known"].outcome == known
+ assert rows["replies_strangers"].outcome == strangers
+ assert rows["follow_ups"].outcome == follow_ups
+ assert rows["links"].outcome == links
+ assert rows["sensitive"].outcome == "always_waits"
+ assert may_do.LEVEL_NAMES[mode] in rows["replies_known"].why
+ assert section.notes and "rides on" in section.notes[0]
+ assert "a day" in section.footer
+
+
+def test_everything_names_the_lead_and_what_it_rides_on(ids: dict[str, int]) -> None:
+ pid = ids["principal"]
+ _handling(pid, "careful")
+ ttl.set_(ttl.person_scope(pid), enabled=True, updated_by="t")
+ ttl.add_rule(ttl.person_scope(pid), "domain", "acme.com", created_by="t")
+ section = _you(pid)
+ rows = _rows(section)
+ assert rows["replies_strangers"].outcome == "goes" and "Everything" in rows["replies_strangers"].why
+ assert rows["follow_ups"].outcome == "goes"
+ # At Everything a link still waits, whatever the level underneath allowed.
+ assert rows["links"].outcome == "waits" and rows["links"].what == "A reply with a link in it"
+ assert rows["rules"].items == ("Anyone at acme.com",)
+ assert "Everything" in section.notes[0] and "turns Everything off" in section.notes[0]
+
+
+def test_only_the_owner_sees_the_company_rules_by_name(ids: dict[str, int]) -> None:
+ # Take the lead as you is the owner's, but a row left on (say, by an
+ # earlier owner) must not hand the company's rules to anyone else.
+ pid = ids["teammate"]
+ _handling(pid, "careful")
+ ttl.set_(ttl.person_scope(pid), enabled=True, updated_by="t")
+ ttl.add_rule(ttl.person_scope(pid), "domain", "acme.com", created_by="t")
+ ttl.add_rule(ttl.SCOPE_COMPANY, "words", "acquisition", created_by="t")
+ row = _rows(_you(pid, principal=False))["rules"]
+ assert row.items == ("Anyone at acme.com",)
+ assert "acquisition" not in row.why and "1 rule" in row.why
+ assert _rows(_you(pid))["rules"].items == ("Anyone at acme.com", "Words: acquisition")
+
+
+def test_training_holds_replies_and_counts_what_it_allowed(ids: dict[str, int]) -> None:
+ pid = ids["principal"]
+ _handling(pid, "bold")
+ ttl.set_(ttl.person_scope(pid), enabled=True, updated_by="t")
+ training.set_(pid, {training.REPLIES: True}, updated_by="t")
+ training.allow_sender(pid, "[email protected]", "Dana Park", decision_id=None)
+ rows = _rows(_you(pid))
+ # In training Everything doesn't apply: only allowed senders go.
+ assert rows["replies_known"].outcome == "waits" and "1 sender you allowed" in rows["replies_known"].why
+ assert "links" not in rows
+ # Follow-ups aren't in training, so the lead still covers them.
+ assert rows["follow_ups"].outcome == "goes" and "Everything" in rows["follow_ups"].why
+
+
+def test_without_signed_sign_ins_nothing_is_sent_as_you(ids: dict[str, int]) -> None:
+ pid = ids["principal"]
+ _handling(pid, "bold")
+ section = may_do.as_you(pid, can_have_it=True, signing=False)
+ assert section.goes == 0
+ assert any("Signed sign-ins are off" in n for n in section.notes)
+
+
+def test_someone_without_act_as_me_is_told_so(ids: dict[str, int]) -> None:
+ section = may_do.as_you(ids["teammate"], can_have_it=False, signing=True)
+ assert section.available is False and section.rows == []
+ assert "owner" in section.unavailable
+
+
+# ── as the Executive ──────────────────────────────────────────────────────────
+
+
+def test_the_executive_section_is_the_owners_alone() -> None:
+ section = may_do.as_the_executive(is_principal=False)
+ assert section.available is False and section.rows == []
+
+
+def test_take_the_lead_off_is_one_row() -> None:
+ rows = may_do.as_the_executive(is_principal=True).rows
+ assert [r.id for r in rows] == ["lead"] and rows[0].outcome == "off"
+
+
+def test_ask_first_switches_and_meetings(ids: dict[str, int]) -> None:
+ ttl.set_(ttl.SCOPE_EXECUTIVE, enabled=True, ask_first={"money": False}, updated_by="t")
+ ttl.add_rule(ttl.SCOPE_COMPANY, "words", "discount", created_by="t")
+ section = may_do.as_the_executive(is_principal=True)
+ rows = _rows(section)
+ assert rows["lead"].outcome == "goes"
+ assert rows["kind:money"].outcome == "goes"
+ assert rows["kind:contracts"].outcome == "waits"
+ # What it thinks of itself never books on its own: the meeting gates need
+ # someone on a verified surface in the turn.
+ assert rows["meetings"].outcome == "always_waits"
+ assert rows["meetings_chat"].outcome == "waits"
+ assert rows["rules"].items == ("Words: discount",)
+ assert "Department levels don't hold" in section.footer
+
+
+def test_training_waits_until_something_is_allowed() -> None:
+ ttl.set_(ttl.SCOPE_EXECUTIVE, enabled=True, training=True, ask_first={"money": False}, updated_by="t")
+ rows = _rows(may_do.as_the_executive(is_principal=True))
+ assert rows["lead"].outcome == "waits"
+ assert rows["kind:money"].outcome == "waits" and rows["kind:money"].then == "Waits unless allowed"
+
+
+def test_meetings_asked_for_in_chat_follow_the_switch_and_operations(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ from openexecutive.departments.models import AuthorityLevel
+ from openexecutive.memory import workspace_settings
+
+ ledger.set_class_mode("meeting_scheduling", "auto_execute")
+ # Team workspace: Operations must act on its own too.
+ assert may_do._meetings_in_chat().outcome == "waits"
+
+ class _State:
+ class config: # noqa: N801 — a stand-in for DepartmentConfig
+ authority_level = AuthorityLevel.AUTO_EXECUTE
+
+ monkeypatch.setattr("openexecutive.departments.registry.get_state", lambda slug: _State())
+ assert may_do._meetings_in_chat().outcome == "goes"
+ # Solo: the switch alone decides.
+ monkeypatch.setattr("openexecutive.departments.registry.get_state", lambda slug: None)
+ workspace_settings.set_workspace_mode("solo")
+ assert may_do._meetings_in_chat().outcome == "goes"
+
+
+# ── the route ─────────────────────────────────────────────────────────────────
+
+
+def client() -> TestClient:
+ app = FastAPI()
+ app.include_router(route.router)
+ return TestClient(app)
+
+
+def _section(body: dict[str, Any], key: str) -> dict[str, Any]:
+ return next(s for s in body["sections"] if s["key"] == key)
+
+
+def test_the_owner_sees_all_three(client: TestClient, ids: dict[str, int]) -> None:
+ _handling(ids["principal"], "bold")
+ body = client.get("/what-it-may-do", headers=OWNER).json()
+ assert [s["key"] for s in body["sections"]] == ["as_you", "executive", "departments"]
+ you = _section(body, "as_you")
+ assert you["available"] and you["goes"] >= 3
+ assert _section(body, "executive")["available"] is True
+ assert body["paused"] is False
+
+
+def test_a_teammate_sees_their_own_and_the_departments(client: TestClient, ids: dict[str, int]) -> None:
+ body = client.get("/what-it-may-do", headers=TEAMMATE).json()
+ assert _section(body, "as_you")["available"] is False
+ assert _section(body, "executive")["available"] is False
+ assert _section(body, "departments")["available"] is True
+
+
+def test_contacts_strangers_and_anonymous_callers_are_refused(
+ client: TestClient, ids: dict[str, int], monkeypatch: pytest.MonkeyPatch
+) -> None:
+ assert client.get("/what-it-may-do", headers=CONTACT).status_code == 403
+ assert client.get("/what-it-may-do", headers={"x-caller-email": "[email protected]"}).status_code == 403
+ assert client.get("/what-it-may-do").status_code == 403
+ monkeypatch.setenv("OE_LOCAL_LOGIN", "1")
+ assert client.get("/what-it-may-do").status_code == 200
+
+
+def test_it_says_when_the_executive_is_paused(
+ client: TestClient, ids: dict[str, int], monkeypatch: pytest.MonkeyPatch
+) -> None:
+ monkeypatch.setattr("openexecutive.scheduler.pause.is_paused", lambda: True)
+ assert client.get("/what-it-may-do", headers=OWNER).json()["paused"] is True
diff --git a/packages/core/tests/unit/test_scheduler_routes_to_person.py b/packages/core/tests/unit/test_scheduler_routes_to_person.py
index 52994f2c..018b9237 100644
--- a/packages/core/tests/unit/test_scheduler_routes_to_person.py
+++ b/packages/core/tests/unit/test_scheduler_routes_to_person.py
@@ -238,7 +238,7 @@ def test_escalate_creates_urgent_alert_and_holds() -> None:
) as mock_chat:
asyncio.run(_execute_action(action, gateway=None))
- # Nothing is sent: "Escalates to a human" promises the specialist will not act.
+ # Nothing is sent: "Escalates to a person" promises the specialist will not act.
mock_chat.assert_not_called()
# An urgent card went to the approver instead.
diff --git a/packages/ui/scripts/navConfig.test.mjs b/packages/ui/scripts/navConfig.test.mjs
index 76cb8031..2dc8cf66 100644
--- a/packages/ui/scripts/navConfig.test.mjs
+++ b/packages/ui/scripts/navConfig.test.mjs
@@ -25,7 +25,7 @@ test("the main menu is seven places, team is the default", () => {
"Chats → /chats",
"Work → /jobs",
"Company → /people",
- "Delegate → /delegate/act-as-me",
+ "Delegate → /delegate/what-it-may-do",
"Knowledge → /knowledge",
"Pulse → /memories",
]);
@@ -35,7 +35,7 @@ test("the main menu is seven places, team is the default", () => {
test("solo swaps Company for You, which opens on Goals", () => {
const solo = links(buildDestinations({ mode: "solo", roleKind: "owner" }));
assert.equal(solo[3], "You → /goals");
- assert.equal(solo[4], "Delegate → /delegate/act-as-me");
+ assert.equal(solo[4], "Delegate → /delegate/what-it-may-do");
assert.equal(solo.length, 7);
});
@@ -56,19 +56,21 @@ test("team hubs: Work and Company tabs", () => {
);
});
-test("Delegate holds Act as me, Handle it for me and Take the lead, each a named feature", () => {
+test("Delegate opens on What it may do, then Act as me, Handle it for me and Take the lead, each a named feature", () => {
for (const opts of [{}, { mode: "solo", roleKind: "owner" }]) {
const delegate = buildHubs(opts).find((h) => h.key === "delegate");
assert.deepEqual(links(delegate.tabs), [
+ "What it may do → /delegate/what-it-may-do",
"Act as me → /delegate/act-as-me",
"Handle it for me → /delegate/handle-it",
"Take the lead → /delegate/take-the-lead",
]);
assert.deepEqual(
delegate.tabs.map((t) => t.feature),
- ["act_as_me", "handle_it", "take_the_lead"],
+ [undefined, "act_as_me", "handle_it", "take_the_lead"],
);
assert.equal(hubForPath("/delegate/handle-it", opts)?.key, "delegate");
+ assert.equal(hubForPath("/delegate/what-it-may-do", opts)?.key, "delegate");
}
});
diff --git a/packages/ui/src/app/delegate/page.tsx b/packages/ui/src/app/delegate/page.tsx
index ab08abe0..8709afab 100644
--- a/packages/ui/src/app/delegate/page.tsx
+++ b/packages/ui/src/app/delegate/page.tsx
@@ -1,6 +1,6 @@
import { redirect } from "next/navigation";
-// Delegate opens on its first tab.
+// Delegate opens on its first tab: what it may do without asking.
export default function DelegatePage() {
- redirect("/delegate/act-as-me");
+ redirect("/delegate/what-it-may-do");
}
diff --git a/packages/ui/src/app/delegate/take-the-lead/page.tsx b/packages/ui/src/app/delegate/take-the-lead/page.tsx
index ab416267..d467ca99 100644
--- a/packages/ui/src/app/delegate/take-the-lead/page.tsx
+++ b/packages/ui/src/app/delegate/take-the-lead/page.tsx
@@ -2,11 +2,10 @@
import DelegatePage from "@/components/delegate/DelegatePage";
import TakeTheLeadCard from "@/components/settings/TakeTheLeadCard";
-import { MeetingAutonomySwitch } from "@/components/settings/WorkspaceCard";
// Delegate → Take the lead: what the Executive does in its own name without
-// waiting to be asked, and booking meetings without asking. Pause, on
-// Settings → Your Executive, stops all of it.
+// waiting to be asked, with its Always asks first list (meetings asked for
+// in chat included). Pause, on Settings → Your Executive, stops all of it.
export default function TakeTheLeadPage() {
return (
<DelegatePage
@@ -14,7 +13,6 @@ export default function TakeTheLeadPage() {
description="What the Executive does in its own name, without waiting to be asked. People can see it's the Executive."
>
<TakeTheLeadCard />
- <MeetingAutonomySwitch />
</DelegatePage>
);
}
diff --git a/packages/ui/src/app/delegate/what-it-may-do/page.tsx b/packages/ui/src/app/delegate/what-it-may-do/page.tsx
new file mode 100644
index 00000000..563d5f00
--- /dev/null
+++ b/packages/ui/src/app/delegate/what-it-may-do/page.tsx
@@ -0,0 +1,22 @@
+"use client";
+
+import WhatItMayDoView from "@/components/delegate/WhatItMayDo";
+
+// Delegate → What it may do: everything that goes out without asking, who it
+// goes out as, and the setting that allows it. Read-only; each row links to
+// the tab where its setting lives.
+export default function WhatItMayDoPage() {
+ return (
+ <main className="flex-1 min-h-0 overflow-y-auto">
+ <div className="max-w-4xl mx-auto px-4 sm:px-6 pt-6 sm:pt-8 pb-16">
+ <h1 className="text-2xl sm:text-3xl tracking-tight">What it may do</h1>
+ <p className="mt-3 text-[15px] text-fg-muted leading-relaxed">
+ Everything that goes out without asking you, and the setting that allows it.
+ </p>
+ <div className="mt-6">
+ <WhatItMayDoView />
+ </div>
+ </div>
+ </main>
+ );
+}
diff --git a/packages/ui/src/app/departments/[slug]/page.tsx b/packages/ui/src/app/departments/[slug]/page.tsx
index ecb35b64..55fceddd 100644
--- a/packages/ui/src/app/departments/[slug]/page.tsx
+++ b/packages/ui/src/app/departments/[slug]/page.tsx
@@ -59,7 +59,7 @@ const AUTHORITY_META: Record<
hint: "The specialist drafts actions and routes them to a person for approval before anything happens.",
},
escalate: {
- label: "Escalates to a human",
+ label: "Escalates to a person",
hint: "The specialist will not act — it forwards everything to a human.",
},
};
@@ -661,6 +661,11 @@ export default function DepartmentDetailPage() {
</label>
);
})}
+ <p className={HINT_CLS}>
+ This covers the department&apos;s check-ins, scheduled messages and alerts, and what its team
+ members ask for in chat; Operations also covers meetings people ask for. It doesn&apos;t cover
+ what the Executive does on its own under Take the lead: Always asks first holds that.
+ </p>
</fieldset>
<CheckInPicker
diff --git a/packages/ui/src/components/delegate/WhatItMayDo.tsx b/packages/ui/src/components/delegate/WhatItMayDo.tsx
new file mode 100644
index 00000000..0141eff8
--- /dev/null
+++ b/packages/ui/src/components/delegate/WhatItMayDo.tsx
@@ -0,0 +1,199 @@
+"use client";
+
+import Link from "next/link";
+import { useEffect, useId, useState } from "react";
+
+import SettingsCard from "@/components/settings/SettingsCard";
+import SectionTabs, { sectionPanelProps } from "@/components/ui/SectionTabs";
+import { getWhatItMayDo, type MayDoOutcome, type MayDoRow, type MayDoSection, type WhatItMayDo } from "@/lib/api";
+
+// Delegate → What it may do: read-only. One row per thing that can go out
+// without asking, what happens to it, and the setting that decides it, with
+// a link there. The three parts (as you, as the Executive, departments) sit
+// behind pills so the page stays one screen. Everything is worked out on the
+// server from the settings the gates themselves read (delegation/may_do.py).
+
+const TAB_LABELS: Record<MayDoSection["key"], string> = {
+ as_you: "As you",
+ executive: "As the Executive",
+ departments: "Departments",
+};
+
+const OUTCOME_DOT: Record<MayDoOutcome, string> = {
+ goes: "bg-emerald-500",
+ waits: "bg-amber-500",
+ always_waits: "bg-red-500",
+ drafts: "bg-fg-subtle",
+ off: "bg-fg-subtle/60",
+};
+
+function settingHref(setting: string): { href: string; label: string } | null {
+ if (setting === "act_as_me") return { href: "/delegate/act-as-me", label: "Act as me" };
+ if (setting === "handle_it") return { href: "/delegate/handle-it", label: "Handle it for me" };
+ if (setting === "take_the_lead") return { href: "/delegate/take-the-lead", label: "Take the lead" };
+ if (setting === "pause") return { href: "/settings/executive", label: "Your Executive" };
+ if (setting.startsWith("department:")) {
+ const slug = setting.slice("department:".length);
+ return { href: `/departments/${encodeURIComponent(slug)}`, label: "Department settings" };
+ }
+ return null;
+}
+
+function Outcome({ outcome, then }: { outcome: MayDoOutcome; then: string }) {
+ return (
+ <span className="inline-flex items-center gap-2 text-sm font-medium text-fg whitespace-nowrap">
+ <span aria-hidden className={`h-2 w-2 flex-shrink-0 rounded-full ${OUTCOME_DOT[outcome]}`} />
+ {then}
+ </span>
+ );
+}
+
+function Row({ row }: { row: MayDoRow }) {
+ const link = settingHref(row.setting);
+ return (
+ <li className="grid gap-1.5 px-4 py-3.5 sm:grid-cols-[minmax(0,1.1fr)_11rem_minmax(0,1.3fr)] sm:gap-4">
+ <div className="min-w-0">
+ <p className="text-[15px] text-fg leading-snug">{row.what}</p>
+ {row.items.length > 0 && (
+ <ul className="mt-1.5 flex flex-wrap gap-1.5">
+ {row.items.map((item) => (
+ <li key={item} className="rounded-md border border-line bg-surface-overlay px-2 py-0.5 text-xs text-fg-muted">
+ {item}
+ </li>
+ ))}
+ </ul>
+ )}
+ </div>
+ <div>
+ <Outcome outcome={row.outcome} then={row.then} />
+ </div>
+ <p className="min-w-0 text-sm text-fg-muted leading-relaxed">
+ {row.why}
+ {link && (
+ <>
+ {" "}
+ <Link href={link.href} className="font-medium text-accent underline-offset-2 hover:underline">
+ {link.label}
+ </Link>
+ </>
+ )}
+ </p>
+ </li>
+ );
+}
+
+function Section({ section }: { section: MayDoSection }) {
+ if (!section.available) {
+ return (
+ <SettingsCard>
+ <p className="text-[15px] text-fg-muted leading-relaxed">{section.unavailable}</p>
+ </SettingsCard>
+ );
+ }
+ return (
+ <div className="space-y-3">
+ {section.notes.map((note) => (
+ <p
+ key={note}
+ className="rounded-r-xl border-l-[3px] border-amber-500 bg-amber-500/10 px-4 py-2.5 text-sm text-fg leading-relaxed"
+ >
+ {note}
+ </p>
+ ))}
+ <section className="overflow-hidden rounded-2xl border border-line bg-surface-elevated">
+ <h2 className="border-b border-line px-4 py-3 text-base font-semibold text-fg">{section.title}</h2>
+ <div
+ aria-hidden
+ className="hidden border-b border-line bg-surface-overlay px-4 py-2 text-xs font-medium uppercase tracking-wider text-fg-subtle sm:grid sm:grid-cols-[minmax(0,1.1fr)_11rem_minmax(0,1.3fr)] sm:gap-4"
+ >
+ <span>What</span>
+ <span>Then</span>
+ <span>Why</span>
+ </div>
+ {section.rows.length === 0 ? (
+ <p className="px-4 py-4 text-sm text-fg-muted">There&apos;s nothing here yet.</p>
+ ) : (
+ <ul className="divide-y divide-line">
+ {section.rows.map((row) => (
+ <Row key={row.id} row={row} />
+ ))}
+ </ul>
+ )}
+ </section>
+ {section.footer && <p className="px-1 text-sm text-fg-subtle leading-relaxed">{section.footer}</p>}
+ </div>
+ );
+}
+
+export default function WhatItMayDoView() {
+ const [data, setData] = useState<WhatItMayDo | null>(null);
+ const [state, setState] = useState<"loading" | "ready" | "hidden" | "error">("loading");
+ const [active, setActive] = useState<MayDoSection["key"]>("as_you");
+ const idBase = useId();
+
+ useEffect(() => {
+ const controller = new AbortController();
+ getWhatItMayDo(controller.signal)
+ .then((found) => {
+ setData(found);
+ setState(found ? "ready" : "hidden");
+ })
+ .catch((err) => {
+ if (controller.signal.aborted) return;
+ console.warn("What it may do:", err);
+ setState("error");
+ });
+ return () => controller.abort();
+ }, []);
+
+ if (state === "loading") return <p className="text-sm text-fg-muted">Loading…</p>;
+ if (state === "error") {
+ return (
+ <SettingsCard>
+ <p className="text-[15px] text-fg-muted">Couldn&apos;t load this. Reload the page to try again.</p>
+ </SettingsCard>
+ );
+ }
+ if (state === "hidden" || !data) {
+ return (
+ <SettingsCard>
+ <p className="text-[15px] text-fg-muted">Only people on the team can see this.</p>
+ </SettingsCard>
+ );
+ }
+
+ // The Executive's part is the owner's alone: no tab for anyone else.
+ const sections = data.sections.filter((s) => s.available || s.key !== "executive");
+ const current = sections.find((s) => s.key === active) ?? sections[0];
+
+ return (
+ <div className="space-y-5">
+ {data.paused && (
+ <p className="rounded-xl border border-line bg-surface-overlay px-4 py-3 text-sm text-fg leading-relaxed">
+ The Executive is paused, so nothing below runs on its own until it resumes. What you send or approve
+ yourself still goes.{" "}
+ <Link href="/settings/executive" className="font-medium text-accent underline-offset-2 hover:underline">
+ Resume
+ </Link>
+ </p>
+ )}
+ <SectionTabs
+ label="What it may do"
+ idBase={idBase}
+ active={current.key}
+ onChange={setActive}
+ tabs={sections.map((s) => ({
+ id: s.key,
+ label: TAB_LABELS[s.key],
+ badge: s.available ? s.goes : null,
+ }))}
+ />
+ <div {...sectionPanelProps(idBase, current.key)}>
+ <Section section={current} />
+ </div>
+ <p className="px-1 text-xs text-fg-subtle">
+ The number on each pill is how many things go out without asking. Nothing on this page changes a setting.
+ </p>
+ </div>
+ );
+}
diff --git a/packages/ui/src/components/onboard/OnboardDepartmentsDraft.tsx b/packages/ui/src/components/onboard/OnboardDepartmentsDraft.tsx
index d19fddfa..6ad5ac1b 100644
--- a/packages/ui/src/components/onboard/OnboardDepartmentsDraft.tsx
+++ b/packages/ui/src/components/onboard/OnboardDepartmentsDraft.tsx
@@ -4,7 +4,7 @@ import { type OnboardDepartmentDraft, type OnboardPersonDraft } from "@/lib/api"
const AUTHORITY_LEVELS = [
{ value: "propose_only", label: "Proposes, you approve" },
- { value: "escalate", label: "Escalates to you" },
+ { value: "escalate", label: "Escalates to a person" },
{ value: "auto_execute", label: "Acts on its own" },
];
diff --git a/packages/ui/src/components/settings/ActAsMeCard.tsx b/packages/ui/src/components/settings/ActAsMeCard.tsx
index 6bc095fa..019855da 100644
--- a/packages/ui/src/components/settings/ActAsMeCard.tsx
+++ b/packages/ui/src/components/settings/ActAsMeCard.tsx
@@ -4,7 +4,7 @@ import { useCallback, useEffect, useLayoutEffect, useRef, useState, type ReactNo
import Icon from "@/components/Icon";
import AdvancedFold from "@/components/settings/AdvancedFold";
-import ModePicker from "@/components/settings/ModePicker";
+import ReachCard from "@/components/settings/ReachCard";
import SettingsCard from "@/components/settings/SettingsCard";
import Switch from "@/components/Switch";
import Button from "@/components/ui/Button";
@@ -16,11 +16,9 @@ import {
learnVoiceProfile,
refreshVoiceSignature,
resetVoiceProfile,
- setDelegationEnabled,
setDelegationTeam,
setInboxWatch,
setReadMyCalendar,
- setTraining,
updateVoiceProfile,
type DelegationSettings,
type DelegationTeam,
@@ -33,16 +31,17 @@ import { formatAgo } from "@/lib/setupStatus";
import { addPhrase, markNew, STYLE_PHRASES, styleSentences } from "@/lib/voiceStyle";
// Delegate → Act as me: let the Executive draft email AS you, in your own
-// Gmail Drafts, when you ask it to — and, with Draft replies to my inbox on,
-// for mail that needs you, which it sends when you tap Send on Today (or on
+// Gmail Drafts, when you ask it to — and, with How far it goes as you at
+// Drafts for my inbox or above, for mail that needs you, which it sends when you tap Send on Today (or on
// its own, under Handle it for me).
-// Backed by GET/PUT /delegation, /delegation/inbox and /delegation/voice.
+// Backed by GET /delegation, PUT /delegation/reach (ReachCard) and /delegation/voice.
// Not offered to anyone who can't have it (the owner can, and team members
// once the owner lets them: PUT /delegation/team) or on a backend without
// it: the hub then shows no tile, and this page says so.
//
-// The page body: the mailbox, Write drafts as me and Draft replies to my
-// inbox up front; How I write and Let team members use it under Advanced.
+// The page body: the mailbox, How far it goes as you and, while the inbox
+// watcher is on, Your inbox up front; How I write and Let team members use
+// it under Advanced.
export const ACT_AS_ME_INTRO =
"Let the Executive write email as you, in your own voice. When you ask it to reply to or write an email as you, it saves a draft in your own mailbox (Gmail or Outlook) for you to review and send. Nothing goes out as you unless you send it, from your mailbox or with Send on a reply waiting on Today. Everything else it writes stays in its own name.";
@@ -77,8 +76,6 @@ function greetingFields(p: VoiceProfile): Record<string, string> {
return Object.fromEntries(AUDIENCES.map((a) => [a, p.greetings[a] ?? ""]));
}
-type DraftsMode = "off" | "training" | "on";
-
// `onSettings` hears every change made here, so the page's other cards
// (Handle it for me, What it's learned) keep up; `children` sit after Draft
// replies to my inbox, before Advanced.
@@ -99,7 +96,6 @@ export default function ActAsMeCard({
);
const [state, setState] = useState<"loading" | "hidden" | "ready" | "error">("loading");
const [busy, setBusy] = useState(false);
- const [error, setError] = useState<string | null>(null);
const load = useCallback(async (signal?: AbortSignal) => {
try {
@@ -174,30 +170,8 @@ export default function ActAsMeCard({
const mailbox = outlook ? "Outlook" : "Gmail";
const on = settings.enabled;
- // Off / In training / On: On and In training both write drafts; In
- // training also offers "Do it like this next time" on a draft you changed
- // (Drafts in training, delegation/training.py).
- const draftsMode: DraftsMode = !on ? "off" : settings.training?.drafts ? "training" : "on";
- const pickDrafts = async (next: DraftsMode) => {
- setBusy(true);
- setError(null);
- try {
- if (next === "off") {
- setSettings(await setDelegationEnabled(false));
- } else {
- if (!on) setSettings(await setDelegationEnabled(true));
- setSettings(await setTraining({ drafts: next === "training" }));
- }
- } catch (err) {
- setError(err instanceof Error ? err.message : "Could not save the setting.");
- } finally {
- setBusy(false);
- }
- };
-
const recheck = async () => {
setBusy(true);
- setError(null);
await load();
setBusy(false);
};
@@ -246,41 +220,13 @@ export default function ActAsMeCard({
)}
</SettingsCard>
- <SettingsCard
- title="Write drafts as me"
- titleId="act-as-me-label"
- description={
- on || connected
- ? `Ask it in chat — “reply to Dana as me: yes to the 5th” — and the draft waits in your ${mailbox} Drafts. Nothing is sent.`
- : "Connect your mailbox first."
- }
- >
- <ModePicker<DraftsMode>
- labelledBy="act-as-me-label"
- value={draftsMode}
- disabled={busy || (!on && !connected)}
- options={[
- { value: "off", label: "Off" },
- { value: "training", label: "In training" },
- { value: "on", label: "On" },
- ]}
- onPick={(next) => void pickDrafts(next)}
- />
- <p className="mt-3 text-sm text-fg-muted leading-relaxed">
- {draftsMode === "training"
- ? "When you change a draft, tick Do it like this next time and it learns how you write to that person."
- : draftsMode === "on"
- ? "It writes drafts as you, in the style under How I write."
- : "The Executive only ever writes as itself."}
- </p>
- {error && <p className="mt-2 text-sm text-red-500">{error}</p>}
- </SettingsCard>
+ {connected || on ? (
+ <ReachCard settings={settings} onSettings={setSettings} />
+ ) : null}
- {settings.inbox && (
+ {settings.inbox?.enabled && (
<InboxSection
inbox={stoppedWaiting ? { ...settings.inbox, checking: false } : settings.inbox}
- actAsMeOn={on}
- handleItOn={!!settings.handle_it?.enabled}
mailbox={settings.gmail?.provider === "microsoft" ? "Outlook" : "Gmail"}
onSettings={setSettings}
onInbox={(inbox) => {
@@ -368,19 +314,17 @@ function TeamSection({
);
}
-// "Draft replies to my inbox" (PUT /delegation/inbox; Check now is POST
-// /delegation/inbox/check). Needs Act as me on; the replies wait on Today.
+// Your inbox, while the dial is at Drafts for my inbox or higher: how the
+// watcher is doing, Check now (POST /delegation/inbox/check) and where its
+// replies are kept (PUT /delegation/inbox {mailbox_drafts}). The switch
+// itself is a step of How far it goes as you.
function InboxSection({
inbox,
- actAsMeOn,
- handleItOn,
mailbox,
onSettings,
onInbox,
}: {
inbox: InboxWatch;
- actAsMeOn: boolean;
- handleItOn: boolean;
mailbox: string;
onSettings: (next: DelegationSettings) => void;
onInbox: (next: InboxWatch) => void;
@@ -389,18 +333,6 @@ function InboxSection({
const [error, setError] = useState<string | null>(null);
const on = inbox.enabled;
- const toggle = async () => {
- setBusy(true);
- setError(null);
- try {
- onSettings(await setInboxWatch({ enabled: !on }));
- } catch (err) {
- setError(err instanceof Error ? err.message : "Could not save the setting.");
- } finally {
- setBusy(false);
- }
- };
-
// Also keep each reply in their mailbox's Drafts (off: on its card alone).
const inDrafts = !!inbox.mailbox_drafts;
const keepInDrafts = async (next: boolean) => {
@@ -430,25 +362,9 @@ function InboxSection({
const last = inbox.last_poll_at && !inbox.checking ? ` Last checked ${formatAgo(inbox.last_poll_at)}.` : "";
return (
<SettingsCard
- title="Draft replies to my inbox"
+ title="Your inbox"
titleId="act-as-me-inbox-label"
- description={
- on
- ? handleItOn
- ? "When mail comes in that needs you, it writes a first reply. Handle it for me, on the next tab, sends the simple ones; the rest wait on Today, where you send, edit or dismiss them."
- : "When mail comes in that needs you, it writes a first reply and puts it on Today, where you can edit it, send it or dismiss it. Nothing is sent until you tap Send."
- : actAsMeOn
- ? "Off: it only drafts when you ask it to in chat."
- : "Turn on Write drafts as me first."
- }
- action={
- <Switch
- checked={on}
- onChange={() => void toggle()}
- disabled={busy || (!on && !actAsMeOn)}
- labelledBy="act-as-me-inbox-label"
- />
- }
+ description="When mail comes in that needs you, it writes a first reply and puts it on Today, where you can edit it, send it or dismiss it."
>
{on && (
<div className="flex flex-wrap items-center gap-x-4 gap-y-2">
@@ -522,7 +438,7 @@ function CalendarSection({
? "Ask about your day or your week in chat and it reads your own calendar. It never changes it."
: actAsMeOn
? "Off: it can't see your calendar. On, it reads it when you ask, and never changes it."
- : "Turn on Write drafts as me first."
+ : "Move How far it goes as you up from Off first."
}
action={
<Switch
diff --git a/packages/ui/src/components/settings/HandleItCard.tsx b/packages/ui/src/components/settings/HandleItCard.tsx
index caa1e0b5..d03eb9d8 100644
--- a/packages/ui/src/components/settings/HandleItCard.tsx
+++ b/packages/ui/src/components/settings/HandleItCard.tsx
@@ -3,7 +3,7 @@
import { useEffect, useState } from "react";
import LeadRulesEditor from "@/components/settings/LeadRulesEditor";
-import ModePicker from "@/components/settings/ModePicker";
+import ReachCard from "@/components/settings/ReachCard";
import SettingsCard from "@/components/settings/SettingsCard";
import {
addMyLeadRule,
@@ -11,9 +11,6 @@ import {
getDelegation,
getHandledReplies,
getMyLeadRules,
- setHandleIt,
- setLeadAsYou,
- setTraining,
type DelegationSettings,
type HandledReply,
type HandleIt,
@@ -22,17 +19,15 @@ import {
} from "@/lib/api";
import { formatAgo } from "@/lib/setupStatus";
-// Handle it for me (PUT /delegation/handle-it), 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). Off / In training / On, as on
-// Take the lead: In training (Replies in training, delegation/training.py,
-// PUT /delegation/training) every reply waits on Today unless you allowed that
-// person with Send + allow, and "Train follow-ups too" does the same for
-// follow-ups. Who it handles is the level: Easy ones, People I know, Most mail,
-// and for the owner, when it's On, Everything, which uses Take the lead
-// (PUT /delegation/take-the-lead), where links, the topics that always wait
-// and the added rules hold a reply back. Below, what it sent in the last week
-// (GET /delegation/handled).
+// 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). Its levels are the sending steps of How far it
+// goes as you (ReachCard, PUT /delegation/reach): Easy ones, People I know,
+// Most mail, and for the owner Everything, which uses Take the lead as you,
+// where links, the topics that always wait and the added rules hold a reply
+// back. In training (Replies and Follow-ups, delegation/training.py) every
+// reply waits on Today unless you allowed that person with Send + allow.
+// Below the dial, what it sent in the last week (GET /delegation/handled).
export const HANDLE_IT_MODES: { mode: HandleItMode; label: string; replies: string; followUps: string }[] = [
{
mode: "careful",
@@ -102,46 +97,20 @@ export default function HandleItCard({ load }: { load: DelegationLoad }) {
}
if (state === "hidden" || !settings?.handle_it || !settings.inbox) return null;
return (
- <HandleItSection
- handleIt={settings.handle_it}
- inboxOn={settings.inbox.enabled}
- repliesInTraining={Boolean(settings.training?.replies)}
- followUpsInTraining={Boolean(settings.training?.follow_ups)}
- onSettings={setSettings}
- />
+ <>
+ <ReachCard settings={settings} onSettings={setSettings} />
+ <HandleItSection handleIt={settings.handle_it} inboxOn={settings.inbox.enabled} />
+ </>
);
}
-type Mode = "off" | "training" | "on";
-type Level = HandleItMode | "lead";
-
-const LEAD_LEVEL = {
- label: "Everything",
- replies: "Uses Take the lead. It decides what to send as you. Replies with a link, the topics that always wait and your rules still hold it back.",
-};
-
-export function HandleItSection({
- handleIt,
- inboxOn,
- repliesInTraining = false,
- followUpsInTraining = false,
- onSettings,
-}: {
- handleIt: HandleIt;
- inboxOn: boolean;
- repliesInTraining?: boolean;
- followUpsInTraining?: boolean;
- onSettings: (next: DelegationSettings) => void;
-}) {
- const [busy, setBusy] = useState(false);
- const [error, setError] = useState<string | null>(null);
+// What Handle it for me sent, and, at Everything, your own rules. The dial
+// that turns it on and sets its level is How far it goes as you (ReachCard).
+export function HandleItSection({ handleIt, inboxOn }: { handleIt: HandleIt; inboxOn: boolean }) {
const [handled, setHandled] = useState<HandledReply[] | null>(null);
const [rules, setRules] = useState<LeadRule[] | null>(null);
const on = handleIt.enabled;
const lead = Boolean(on && handleIt.lead);
- const mode: Mode = !on ? "off" : repliesInTraining ? "training" : "on";
- const level: Level = lead ? "lead" : handleIt.mode;
- const canTurnOn = inboxOn && handleIt.available;
useEffect(() => {
if (!on) return;
@@ -161,139 +130,19 @@ export function HandleItSection({
return () => controller.abort();
}, [lead]);
- const save = async (work: () => Promise<void>) => {
- setBusy(true);
- setError(null);
- try {
- await work();
- } catch (err) {
- setError(err instanceof Error ? err.message : "Could not save the setting.");
- } finally {
- setBusy(false);
- }
- };
-
- // Training first, then the level, so turning it on never sends anything
- // before the training is in place. Putting it in training turns Take the
- // lead as you off on the server.
- const pickMode = (next: Mode) =>
- save(async () => {
- if (next === "off") {
- if (lead) await setLeadAsYou(false);
- onSettings(await setHandleIt({ enabled: false }));
- return;
- }
- const train = next === "training";
- if (train !== repliesInTraining || train !== followUpsInTraining) {
- onSettings(await setTraining({ replies: train, follow_ups: train }));
- }
- if (!on) onSettings(await setHandleIt({ enabled: true, mode: handleIt.mode }));
- });
-
- // Take the lead as you is its own switch on the server, so leaving
- // Everything turns it off first.
- const pickLevel = (next: Level) =>
- save(async () => {
- if (next === "lead") {
- onSettings(await setLeadAsYou(true));
- return;
- }
- if (lead) await setLeadAsYou(false);
- onSettings(await setHandleIt({ enabled: true, mode: next }));
- });
-
- const levels: { value: Level; label: string; replies: string; followUps?: string; disabled?: boolean }[] = [
- ...HANDLE_IT_MODES.map((m) => ({ value: m.mode as Level, label: m.label, replies: m.replies, followUps: m.followUps })),
- ...(handleIt.lead_available
- ? [{ value: "lead" as Level, label: LEAD_LEVEL.label, replies: LEAD_LEVEL.replies, disabled: mode === "training" }]
- : []),
- ];
- const picked = levels.find((l) => l.value === level);
-
return (
<SettingsCard
- title="Handle it for me"
+ title="What it sent"
titleId="handle-it-label"
description={
- !handleIt.available
- ? "Needs signed sign-ins on this server before it can send anything as you."
- : !inboxOn
- ? "Turn on Draft replies to my inbox on the Act as me tab first."
- : "Replies and follow-ups it sends as you."
+ !inboxOn
+ ? "Move How far it goes as you to a Handle it for me step to have it send replies as you."
+ : !on
+ ? "Handle it for me is off: every reply waits for you to tap Send."
+ : "Replies and follow-ups it sent as you on its own."
}
>
<div className="flex flex-col gap-4">
- <div>
- <ModePicker<Mode>
- labelledBy="handle-it-label"
- value={mode}
- disabled={busy || (!on && !canTurnOn)}
- options={[
- { value: "off", label: "Off" },
- { value: "training", label: "In training" },
- { value: "on", label: "On" },
- ]}
- onPick={(next) => void pickMode(next)}
- />
- <p className="mt-3 text-sm text-fg-muted leading-relaxed">
- {mode === "training"
- ? "Every reply comes to you on Today first. Tap Send + allow and it handles that person on its own from then on."
- : mode === "on"
- ? "It sends replies and follow-ups on its own, to the people below. Whatever it doesn't send waits for you on Today."
- : "Every reply waits for you to tap Send."}
- </p>
- </div>
- {on && (
- <div className="border-t border-line pt-4">
- <h3 id="handle-it-level-label" className="text-[15px] font-semibold text-fg">
- Who it handles
- </h3>
- <div className="mt-2">
- <ModePicker<Level>
- labelledBy="handle-it-level-label"
- value={level}
- disabled={busy}
- compact
- options={levels.map((l) => ({ value: l.value, label: l.label, disabled: l.disabled }))}
- onPick={(next) => void pickLevel(next)}
- />
- </div>
- {picked && (
- <p className="mt-2 text-sm text-fg-muted leading-snug">
- {picked.followUps ? `${picked.replies} Follow-ups: ${picked.followUps}` : picked.replies}
- </p>
- )}
- {mode === "training" && handleIt.lead_available && (
- <p className="mt-1 text-sm text-fg-muted">Everything opens up once it&apos;s On.</p>
- )}
- </div>
- )}
- {on && (mode === "training" || followUpsInTraining) && (
- <label className="flex cursor-pointer items-start gap-3 border-t border-line pt-4">
- <input
- type="checkbox"
- checked={followUpsInTraining}
- disabled={busy}
- onChange={(e) => {
- const train = e.target.checked;
- void save(async () => onSettings(await setTraining({ follow_ups: train })));
- }}
- className="mt-0.5 h-5 w-5 flex-shrink-0 accent-indigo-500"
- />
- <span>
- <span className="block text-[15px] font-semibold text-fg">Train follow-ups too</span>
- <span className="mt-0.5 block text-sm text-fg-muted leading-snug">
- Untick to let follow-ups go out at this level while replies stay in training.
- </span>
- </span>
- </label>
- )}
- {on && (
- <p className="text-sm text-fg-muted">
- Money, contracts, legal, hiring, the press and passwords always wait for you, and it never writes to anyone
- the email didn&apos;t go to.
- </p>
- )}
{lead && (
<div>
<h3 className="text-[15px] font-semibold text-fg">Your rules</h3>
@@ -303,7 +152,6 @@ export function HandleItSection({
<LeadRulesEditor
rules={rules ?? []}
emptyText="No rules of your own yet."
- disabled={busy}
onAdd={async (kind, value) => setRules(await addMyLeadRule(kind, value))}
onDelete={async (id) => setRules(await deleteMyLeadRule(id))}
/>
@@ -340,7 +188,6 @@ export function HandleItSection({
</ul>
)}
</div>
- {error && <p className="mt-2 text-sm text-red-500">{error}</p>}
</SettingsCard>
);
}
diff --git a/packages/ui/src/components/settings/ReachCard.tsx b/packages/ui/src/components/settings/ReachCard.tsx
new file mode 100644
index 00000000..192b8ff0
--- /dev/null
+++ b/packages/ui/src/components/settings/ReachCard.tsx
@@ -0,0 +1,288 @@
+"use client";
+
+import { useState } from "react";
+
+import SettingsCard from "@/components/settings/SettingsCard";
+import { HANDLE_IT_MODES } from "@/components/settings/HandleItCard";
+import { getDelegation, setReach, setTraining, type DelegationSettings, type ReachStep } from "@/lib/api";
+
+// How far it goes as you: the one dial for everything Act as me does from
+// your own mailbox (PUT /delegation/reach). It replaces three switches that
+// used to depend on each other out of sight: Write drafts as me, Draft
+// replies to my inbox and Handle it for me with its level. The first steps
+// write and never send; the rest are Handle it for me, which sends. Moving
+// down says what stops before it saves. In training (Replies and Follow-ups,
+// delegation/training.py) applies to the sending steps.
+
+type Step = {
+ value: ReachStep;
+ label: string;
+ line: string;
+ sends: boolean;
+};
+
+const LEAD_LINE =
+ "It decides what to send as you. Replies with a link, the topics that always wait and your rules still hold it back.";
+
+export function reachOf(settings: DelegationSettings): ReachStep {
+ if (!settings.enabled) return "off";
+ if (!settings.inbox?.enabled) return "when_asked";
+ const h = settings.handle_it;
+ if (!h?.enabled) return "inbox";
+ if (h.lead) return "everything";
+ return h.mode;
+}
+
+function stepsFor(settings: DelegationSettings, mailbox: string): Step[] {
+ const sending: Step[] = HANDLE_IT_MODES.map((m) => ({
+ value: m.mode,
+ label: m.label,
+ line: `${m.replies} Follow-ups: ${m.followUps}`,
+ sends: true,
+ }));
+ return [
+ { value: "off", label: "Off", line: "The Executive only ever writes as itself.", sends: false },
+ {
+ value: "when_asked",
+ label: "Drafts when I ask",
+ line: `Ask in chat, “reply to Dana as me: yes to the 5th”, and the draft waits in your ${mailbox} Drafts.`,
+ sends: false,
+ },
+ {
+ value: "inbox",
+ label: "Drafts for my inbox",
+ line: "It also writes a first reply to mail that needs you and puts it on Today. You tap Send.",
+ sends: false,
+ },
+ ...sending,
+ ...(settings.handle_it?.lead_available
+ ? [{ value: "everything" as ReachStep, label: "Everything", line: LEAD_LINE, sends: true }]
+ : []),
+ ];
+}
+
+// What moving from `from` down to `to` stops, in a sentence.
+function whatStops(steps: Step[], from: ReachStep, to: ReachStep): string {
+ const i = steps.findIndex((s) => s.value === from);
+ const j = steps.findIndex((s) => s.value === to);
+ if (j >= i) return "";
+ const target = steps[j];
+ if (from === "everything" && target.sends) return "It goes back to sending only what this level allows.";
+ if (steps[i].sends && target.sends) return "It sends less on its own: only what this level allows.";
+ if (steps[i].sends && to === "inbox") return "It stops sending replies and follow-ups on its own. Every reply waits for you.";
+ if (to === "when_asked") return "It stops writing replies to your inbox, and sends nothing on its own.";
+ return "It stops writing anything as you, and turns Read my calendar off too.";
+}
+
+export default function ReachCard({
+ settings,
+ onSettings,
+}: {
+ settings: DelegationSettings;
+ onSettings: (next: DelegationSettings) => void;
+}) {
+ const [busy, setBusy] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+ const [confirming, setConfirming] = useState<ReachStep | null>(null);
+
+ const mailbox = settings.gmail?.provider === "microsoft" ? "Outlook" : "Gmail";
+ const steps = stepsFor(settings, mailbox);
+ const current = reachOf(settings);
+ const currentStep = steps.find((s) => s.value === current);
+ const sending = Boolean(currentStep?.sends);
+ const training = Boolean(settings.training?.replies);
+ const followUpsTraining = Boolean(settings.training?.follow_ups);
+ const connected = settings.gmail?.status === "connected";
+ const canSend = Boolean(settings.handle_it?.available);
+
+ const save = async (work: () => Promise<DelegationSettings>) => {
+ setBusy(true);
+ setError(null);
+ try {
+ onSettings(await work());
+ setConfirming(null);
+ } catch (err) {
+ setError(err instanceof Error ? err.message : "Could not save the setting.");
+ // A refused move up can stop part way, at a lower step: show where it is.
+ try {
+ const now = await getDelegation();
+ if (now) onSettings(now);
+ } catch {
+ // Keep what's shown; the error above already says it didn't save.
+ }
+ } finally {
+ setBusy(false);
+ }
+ };
+
+ const pick = (to: ReachStep) => {
+ if (to === current) return;
+ const i = steps.findIndex((s) => s.value === current);
+ const j = steps.findIndex((s) => s.value === to);
+ if (j < i) {
+ setConfirming(to);
+ return;
+ }
+ void save(() => setReach(to));
+ };
+
+ const disabledReason = (step: Step): string | null => {
+ if (step.value === "off") return null;
+ if (!connected && current === "off") return "Connect your mailbox first.";
+ if (step.sends && !canSend) return "Needs signed sign-ins on this server.";
+ if (step.value === "everything" && (training || followUpsTraining)) return "Opens up once it's out of training.";
+ return null;
+ };
+
+ const groups: { title: string; steps: Step[] }[] = [
+ { title: "Writes as you, never sends", steps: steps.filter((s) => !s.sends) },
+ { title: "Handle it for me sends as you", steps: steps.filter((s) => s.sends) },
+ ];
+
+ return (
+ <SettingsCard
+ title="How far it goes as you"
+ titleId="reach-label"
+ description="One setting for everything it writes or sends from your own mailbox. Each step adds to the one above it."
+ >
+ <div role="radiogroup" aria-labelledby="reach-label" className="flex flex-col gap-5">
+ {groups.map((group) => (
+ <div key={group.title}>
+ <h3 className="mb-2 text-xs font-medium uppercase tracking-wider text-fg-subtle">{group.title}</h3>
+ <div className="flex flex-col gap-2">
+ {group.steps.map((step) => {
+ const checked = step.value === current;
+ const reason = disabledReason(step);
+ return (
+ <label
+ key={step.value}
+ className={`flex items-start gap-3 rounded-xl border p-3.5 transition-colors ${
+ checked ? "border-accent/60 bg-accent/10" : "border-line bg-surface-elevated hover:border-line-strong"
+ } ${reason && !checked ? "cursor-not-allowed opacity-60" : "cursor-pointer"}`}
+ >
+ <input
+ type="radio"
+ name="reach"
+ value={step.value}
+ checked={checked}
+ disabled={busy || (Boolean(reason) && !checked)}
+ onChange={() => pick(step.value)}
+ className="mt-1 h-4 w-4 flex-shrink-0 accent-indigo-500"
+ />
+ <span className="min-w-0">
+ <span className="block text-[15px] font-medium text-fg">{step.label}</span>
+ <span className="mt-0.5 block text-sm text-fg-muted leading-snug">
+ {reason && !checked ? reason : step.line}
+ </span>
+ </span>
+ </label>
+ );
+ })}
+ </div>
+ </div>
+ ))}
+ </div>
+
+ {confirming && (
+ <div className="mt-4 rounded-xl border border-amber-500/40 bg-amber-500/10 p-4">
+ <p className="text-sm text-fg leading-relaxed">
+ Move to {steps.find((s) => s.value === confirming)?.label}? {whatStops(steps, current, confirming)}
+ </p>
+ <div className="mt-3 flex flex-wrap gap-2">
+ <button
+ type="button"
+ disabled={busy}
+ onClick={() => void save(() => setReach(confirming))}
+ className="h-9 rounded-lg bg-fg px-3 text-sm font-medium text-fg-inverse disabled:opacity-50"
+ >
+ {busy ? "Saving…" : "Move down"}
+ </button>
+ <button
+ type="button"
+ disabled={busy}
+ onClick={() => setConfirming(null)}
+ className="h-9 rounded-lg border border-line px-3 text-sm font-medium text-fg"
+ >
+ Cancel
+ </button>
+ </div>
+ </div>
+ )}
+
+ {/* Shown from Drafts for my inbox up, so it can be in training before
+ the first move to a step that sends: training stays across moves. */}
+ {(sending || current === "inbox") && (
+ <div className="mt-5 flex flex-col gap-3 border-t border-line pt-4">
+ <label className="flex cursor-pointer items-start gap-3">
+ <input
+ type="checkbox"
+ checked={training}
+ disabled={busy || current === "everything"}
+ onChange={(e) => {
+ const train = e.target.checked;
+ void save(() => setTraining({ replies: train, follow_ups: train }));
+ }}
+ className="mt-0.5 h-5 w-5 flex-shrink-0 accent-indigo-500"
+ />
+ <span>
+ <span className="block text-[15px] font-semibold text-fg">In training</span>
+ <span className="mt-0.5 block text-sm text-fg-muted leading-snug">
+ {current === "everything"
+ ? "Move to Most mail or below to train it."
+ : !sending
+ ? "Tick this before moving to a step that sends, and every reply comes to you first until you allow that person."
+ : "Every reply comes to you first. Tap Send + allow and it handles that person on its own from then on, within this step."}
+ </span>
+ </span>
+ </label>
+ {(training || followUpsTraining) && (
+ <label className="ml-8 flex cursor-pointer items-start gap-3">
+ <input
+ type="checkbox"
+ checked={followUpsTraining}
+ disabled={busy}
+ onChange={(e) => {
+ const train = e.target.checked;
+ void save(() => setTraining({ follow_ups: train }));
+ }}
+ className="mt-0.5 h-5 w-5 flex-shrink-0 accent-indigo-500"
+ />
+ <span>
+ <span className="block text-[15px] font-semibold text-fg">Train follow-ups too</span>
+ <span className="mt-0.5 block text-sm text-fg-muted leading-snug">
+ Untick to let follow-ups go out at this step while replies stay in training.
+ </span>
+ </span>
+ </label>
+ )}
+ <p className="text-sm text-fg-muted">
+ Money, contracts, legal, hiring, the press and passwords always wait for you, and it never writes to anyone
+ the email didn&apos;t go to.
+ </p>
+ </div>
+ )}
+ {current !== "off" && (
+ <label className="mt-5 flex cursor-pointer items-start gap-3 border-t border-line pt-4">
+ <input
+ type="checkbox"
+ checked={Boolean(settings.training?.drafts)}
+ disabled={busy}
+ onChange={(e) => {
+ const learn = e.target.checked;
+ void save(() => setTraining({ drafts: learn }));
+ }}
+ className="mt-0.5 h-5 w-5 flex-shrink-0 accent-indigo-500"
+ />
+ <span>
+ <span className="block text-[15px] font-semibold text-fg">Learn from my edits</span>
+ <span className="mt-0.5 block text-sm text-fg-muted leading-snug">
+ 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.
+ </span>
+ </span>
+ </label>
+ )}
+ {error && <p className="mt-3 text-sm text-red-500">{error}</p>}
+ </SettingsCard>
+ );
+}
diff --git a/packages/ui/src/components/settings/TakeTheLeadCard.tsx b/packages/ui/src/components/settings/TakeTheLeadCard.tsx
index edae5b58..4b7ff531 100644
--- a/packages/ui/src/components/settings/TakeTheLeadCard.tsx
+++ b/packages/ui/src/components/settings/TakeTheLeadCard.tsx
@@ -2,6 +2,7 @@
import { useEffect, useState } from "react";
+import { MeetingAskFirstRow } from "@/components/settings/WorkspaceCard";
import LeadRulesEditor from "@/components/settings/LeadRulesEditor";
import SettingsCard from "@/components/settings/SettingsCard";
import Switch from "@/components/Switch";
@@ -70,6 +71,10 @@ export default function TakeTheLeadCard() {
return (
<SettingsCard>
<p className="text-sm text-fg-muted">Couldn&apos;t load Take the lead.</p>
+ {/* The meeting row has its own endpoint, so it still works here. */}
+ <ul className="mt-3 flex flex-col">
+ <MeetingAskFirstRow />
+ </ul>
</SettingsCard>
);
}
@@ -192,40 +197,40 @@ export default function TakeTheLeadCard() {
</div>
)}
{lead.enabled && (
- <>
- <p className="rounded-xl bg-surface-overlay/60 px-4 py-3 text-sm leading-relaxed text-fg-muted">
- Department approval levels still apply. A department on Proposes still sends its meetings to its head for
- a yes. Set a department to Acts on its own to let it book without asking.
- </p>
- <div>
- <h3 className="text-[15px] font-semibold text-fg">Always asks first</h3>
- <p className="mt-1 text-sm text-fg-muted">
- These wait for you, or for whoever approves that area (like spending or hiring), with a card on Today.
- </p>
- <ul className="mt-3 flex flex-col divide-y divide-line rounded-xl border border-line">
- {lead.ask_first.map((item) => {
- const id = `ask-first-${item.kind}`;
- return (
- <li key={item.kind} className="flex min-h-touch items-center justify-between gap-3 px-4 py-2">
- <span className="min-w-0">
- <span id={id} className="block text-[15px]">
- {item.label}
- </span>
- <span className="mt-0.5 block text-[13px] leading-snug text-fg-muted">{item.hint}</span>
- </span>
- <Switch
- checked={item.on}
- onChange={() => void save({ ask_first: { [item.kind]: !item.on } })}
- disabled={busy}
- labelledBy={id}
- />
- </li>
- );
- })}
- </ul>
- </div>
- </>
+ <p className="rounded-xl bg-surface-overlay/60 px-4 py-3 text-sm leading-relaxed text-fg-muted">
+ Department levels don&apos;t hold what it does here: the switches and rules below do. A meeting it thinks
+ of always waits for a yes.
+ </p>
)}
+ <div>
+ <h3 className="text-[15px] font-semibold text-fg">Always asks first</h3>
+ <p className="mt-1 text-sm text-fg-muted">
+ These wait for you, or for whoever approves that area (like spending or hiring), with a card on Today.
+ {!lead.enabled && " While Take the lead is off, only the last one applies: the rest are kept for when it's on."}
+ </p>
+ <ul className="mt-3 flex flex-col divide-y divide-line rounded-xl border border-line">
+ {lead.ask_first.map((item) => {
+ const id = `ask-first-${item.kind}`;
+ return (
+ <li key={item.kind} className="flex min-h-touch items-center justify-between gap-3 px-4 py-2">
+ <span className="min-w-0">
+ <span id={id} className="block text-[15px]">
+ {item.label}
+ </span>
+ <span className="mt-0.5 block text-[13px] leading-snug text-fg-muted">{item.hint}</span>
+ </span>
+ <Switch
+ checked={item.on}
+ onChange={() => void save({ ask_first: { [item.kind]: !item.on } })}
+ disabled={busy}
+ labelledBy={id}
+ />
+ </li>
+ );
+ })}
+ <MeetingAskFirstRow />
+ </ul>
+ </div>
<div>
<h3 className="text-[15px] font-semibold text-fg">Company rules</h3>
<p className="mt-1 mb-3 text-sm text-fg-muted">
diff --git a/packages/ui/src/components/settings/TrainingCard.tsx b/packages/ui/src/components/settings/TrainingCard.tsx
index 950a7b7e..712d16b3 100644
--- a/packages/ui/src/components/settings/TrainingCard.tsx
+++ b/packages/ui/src/components/settings/TrainingCard.tsx
@@ -15,9 +15,9 @@ import {
// Training on Delegate → Act as me (delegation/training.py), the way Take the
// lead has it: like someone new, each job can be In training, where it brings
-// you its work first and learns who and how from what you approve. Each job's
-// card carries its own Off / In training / On (Write drafts as me, Handle it
-// for me); this file holds the note at the top, the Suggested actions card
+// you its work first and learns who and how from what you approve. Replies,
+// follow-ups and drafts are trained from How far it goes as you (ReachCard);
+// this file holds the note at the top, the Suggested actions card
// (Always ask / In training, PUT /delegation/training) and, at the bottom, one
// "What it's learned" list, each item named by its job, with Remove
// (DELETE /delegation/learned/{id}).
diff --git a/packages/ui/src/components/settings/WorkspaceCard.tsx b/packages/ui/src/components/settings/WorkspaceCard.tsx
index 1da11525..a02a9ae0 100644
--- a/packages/ui/src/components/settings/WorkspaceCard.tsx
+++ b/packages/ui/src/components/settings/WorkspaceCard.tsx
@@ -21,9 +21,8 @@ import {
import { roleFormErrors, roleFormFrom, roleUpdate, type RoleForm } from "@/lib/principalRole";
// Settings → Workspace: who Open Executive is for (personal, or for your
-// team), your role when it's just you, the time zone its briefs run in, and
-// whether it books meetings without asking, as one card each, with company
-// email domains under Advanced. Mode, role and zone go through PUT
+// team), your role when it's just you, and the time zone its briefs run in,
+// as one card each, with company email domains under Advanced. Mode, role and zone go through PUT
// /workspace and then the app-wide WorkspaceProvider is refreshed so the nav
// and pages follow. The page supplies the title; this is the body.
@@ -363,11 +362,14 @@ function RoleSection() {
);
}
-// "Book meetings without asking" — the meeting_scheduling decision class
-// between "propose" (each booking waits for approval in the briefing) and
-// "auto_execute". Hidden when this backend has no such setting (404). Shown
-// on Delegate → Take the lead, with what else the Executive does by itself.
-export function MeetingAutonomySwitch() {
+// Meetings someone asks for in chat, as a row of Take the lead's Always asks
+// first list: the meeting_scheduling decision class between "propose" (asks
+// first: each booking waits for a yes on Today) and "auto_execute". Hidden
+// when this backend has no such setting (404). It covers only bookings
+// someone asks for in chat: both meeting gates need a person on a verified
+// surface in the turn, so a booking Take the lead thinks of always waits
+// (calendar_tools), and with a team Operations must act on its own too.
+export function MeetingAskFirstRow() {
const [mode, setMode] = useState<DecisionClassMode | null>(null);
const [state, setState] = useState<"loading" | "ready" | "absent" | "error">("loading");
const [busy, setBusy] = useState(false);
@@ -392,20 +394,12 @@ export function MeetingAutonomySwitch() {
}, []);
if (state === "absent" || state === "loading") return null;
- if (state === "error") {
- return (
- <SettingsCard>
- <p className="text-sm text-fg-muted">Couldn&apos;t load the meeting-booking setting.</p>
- </SettingsCard>
- );
- }
-
- const on = mode === "auto_execute";
+ const asks = mode !== "auto_execute";
const toggle = async () => {
setBusy(true);
setError(null);
try {
- const next = await setDecisionClassMode(MEETING_SCHEDULING_CLASS, on ? "propose" : "auto_execute");
+ const next = await setDecisionClassMode(MEETING_SCHEDULING_CLASS, asks ? "auto_execute" : "propose");
setMode(next.mode);
} catch (err) {
setError(err instanceof Error ? err.message : "Could not save the setting.");
@@ -415,17 +409,21 @@ export function MeetingAutonomySwitch() {
};
return (
- <SettingsCard
- title="Book meetings without asking"
- titleId="ws-meetings-label"
- description={
- on
- ? "The Executive books meetings on your calendar on its own."
- : "Each meeting the Executive wants to book waits for your approval in the briefing."
- }
- action={<Switch checked={on} onChange={() => void toggle()} disabled={busy} labelledBy="ws-meetings-label" />}
- >
- {error && <p className="text-sm text-red-500">{error}</p>}
- </SettingsCard>
+ <li className="flex min-h-touch items-center justify-between gap-3 px-4 py-2">
+ <span className="min-w-0">
+ <span id="ask-first-meetings" className="block text-[15px]">
+ Meetings asked for in chat
+ </span>
+ <span className="mt-0.5 block text-[13px] leading-snug text-fg-muted">
+ {state === "error"
+ ? "Couldn't load this setting."
+ : error ??
+ "Meetings you or a teammate ask it to book (with a team, Operations must also act on its own). A meeting it thinks of itself always waits."}
+ </span>
+ </span>
+ {state === "ready" && (
+ <Switch checked={asks} onChange={() => void toggle()} disabled={busy} labelledBy="ask-first-meetings" />
+ )}
+ </li>
);
}
diff --git a/packages/ui/src/components/shell/AppShell.tsx b/packages/ui/src/components/shell/AppShell.tsx
index e2328482..bf1823da 100644
--- a/packages/ui/src/components/shell/AppShell.tsx
+++ b/packages/ui/src/components/shell/AppShell.tsx
@@ -60,6 +60,7 @@ const SEGMENT_LABELS: Record<string, string> = {
executive: "Your Executive",
"act-as-me": "Act as me",
delegate: "Delegate",
+ "what-it-may-do": "What it may do",
"handle-it": "Handle it for me",
"take-the-lead": "Take the lead",
memory: "About you",
diff --git a/packages/ui/src/components/shell/navConfig.ts b/packages/ui/src/components/shell/navConfig.ts
index f3488d72..27851fc8 100644
--- a/packages/ui/src/components/shell/navConfig.ts
+++ b/packages/ui/src/components/shell/navConfig.ts
@@ -165,10 +165,17 @@ const WORK_TABS: NavItem[] = [
},
];
-// The Delegate hub's tabs: what the Executive does as you (Act as me,
-// Handle it for me) and on its own (Take the lead). Each is a named feature,
-// so its tab shows the brand label.
+// The Delegate hub's tabs: what it may do without asking (one read-only
+// page over all of them), then what the Executive does as you (Act as me,
+// Handle it for me) and on its own (Take the lead). Each of those is a named
+// feature, so its tab shows the brand label.
const DELEGATE_TABS: NavItem[] = [
+ {
+ href: "/delegate/what-it-may-do",
+ label: "What it may do",
+ icon: "eye",
+ description: "Everything that goes out without asking you, and the setting that allows it.",
+ },
{
href: "/delegate/act-as-me",
label: "Act as me",
diff --git a/packages/ui/src/lib/api.ts b/packages/ui/src/lib/api.ts
index 060fbacb..2cb6bb2b 100644
--- a/packages/ui/src/lib/api.ts
+++ b/packages/ui/src/lib/api.ts
@@ -1614,7 +1614,7 @@ export async function updateWorkspace(update: WorkspaceUpdate): Promise<Workspac
// ----------------------------------------------------------------------------
// Act as me — the Executive drafts email AS you, in your own Drafts (Gmail or Outlook),
-// when you ask it to or (with Draft replies to my inbox on) for mail that
+// when you ask it to or (with Drafts for my inbox or above) for mail that
// needs you. It sends only a reply card's draft, when you tap Send. The owner
// can have it, and team members too once the owner lets them.
// ----------------------------------------------------------------------------
@@ -2269,7 +2269,7 @@ export interface DecisionClassSetting {
mode: DecisionClassMode;
}
-// The class behind "Book meetings without asking".
+// The class behind "Meetings asked for in chat" in Take the lead's Always asks first.
export const MEETING_SCHEDULING_CLASS = "meeting_scheduling";
/** The class's mode, or null when this backend has no setting for it (404). */
@@ -4977,6 +4977,62 @@ export async function declineWatchSuggestion(
return res.json();
}
+// How far it goes as you (PUT /delegation/reach): one dial over Act as me,
+// the inbox watcher, Handle it for me and its level, and Everything.
+export type ReachStep = "off" | "when_asked" | "inbox" | HandleItMode | "everything";
+
+export async function setReach(step: ReachStep): Promise<DelegationSettings> {
+ const res = await fetch(`${API_BASE}/delegation/reach`, {
+ method: "PUT",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ step }),
+ });
+ if (!res.ok) throw await delegationError(res, "Couldn't change how far it goes.");
+ return res.json();
+}
+
+// ---------------------------------------------------------------------------
+// Delegate → What it may do (GET /what-it-may-do): read-only. What goes out
+// without asking, as you and as the Executive, and each department's level,
+// each with the setting that decides it.
+// ---------------------------------------------------------------------------
+
+export type MayDoOutcome = "goes" | "waits" | "always_waits" | "drafts" | "off";
+
+export interface MayDoRow {
+ id: string;
+ what: string;
+ outcome: MayDoOutcome;
+ then: string;
+ why: string;
+ /** act_as_me | handle_it | take_the_lead | pause | department:<slug> | "" */
+ setting: string;
+ items: string[];
+}
+
+export interface MayDoSection {
+ key: "as_you" | "executive" | "departments";
+ title: string;
+ available: boolean;
+ unavailable: string;
+ notes: string[];
+ rows: MayDoRow[];
+ footer: string;
+ goes: number;
+}
+
+export interface WhatItMayDo {
+ paused: boolean;
+ sections: MayDoSection[];
+}
+
+export async function getWhatItMayDo(signal?: AbortSignal): Promise<WhatItMayDo | null> {
+ const res = await fetch(`${API_BASE}/what-it-may-do`, { signal });
+ if (res.status === 403 || res.status === 404) return null;
+ if (!res.ok) throw new Error("Couldn't load what it may do.");
+ return res.json();
+}
+
// ---------------------------------------------------------------------------
// Decisions / Trust Ledger (first-climb autonomy)
// ---------------------------------------------------------------------------