AI-powered virtual executive team — a single coherent executive persona backed by 8 specialist agents (FastAPI + Next.js).
feat(chat): group chats by topic on the Chats page (#521)
Rufus3c6497e6a5a4
diff --git a/packages/core/openexecutive/api/models.py b/packages/core/openexecutive/api/models.pyindex 5b32ae41..26458f59 100644--- a/packages/core/openexecutive/api/models.py+++ b/packages/core/openexecutive/api/models.py@@ -287,6 +287,9 @@ class SessionSummary(BaseModel):preview: str | None = None# When its owner pinned it to the top of their list; absent when not.pinned_at: str | None = None+ # The owner's topic this chat is filed under (`GET /sessions/topics`);+ # absent when none, and on a chat shared with the caller.+ topic_id: int | None = None# A chat someone shared with the caller (`GET /sessions/shared-with-me`,# or opened by id): they read it and write in it with its owner, but only# the owner renames, pins, shares or deletes it. `shared_by` names thediff --git a/packages/core/openexecutive/api/routes/chat.py b/packages/core/openexecutive/api/routes/chat.pyindex 4589aaed..377d1ce3 100644--- a/packages/core/openexecutive/api/routes/chat.py+++ b/packages/core/openexecutive/api/routes/chat.py@@ -155,23 +155,20 @@ _rename_tasks: set[asyncio.Task[None]] = set()def _rename_session_in_background(session_id: str, message: str, full_response: str, turn_id: str) -> None:- """Generate and store a session title without holding up the stream.+ """Generate and store a session title (and topic) without holding up the stream.Used on the stop path only. Everywhere else the rename is awaited so thesidebar has the good title by the time the client acts on `done`."""from openexecutive.config import get_settings- from openexecutive.memory.session_store import update_session_title- from openexecutive.utils.session_title import generate_session_title+ from openexecutive.utils.chat_topics import name_chatasync def _run() -> None:try:- new_title = await asyncio.wait_for(- generate_session_title(message, full_response),+ await asyncio.wait_for(+ name_chat(session_id, message, full_response),timeout=get_settings().utility_fast_timeout_s,)- if new_title:- update_session_title(session_id, new_title)except Exception:# asyncio.TimeoutError is an Exception subclass in 3.11+, so this# covers the timeout and any DB failure. A missed rename only@@ -1596,19 +1593,14 @@ async def _run_chat_turn(session.session_id, message, full_response, turn_id)elif is_first_turn:- from openexecutive.memory.session_store import (- update_session_title,- )- from openexecutive.utils.session_title import (- generate_session_title,- )+ from openexecutive.utils.chat_topics import name_chat+try:- new_title = await asyncio.wait_for(- generate_session_title(message, full_response),+ # Titles the chat and files it under a topic.+ await asyncio.wait_for(+ name_chat(session.session_id, message, full_response),timeout=settings.utility_fast_timeout_s,)- if new_title:- update_session_title(session.session_id, new_title)except Exception:# asyncio.TimeoutError is a subclass of Exception in# Python 3.11+; catching Exception covers both thediff --git a/packages/core/openexecutive/api/routes/sessions.py b/packages/core/openexecutive/api/routes/sessions.pyindex a996fd30..28f9c269 100644--- a/packages/core/openexecutive/api/routes/sessions.py+++ b/packages/core/openexecutive/api/routes/sessions.py@@ -25,7 +25,7 @@ from openexecutive.api.routes.chat import (chat_people,forget_session,)-from openexecutive.memory import chat_export+from openexecutive.memory import chat_export, chat_topicsfrom openexecutive.memory.session_store import (delete_session,get_session_metadata,@@ -135,6 +135,106 @@ def _person_name(person_id: int | None) -> str | None:return person.full_name if person is not None else None+class ChatTopic(BaseModel):+ id: int+ name: str+ # How many of the caller's chats are filed under it.+ chat_count: int+ # The owner named, pinned or filed a chat under it: it shows even with+ # one chat, and the tidy never merges it away.+ kept: bool = False+ pinned_at: str | None = None+++class ChatTopics(BaseModel):+ topics: list[ChatTopic]+ # True while older chats are being filed in the background; list again+ # in a few seconds to see them under their topics.+ organizing: bool = False+++class TopicUpdate(BaseModel):+ """Rename and / or pin a topic. A field left out is left as it is."""++ name: str | None = Field(default=None, min_length=1, max_length=chat_topics.MAX_TOPIC_CHARS)+ pinned: bool | None = None+++class TopicMerge(BaseModel):+ into_id: int+++def _require_caller(request: Request) -> int:+ caller = _resolve_caller_person_id(request)+ if caller is None:+ raise HTTPException(status_code=404, detail="Topic not found")+ return caller+++def _topic_name(raw: str) -> str:+ name = chat_topics.clean_topic_name(raw)+ if not name:+ raise HTTPException(status_code=422, detail="A topic needs a name")+ return name++[email protected]("/sessions/topics", response_model=ChatTopics, response_model_exclude_none=True)+async def get_topics(request: Request) -> ChatTopics:+ """The caller's chat topics. The first time, and whenever chats are+ waiting for one, it starts filing them in the background+ (``organizing``)."""+ from openexecutive.utils import chat_topics as topic_model++ caller = _resolve_caller_person_id(request)+ if caller is None:+ return ChatTopics(topics=[])+ topics = await asyncio.to_thread(chat_topics.list_topics, caller)+ organizing = topic_model.backfill_running(caller)+ if not organizing:+ waiting: bool = await asyncio.to_thread(chat_topics.has_untagged, caller)+ if waiting:+ organizing = topic_model.start_backfill(caller)+ return ChatTopics(topics=[ChatTopic(**t) for t in topics], organizing=organizing)++[email protected]("/sessions/topics/{topic_id}", response_model=ChatTopic, response_model_exclude_none=True)+def update_topic(topic_id: int, body: TopicUpdate, request: Request) -> ChatTopic:+ """Rename or pin one of the caller's topics. Renaming to the name of+ another of their topics merges the two."""+ caller = _require_caller(request)+ if chat_topics.owned_topic(caller, topic_id) is None:+ raise HTTPException(status_code=404, detail="Topic not found")+ if body.name is not None:+ moved = chat_topics.rename_topic(caller, topic_id, _topic_name(body.name))+ topic_id = moved if moved is not None else topic_id+ if body.pinned is not None:+ chat_topics.pin_topic(caller, topic_id, body.pinned)+ for t in chat_topics.list_topics(caller):+ if t["id"] == topic_id:+ return ChatTopic(**t)+ raise HTTPException(status_code=404, detail="Topic not found")++[email protected]("/sessions/topics/{topic_id}/merge", status_code=status.HTTP_204_NO_CONTENT)+def merge_topic(topic_id: int, body: TopicMerge, request: Request) -> Response:+ """Move every chat under one of the caller's topics to another of theirs."""+ caller = _require_caller(request)+ if not chat_topics.merge_topics(caller, topic_id, body.into_id):+ raise HTTPException(status_code=404, detail="Topic not found")+ chat_topics.keep_topic(caller, body.into_id)+ return Response(status_code=status.HTTP_204_NO_CONTENT)++[email protected]("/sessions/topics/{topic_id}", status_code=status.HTTP_204_NO_CONTENT)+def ungroup_topic(topic_id: int, request: Request) -> Response:+ """Drop one of the caller's topics. Its chats go under no topic and stay+ there; none is deleted."""+ caller = _require_caller(request)+ if not chat_topics.ungroup_topic(caller, topic_id):+ raise HTTPException(status_code=404, detail="Topic not found")+ return Response(status_code=status.HTTP_204_NO_CONTENT)++@router.get("/sessions/shared-with-me",response_model=list[SessionSummary],@@ -172,6 +272,7 @@ def get_session(session_id: str, request: Request) -> SessionSummary:# Only the owner pins, so a member never sees the owner's pin._, owner = get_session_owner(session_id)summary.pinned_at = None+ summary.topic_id = Nonesummary.shared_with_you = Truesummary.shared_by = _person_name(owner) or "Someone on your team"return summary@@ -304,21 +405,39 @@ async def live_session(session_id: str, request: Request) -> StreamingResponse:class SessionUpdate(BaseModel):- """Rename and / or pin a chat. A field left out is left as it is."""+ """Rename, pin and / or file a chat. A field left out is left as it is.+ ``topic_id`` null files it under no topic; ``topic_name`` files it under+ the caller's topic of that name, made if new."""title: str | None = Field(default=None, min_length=1, max_length=120)pinned: bool | None = None+ topic_id: int | None = None+ topic_name: str | None = Field(default=None, min_length=1, max_length=chat_topics.MAX_TOPIC_CHARS)@router.patch("/sessions/{session_id}", response_model=SessionSummary, response_model_exclude_none=True)def update_session(session_id: str, body: SessionUpdate, request: Request) -> SessionSummary:"""The owner names their chat (the automatic title never replaces itafter) or pins it to the top of their list."""- _require_owner(request, session_id)- if body.title is not None:- title = " ".join(body.title.split())- if not title:- raise HTTPException(status_code=422, detail="A title can't be blank")+ owner = _require_owner(request, session_id)+ # Everything is checked before anything is written, so a refused field+ # leaves the chat as it was.+ title = " ".join(body.title.split()) if body.title is not None else None+ if title == "":+ raise HTTPException(status_code=422, detail="A title can't be blank")+ topic_name = _topic_name(body.topic_name) if body.topic_name is not None else None+ if (+ topic_name is None+ and "topic_id" in body.model_fields_set+ and body.topic_id is not None+ and chat_topics.owned_topic(owner, body.topic_id) is None+ ):+ raise HTTPException(status_code=404, detail="Topic not found")+ if topic_name is not None:+ chat_topics.file_session(session_id, owner, name=topic_name)+ elif "topic_id" in body.model_fields_set:+ chat_topics.file_session(session_id, owner, topic_id=body.topic_id)+ if title is not None:rename_session(session_id, title)if body.pinned is not None:set_pinned(session_id, body.pinned)diff --git a/packages/core/openexecutive/architecture/architecture-facts.yaml b/packages/core/openexecutive/architecture/architecture-facts.yamlindex 35a5b4ec..fc1d1210 100644--- a/packages/core/openexecutive/architecture/architecture-facts.yaml+++ b/packages/core/openexecutive/architecture/architecture-facts.yaml@@ -2377,6 +2377,22 @@ memory:a chat-app conversation's reply also lives in that app. The page asksfirst when the reply being redone already did something (action chips),since the new turn could do it again.+ chat_topics: |+ The Chats page groups a person's own chats by date or by topic+ (memory/chat_topics.py, utils/chat_topics.py). Topics are per owner+ (chat_topics rows; sessions.topic_id, sessions.topic_source). Why it+ costs almost nothing: the one utility-fast call that already titled a+ new chat now returns its topic too, choosing from the owner's recent+ topic names, so filing adds a few tokens, not a call. A second short+ call runs only when that turn made a new topic: it checks the new name+ against the others (names only) and merges a duplicate at once, rather+ than a scheduled tidy. Older chats are filed from their titles in+ batches, started by the first Topic view, not at boot, so an idle tenant+ spends no CPU or usage on it. What the owner does sticks: a chat they+ filed (topic_source 'owner') is never refiled, and a topic they renamed,+ pinned, merged into or filed a chat under (kept) is never merged away.+ A chat shared with someone keeps its owner's topic, which the reader+ never sees.session_scoping: |Decisions and advice rows carry a session_id so per-thread continuity(Discord, Telegram) can pull just-this-thread history without leakingdiff --git a/packages/core/openexecutive/architecture/prebuilt/api.json b/packages/core/openexecutive/architecture/prebuilt/api.jsonindex 8b62100d..a4760fcc 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`, `DELETE /sessions/{id}/shares/me`, `GET /sessions/{id}/people`, `GET /sessions/{id}/live`, `POST /sessions/{id}/typing`, `GET /sessions/{id}/export`, `POST /sessions/{id}/rewind` | List, read and delete saved chat sessions (assistant messages carry their row `id` and any `feedback`). The list is scoped to the caller, and each chat carries `preview`: its last message as one plain line, Markdown marks stripped and cut at a word near 120 characters, with `You:` before the person's own words. With `?q=` it is a search: the caller's own chats whose title or message text contains the words (case-insensitive, `LIKE` with wildcards escaped), each with `match_count` (messages that contain them; 0 for a title-only match) and `snippet` (the newest matching message, around the match, prefixed `You:` or `Executive:`). Scoped exactly like the list, so nobody else's conversation can match. The Chats page searches this way and opens a result with `?find=`, so the chat starts on that message and steps through the others. A chat-app conversation started with /new is left off the list until its first turn (`memory.conversations`). Every per-session route checks ownership, because session ids are guessable (`slack:dm:<user id>`, `telegram:<chat id>`): only the session's owner or the principal gets through, and a legacy row with no owner is the principal's alone. A teammate's own chat (a web chat, a DM, a private Telegram chat; not a channel or group conversation, `chat._shared_space`) is theirs alone, the principal included, as their mail with the Executive is. Anyone else gets the same 404 as for an unknown id, so the routes can't be used to find out which chats exist. The one other way in is having started the chat in this process (matched by Person id or verified email, so it survives the caller being added to the roster), which is how a caller the roster can't resolve keeps using their own chat. That record is in memory, so after a restart such an ownerless chat is refused for reads. The principal can continue someone else's ownerless chat without becoming its owner. Deleting a session also drops its in-memory copy, so a later turn naming that id starts fresh. The feedback route records 👍/👎 (`{\"feedback\": \"up\"|\"down\"|null}`) on one assistant reply; only the session's own caller or the principal may rate it. The rater is stored (`feedback_by_person_id`), and a 👎 on a reply to the rater's own message triggers a working-style pass for them (paced; see attunement). The chat stream's `done` event carries `message_id` for the persisted reply. The followup route returns `{\"suggestion\": string|null}` — one suggested next user message, written by the utility-fast model from the last few turns, that the chat composer shows as its greyed placeholder (Tab / → or the inline chip fills it in without sending). It is null unless the session ends on a persisted assistant reply, and null (uncached) when the model fails. Same ownership check as feedback; successful suggestions are cached in-process per (session, reply id). Messages from `GET /sessions/{id}/messages` carry each assistant reply's saved `sources` (the same shape as the chat stream's `sources` event, without `type`), so a reloaded chat shows them again. The owner (not the principal on someone else's chat; the principal for an ownerless one) also has the chat controls. `PATCH` takes `{title?, pinned?}`: a name they give is kept (`sessions.title_locked`, so the automatic title never replaces it) and a pinned chat lists first, newest pin first, with `pinned_at`. `PUT /sessions/{id}/shares {person_ids}` adds exactly those team members to it (not contacts, the archived or the owner: 422), audited `session_shared`; a chat that read its owner's own mail (`mail_private`) is never shared (409) and stops being open to those it was shared with before, and a chat-app conversation is never shared (409). Those added get it from `GET /sessions/shared-with-me` (with `shared_with_you`, `shared_by`, `shared_at`) and **write in it with the owner**: `POST /chat` with its id runs their turn as themselves (`chat._shared_member` widens the turn's access, never its ownership), and they may read it, its messages (without the owner's ratings) and its export. They can't rate, rename, delete, share or redo it, and `DELETE /sessions/{id}/shares/me` takes them out of it (audited `session_shared`, with them under `removed`). In a chat several people are in, messages carry `sender_person_id` and `sender_name` (a message from before it was shared is the owner's), `GET /sessions/{id}/people` returns `{you, people: [{person_id, full_name, owner}]}` (owner first; empty for a chat of one), and redo is refused (409) when the last message is someone else's. `GET /sessions/{id}/live` is a server-sent event stream each open page holds (`api.chat_live`, one in-process broker): `ready` first (with the running turn so far, if any), then `turn_started` (who sent what), the reply's `chunk` / `thinking` / `activity` / `action_taken` / `phase`, `turn_ended` (the page reads the chat again), `typing` (from `POST /sessions/{id}/typing`, at most once per 2 s per person) and `people`. `removed`, `deleted` and `resync` (a page that fell 1024 events behind) end it; the access check runs again on every 20 s keepalive. At most 12 pages per person, 40 per chat and 2000 per process (429). Archiving someone takes them out of every chat shared with them, and their open streams close at the next keepalive. The page closes it while its tab is hidden. `GET /sessions/{id}/export` returns the chat as a Markdown file (`memory.chat_export`: each message under its writer's People name or `Executive`, the reply's sources listed under it). `POST /sessions/{id}/rewind {last_message_id}` takes back the last turn for Try again and Edit: under the conversation's turn lock it deletes the last reply and the messages it answered, but only while that reply is still the chat's last row, and returns those messages' words (`{message}`), which the page sends again as an ordinary `/chat` turn through the usual gates. 409 while a turn is answering, for a stale reply id, and for a chat-app conversation (its reply also lives in Slack, Telegram or Discord); audited `session_rewound`. |\n| `today` | `GET /today`, `GET /today/activity`, `GET /today/activity/daily`, `GET /today/brief-delivery`, `GET /today/value`, `GET /today/top-three`, `GET /today/weekly-review` | 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| `reflection` | `GET /memories/reflection` (`?person_id=`), `DELETE /memories/reflection/misses/{id}` | What it got wrong: the turns the conversation review graded a miss (`memory.chat_review`), with the person's words, the reply, the tools run, what they wanted instead, the `kind` (`company` / `product`) and the signals, plus `weeks` (`{week, graded, misses}` per ISO week, newest first) and `sees_everyone`. The caller is resolved as for `history` (403 `sign_in_required` / `not_on_roster`); each person sees their own, the principal those from chats `chat._session_access` lets them open (a teammate's own web chat or DM and a mail-private conversation stay their owner's; channels and groups are open), or one person's with `?person_id=` (a teammate naming someone else gets 403 `not_yours`); the weekly counts carry no words and are not filtered. The same response carries `lessons` (`memory/lessons.py`: live first, then retired, each with `shown`/`fine_after`/`miss_after` and `retired_reason`), filtered by the same rule, and `DELETE /memories/reflection/lessons/{id}` retires one (204; 404 for a lesson the caller may not see, already retired, or missing). `DELETE` forgets one miss (`is_principal_or_self`; 404 `not_found` otherwise) and writes a `chat_review` audit row. Each miss also carries its nightly replay (`memory/replay.py`): `replay_state` (`open` / `closed` / `evidence`), `replayed_at`, `closed_at`, `replay_notes`; and the response carries `replay` (`{misses, would_pass, evidence, last_run_at}`: of the caller's visible misses from the last 30 days, how many would go right today). |\n| `notifications` | `GET /notifications/settings`, `PUT /notifications/settings` | Settings → Notifications: the **caller's own** settings only, resolved as for the notes (a signed-in person on the People list, or the principal under local login; otherwise 403 `sign_in_required` / `not_on_roster`). `GET` returns `{quiet_hours: {enabled, start, end, days}, delivery, urgent_through, timezone, effective_timezone, held_count, gets_briefs, updated_at}` — `days` is `every_day` or `weekdays`, `delivery` `instant` or `digest`, `timezone` the zone they chose (`\"\"` for the workspace's), `held_count` how many messages wait for their quiet hours or brief (counted, never listed), `gets_briefs` whether they are the principal. `PUT` takes `{quiet_hours, delivery, urgent_through, timezone}` and replaces them (extra fields, equal start and end, a bad time or an unknown zone → 422); switching `digest` → `instant` makes what waited for the brief go now. Audited as `notification_settings_changed`. See Org. |\n| `audit` | `GET /audit/logs`, `GET /audit/logs/{id}`, `GET /audit/sessions/{id}`, `GET /audit/usage`, `POST /audit/log` | Durable audit trail of side effects. `/audit/sessions/{id}` adds a per-session token cost summary; `/audit/usage` aggregates token usage and OpenRouter cost across all sessions (totals, by day, by model, and by source — the part of the system that made the calls — including server-side web-search counts), plus `scripts`: how many `run_script` scripts ran (and worked, and in workflows), the tool calls they made, their time, and `turns_avoided` — an upper bound on the model turns those calls would otherwise have needed (each call past a script's first) — and `python_jobs`: how many Python jobs ran (and worked, ran a kept Custom tool, took a chat attachment), their time, CPU, largest peak memory and bytes in and out, and the tokens and charge of the turns that ran one. The Token usage page shows it as a Scripts section. Rows private to the principal (`private_to_principal`: a turn about their private mail, or a row naming one of their contacts on their own turn) are theirs alone: for any other caller, resolved as for `/alerts`, the usage totals leave them out. Once a principal is on the roster, anyone else reads only their own rows (a teammate's own turns, their Act as me work) in the list, by id and in a session, and the principal reads those as actions only — what was done, when and in whose conversation, with the text, details and `full` left out, and no text search over them; any other row's id is a 404, and a session shows only the rows the caller reads. |\n| `architecture` | `GET /architecture/sections`, `.../sections/{id}` | This documentation surface. |\n| `guide` | `GET /guide/sections`, `.../sections/{id}` | Plain-language user-guide content surface — mirrors `architecture` (static, version-controlled files; no LLM on the serving path). |\n| `health` | `GET /health`, `GET /health/honcho` | Liveness probes. Only `/health` is unauthenticated; `/health/honcho` sits behind the gate like everything else, because the exemption is an exact-path set. `/health` also carries `google_tools_missing`, the pinned Google tools startup priming could not find: `[]` once it has checked and they are all there, a list of names when a workspace-mcp rename or the configured services and tool tier left one out, and `null` for no answer — Google Workspace is not configured, or the probe has not finished or it failed. Only `[]` asserts they are present. It also carries `gateway`, the MCP gateway's state from its supervisor (`orchestrator.gateway_boot`): `state` is `off` (MCP not enabled), `no_servers` (enabled, the config names none), `starting` (an attempt is running), `up` or `down` (every attempt so far failed; `next_retry_at` is the next one), with `attempts`, `up_since` and `email_poller` (whether the poller that rides on the gateway runs); the failure's own text stays out, since the route is open to anyone, and goes to the log and the owner's notice on Home. A hosted instance whose gateway never came up used to answer `ok` here with no email going out or in. Only `[]` asserts the tools are present, so a probe that died cannot read as healthy; Setup status says which of the three `null` means. |\n| `version` | `GET /version` | The running version, the latest release on GitHub and `update_available`, for Settings → About. The GitHub answer is cached 6h, only a semver `tag_name` is used and the release link is built from it; `UPDATE_CHECK_ENABLED=false` skips the call and still returns the running version. No in-app updater: upgrading is host-side (`docs/deployment.md#upgrading`). |\n| `setup_status` | `GET /setup/status` | Settings → Setup status: one light per part of the install — AI model, company setup, owner, the Executive's address, API protection, Gmail, your own mailbox (Act as me), Slack, Discord, Telegram, Google Chat, the scheduler, the daily brief (when and where it goes) and Honcho — as `{checked_at, checks: [{id, label, state, summary, fix, link, last_activity}]}`, where `state` is `ok`, `warn`, `error` or `off` (optional and not set up), `fix` says what to do in plain language, `link` is an in-app page that helps (`/people`, `/onboard`) and `last_activity` is the channel's latest `integration_inbound` audit time. It tests live, with at most one free read-only call per service, each bounded to 5 s: Anthropic `models.list` (so an organisation key missing `ANTHROPIC_WORKSPACE_ID` shows up), Slack `auth.test`, Telegram `getMe` and `getWebhookInfo`, Discord `users/@me` only while the bot is still connecting, and — once the owner's own Gmail credential exists — Google's token refresh and Gmail `users/me/profile`. It also reads the listeners the lifespan leaves on `app.state` (Slack's socket, the Discord bot and its task, the MCP gateway), the scheduler heartbeat and the pause switch. When `google_workspace` is configured, the lifespan also starts `MCPGateway.prime_pinned_tools()` in the background (held on `app.state.mcp_prime_task`, cancelled at shutdown), so the pinned Google tools named in the prompt are callable without a search. With `DRIVE_SYNC_ENABLED` the lifespan also bootstraps the `drive_sync_scan` heartbeat beside Notion's (see Scheduler); the Drive folder sync has no HTTP route, only the `openexecutive sync-drive` / `purge-drive` CLI. With `CONFLUENCE_SYNC_ENABLED` it bootstraps the `confluence_sync_scan` heartbeat the same way; that sync is run by hand with `openexecutive sync-confluence` / `purge-confluence`. Sample values copied from `.env.example` are named as such without being sent anywhere. No token reaches a response or a log line: probes report a status code, a service's short error code or an exception's class name. Requests within 5 s of a run get that run's answer and concurrent requests share one run (kept per app on `app.state`), so the button can't become a stream of calls to those services. Gated like every other route; the UI adds a sign-in light of its own, from its own settings. |\n| `documents` | `POST\\|GET\\|DELETE /documents`, `GET /documents/{filename}`, `GET /documents/sources`, `POST /documents/sources/{drive\\|onedrive\\|notion}/sync`, `GET /documents/{drive\\|onedrive\\|notion}`, `GET /documents/{drive\\|onedrive\\|notion}/{id}` | Upload, list, view extracted text, and delete indexed company docs. `GET /documents` rows carry `source: \"upload\"` and the `domain` the upload was indexed under. The connected-source routes back the knowledge page's single Company documents list: `/documents/sources` gives each source's `{id, label, enabled, syncing, last_run, last_error, interval_minutes, file_count}`; `/documents/drive`, `/documents/onedrive` and `/documents/notion` list synced files from the sync state (`{enabled, last_run, last_error, files: [{id, name, url, modified_at, synced_at, indexed}]}`; a Drive row also carries `unreadable_reason`, why a file with `indexed: false` has no text — e.g. a scan OCR could not read — or null); `/documents/{drive\\|onedrive\\|notion}/{id}` returns the stored text (a OneDrive id is `<drive id>:<item id>`) for an id on record (the path comes from the state, never the caller). They are read-only — a synced file is removed where it lives. `POST …/sync` starts one tick of the same sync the scheduler runs as a background task (202); 409 when the source is not connected or a tick is already running (every sync holds a per-process run lock, so a manual run never overlaps the heartbeat; the route also keeps its own started task per source and re-checks just before starting one, so two simultaneous requests start one tick, not two), 429 with `Retry-After` within 60 s of the last successful run or of the end of the last tick in this process, failed ones included, so a failing or slow source can't be re-run back-to-back. The page's text view never loads images from synced content (a remote image would be a read beacon for whoever edits the shared folder). Upload is keyed on the filename, so re-uploading a document replaces its chunks rather than duplicating them, and `DELETE` removes the rows as well as the file. `domain` must be one of the nine specialist domains (including `sales`) or `general`; anything else is a 400 rather than a 200 that indexes where no specialist can retrieve. A scanned PDF is converted (`knowledge.pdf_reader`) before it is indexed and in the text view, as are scanned PDFs in `POST /chat/upload` and the client / onboarding intake uploads. The upload is streamed to disk 1 MB at a time and refused with a 413 once it passes 50 MB, and the file is parsed in a short-lived child process (see the RAG section), so a large document does not stay in the API process's memory. A Word or Excel file that cannot be parsed, or whose parse runs out of time, is a 422 with a readable reason. When every parser is busy, the response is a 503 with `Retry-After`. |\n| `executive` | `GET /executive/status`, `POST /executive/pause`, `POST /executive/resume` | Operator pause switch for all autonomous work (scheduler, Gmail poller, workflow resumer); inbound chat and DMs stay live. Status returns `{paused, paused_at, paused_by, reason, held_actions, can_resume}` — `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, answered as the verified caller (`api.caller`) by the web app's rules. 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.",+ "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 /sessions/topics`, `PATCH\\|DELETE /sessions/topics/{topic_id}`, `POST /sessions/topics/{topic_id}/merge`, `GET\\|PATCH /sessions/{id}`, `GET /sessions/{id}/messages`, `DELETE /sessions/{id}`, `POST /sessions/{id}/messages/{message_id}/feedback`, `GET /sessions/{id}/followup`, `GET\\|PUT /sessions/{id}/shares`, `DELETE /sessions/{id}/shares/me`, `GET /sessions/{id}/people`, `GET /sessions/{id}/live`, `POST /sessions/{id}/typing`, `GET /sessions/{id}/export`, `POST /sessions/{id}/rewind` | List, read and delete saved chat sessions (assistant messages carry their row `id` and any `feedback`). The list is scoped to the caller, and each chat carries `preview`: its last message as one plain line, Markdown marks stripped and cut at a word near 120 characters, with `You:` before the person's own words. With `?q=` it is a search: the caller's own chats whose title or message text contains the words (case-insensitive, `LIKE` with wildcards escaped), each with `match_count` (messages that contain them; 0 for a title-only match) and `snippet` (the newest matching message, around the match, prefixed `You:` or `Executive:`). Scoped exactly like the list, so nobody else's conversation can match. The Chats page searches this way and opens a result with `?find=`, so the chat starts on that message and steps through the others. Each of the owner's chats also carries `topic_id`, the topic it is filed under (`memory.chat_topics`). `GET /sessions/topics` lists the caller's topics (`id`, `name`, `chat_count`, `kept`, `pinned_at`) and, when some of their chats have no topic yet, starts filing them in the background from their titles and answers `organizing: true` until done. `PATCH /sessions/topics/{topic_id}` renames (a name another of their topics has merges the two) or pins one, `POST …/merge` moves its chats into another (`into_id`), and `DELETE` ungroups it, leaving its chats under no topic; another person's topic is a 404. `PATCH /sessions/{id}` also takes `topic_id` (null for none) or `topic_name` (made if new) to file the chat, which then is never refiled on its own. A chat-app conversation started with /new is left off the list until its first turn (`memory.conversations`). Every per-session route checks ownership, because session ids are guessable (`slack:dm:<user id>`, `telegram:<chat id>`): only the session's owner or the principal gets through, and a legacy row with no owner is the principal's alone. A teammate's own chat (a web chat, a DM, a private Telegram chat; not a channel or group conversation, `chat._shared_space`) is theirs alone, the principal included, as their mail with the Executive is. Anyone else gets the same 404 as for an unknown id, so the routes can't be used to find out which chats exist. The one other way in is having started the chat in this process (matched by Person id or verified email, so it survives the caller being added to the roster), which is how a caller the roster can't resolve keeps using their own chat. That record is in memory, so after a restart such an ownerless chat is refused for reads. The principal can continue someone else's ownerless chat without becoming its owner. Deleting a session also drops its in-memory copy, so a later turn naming that id starts fresh. The feedback route records 👍/👎 (`{\"feedback\": \"up\"|\"down\"|null}`) on one assistant reply; only the session's own caller or the principal may rate it. The rater is stored (`feedback_by_person_id`), and a 👎 on a reply to the rater's own message triggers a working-style pass for them (paced; see attunement). The chat stream's `done` event carries `message_id` for the persisted reply. The followup route returns `{\"suggestion\": string|null}` — one suggested next user message, written by the utility-fast model from the last few turns, that the chat composer shows as its greyed placeholder (Tab / → or the inline chip fills it in without sending). It is null unless the session ends on a persisted assistant reply, and null (uncached) when the model fails. Same ownership check as feedback; successful suggestions are cached in-process per (session, reply id). Messages from `GET /sessions/{id}/messages` carry each assistant reply's saved `sources` (the same shape as the chat stream's `sources` event, without `type`), so a reloaded chat shows them again. The owner (not the principal on someone else's chat; the principal for an ownerless one) also has the chat controls. `PATCH` takes `{title?, pinned?}`: a name they give is kept (`sessions.title_locked`, so the automatic title never replaces it) and a pinned chat lists first, newest pin first, with `pinned_at`. `PUT /sessions/{id}/shares {person_ids}` adds exactly those team members to it (not contacts, the archived or the owner: 422), audited `session_shared`; a chat that read its owner's own mail (`mail_private`) is never shared (409) and stops being open to those it was shared with before, and a chat-app conversation is never shared (409). Those added get it from `GET /sessions/shared-with-me` (with `shared_with_you`, `shared_by`, `shared_at`) and **write in it with the owner**: `POST /chat` with its id runs their turn as themselves (`chat._shared_member` widens the turn's access, never its ownership), and they may read it, its messages (without the owner's ratings) and its export. They can't rate, rename, delete, share or redo it, and `DELETE /sessions/{id}/shares/me` takes them out of it (audited `session_shared`, with them under `removed`). In a chat several people are in, messages carry `sender_person_id` and `sender_name` (a message from before it was shared is the owner's), `GET /sessions/{id}/people` returns `{you, people: [{person_id, full_name, owner}]}` (owner first; empty for a chat of one), and redo is refused (409) when the last message is someone else's. `GET /sessions/{id}/live` is a server-sent event stream each open page holds (`api.chat_live`, one in-process broker): `ready` first (with the running turn so far, if any), then `turn_started` (who sent what), the reply's `chunk` / `thinking` / `activity` / `action_taken` / `phase`, `turn_ended` (the page reads the chat again), `typing` (from `POST /sessions/{id}/typing`, at most once per 2 s per person) and `people`. `removed`, `deleted` and `resync` (a page that fell 1024 events behind) end it; the access check runs again on every 20 s keepalive. At most 12 pages per person, 40 per chat and 2000 per process (429). Archiving someone takes them out of every chat shared with them, and their open streams close at the next keepalive. The page closes it while its tab is hidden. `GET /sessions/{id}/export` returns the chat as a Markdown file (`memory.chat_export`: each message under its writer's People name or `Executive`, the reply's sources listed under it). `POST /sessions/{id}/rewind {last_message_id}` takes back the last turn for Try again and Edit: under the conversation's turn lock it deletes the last reply and the messages it answered, but only while that reply is still the chat's last row, and returns those messages' words (`{message}`), which the page sends again as an ordinary `/chat` turn through the usual gates. 409 while a turn is answering, for a stale reply id, and for a chat-app conversation (its reply also lives in Slack, Telegram or Discord); audited `session_rewound`. |\n| `today` | `GET /today`, `GET /today/activity`, `GET /today/activity/daily`, `GET /today/brief-delivery`, `GET /today/value`, `GET /today/top-three`, `GET /today/weekly-review` | 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| `reflection` | `GET /memories/reflection` (`?person_id=`), `DELETE /memories/reflection/misses/{id}` | What it got wrong: the turns the conversation review graded a miss (`memory.chat_review`), with the person's words, the reply, the tools run, what they wanted instead, the `kind` (`company` / `product`) and the signals, plus `weeks` (`{week, graded, misses}` per ISO week, newest first) and `sees_everyone`. The caller is resolved as for `history` (403 `sign_in_required` / `not_on_roster`); each person sees their own, the principal those from chats `chat._session_access` lets them open (a teammate's own web chat or DM and a mail-private conversation stay their owner's; channels and groups are open), or one person's with `?person_id=` (a teammate naming someone else gets 403 `not_yours`); the weekly counts carry no words and are not filtered. The same response carries `lessons` (`memory/lessons.py`: live first, then retired, each with `shown`/`fine_after`/`miss_after` and `retired_reason`), filtered by the same rule, and `DELETE /memories/reflection/lessons/{id}` retires one (204; 404 for a lesson the caller may not see, already retired, or missing). `DELETE` forgets one miss (`is_principal_or_self`; 404 `not_found` otherwise) and writes a `chat_review` audit row. Each miss also carries its nightly replay (`memory/replay.py`): `replay_state` (`open` / `closed` / `evidence`), `replayed_at`, `closed_at`, `replay_notes`; and the response carries `replay` (`{misses, would_pass, evidence, last_run_at}`: of the caller's visible misses from the last 30 days, how many would go right today). |\n| `notifications` | `GET /notifications/settings`, `PUT /notifications/settings` | Settings → Notifications: the **caller's own** settings only, resolved as for the notes (a signed-in person on the People list, or the principal under local login; otherwise 403 `sign_in_required` / `not_on_roster`). `GET` returns `{quiet_hours: {enabled, start, end, days}, delivery, urgent_through, timezone, effective_timezone, held_count, gets_briefs, updated_at}` — `days` is `every_day` or `weekdays`, `delivery` `instant` or `digest`, `timezone` the zone they chose (`\"\"` for the workspace's), `held_count` how many messages wait for their quiet hours or brief (counted, never listed), `gets_briefs` whether they are the principal. `PUT` takes `{quiet_hours, delivery, urgent_through, timezone}` and replaces them (extra fields, equal start and end, a bad time or an unknown zone → 422); switching `digest` → `instant` makes what waited for the brief go now. Audited as `notification_settings_changed`. See Org. |\n| `audit` | `GET /audit/logs`, `GET /audit/logs/{id}`, `GET /audit/sessions/{id}`, `GET /audit/usage`, `POST /audit/log` | Durable audit trail of side effects. `/audit/sessions/{id}` adds a per-session token cost summary; `/audit/usage` aggregates token usage and OpenRouter cost across all sessions (totals, by day, by model, and by source — the part of the system that made the calls — including server-side web-search counts), plus `scripts`: how many `run_script` scripts ran (and worked, and in workflows), the tool calls they made, their time, and `turns_avoided` — an upper bound on the model turns those calls would otherwise have needed (each call past a script's first) — and `python_jobs`: how many Python jobs ran (and worked, ran a kept Custom tool, took a chat attachment), their time, CPU, largest peak memory and bytes in and out, and the tokens and charge of the turns that ran one. The Token usage page shows it as a Scripts section. Rows private to the principal (`private_to_principal`: a turn about their private mail, or a row naming one of their contacts on their own turn) are theirs alone: for any other caller, resolved as for `/alerts`, the usage totals leave them out. Once a principal is on the roster, anyone else reads only their own rows (a teammate's own turns, their Act as me work) in the list, by id and in a session, and the principal reads those as actions only — what was done, when and in whose conversation, with the text, details and `full` left out, and no text search over them; any other row's id is a 404, and a session shows only the rows the caller reads. |\n| `architecture` | `GET /architecture/sections`, `.../sections/{id}` | This documentation surface. |\n| `guide` | `GET /guide/sections`, `.../sections/{id}` | Plain-language user-guide content surface — mirrors `architecture` (static, version-controlled files; no LLM on the serving path). |\n| `health` | `GET /health`, `GET /health/honcho` | Liveness probes. Only `/health` is unauthenticated; `/health/honcho` sits behind the gate like everything else, because the exemption is an exact-path set. `/health` also carries `google_tools_missing`, the pinned Google tools startup priming could not find: `[]` once it has checked and they are all there, a list of names when a workspace-mcp rename or the configured services and tool tier left one out, and `null` for no answer — Google Workspace is not configured, or the probe has not finished or it failed. Only `[]` asserts they are present. It also carries `gateway`, the MCP gateway's state from its supervisor (`orchestrator.gateway_boot`): `state` is `off` (MCP not enabled), `no_servers` (enabled, the config names none), `starting` (an attempt is running), `up` or `down` (every attempt so far failed; `next_retry_at` is the next one), with `attempts`, `up_since` and `email_poller` (whether the poller that rides on the gateway runs); the failure's own text stays out, since the route is open to anyone, and goes to the log and the owner's notice on Home. A hosted instance whose gateway never came up used to answer `ok` here with no email going out or in. Only `[]` asserts the tools are present, so a probe that died cannot read as healthy; Setup status says which of the three `null` means. |\n| `version` | `GET /version` | The running version, the latest release on GitHub and `update_available`, for Settings → About. The GitHub answer is cached 6h, only a semver `tag_name` is used and the release link is built from it; `UPDATE_CHECK_ENABLED=false` skips the call and still returns the running version. No in-app updater: upgrading is host-side (`docs/deployment.md#upgrading`). |\n| `setup_status` | `GET /setup/status` | Settings → Setup status: one light per part of the install — AI model, company setup, owner, the Executive's address, API protection, Gmail, your own mailbox (Act as me), Slack, Discord, Telegram, Google Chat, the scheduler, the daily brief (when and where it goes) and Honcho — as `{checked_at, checks: [{id, label, state, summary, fix, link, last_activity}]}`, where `state` is `ok`, `warn`, `error` or `off` (optional and not set up), `fix` says what to do in plain language, `link` is an in-app page that helps (`/people`, `/onboard`) and `last_activity` is the channel's latest `integration_inbound` audit time. It tests live, with at most one free read-only call per service, each bounded to 5 s: Anthropic `models.list` (so an organisation key missing `ANTHROPIC_WORKSPACE_ID` shows up), Slack `auth.test`, Telegram `getMe` and `getWebhookInfo`, Discord `users/@me` only while the bot is still connecting, and — once the owner's own Gmail credential exists — Google's token refresh and Gmail `users/me/profile`. It also reads the listeners the lifespan leaves on `app.state` (Slack's socket, the Discord bot and its task, the MCP gateway), the scheduler heartbeat and the pause switch. When `google_workspace` is configured, the lifespan also starts `MCPGateway.prime_pinned_tools()` in the background (held on `app.state.mcp_prime_task`, cancelled at shutdown), so the pinned Google tools named in the prompt are callable without a search. With `DRIVE_SYNC_ENABLED` the lifespan also bootstraps the `drive_sync_scan` heartbeat beside Notion's (see Scheduler); the Drive folder sync has no HTTP route, only the `openexecutive sync-drive` / `purge-drive` CLI. With `CONFLUENCE_SYNC_ENABLED` it bootstraps the `confluence_sync_scan` heartbeat the same way; that sync is run by hand with `openexecutive sync-confluence` / `purge-confluence`. Sample values copied from `.env.example` are named as such without being sent anywhere. No token reaches a response or a log line: probes report a status code, a service's short error code or an exception's class name. Requests within 5 s of a run get that run's answer and concurrent requests share one run (kept per app on `app.state`), so the button can't become a stream of calls to those services. Gated like every other route; the UI adds a sign-in light of its own, from its own settings. |\n| `documents` | `POST\\|GET\\|DELETE /documents`, `GET /documents/{filename}`, `GET /documents/sources`, `POST /documents/sources/{drive\\|onedrive\\|notion}/sync`, `GET /documents/{drive\\|onedrive\\|notion}`, `GET /documents/{drive\\|onedrive\\|notion}/{id}` | Upload, list, view extracted text, and delete indexed company docs. `GET /documents` rows carry `source: \"upload\"` and the `domain` the upload was indexed under. The connected-source routes back the knowledge page's single Company documents list: `/documents/sources` gives each source's `{id, label, enabled, syncing, last_run, last_error, interval_minutes, file_count}`; `/documents/drive`, `/documents/onedrive` and `/documents/notion` list synced files from the sync state (`{enabled, last_run, last_error, files: [{id, name, url, modified_at, synced_at, indexed}]}`; a Drive row also carries `unreadable_reason`, why a file with `indexed: false` has no text — e.g. a scan OCR could not read — or null); `/documents/{drive\\|onedrive\\|notion}/{id}` returns the stored text (a OneDrive id is `<drive id>:<item id>`) for an id on record (the path comes from the state, never the caller). They are read-only — a synced file is removed where it lives. `POST …/sync` starts one tick of the same sync the scheduler runs as a background task (202); 409 when the source is not connected or a tick is already running (every sync holds a per-process run lock, so a manual run never overlaps the heartbeat; the route also keeps its own started task per source and re-checks just before starting one, so two simultaneous requests start one tick, not two), 429 with `Retry-After` within 60 s of the last successful run or of the end of the last tick in this process, failed ones included, so a failing or slow source can't be re-run back-to-back. The page's text view never loads images from synced content (a remote image would be a read beacon for whoever edits the shared folder). Upload is keyed on the filename, so re-uploading a document replaces its chunks rather than duplicating them, and `DELETE` removes the rows as well as the file. `domain` must be one of the nine specialist domains (including `sales`) or `general`; anything else is a 400 rather than a 200 that indexes where no specialist can retrieve. A scanned PDF is converted (`knowledge.pdf_reader`) before it is indexed and in the text view, as are scanned PDFs in `POST /chat/upload` and the client / onboarding intake uploads. The upload is streamed to disk 1 MB at a time and refused with a 413 once it passes 50 MB, and the file is parsed in a short-lived child process (see the RAG section), so a large document does not stay in the API process's memory. A Word or Excel file that cannot be parsed, or whose parse runs out of time, is a 422 with a readable reason. When every parser is busy, the response is a 503 with `Retry-After`. |\n| `executive` | `GET /executive/status`, `POST /executive/pause`, `POST /executive/resume` | Operator pause switch for all autonomous work (scheduler, Gmail poller, workflow resumer); inbound chat and DMs stay live. Status returns `{paused, paused_at, paused_by, reason, held_actions, can_resume}` — `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, answered as the verified caller (`api.caller`) by the web app's rules. 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-16T21:00:00Z"+ "generated_at": "2026-10-17T14:32:47.331884+00:00"}diff --git a/packages/core/openexecutive/architecture/prebuilt/integrations.json b/packages/core/openexecutive/architecture/prebuilt/integrations.jsonindex dd1887c4..20908cf0 100644--- a/packages/core/openexecutive/architecture/prebuilt/integrations.json+++ b/packages/core/openexecutive/architecture/prebuilt/integrations.json@@ -1,7 +1,7 @@{"section_id": "integrations","title": "Integrations",- "markdown": "External channels connect callers to the Executive. Each inbound adapter resolves the sender to a Person — the chat adapters via `find_person_by_{slack,discord,telegram}_id`, the email poller via `people.identity.resolve_email_sender` (a primary address or an alias, then the company-domain rule; see Org) — and threads `person_id` into `Executive.chat()`. A sender who resolves to nobody is no longer simply dropped: see **New senders (roster requests)** below.\n\n### Inbound channels\n\n- **Slack** (`integrations.slack_bot`) — async Bolt app (`AsyncApp`) embedded in the lifespan, hearing Slack one of two ways: socket mode (`AsyncSocketModeHandler`, with `SLACK_APP_TOKEN`) or, with only `SLACK_SIGNING_SECRET`, the Events API over HTTP at `POST /webhook/slack` (`integrations.slack_events`), where the route checks each request's signature and age (and a 1 MB cap) before Bolt sees it, so unsigned traffic never reaches Bolt's logging; it then takes each signed request once, answering an identical replay (same signature) or Slack's re-signed retry of an `event_id` it already took with an empty 200 that never reaches Bolt (an in-memory, per-process set kept for twice the signature window and capped in size; keys are forgotten if Bolt fails, so a retry of a failed delivery still runs), and Bolt acknowledges at once while the listener runs. Either way a repeated event id is dropped (Slack resends what it thinks went unacknowledged), as is an event delivered for another workspace. Responds to `@mention`s, DMs, and thread continuations, with per-conversation session memory (see **Conversation state** below). Text only: there is no interactivity endpoint and no Block Kit, so nothing Slack sends carries a button.\n- **Discord** (`integrations.discord_bot`) — discord.py gateway embedded in the lifespan; per-thread auto-titling, session-scoped memory, author attribution, configurable `@mention` thread promotion.\n- **Telegram** — webhook gating + per-chat history. Replies (and every outbound Telegram message) go out as Telegram's HTML subset (`utils.markdown_telegram`: markdown-it-py with raw HTML and images off, text escaped), so the Executive's Markdown shows as formatting; links show as their text and target in plain text and never become tags, so quoted text can't hide where one goes; a chunk Telegram refuses is sent again as plain text.\n- **Google Chat** — webhook + service-account auth. It resolves no approval gates and has no roster gate (the webhook authenticates Google, not the sender), and it never populates the session's trusted alert ids, so `ack_alert`'s trust check — which now runs on every session rather than only those declaring an `origin_channel` — refuses there by default, and its `<channel>` block says plainly that a sign-off cannot be answered from it. It does look its sender up on People by the Google account email on the signed event, but hands that entry only to the department gate (`Session.gate_sender_person_id`): the principal's own sends and edits go, a teammate's meet their department's authority, and anyone else's wait for approval. It is never `caller_person_id`, so it grants nothing else.\n- **Email** (`integrations.email_poller`) — MCP poll loop over the Executive's own mailbox — Gmail via `workspace-mcp` or Outlook via `ms-365-mcp-server`, chosen by `EMAIL_PROVIDER` (see *Workspace providers* below); it starts only once the MCP gateway is up, never surfaces Reply-To redirects, filters auto-replies. Its sessions carry `origin_channel=\"email\"`: the untrusted-content policy (`orchestrator.content_trust`) reads that tag to tell mail from the principal's own surfaces — left empty, as it once was, every stranger's body reached the decision extractor as the principal's words. The mail goes into the turn inside an `<untrusted_content source=\"email\" author=\"<sender>\" author_verified=\"no\">` block that says it carries none of the principal's authority, with the framing line and any `[POLICY]` notice outside it; mail from the principal's primary address that Gmail authenticated (`dmarc=pass`) is their own words — but only their new text goes in unwrapped: when the mail quotes or forwards another message (`_new_text_lines` cut something), the message as received follows in an `<untrusted_content source=\"email_quoted\">` block, since a stranger's text they replied to or passed on is not theirs. While the Executive is paused (`scheduler.pause`) it skips each poll and leaves the inbox unread, so held mail is processed on the first poll after resume; the chat adapters above are not paused. The poller handles one message at a time, so each Executive turn on an email has a deadline, `EMAIL_TURN_TIMEOUT_S` (300 s): past it the turn is cut off, an `integration_inbound` row with outcome `turn_timeout` records it, and the message is marked read and not run again (it may already have replied). A message whose handling keeps raising is given up after three tries in a run and marked read, rather than retried every poll. Each gateway call it makes is bounded by `MCP_TOOL_TIMEOUT_S` (see Lifecycle). The Executive sees the whole message; peer memory records only `_email_memory_text` — the subject, the sender's new text (cut at the first quoted or forwarded message) and the attachment filenames — parsed from the rendered message with any trailing `--- REPLY ---` block dropped first, without backtracking-prone regexes, since the text is sender-controlled, and only for a rostered sender, the only kind with a peer to record into. The poller's `integration_inbound` row keeps the mail's text for the audit log, the way the reply's `chat_turn` row keeps the Executive's answer: `full.message` is the sender's new text (what web chat keeps for a turn), `full.attachments` the attachment filenames, and `details.preview` the first 120 characters of the new text, so /audit shows what was asked next to what was answered (the summary still reads `Inbound email from <sender>: <subject>`). The whole body with its quoted chain (`full.body`) is kept only on a row private to the principal: the chain is other people's mail — a contact's, on the principal's reply to one — and every signed-in user reads a public row. Each field is cut by its escaped JSON length (20,000 characters of text, 8,000 of attachment names), the measure the logger's 64 KB cap uses, so a long mail in a non-Latin script loses its tail rather than the row's structure. Outbound, the principal briefs and the client-rotation digest are emailed through the same gateway with the configured backend's send tool (`google_workspace__send_gmail_message` or `microsoft_365__send-mail`, via `workspace.registry.send_from_executive`, from the Executive's own mailbox to the principal's address, subject `<brief title> — <date>`, the date in the user's zone) as formatted HTML — rendered from the brief's Markdown with raw HTML and images off, so text quoted from outside shows as text and opening the email loads nothing remote. Email is first when the principal prefers it, and otherwise the backup after every chat channel, tried only when Slack, Discord and Telegram are missing or fail; an in-band error from the tool counts as a failed send and the next channel is tried. An emailed brief is not a DM, so the per-Person outbound guard below does not apply — the gateway's roster egress gate does.\n\n Two senders get their own framing. Mail from one of the principal's **contacts** (a `kind=\"contact\"` People row — see Org) replaces the non-roster `[POLICY]` notice with a contact one: it names them (name and role/company), says not to reply unless the principal asks and not to tell anyone else, and asks for a summary in an alert for the principal instead. Mail from anyone not in People, a contact or a stranger, is held as outside content for its whole turn (`orchestrator.outside_content`): no connected-app write, contact change, follow-up, link, script or workflow, no direct message, only reads and an alert private to the principal. Both this turn and the forwarded-by-principal turn below are marked `Session.private_to_principal`: they can email, DM or invite only the principal, an alert they raise is private to the principal, and they are not offered the tools that reach anyone else or start work outside the turn (`schedule_tools.PRIVATE_TURN_WITHHELD_TOOLS`: broadcasts, meeting bookings, workflows, follow-ups, watches, artifacts, goal updates, skill drafts, connecting a new MCP server), and of the MCP tools only Google Workspace reads and the gated Gmail send (see MCP below). Every audit row about such mail is private to the principal (see Audit Log), the poller's two `integration_inbound` rows included (`_private_to_principal_mail`), so the audit log's other readers see none of it. The poller holds `audit.private_rows` for the whole handling of such a mail, because some rows are written before the turn binds its private session: the knowledge retrieval quotes the mail's From line, subject and opening. The rows themselves read exactly like an outside sender's: the `integration_inbound` row is the non-roster one (`accepted_non_roster`), and the notice opens with the non-roster notice's exact sentence. The poller handles each message with no session bound, so one message's private turn never marks the next message's rows. The turn stays unattributed (`person_id` None — no peer memory, no co-presence), and the gateway refuses mail to a contact on a poller turn anyway. Mail **forwarded by the principal** — the sender resolves to the principal and `_new_text_lines` reports a forwarded message — is wrapped in a `<forwarded_by_principal>` block: summarise it, draft a reply the principal could send (as text in the reply, never sent or saved as a Gmail draft), note any commitment or date, and offer to add the original sender as a contact (confirmed from the web app or the principal's Slack / Discord, since an ordinary email turn cannot change the People list — the one email that can is the principal's tokened reply to a roster-request email, which is parsed before any model turn; see below). The reply still goes to the principal only. The From header is unauthenticated, so this framing grants nothing: a spoofed \"forward\" just gets the real principal a summary.\n\n **An email that got no reply goes to Needs you.** Mail from the team or the principal is answered by the model calling the mailbox's send tool, so a turn can end with nothing sent (a tool refused, the answer only written). The gateway marks on the conversation who each accepted send reached (`Session.mail_sent_to`: Gmail `send_gmail_message` to/cc, Outlook `send-mail` recipients; `mail_replied_ids`: the message an Outlook `reply-mail-message` / `reply-all-mail-message` answered). After the turn the poller (`_note_reply_outcome`) checks the sender, by any of their addresses, or the message id; with no reply it files a card through `integrations.unanswered_mail` (source `unanswered_email`, high, tagged `private:principal` and routed to the principal, so only their own /today shows it), whatever the model did. Repeats in the thread fold into it (one card per thread, occurrence count), and a later turn that does reply resolves it. A reply the poller sees is also logged (`unanswered_mail.record_reply`, a private `integration_outbound` row keyed by thread), and the briefs read both: each INBOUND email from the roster says \"the Executive replied\" only on that evidence, or \"no reply went out\" while its card is open (`open_thread_keys`), so the brief stops telling the principal to answer mail the Executive already answered. Only mail Gmail proved is the principal's (`Session.email_authenticated`) reads \"Your email got no reply\" with its subject and what the Executive wrote, which never reached them; a teammate's card names who is waiting and never their subject or text (their conversation is theirs alone); mail that only claims a teammate's or the principal's address says it could not be proven and carries nothing the sender wrote. A plain-text `Error …` tool result is not counted as a send. Contacts and senders off the team are not answered by design and keep their own paths. Why: the brief read the inbound log and said people were waiting while Needs you, which shows alerts only, stayed empty, since an alert depended on the model choosing `create_alert`.\n\n **Other mail sources** (`integrations.mail_sources`). Mail read from anywhere but the Executive's own mailbox (a hosted inbound address, a relay) follows the same rules through a vendor-neutral hook. Nothing is registered by default and the hook has no settings: a deployment registers a `MailSource` (its loop, an `enabled` check, and how to replay a held message), the lifespan starts the enabled ones, and each message goes to `handle_inbound` as an `InboundMail`: the parsed message, the address it came to, `prove_sender` (DMARC, or SPF and DKIM aligned, as the source can tell), `send_answer`, an optional attachment reader and what a held message keeps. `handle_inbound` runs the poller's own handling (`email_poller._handle_mail`): sender resolution, private-to-principal rows, the teammate's own rows only when proven, untrusted-content wrapping, the principal's proven mail, the forwarded-by-principal framing, hydration and the turn deadline. Because a source mails the answer itself (with the AI line, and an `integration_outbound` row) rather than the model calling a send tool, three things differ: a stranger is held for the principal silently, with no acknowledgement and no turn, and replayed through the source that read it (`replay_held_mail` dispatches on the payload's `mail_source`); a contact's mail, and mail claiming a teammate that nothing proves, is answered to the principal and never to the sender; and roster-request and fact confirmations are answered only from the mailbox they were sent from. A source must be registered to be handled, it does nothing while the Executive is paused (`handle_inbound` returns `PAUSED` and the source keeps the message), a stranger the request queue won't take is logged as not held, and a sender who is neither team nor contact by the time the turn runs gets no answer at all.\n\nSlack, Discord, and Telegram are roster-gated on inbound: an unrostered sender's message never reaches the Executive (`details.outcome=\"rejected_unknown_sender\"`). The gates look up **team members only** — a contact's Slack, Discord or Telegram id is treated as unknown, so a contact can never talk to the bot (nor count as a co-present peer). What happens next is the roster request below — except for a contact, a thread continuation, a Telegram group or an unverified Telegram webhook, which stay silent. Email is not inbound-gated — non-roster mail flows through with a `[POLICY]` notice so triage can classify it. Slack/Discord thread continuations pass the shared `integrations.response_gate` (utility-fast model, biased toward replying). Slack only continues a thread it has replied in: it reads the thread with `conversations_replies` (5 s bound) and looks for its own user id, which `auth_test` resolves at startup. If that lookup fails, mentions and DMs still work and thread continuations stop until a retry succeeds (`slack_bot._resolve_bot_user_id`, at most once a minute, from the channel `message` listener). When Slack doesn't return the thread in time, the thread's stored history (`slack:thread:{channel}:{thread_ts}`, written on every turn the bot answers there) stands in: with history, a rostered sender gets an ephemeral \"I couldn't read this thread just now… @-mention me\" and the drop is audited (`outcome=dropped_thread_unreadable`). A thread the bot never answered in stays silent. A message the gate skips is audited (`outcome=skipped_gate`, with the gate's reason) and gets an :eyes: reaction (`reactions_add`, which needs the bot's `reactions:write` scope; without it the reaction is skipped), so a sender the gate misjudged can see the message was read and @-mention the bot.\n\n**No link previews on replies.** The Executive's replies go out with previews off — Telegram `sendMessage` carries `link_preview_options.is_disabled`, Slack's reply `say` passes `unfurl_links=False` / `unfurl_media=False`, and every Discord reply send passes `suppress_embeds=True`. The direct messages the Executive starts are the same: `send_slack_dm` posts with `unfurl_links=False` / `unfurl_media=False`, and Discord's `send_dm` sets the `SUPPRESS_EMBEDS` flag on each chunk, so a reminder or a brief sent by DM carries no preview either. Otherwise the chat service fetches a link in the text on its own, so a reply that quotes someone's mail (Act as me reads it) could carry data to a sender's server with no click. The web chat does the same for images: `Message.tsx` loads only an image the app itself serves (`lib/markdownImages.loadsInline`) and shows any other as a link.\n\n### Alert triage of chat messages\n\nEvery chat-app message that passes the roster gate (Telegram, Slack, Discord, Google Chat) is also handed to alert triage through `alerts.pipeline.schedule_chat_message_evaluation`. The sender is named by their People record (`full_name`), not by the name they typed into the chat app, so a person whose account there is called something else is never read as a stranger; the chat app's own name (or raw user id) is used only when nobody on the roster matched. The principal's own messages to their Executive are a conversation, not news for their brief, so they are not triaged at all. Triage sees the sender as `sender:` and the room as `channel:`. Google Chat's inbound audit row also carries the matched People id (`sender_person_id`), looked up before the row is written, so the brief can tell the principal's own messages apart by id, never by a display name anyone can set.\n\n### New senders (roster requests)\n\nSomeone who writes in and is not on the People list — and is not one of the principal's contacts — is **held, acknowledged and asked about** instead of dropped (`integrations.roster_intake.intake` over the `people.roster_requests` ledger; lifecycle in Org). Each adapter calls it after its gate:\n\n- **Slack** — a DM or an `@mention` (not a thread continuation: the bot was not addressed there). The name and profile email come from `users_info` (5 s timeout). The acknowledgement goes in the DM, or as an **ephemeral** message for a mention, so nobody else in the channel learns who is and is not on the roster. The held event keeps only a fixed set of keys (text, user, channel, ts, thread, files).\n- **Discord** — a DM or a mention (not a thread the bot merely follows). The acknowledgement goes in the DM, or by DM for a channel mention; `/ask` answers the interaction with an ephemeral acknowledgement first (Discord allows 3 s), then holds the prompt. Its old \"ask the admin to add you\" reply is gone.\n- **Telegram** — only a **private** chat, and only when `TELEGRAM_WEBHOOK_SECRET` is set and valid: Telegram identifies the chat rather than the sender, and without the secret anyone could forge an update. A group, or an unverified webhook, stays silent as before. Attachment file ids are held and downloaded only on replay.\n- **Email** — non-roster mail that is not private to the principal (so never a contact's) and does not look machine-sent (`looks_automated`: a no-reply / notifications / billing-style local part, a `List-Id` / `List-Unsubscribe` / `Auto-Submitted` / bulk `Precedence` header, or a DMARC failure). The mail is **still triaged** by the Executive on this pass; its `[POLICY]` notice now says the sender was already told their message is waiting and the principal was asked who they are, so the model raises no second alert just to add them, and that the email will come back once they are added.\n\nEvery path skips a contact first (`find_person_by_*_id(..., include_contacts=True)`, or the email poller's private-mail rule): a contact has no chat access and gets no request and no acknowledgement, and the team-visible `rejected_unknown_sender` / `accepted_non_roster` rows read the same for a contact as for a stranger.\n\n**The acknowledgement** is one fixed text (`roster_intake.ACK_TEXT` — \"your message arrived … waiting for confirmation\"), never the model and never an echo of what they wrote, so a forged sender gains nothing by triggering it. It is sent at most once per sender per `ROSTER_ACK_WINDOW_DAYS` (7) and at most `ROSTER_ACK_DAILY_CAP` (20) a day across all senders (`claim_ack`, one transaction; a failed send releases its claim). An email acknowledgement is the one send the MCP gateway lets reach an address off the roster: `send_email_ack` sets `mcp_gateway.roster_ack_grant`, a one-shot ContextVar grant that admits a single `send_gmail_message` with exactly the granted recipient (a plain string, no list), subject and body and no other key, then is spent (audited `integration_outbound`, `kind: roster_ack`, private). An email sender is acknowledged only when Gmail authenticated them: once `claim_ack` succeeds, the poller's `send_ack` re-reads the mail as raw MIME and needs Gmail's own topmost `Authentication-Results` reporting `dmarc=pass` for the From domain (`fact_confirmation.sender_authenticated`, fail-closed). The printed headers the poller reads never carry that header, so without the second read a forged From would draw the acknowledgement to whoever it names — backscatter from the Executive's mailbox. An unauthenticated sender makes `send_ack` raise `roster_intake.AckWithheld`: the claim is released, and they are held silently. `authenticated_by_gmail` strips quoted strings and comments before reading the verdict — Gmail copies the envelope sender and DKIM tags into its own stamp, and a quoted local part could otherwise carry a fake `dmarc=pass` — and needs exactly one `dmarc=` verdict reading exactly `dmarc=pass header.from=<domain>` (Gmail may follow it with its own `dara=` resinfo, so its position is not checked). Residual: when Gmail writes no verdict at all (a From domain without DMARC) and echoes an unsanitised `;dmarc=pass header.from=…` elsewhere in its stamp, that echo would read as the verdict; bounded by the acknowledgement caps. A withheld acknowledgement is audited `roster_ack_withheld`. `intake` acknowledges before surfacing the card and telling the principal, and both follow the request's `ack_sent_at`: a withheld, failed or capped acknowledgement reads \"haven't been told anything yet\" on the Today card, in the principal's prompt and in the email `[POLICY]` notice.\n\n**Telling the principal.** A new request puts a private card on the principal's `/today` (see Today) and pushes a prompt on their delivery plan — preferred chat DM, then the others, then email — for a chat sender or an email sender on the company's own domain; an outside email sender waits on the card, as does everything past `ROSTER_REQUEST_DAILY_CAP` (30) pushes a day (the same cap bounds how many requests open a day; a declined sender is not raised again for 30 days). A chat prompt can be answered in place (\"that's Annamarie, add her to the team\"). An email prompt carries a one-time token (`RR-` + 20 base32 characters, stored hashed); the poller checks every inbound mail for one **before** triage (`try_email_roster_answer`): the reply must come from the principal's primary address exactly (not an alias, not the company-domain rule), carry the token of a pending request, not be an automatic reply, and not fail DMARC where the header is visible; and is parsed by `parse_decision`'s `roster_identity` shape — anything else falls through to the ordinary path. The token is hidden (`RR-[hidden]`) in every other Google Workspace result the gateway returns — the confirmation sits in the Executive's Sent folder, and any turn could otherwise read it — except the poller's own fetch of an inbound message (`mcp_gateway.reveal_roster_tokens`); a token-bearing mail that is not an answer is scrubbed before triage.\n\n**Replay.** Once the principal answers (web card, chat tool, email reply) — or a People-page / `upsert_person` write makes the sender match someone (`after_roster_write`) — the held messages are replayed through the adapter that received them (`register_replayer`: Slack re-runs the held event, Discord and Telegram their held text, email re-fetches the message from Gmail and handles it as mail from a known sender), oldest first, now attributed to the new Person. A teammate gets every held message; a new contact only held email (it takes the private contact path; held chat is dropped); a decline drops everything. Replays run in a **fresh `contextvars.Context`**: the answer may have come from the principal's own verified turn, and a stranger's message must never be read with the principal's session — and their contacts — still bound.\n\n### Standing facts by email (confirm by reply)\n\nThe principal can ask for a standing fact, a retirement or a company-profile edit by email, and the fact tools check it exactly as in chat (the own-words gates run on `_email_memory_text`, the sender's new text, not the quoted chain or attachments). An email's From line proves nothing, though, and a standing fact is read by every later prompt as the principal's own account. So an emailed change is **held, never applied**, until the principal's own mailbox confirms it (`integrations.fact_confirmation`, `memory.facts.fact_confirmations`):\n\n- **Who may ask.** The poller stamps every email turn with `Session.email_from` (the bare lowercased From address) and `email_authenticated`. The text the poller reads never carries `Authentication-Results` (workspace-mcp prints a fixed set of headers), so for mail claiming the principal's primary address it reads the message again as raw MIME (`fact_confirmation.sender_authenticated`) and requires Gmail's own stamp: the **topmost** `Authentication-Results` header (Gmail adds it on receipt, above anything the sender wrote), authserv-id `mx.google.com`, reporting `dmarc=pass` for the From address's domain, with the raw From matching (`authenticated_by_gmail`). It fails closed: no header, `dmarc=none`, a temporary error or a failed read all leave the turn unauthenticated. Mail from a teammate other than the principal is read the same way, before its inbound audit row is written: authenticated, the whole handling of it is theirs alone in the audit log (`rows_for_person`, see Audit) and the turn reads their own mail as them (`Session.email_sender_authenticated`); unauthenticated, it keeps the ordinary rule. Mail from anyone else costs no second read and is never authenticated. `fact_tools._gate` admits an email turn only from the principal's **primary** address, exactly (no alias, no company-domain rule), authenticated, and not private to the principal (mail they forwarded stays refused, as do contacts, teammates and unknown senders).\n- **The hold.** The tool returns `awaiting_confirmation` (no action chip, and the model is told to say nothing has changed). `request_confirmation` stores the change with the SHA-256 of a fresh one-time token (`FC-` + 20 base32 characters, 100 bits; 7-day expiry; at most 10 waiting at once) and emails the token to the principal's roster address, outside any turn's outbound context. A profile edit is dry-run first, so one that cannot apply is reported in the turn, before any email goes out. If the email fails, nothing is held.\n- **Keeping the token from any model.** The tool result never carries it, and `mcp_gateway.hide_roster_tokens` now scrubs `FC-` tokens as well as `RR-` ones (`FC-[hidden]`) from every Google Workspace result except the poller's own fetch of an inbound message. Act as me's reads of the principal's own Gmail, where the confirmation email lands, hide them too (`delegation.gmail.parse_message` and the thread search), so the drafting model never sees a live token either.\n- **The reply.** `_handle_one_email` hands every message to `try_email_fact_confirmation` right after the roster-answer check, before any model turn. It acts only on a reply from the principal's primary address carrying the token of a **pending** confirmation. A made-up, spent, cancelled or expired reference matches nothing and falls through to the ordinary path with the token hidden, so no old or forged token can make the Executive email the principal. A reply with a live token is read again as raw MIME (`read_raw`) and must pass the same Gmail DMARC check as the request; one that doesn't (or whose raw read fails) is refused, the change keeps waiting, and the principal is told. Then an **automatic reply** is consumed quietly — no answer, no model turn, the change keeps waiting: the printed headers catch a Gmail vacation reply (`Precedence: bulk`), and the raw headers catch what they don't show (`automatic_reply`: `Auto-Submitted` other than `no`, `X-Auto-Response-Suppress` and similar, `Precedence: auto_reply`, an out-of-office subject), since an Exchange out-of-office echoes the token from the principal's own address and may well say \"I'll confirm on my return\". The raw message starts at the tool's exact separator line (`\\n\\n--- RAW MIME ---\\n`), so a sender-written Subject imitating it cannot supply the headers. CONFIRM (or yes / approve) applies the change through `fact_tools.apply_confirmed`, the same apply step chat uses. CANCEL (or no) drops it, and an unclear reply leaves it waiting. The principal gets a one-line result either way. A compare-and-set on the row means two replies can apply it only once.\n- **Audit.** Private `fact_confirmation` rows record held / applied / cancelled / refused. The applied change also writes the fact tools' usual private rows, with `source_channel=\"email\"` as its provenance.\n\n### Checking a channel is set up\n\nSettings → Setup status (`GET /setup/status`, `api/setup_checks.py`) gives each channel a light and a plain-language fix. It tests the credentials with one free read-only call — Slack `auth.test`; Telegram `getMe`, then `getWebhookInfo` (is a webhook registered, is it this app's `/webhook/telegram`, did a delivery fail in the past day); Discord `users/@me`, only while the bot is still connecting — and reads what the lifespan left on `app.state`: the Slack socket's `is_connected()`, the Discord bot's `is_ready()` together with its gateway socket being open (discord.py stays ready while it reconnects after a drop), or the exception its task stopped with (`LoginFailure`, `PrivilegedIntentsRequired`), and the MCP gateway. A listening Slack is amber while the listener hasn't resolved its own user id (`slack_bot.bot_user_id()`), since thread continuations are off until it does. Because inbound is roster-gated, a connected Slack, Discord or Telegram is amber while nobody on the roster has its id (`slack_user_id`, `discord_user_id`, `telegram_chat_id`), or when its latest `integration_inbound` row is a `Rejected: …` from the past day whose sender still isn't on the roster — the page shows the sender's id, never message text. Local login with no `TELEGRAM_WEBHOOK_SECRET` is red for Telegram, since the local-login gate turns its webhook away. Google Chat and Gmail are checked from configuration: a numeric project number and a readable service-account key; the OAuth client (or service-account key) the workspace-mcp child signs in with. Gmail is also amber when startup priming could not find every pinned Google tool (`MCPGateway.prime_pinned_tools`, whose result the gateway keeps on `pinned_tools`): the row names a few of the missing tools and counts the rest, and points at the `MCPGateway` log lines. It is amber too while that probe has not finished, and when the probe itself failed — the one check that reads green is the one that ran and found everything, so a crashed probe is never silently fine. The row speaks for the whole `google_workspace` server, so a missing Docs or Drive tool shows up under Email (Gmail).\n\nA channel setting written `KEY= # note` in a `.env` file arrives as the note's text, because python-dotenv strips only a comment that follows a value. `Settings` reads such a value as unset for the Slack, Telegram, Discord and Google Chat credentials, so the line no longer switches a channel on with its own comment as the token. `TELEGRAM_WEBHOOK_SECRET` is the exception, because read as unset a junk secret would turn the webhook's check off. It is kept instead, and since Telegram can only ever send 1–256 of `A-Z a-z 0-9 _ -` (what `setWebhook` accepts), a secret outside that set — a leftover comment, a pasted `<value from Step 2>` — could only be matched by someone who guessed it: while it is set the webhook refuses every update, neither the local-login gate nor the roster tools count it as proof (`Settings.telegram_webhook_secret_valid`), and Setup status shows it red (`.env.example` shipped four such lines; the notes now sit on their own lines).\n\n### Conversation state\n\nEvery adapter keys a deterministic `session_id` off the conversation surface and replays that session's stored turns into `Session.conversation_history`, so a follow-up (\"yes, go ahead\") lands with the question still in context. Slack's ids are `slack:dm:{user}`, `slack:thread:{channel}:{thread_ts}`, and `slack:channel:{channel}:{user}` for a mention that starts a thread; because the bot's reply roots a Slack thread at that message's `ts`, the turn is double-written to that thread's session too, so the first continuation inside it is not cold. A reply inside a thread THAT PERSON ROOTED also offers the parent `slack:channel:{channel}:{user}` id when matching an approval gate, since a gate raised on the mention recorded that session while the answer arrives under the thread's. The root-author check is load-bearing: widening on \"threaded and not a DM\" alone offered one person's channel session inside any thread in that channel, so a remark they made to a colleague could resolve their open gate and post the run's title into that colleague's thread. Discord has the same shape — its auto-thread router promotes a mention reply into a bot-owned thread — and the same alias. An @-mention inside a DM is handled once, by the DM path: Slack fires both events, and taking both forked the conversation across two session ids. The same id is the audit grouping key and the scope passed to `format_for_prompt`. A per-session `asyncio.Lock` serializes turns within one conversation — the inflight semaphore caps fan-out across the workspace, which does nothing to stop two messages in the same thread from both reading history before either writes it. Persistence happens after the reply is sent and its failure is logged, never surfaced: the user already has their answer.\n\n**Conversations within a chat app.** A Telegram chat, a Slack or Discord DM and a person's @mentions in one channel (`slack:channel:…`, `discord:channel:…`) are each one endless stream, so they are cut into conversations (`memory.conversations`, shared helpers in `integrations/conversations.py`). Each adapter computes the stream's base id as before and asks `conversation_for` which conversation a message belongs to: the newest, unless the stream has been quiet for two hours (`CONVERSATION_GAP`), when the next one starts. The first conversation keeps the bare base id; later ones add `~2`, `~3`, … (`memory.conversation_ids`). A whole message of `/new`, \"new chat\" or \"new conversation\" starts a fresh one instead of a turn and is answered with the name of the one it ended; the new row has no messages and stays off the Chats page until its first turn. After a conversation's first exchange `title_after_turn` names it in the background with `utils.session_title.generate_session_title` (the first words of the message if that fails), as a web chat's first turn does. Threads (`slack:thread:…`, `discord:thread:…`), email and every other id are left whole. What has to see the whole stream compares base ids: the inbound resolver, so an approval asked before a cut is answered after it, and the session-scoped decisions and advice `format_for_prompt` renders. At boot `split_existing_streams` cuts history saved before this by the same rule, once (`app_migrations`), titling each part from its first message and carrying a read-mail lock to every part. An adapter installed outside the package adds its streams with `conversation_ids.register_rolling` and cuts its own old history once, with its own migration name and an `only` filter for its base ids, because the built-in sweep may already have run without it.\n\nThis was absent on Slack until #136. Every message built a fresh `Session` and minted a per-*message* id (`thread_ts` falls back to the message's own `ts`, so a DM never repeated one), which meant a multi-turn confirmation could not work: the Executive asked whether to send a briefing to Slack, the user said yes, and the next turn had no record of the question.\n\n### What the model is told about the channel\n\nChat adapters pass a `<channel>` block (`integrations.channel_context`) in the **user turn** — never a cached system block. It names the surface, states that the person cannot see the app's cards or buttons, and draws the line the assistant kept crossing: briefing proposals and alerts are actioned on the briefing page; a proposal that books something can only be approved there; a workflow sign-off the Executive is explicitly waiting on *can* be answered in the conversation. The principal's DMs on Slack, Discord and Telegram also receive the open-alert digest (`briefing.context.format_open_alerts_for_prompt`) as the `<briefing>` block, gated to DMs because the board is company-wide and a shared channel must not pull it in. That digest is the ONLY trusted source of an `alert_id` for `ack_alert`. The briefing page's `[Discuss mode — alert_id=N]` primer is a pointer to which item is under discussion, not authority on its own: the server accepts that id only if it is also on the live board it derived itself. An id appearing anywhere else, including inside an alert's own body, is not trusted: alerts are minted from inbound email and chat, so their bodies are attacker-controlled. Two mechanisms enforce that rather than one prompt rule. Every field the digest interpolates is collapsed to a single line, because a newline in an attacker-written headline, suggested action, tag or review note would otherwise forge a whole extra `[N]` line — a fabricated instruction to clear somebody else's alert. And the live board the server derived is recorded on the session, so `ack_alert` refuses any id outside it — on EVERY session, web included; the web previously had no check at all. The recorded set is the whole live board (the cap `/today` renders as cards), not just the rows the digest printed, so a card past the digest's 30-row render cap is still ackable rather than sending the principal back to the page. Be precise about what this buys: it stops an id that is invented, closed, snoozed or expired, including one quoted out of an attacker-written alert body. It does NOT stop the model being argued into acking the wrong LIVE card — one alert's body can still make a case about another id that is genuinely open. Scoping trust to the single item under discussion would need the primer id carried server-side, which it is not.\n\n### Handler failures\n\nAn adapter's catch-all replies \"I encountered an error processing your request.\" On Slack that used to be the whole story — one uncorrelated log line, no audit row, and an unguarded error-send that could itself escape into Bolt. It now logs with the session, sender, channel, thread and mode, and writes an `integration_inbound` row with `details.outcome=\"handler_error\"`, joining the inbound row under the same `session_id`. Upstream, a single crashing tool handler no longer takes the turn down at all: the orchestrator's tool gathers use `return_exceptions=True`, hand the model an error `tool_result`, and audit it with `ok=false` (cancellation is re-raised, not swallowed).\n\n### Attachments\n\n`integrations.attachments` handles web chat, Discord, Telegram, Slack and Google Chat. Images become Anthropic vision blocks; documents (PDF/DOCX/TXT/MD/CSV) are inlined into the turn that carried them — inside an `<untrusted_content source=\"attachment\" author=\"<name>\">` block (`content_trust.wrap_untrusted`, whose closing tag the text cannot forge), under an `[Attached: <name>]` label, which the open-loop pass reads as \"not the speaker's words\" and the decision extractor strips before it reads the turn — and indexed into the ChromaDB `inbound_attachments` collection. 20 MB/file cap; web chat uses `POST /chat/upload`.\n\n**Scanned PDFs** are read, not reported empty. A PDF with no text layer goes through `knowledge.pdf_reader`: with `PDF_PROVIDER_READING=true` (opt-in, off by default) the deployment's own model reads it through its provider's PDF support (Anthropic natively, OpenRouter's `file-parser`, a local server only with `LOCAL_PDF_INPUT`); otherwise, and as the fallback, local OCR (pypdfium2 + RapidOCR, offline, no key) — so every deployment converts them. The label then reads `(converted from scanned pages)`, and an unreadable one says why. The index takes the text already extracted for the turn, so a scan is converted once. A file a channel delivered (everything here except `POST /chat/upload`, where the signed-in user sends it) converts at most `PDF_INBOUND_MAX_PAGES` (30) pages and draws on a rolling `PDF_INBOUND_PAGES_PER_HOUR` (300) budget shared by all senders, so sending scans cannot run up unbounded model spend or CPU.\n\nPer channel:\n- **Slack** — a `file_share` message (previously dropped outright for its `subtype`) is handled like any message; files download only after the roster gate and the response gate, with the bot token sent only to `https://files.slack.com/` (needs the `files:read` scope). History and peer memory record the words plus `(Attached files: …)`, never a document's text.\n- **Google Chat** — uploaded attachments download through `media.download` with the reply credentials (`chat.bot`), checked against the 20 MB cap per chunk, 5 per message; an attachment-only message is no longer dropped. The webhook authenticates Google, not the sender, so files are read only when the event's `user.email` is on the People roster (a team member); anyone else's files are named to the Executive, never downloaded. A Drive file shared into a message is left to the Drive tools, with its id.\n- **Email** — the poller (`integrations.email_attachments`) downloads up to 5 readable attachments of the message itself via `get_gmail_attachment_content` — workspace-mcp in stdio mode saves the file and answers `Saved to: <path>`, which must start its line, be the last such line and end in the answer's `Saved filename:` (the answer echoes the sender-chosen attachment name first, and a name carrying `Saved to: /…` must not redirect the read), then resolve inside the tool download folders — and appends their text to the turn (15k chars each). Only for a sender the principal knows (team, contact, principal); a stranger's files stay a list. It runs outside the model loop, so it works on private turns without adding the attachment tool to `PRIVATE_TURN_MCP_TOOLS`.\n- Anything else (a Drive PDF, a skipped attachment) — the Executive's `read_document` tool.\n\nIndexed chunks are keyed on `attachment:<bare filename>` and tagged `type=attachment`. An attachment's name is chosen by whoever sent the message and the name is the chunk-id namespace, so without the prefix an inbound `strategy-2026.md` would upsert over the curated company document of that name. The prefix separates inbound content from curated uploads and keeps provenance visible; it does not separate senders from one another.\n\nIsolation is the **collection**: `retriever.retrieve` never queries `inbound_attachments` at all, so an attachment cannot resurface as company knowledge in a later, unrelated turn. Attachment processing is roster-gated on Discord too — it previously ran before the gate, so an unrostered sender's file was downloaded and indexed before their message was dropped. These rows still have no operator surface: they are never written to `company/docs/`, so `GET /documents` does not list them.\n\nThis replaced a domain-based scheme that did not work. The chunks lived in `company_docs` under a domain outside the specialist set, on the premise that an unrecognised domain matched no filter. It matched every one — `ChromaDBStore.query` attaches a `where` clause only when a domain filter is present, and an Executive-level retrieval passes none — so attachments came back under “From your company documents”, top-ranked and indistinguishable from a curated upload. Legacy rows are migrated across on boot.\n\n### MCP gateway & outbound\n\nMCP runs in **both directions**. As a *client*, `orchestrator.mcp_gateway.MCPGateway` proxies MCP servers (Gmail, Calendar, Drive, Outlook mail and calendar — whatever `mcp_servers.json` configures) as Executive tools, with egress gating on Gmail recipients, Calendar attendees, Drive share grantees, and Microsoft 365 recipients/attendees against the roster (and a refusal of public / whole-domain Drive sharing). The Gmail gate also accepts only a fixed set of argument keys, so workspace-mcp's `reply_all` (recipients taken from the thread, never checked) and `forward_message_id` / `include_forwarded_attachments` (forwarding any inbox message) are refused; a reply is `thread_id` plus an explicit, roster-checked `to`. Three more refusals close paths around those gates: every Apps Script tool (code running as the Executive's account, outside the gates, and since workspace-mcp 1.29.0 schedulable to keep running); any argument that makes the server fetch a URL (`fileUrl` / `file_url` on the Drive and import tools, a Gmail attachment given as a `url`), since the fetch can carry data out in its query string before any recipient gate matters; and text Google would mail to someone the roster never checked (`rsvp_comment` to an event's organizer, an out-of-office `decline_message` to whoever invites the Executive). Every gate reads its arguments by normalized spelling: workspace-mcp 1.29.0 renames a camelCase key such as `Attendees`, `userGoogleEmail` or `rsvpComment` to the real parameter, so a gate matching the exact key would never see it. Arguments that are not a JSON object are refused for the same reason. Google-side fetches are refused too: any key ending in `url` / `uri` at any depth whose value has a URL scheme (a Slides image or page background, a Docs or Forms image; a document hyperlink and a meeting link are stored, not fetched, and pass, as does a Drive file id), (a value is a URL after the characters a URL parser strips are removed, and `//host` counts), and on every tool that can write cells — the Sheets tools and the Drive create / update / import tools, which turn CSV into a Sheet — any string anywhere holding a formula call that fetches (`IMPORTDATA`, `IMPORTXML`, `IMPORTHTML`, `IMPORTFEED`, `IMAGE`), JSON-encoded or mid-CSV included: a string argument that encodes JSON is read as the server decodes it (one too large to read is refused), text is also scanned with character references decoded and comments / CDATA removed, and an upload that would become a native Sheet may only be text `content` — a `base64_content` or server-side `file_path` upload there is refused, since an XLSX hides its formulas behind zip members and XML encodings; a PNG to Drive or a DOCX to Docs is untouched. Not covered, unverified: whether Drive's HTML / Markdown import fetches an `<img src>` when it converts `content` into a Doc. A `manage_event` call that names no attendees is sent with `send_updates=\"none\"`, so the event's existing guests are not emailed text the gate never checked. A delete is sent the same way, except the typed `cancel_calendar_event` of a meeting the Executive booked, which keeps its cancellation notice. Google Docs, Sheets, Slides, Forms and Drive writes run only on files and folders the Executive's own Google account owns (`_check_google_file_write`, read through `get_drive_file_permissions` at call time, fail-closed; only a name starting with a read verb skips it), as OneDrive writes do. Someone added to People in the current turn is left out of the allow-list until the next turn. The allow-list (`_egress_sets`, built by `_roster_allow_set` as a `people.identity.RosterAllow`) is every team member's email and email aliases plus the Executive's own address, always, and — for a teammate — any address on one of the company's own domains whose local part (`+tag` dropped) matches theirs, the same rule inbound mail is matched by; a **contact's** email joins it only when `people_tools.contacts_reachable_now()` is true — a turn the principal started on a verified surface (web chat, their own Slack or Discord, a verified private Telegram chat), or inside `grant_contact_egress()` (the decisions approve route, when the approver is the principal). On any other turn — an inbound email, a teammate, the scheduler, a workflow, the alert review — a contact's address is refused exactly like a stranger's, so the refusal cannot reveal that it belongs to a contact (contacts are private to the principal). The single exception to the roster rule is the fixed roster-request acknowledgement above, under its one-shot `roster_ack_grant`. A turn about the principal's private mail (`Session.private_to_principal`) narrows the list to the principal's own address and the Executive's. Such a turn may call only the MCP tools in `schedule_tools.PRIVATE_TURN_MCP_TOOLS`: Google Workspace reads (`search_gmail_messages`, `get_gmail_message_content`, `get_events`, `list_calendars`, `query_freebusy`, and the Drive, Docs and Sheets reads such as `search_drive_files`, `get_drive_file_content`, `get_doc_content` and `read_sheet_values`) and the two Gmail tools this gate narrows to the principal (`send_gmail_message`, `draft_gmail_message`). It is an exact allow-list, not a server: workspace-mcp runs at the tier `WORKSPACE_MCP_TOOL_TIER` names, `complete` by default, where a Google Chat message to a space, a Docs, Sheets or Drive write into a file already shared with others, `manage_event` on a shared calendar (its gate checks attendees and pins notifications, nothing else) reaches people with no recipient check; and every other server has none at all (a Slack or Notion server, the default `fetch` server, whose URL can carry the turn's content, a server loaded at runtime). Its `search_tools` results show only the allowed tools (`workflows.tool_catalog.filter_search_results`; output it cannot parse reads as no match), and a `call_tool` naming anything else is refused with an error tool_result and an audit row private to the principal (`schedule_tools.private_turn_withholds`), a missing name included. `search_tools` and `call_tool` stay offered, so the tool list and its cached prefix do not change. The typed calendar tool (`_resolve_attendees`) and the chat DM tools (`message_person`, `send_telegram_message`, `send_discord_dm` and their person-id recovery) apply the same rule — a contact's id reads as an unknown one off the principal's turn — and a private turn may DM or invite only the principal (`PRIVATE_TURN_REFUSAL` otherwise); `message_person` never falls back to a \"Needs you\" alert for a contact, who cannot sign in to see it. The Google Workspace server (`workspace-mcp`) behind those Gmail/Calendar/Drive tools runs **co-located inside the API** as a stdio child of the gateway — fitting the single-tenant model (one install = one company = one exec Google account), so there's no separate service to operate. It's baked into the API image and launched by `docker/workspace-mcp-launch.sh`, which selects single-user OAuth (token persisted at `/data/google_credentials`) or service-account domain-wide delegation from `GWORKSPACE_AUTH_MODE`. The optional `WORKSPACE_MCP_TOOLS` (comma-separated service names, default `all`) limits which Google services it loads. The gateway forwards the Google secrets to the child via `_FORWARDED_ENV_VARS`. Every `google_workspace__*` call acts as the Executive's own account. workspace-mcp takes the acting account per call (`user_google_email`) and nothing used to check it, so under domain-wide delegation a model-chosen address could open anyone's mailbox in the domain; `mcp_gateway._check_acting_account` now refuses a value naming any other address — before every other gate, with an `integration_outbound_blocked` audit row. An absent value stays allowed (the server's own account).\n\n**What the model is told is connected.** `MCPGateway.start()` records the configured server names (`server_names`), and the Executive renders them with the channel settings into block 0's *Connected Systems* section (`prompts.connected_systems`; see the caching section). While Google is connected that section pins the Google tool names the Executive uses constantly (`GOOGLE_TOOL_MANIFEST`, narrowed by `connected_systems.google_tool_manifest` to the services and tier actually loaded) and tells it to call them with `call_tool` directly, with no `search_tools` round trip. The narrowing is the point: a name pinned for a service workspace-mcp never imported is not in the index, so the model calls it, receives extensible-mcp's “has not been discovered via search_tools” refusal, and has no way to square that with its own instructions. extensible-mcp only runs a tool one of the session's searches has returned, and remembers it for the session's life, so the gateway does that discovery itself: the lifespan starts `MCPGateway.prime_pinned_tools()` in the background once the gateway is up with `google_workspace` configured (an exact-name search per pinned tool, the way `workflows.tool_catalog.resolve` does it, over the same narrowed set the prompt advertises — `connected_systems.pinned_google_tools`, so priming never probes a service that was not loaded). A name neither the prompt nor priming can account for is logged once, naming both causes: excluded by `WORKSPACE_MCP_TOOLS` / `WORKSPACE_MCP_TOOL_TIER`, or renamed by workspace-mcp since the pin. A pinned call that still comes back with extensible-mcp's \"has not been discovered via search_tools\" refusal, for example before priming finished, is discovered and retried once. That happens after every gate has passed the same arguments, and only for pinned names: any other tool still needs the model's own search, and nothing here widens what a call may do, including the private-turn allow-list.\n\n**Microsoft 365** is the Outlook twin: `@softeria/ms-365-mcp-server` (a Node package, pinned) is installed in a throwaway Node build stage and only the `node` binary plus the package are copied into the API image, launched by `docker/ms365-mcp-launch.sh` as the `microsoft_365` entry with an **explicit tool allow-list** (`--enabled-tools`, an anchored regex) rather than the upstream `mail,calendar` preset — that preset also registers inbox forwarding rules, mailbox settings (external auto-reply), calendar sharing and event forwarding, which can address people the gateway never sees. Exactly the Outlook mail + calendar tools and the OneDrive tools are exposed (`microsoft_365__send-mail`, `microsoft_365__create-calendar-event`, `microsoft_365__search-onedrive-files`, …; hyphenated Graph endpoint aliases, proxied verbatim), and every admitted tool is either roster-gated or carries no recipient; the gate also covers the excluded writers in case an operator widens the list. Both servers can be configured at once. Auth is the MSAL device-code flow against the operator's own Entra app registration (`MS365_MCP_CLIENT_ID` is required; the server's built-in public client is refused); the refresh token persists at `/data/ms365_credentials` and is seeded once with `ms365-mcp-launch.sh --login` from inside the container — the server has a native device-code CLI, so there is no mint script and nothing to copy. The launcher scrubs the literal `$VAR` placeholders extensible-mcp leaves for unset variables (otherwise MSAL would be handed `$MS365_MCP_TENANT_ID` as an authority), and `MS365_MCP_EXPECTED_USERNAME` pins the bound mailbox. The egress gate for this family walks Graph's nested shapes (`body.Message.toRecipients[].emailAddress.address`, `body.attendees[]…`) — every email-shaped string outside the free-text fields must be on the roster, control characters and non-ASCII addresses are refused, unforeseen keys are still scanned (fail-closed) — and covers the whole write surface: send, reply, reply-all, forward, every draft tool, `update-mail-message` (it can PATCH recipients onto a draft) and create-/update-calendar-event; reads pass through. `delete-calendar-event` makes Exchange mail every attendee, so it reads the event and roster-checks the attendees first, except the typed `cancel_calendar_event` of that same event. Graph's reply, reply-all and send-draft actions carry no recipient in their arguments (the recipient is whoever the referenced `messageId` names), so for those the gate first reads the referenced message through the server and roster-checks the recipients Graph will derive (`replyTo` else `from` for a reply; `replyTo` and `from` together, plus the original to/cc, for reply-all; the draft's own to/cc/bcc for send-draft), refusing on any lookup failure; RSVP and cancel actions get the same treatment through an event lookup, because their comment is emailed to the organizer or every attendee; `download-bytes` is pinned to mail attachment bytes and OneDrive file content (`/drives/{id}/items/{id}/content`, optionally Graph's `?format=pdf` rendering), and a OneDrive result comes back as the file's extracted text rather than base64 — the attachment pin is what makes the poller's promise that an unrostered sender cannot be auto-replied to hold on Outlook as it does on Gmail; and the rendered inbound text quotes any forged `--- REPLY ---` line inside a body so the persona only ever reads the real block. Every mail write's `from`, `sender` and `replyTo` may name only the Executive's own address (the Outlook twin of the Gmail acting-account pin), so the model cannot send as a rostered colleague's mailbox or steer replies elsewhere; and `move-mail-message` into Deleted Items, Junk Email or Recoverable Items is refused, so a move cannot trash mail ungated. The server registers its account tools whatever its tool allow-list says, so the gateway itself refuses `login`, `logout`, `select-account` and `remove-account` (audited like any other refusal) and drops them from `search_tools` results — a chat turn cannot sign the mailbox out, switch accounts or start a sign-in; setup is only the launcher's `--login`, and the read-only `verify-login` / `list-accounts` stay callable. The example config's hyphenated patterns still deny `delete-mail-*`, `logout`, `remove-account` and `download-bytes-to-file` as defense in depth. A successful `send-mail` records the same outbound-context linkage Gmail does.\n\n**OneDrive in chat** (opt-in with `MS365_MCP_ONEDRIVE=true` and a fresh `--login`, since the server asks for its tools' permissions on every token refresh and a sign-in without file consent would otherwise fail mail and calendar too) matches what the Executive can do on Google Drive: search, list a folder, read a file, upload and edit, create folders, move, rename, copy and share; there is no delete tool. The launcher adds `Files.Read.All` at sign-in (`--extra-scopes`), so folders shared *with* the Executive can be read too; writes (upload, new folder, move, copy) land only in the Executive's own drives, checked against `list-drives` at call time, so a planted instruction cannot save company files into a stranger's shared folder. Sharing is gated like Drive sharing: `share-drive-item` invitees must be People on the roster and named by email (an `objectId` or `alias` grantee is refused, since nothing can check it), no `owner` role, and `create-drive-item-share-link` must be scoped to specific people (`scope: \"users\"`): an anonymous or whole-organization link, or one with no scope (the tenant default), is refused. An invite must require sign-in and grant only view or edit, a link must be a view or edit link, and `search-onedrive-files` takes plain words only, since its query goes into the request path unencoded. Files Act as me's `save_my_email_attachment` copied from someone's own mail into the Executive's Drive or OneDrive (`delegation.saved_files`) are that person's alone: on any other turn the gateway refuses a call whose arguments name a recorded file id and drops the entries or lines of a result that name one, failing closed for the file tools when the record can't be read. The folders those copies go in are made by the save (never adopted by name) and recorded, and a model call naming one, by id or by an OneDrive path through it, is refused on every turn, the owner's too, with their ids hidden from results. That tool's own calls are the only Drive and OneDrive writes a turn that read the owner's mail may make: built in code, admitted past the lockdown as those exact objects (`code_built_call`), and still checked by every gate above.\n\nAs a *server*, `openexecutive.mcp_server` exposes OE's own company context and specialist council to external MCP clients at `/mcp` — the inverse direction; see the dedicated **MCP Server** section. The gateway launches extensible-mcp as a `uvx` subprocess whose fastembed tool-search index uses an embedding model baked into the API image and loaded offline, so it no longer re-downloads that model from the Hugging Face Hub on every cold start. extensible-mcp is pinned twice over: to a commit, which fixes its own code, and with `--exclude-newer`, which fixes the resolution of its dependencies — without the cutoff uvx re-resolves them against PyPI on every networked start, so a new release of any of them would reach running deployments on restart. Both live in `_EXTENSIBLE_MCP_LAUNCH_ARGS` in `orchestrator/mcp_gateway.py`, the Dockerfile's pre-warm uses the same arguments (a unit test enforces the match), so an image whose pre-warm succeeded starts the gateway with no network. The pre-warm is best-effort (`|| true`): an image built while GitHub was unreachable fetches the pinned commit on its first start instead. Updating the gateway is a deliberate bump of the commit and cutoff; `uv` itself is not pinned. Because the MCP stdio client does not inherit the parent environment, `MCPGateway.start()` explicitly forwards the embedding-cache/offline env vars (`FASTEMBED_CACHE_PATH`, `HF_HUB_OFFLINE`, …) into the child.\n\n**Emailing an artifact.** A Gmail send or draft may carry `attachments=[{\"artifact_id\": \"alert:12\", \"as\"?: \"docx\"}]`. `call_tool` runs the recipient gate first; only if it passes does `_expand_artifact_attachments` replace each such entry with the rendered file (`content` base64 + `filename` + `mime_type`, workspace-mcp's own attachment shape), produced by `artifact_records.render_artifact_file` — the same renderer as `/artifacts/{id}/download`. Only artifact rows resolve (never an arbitrary alert), links have no file, and an entry mixing `artifact_id` with other keys is refused. A stringified or single-object `attachments` is normalised first, so an artifact entry can never reach workspace-mcp unexpanded (it would silently drop it). At most 5 distinct artifacts per email (repeats are dropped) and 15 MB rendered in total; rendering runs off the event loop via `asyncio.to_thread`. A refusal writes `artifact_attachment_refused`; a successful send writes `artifact_attached` — both carry the recipients. Other attachment entries pass through unchanged. The same expansion serves the Microsoft 365 mail writes: the entry becomes a Graph `#microsoft.graph.fileAttachment` (`name`, `contentType`, `contentBytes`) placed where Graph expects it for that tool (`body.Message.attachments` for `send-mail`, reply, forward and the createReply drafts; `body.attachments` for `create-draft-email`), whether the model put it at the top level or inside the message; an entry anywhere else, one on `update-mail-message` or `send-draft-message` (their requests cannot carry attachments), or one behind a body that is not an object is refused rather than forwarded unexpanded.\n\n**Enablement, and why it degrades instead of dying.** `MCP_ENABLED` left unset is inferred from the presence of `mcp_servers_config_path` — dropping an `mcp_servers.json` next to `profile.yaml` turns MCP on with no further configuration. An **explicit** setting always wins in both directions: `MCP_ENABLED=false` keeps MCP off with the file still in place. It did not: `_resolve_mcp` tested `not self.mcp_enabled`, which cannot tell \"never set\" from \"set to false\", so the file's presence silently overrode the operator. The file is probed through `config.mcp_config_file_present`, never `Path.exists` directly — that re-raises an EACCES on a parent directory, and from inside a validator that comes out of `Settings()` itself, which `api/main.py` calls at module level. The check now reads `model_fields_set` (the fields the env actually supplied) and stores that on a private attr behind the read-only `mcp_auto_enabled` property, because the validator's own assignment joins that set and would otherwise make every auto-enable look explicit downstream.\n\nStartup is **best-effort**, in `main._start_mcp_gateway`. Two checks come before the subprocess: MCP off is a no-op, and a config defining no servers under `mcpServers` is logged and skipped — extensible-mcp's own loader raises on that and exits, and because the child is already gone the only thing that surfaces is anyio's \"Attempted to exit cancel scope in a different task\" from `stdio_client` unwinding, a traceback naming nothing about configuration. The start is also bounded (120s, generous because that child may still clone extensible-mcp on a cold start if the image's pre-warm failed): `ClientSession` carries no `read_timeout_seconds`, so `initialize()` waits forever on a child that is *alive but silent*, and an unbounded wait is a lifespan that never yields — the same healthcheck-never-passes symptom, which no `except` can see. A gateway that fails anyway is logged at ERROR with the config path, the servers it named, and whether the config file or an explicit `MCP_ENABLED` turned MCP on, then torn down under its own timeout; the API boots **without MCP tools and without the email poller** rather than refusing to boot. The guard catches `BaseException`, not `Exception`, re-raising a bare `CancelledError` first: the original failure came from anyio, which wraps a task group's failures in `BaseExceptionGroup` as soon as one is a `BaseException` — and that group is not an `Exception`, so `except Exception` would miss the very shape this contains. The teardown is contained too, since it runs from inside that `except` and would otherwise replace the actionable log with the crash it prevents. `configured_server_names` never raises either, and deliberately catches broadly: it reads an operator-owned path during startup, where an exception is the crash loop rather than a bug report — `Path.is_file` re-raises an EACCES on a parent directory, and `json.loads` answers deeply-nested input with `RecursionError`, which is not a `ValueError`. It tests `is_file()` so a directory or a symlink to a FIFO is never opened, and caps the read at 1 MiB. That exception used to propagate out of the lifespan and kill the container — under `restart: unless-stopped`, a crash loop whose only outward symptom was a healthcheck that never passed. Outbound tools: per-Person DMs (`send_slack_dm`, `send_discord_dm`, `send_telegram_message`) plus room-targeted `send_department_message` and `send_company_broadcast`. All three per-Person DMs refuse a recipient id that matches no non-archived Person row (`schedule_tools._dm_recipient_on_roster`), which is what stops untrusted content in a turn — inbound mail, a chat message, a knowledge document — from directing a DM at an arbitrary workspace member. `send_slack_dm` previously consulted the roster only when the turn was already private to the principal, so on an ordinary turn it applied no roster check at all while its Discord and Telegram siblings did; the room-targeted tools are deliberately ungated, since those channels are team-visible. The per-Person DMs are additionally rate-limited and de-duplicated by the outbound anti-spam guard (below).\n\n### Outbound anti-spam guard\n\nEvery per-Person DM passes a deterministic guard (`orchestrator.outbound_guard.check_outbound_allowed`) after the roster gate and recipient-id recovery but before the network send — the single chokepoint **all** proactive DM paths reach (ad-hoc chat sends, the scheduler's followup/nudge dispatch, principal-brief delivery, the reflection turn, and research-finding routing). On a violation it returns a human-readable reason and the handler **suppresses** the send (`{\"status\":\"suppressed\",\"reason\":…}`), writes a `tool_invocation` audit row with `suppressed=true`, and writes **no** `done` activity row — so a blocked attempt never counts toward its own rate cap, and the Executive can read the reason and hold or `schedule_followup` for the recipient's next window. Three controls: **content dedup** (a near-identical message — whitespace/case-normalized, first 160 chars — already sent to the same recipient within `OUTBOUND_DEDUP_WINDOW_MINUTES`, default 360); a **per-recipient rate cap** (`OUTBOUND_MAX_PER_RECIPIENT_PER_WINDOW`, default 5, over `OUTBOUND_RATE_WINDOW_MINUTES`, default 60); and **quiet hours / availability** (`OUTBOUND_RESPECT_QUIET_HOURS`, default on — refuse while the recipient is on leave or outside their `people.channel` availability windows, surfacing the next open window). Delivery history is read from the existing `status='done'` `scheduled_actions` rows (`episodic.recent_sends_for_channel_ref`), so there is no new table. The guard is **fail-open**: any internal lookup error returns \"allow\", so it can never turn a working send into a crash or a silently-dropped message. Principal briefs and the internal heartbeat kinds use the `__internal__` channel and never reach these handlers, so they are unaffected. Once the guard allows a send, the handlers apply the recipient's own notification settings to the Executive's own (tagged) outreach: in their quiet hours, or when they chose *In my briefs*, the DM is stored and returned as `{\"status\":\"held\"}` rather than sent, and goes when quiet hours end or with their next brief (`outbound_guard.check_hold`; see Org).\n\n### AI disclosure\n\nWhat the Executive sends says it is an AI assistant (`orchestrator.disclosure`), added by plain code so a reply the model writes can't leave it out. **Mail** from its own mailbox gets a line under the body, by default \"<EXEC_DISPLAY_NAME> is an AI assistant working for <company>. To reach a person, reply and ask, or write to <principal's address>.\": the MCP gateway adds it to every Gmail send and draft and every Outlook send, reply, forward and draft (`mcp_gateway._with_disclosure`) **after** every outbound gate has passed and only on what goes to the server, so the gates, the outbound-context record and the audit see the model's own words, and `send_from_executive` gets it the same way. It counts as already there only when it is the last line that shows (in a quoted earlier message or hidden in markup it doesn't), and a send of an existing draft and mail whose every recipient is the principal go as they are. HTML that could hide what follows (an unclosed comment, a style or script block, text styled out of sight: `disclosure.hides_what_follows`) is refused, so the line can't be hidden after it; the model is told to send plain text. The roster acknowledgement to a new sender, the one send to an address nobody checked, gets `BARE_MAIL_LINE` (\"This message was sent by an AI assistant.\"), which names no one, like the acknowledgement itself. **Chat** gets a shorter line (\"<name> · AI assistant\", in italics) on the Executive's replies in Slack, Telegram, Discord and Google Chat and on its own DMs and room posts (`send_slack_dm`, `send_discord_dm`, `send_telegram_message`, `broadcast_tools._dispatch`), but only on the first message in a conversation and again after 24 hours without one (`with_chat_line`, kept in memory, so a restart shows it once more); session history keeps the reply without it. `AI_DISCLOSURE` (default on) turns it off; `AI_DISCLOSURE_MAIL_TEXT` / `AI_DISCLOSURE_CHAT_TEXT` reword the lines, and a wording that doesn't say \"AI\" is ignored for the built-in one. It fails open: a line that can't be built is left off, never a send refused. Replies sent *as a person* under Act as me are the delegation section's (**AI line on replies**).\n\n### Calendar & video links\n\nThe Executive books meetings through two typed tools over the configured calendar backend (`CALENDAR_PROVIDER`: Google Calendar via `manage_event`, or Outlook via `create-calendar-event` — see *Workspace providers*). `create_calendar_event` schedules a **future** meeting (propose→approve by default, or auto-execute once that decision class is promoted) and may be used proactively when a stalled goal warrants a sync. `create_instant_meeting` spins up an **impromptu call starting now**, auto-executing without the approval step and skipping the business-hours/horizon caps, so the Executive can hand back a join link immediately. Because nothing approves it, an instant meeting, and `cancel_calendar_event` too, runs only when someone on the team asked on a surface that verified who they are (the principal, or a rostered teammate in the app or their own chat); a turn an inbound email started gets a refusal to pass on instead, and a team-mode `create_calendar_event` the operations department would auto-execute is proposed instead. Both attach a video-meeting link by default (`add_video_link`; opt out for in-person) — a **Google Meet** link read from `manage_event`'s plain-text reply (which also carries the event id, inside the event link's `eid`), or a **Microsoft Teams** link from `onlineMeeting.joinUrl` — surfaced to the caller plus persisted on the decision ledger as `meet_link`. The tool descriptions are static, backend-neutral text, so the cached tool block never depends on settings; the pre-rename `add_google_meet` key is still honoured for old ledger rows. Either way the caps that matter still hold — roster membership, principal-protection, max attendees, and a daily booking ceiling. A proposal raised in the web chat by the person who approves it (the principal, or its approver when it isn't the principal's private booking) says `approve_here`; its `action_taken` chip then carries the `decision_id`, and the chat shows the approval card (Approve, Edit, Dismiss) under the reply as well as on the briefing — answering either clears both. A booked meeting whose event id was never read can't be cancelled from the app: both cancel paths refuse rather than report a cancel that left it on the calendar.\n\n**Around-the-meeting participation.** The Executive doesn't join the call as a live voice; instead, on every successful booking it schedules a best-effort post-meeting follow-up (~5 min after the end) that DMs a human attendee asking for a quick recap — key decisions and action items. The reply flows back through the same cross-session DM context linkage described below, so the Executive can act on it (summarize, follow up) in a later turn. No meeting-transcript or Drive integration is required.\n\n### Workspace providers\n\nThe Executive can *discover* any mail or calendar tool the gateway exposes, but three code paths call a fixed backend with no model in the loop and used to spell Gmail tool names inline: the inbound mailbox poller (list unread → fetch → mark read), alert email dispatch plus the scheduler's email send-tool hint, and the typed booking tools plus the approval-time conflict check. `integrations.workspace` puts those behind two Protocols (`MailProvider`, `CalendarProvider`) with one module per backend (`google.py`, `microsoft.py`) and a registry keyed on `EMAIL_PROVIDER` / `CALENDAR_PROVIDER` — separate switches (Outlook mail with a Google calendar is legitimate), both defaulting to `google`, so an existing install changes nothing until an operator opts in. The Google backend is the old inline code moved verbatim; tests pin its argument dicts byte-for-byte. The Microsoft backend polls only the Inbox folder (`list-mail-folder-messages` with `isRead eq false`, never the all-folders listing that includes Junk), converts Graph's HTML bodies to text with a real parser, lists a message's attachments so the names appear in the same `N. name (mime, size KB)` shape Gmail's text uses (and reach peer memory), marks read with `update-mail-message`, sends through `send-mail`'s nested shape, books with `isOnlineMeeting` + `onlineMeetingProvider=teamsForBusiness`, cancels with `delete-calendar-event`, and answers the advisory conflict check from the Executive's **own** calendar view (delegated permissions cannot read attendees' free/busy — narrower than Google's `query_freebusy`).\n\nEvery backend renders an inbound message into the same `Subject:` / `From:` / `To:` / `Cc:` + `--- BODY ---` text the persona already expects, and the poller adds a `--- REPLY ---` block naming the exact reply tool and threading ids for *that* message (Gmail: `send_gmail_message` + `thread_id`; Outlook: `reply-mail-message` + `messageId`) after the mail's `<untrusted_content>` block, never inside it. The block rides in the user turn — which is what lets the cached persona say \"use the reply tool in the REPLY block\" instead of naming a vendor tool — and the scheduler's proactive-email trigger names the backend's send tool the same way. Providers never raise on a malformed backend response (they return empty / `None` / `{\"error\": …}`), so one bad cycle never kills a loop, and a chosen backend whose MCP server is missing from `mcp_servers.json` is logged at startup and skipped by the poller: fail-soft, never a boot failure. The poller's newer checks run on that rendered text for both backends (contacts and private turns, roster requests and their emailed answers, the audit row), with three Outlook differences that fail closed: no sender is ever authenticated (the `dmarc=pass` read is Gmail's), so there is no acknowledgement to an unknown sender, no emailed fact confirmation and no principal-authenticated mail; attachments stay a list (the download is Gmail's); and the brief's calendar block is skipped (its listing is Google Calendar's). The code's own emails to the principal (roster prompts, fact confirmations, scheduled deliveries) go through `workspace.registry.send_from_executive`, and `runner.email_ready` follows `EMAIL_PROVIDER`. A private turn's allow-list (`schedule_tools.PRIVATE_TURN_MCP_TOOLS`) and Act as me's mail-touched reads include the Outlook twins of the Gmail and Calendar tools, and roster answer tokens are hidden from Microsoft 365 results as from Google's.\n\n### Cross-session DM context\n\nWhen the principal says \"DM Alex about X\" in one session, OE sends the DM and — if a live conversation is active and the recipient is not one of the principal's contacts (a contact cannot DM the bot, and quoting the principal's conversation into their email reply's unattended turn would put it in the audit log) — records an `outbound_context` linkage row (recipient, full outbound text, originating session id). Email is covered too but recorded one layer deeper — there is no `send_email` tool, so the linkage is written in `orchestrator.mcp_gateway` after a successful `google_workspace__send_gmail_message` or `microsoft_365__send-mail`, one row per `to`/`cc` recipient keyed by the bare lowercased address (OE's own address skipped). When Alex later replies on the 1:1 DM path — or by email — the shared helper `integrations.inbound_hydration.hydrate_user_message` (called by the Discord, Telegram, and Slack handlers, and by the email poller keyed on the sender address) looks up the most-recent `open` linkage for that sender within 72h and prepends an `<outbound_reply_context>` block — the outbound text plus a backstory excerpt from the originating session — to the message handed to `Executive.chat()`. So OE knows what the reply is about instead of starting from an empty per-person session. The block is context for the LLM turn only: peer memory strips it before recording what the person said (`strip_outbound_reply_context`, applied in `sync_turn`, `sync_department_turn` and to the prefetch query), so the Executive's own DM is never attributed to the person who replied to it. The block lands in the user turn (caching rule) and is injected into a copy only — the pristine reply is persisted to history. The linkage is one-shot (consumed on first matched reply, race-safe) so an unrelated later DM isn't re-hydrated. This is deterministic and independent of the per-person `peer_memory` (Honcho) layer.\n\nEvery adapter that persists a turn (Slack, Discord, Telegram, and the web route) records the message's **resolved sender** on `chat_messages.sender_person_id` — the rostered Person the adapter matched, or NULL for an unrostered sender — independently of the session owner, which falls back to the principal on Discord and Telegram so those threads stay visible. Attunement's open loops and feedback rely on this so an outsider's words are never read as someone on the roster's.\n\n### OneDrive folder sync\n\nThe Microsoft twin of the Drive folder sync below (`knowledge.onedrive_sync`, `ONEDRIVE_SYNC_ENABLED`; setup in `docs/onedrive_sync_setup.md`). It copies the files in `ONEDRIVE_SYNC_FOLDERS` (`<drive id>/<item id>` pairs; `openexecutive onedrive-folder <link>` resolves a sharing link) into the isolated `onedrive_docs` collection on its own heartbeat, and shows them on the knowledge page as \"OneDrive\" rows with a **Sync now** button. Microsoft has no service account that sees only what is shared with it (app-only Graph access covers the whole tenant), so it reads as the Executive's own Microsoft 365 sign-in, and the folder list is the scope. It never stores a credential: each tick asks the launcher for a token (`ms365-mcp-launch.sh --access-token`, which runs `docker/ms365-access-token.mjs` through the server's own token cache and will only mint file-read tokens), keeps it in memory, and sends it only to Graph. `knowledge.onedrive_client` issues GETs only, follows a paging link only back to Graph, and fetches a file's pre-authenticated download link without the token; errors never carry that link. PowerPoint and older Office formats are read through Graph's PDF rendering.\n\n### Google Drive folder sync\n\nThe synced files show on the knowledge page's Company documents list as \"Google Drive\" rows (sync time, last edit in Drive, an Open in Drive link and a text view), and the page's source card shows the last run, any sign-in error or count of files that failed to sync, and a **Sync now** button that runs one tick on demand.\n\n\nSeparate from the Drive tools the gateway proxies. The optional folder sync (`knowledge.drive_sync`, `DRIVE_SYNC_ENABLED`; setup in `docs/drive_sync_setup.md`) copies the files in `DRIVE_SYNC_FOLDER_IDS` into the isolated `drive_docs` knowledge collection on a scheduler heartbeat, so the Executive knows those folders without searching Drive live (see RAG). It calls the Drive v3 API directly (`knowledge.drive_client`, `httpx`) as a **service account** with the `drive.readonly` scope (`DRIVE_SYNC_SERVICE_ACCOUNT_FILE`), not as the Executive's own account through workspace-mcp. Google enforces the folder scope, because the account sees only what is shared with it, and the sync can change nothing. Structured JSON means no display text to parse, and every file or folder id is checked against `[A-Za-z0-9_-]{1,128}` before it goes into a URL or a query. The two paths meet in two places. A synced chunk carries its Drive file id and sync time, so the Executive can open the live file with its own `get_drive_file_content`. The setup doc says to share each synced folder with the Executive's account too, so that live open works.\n\n### Confluence space sync\n\nThe optional Confluence sync (`knowledge.confluence_sync`, `CONFLUENCE_SYNC_ENABLED`; setup in `docs/confluence_sync_setup.md`) copies the pages of the spaces in `CONFLUENCE_SYNC_SPACE_KEYS` into the isolated `confluence_wiki` knowledge collection on a scheduler heartbeat, so the Executive knows the company wiki without a tool call (see RAG). It works with Confluence Cloud and Server/Data Center: `knowledge.confluence_client` calls the v1 REST API both serve, directly with `httpx`, signing in with a personal access token (Server/DC) or a username and API token (Cloud). It reads only, never follows a redirect (so the token stays on the configured site), streams responses with a 20 MB cap, and checks page ids and space keys before they reach a URL or a CQL query. The URL must be `https://` unless `CONFLUENCE_SYNC_ALLOW_HTTP` is set, and `CONFLUENCE_SSL_VERIFY` takes `true`, `false` or a CA bundle path for a private certificate authority. With `CONFLUENCE_SYNC_PUBLIC_HOSTS_ONLY` (off by default, for an install where whoever sets the URL must not reach the backend's own network) every request resolves the site's host, refuses it when any address is not public (loopback, private, link-local, shared), and connects to the checked address with the site's name kept for the Host header and the TLS certificate check, directly rather than through a proxy. `confluence_client.config_problem` is the same settings check the app runs at start, for a caller that writes these settings on someone's behalf.\n\nIt is separate from a Confluence MCP server such as mcp-atlassian, which a deployment can add to `mcp_servers.json` for live reads and edits in chat. The two share the env names `CONFLUENCE_URL`, `CONFLUENCE_PERSONAL_TOKEN`, `CONFLUENCE_USERNAME`, `CONFLUENCE_API_TOKEN` and `CONFLUENCE_SSL_VERIFY`, so one set of values serves both, and a synced chunk carries its page id so the Executive can open the live page with such a tool. A Confluence token is a user's, and what the sync reads becomes retrievable by everyone who talks to the Executive, so the space list is required and pages with a read restriction (their own or a parent's) are skipped unless `CONFLUENCE_SYNC_SKIP_RESTRICTED=false`. That keeps any existing member's token safe to use, without a dedicated licence. Manual runs: `openexecutive sync-confluence` / `purge-confluence`.\n\n### Your own Gmail or Outlook (Act as me)\n\nA second, separate mail connection, for **Act as me** (see **Act as Me (Delegation)**): a person's *own* mailbox, which `delegation.gmail.DelegateGmail` reads and drafts into over the Gmail REST API. It is never registered with the MCP gateway, so the model can reach it only through the typed `ghostwrite_email` handler — never by tool name through `call_tool`. The credential is one file per person in `DELEGATION_GOOGLE_CREDENTIALS_DIR` (default `company/delegation_google/`, `/data/delegation_google` in Docker), minted on a computer with a browser by `scripts/connect-own-gmail.py --email <you>` with the Executive's own OAuth client and the scopes `gmail.readonly` and `gmail.compose` — the same seed-it-yourself flow as the Executive's token, since the API serves no OAuth callback. It never lives in `WORKSPACE_MCP_CREDENTIALS_DIR`, where workspace-mcp picks a credential by address.\n\nEvery use re-checks with Google that the credential opens the mailbox on the person's People entry, and refuses outright when that address is the Executive's own: a shared mailbox would make everything the Executive writes look like theirs. Drafts are threaded (`In-Reply-To`, `References` of whole ids ending with the parent, `threadId`) and stamped `X-OE-Ghostwritten`; the only send is `drafts.send` of an existing draft by id, when the person taps Send on its reply card (`delegation.reply_send`). A Gmail rate limit, even as a 403, is an error to retry rather than a reconnect. The voice learner and the thread shown to the ghostwriter keep only each sender's own words through `email_poller.sender_new_text`, the poller's quoted-reply stripper made public. Setup status shows it as **Your own mailbox (Act as me)**.\n\nThe same file can instead hold an Outlook sign-in (`\"provider\": \"microsoft\"`), minted by `scripts/connect-own-outlook.py --email <you>` with a device-code sign-in on the Executive's own Entra app (`MS365_MCP_CLIENT_ID`, `MS365_MCP_TENANT_ID`, default `common`) and the delegated scopes `User.Read`, `Mail.ReadWrite`, `Mail.Send` and `offline_access`. `delegation.gmail.gmail_for` then hands back `delegation.outlook.DelegateOutlook`, which talks to Microsoft Graph directly — never the Microsoft 365 MCP server the Executive's own Outlook uses — with the same methods and the same one send: Graph's `send` on an existing draft, with no body. Microsoft rotates the refresh token on use and the new one is written back into the file. A sender counts as verified only from the topmost `Authentication-Results`, the one Exchange wrote, and only mail in their Sent Items counts as theirs.",+ "markdown": "External channels connect callers to the Executive. Each inbound adapter resolves the sender to a Person — the chat adapters via `find_person_by_{slack,discord,telegram}_id`, the email poller via `people.identity.resolve_email_sender` (a primary address or an alias, then the company-domain rule; see Org) — and threads `person_id` into `Executive.chat()`. A sender who resolves to nobody is no longer simply dropped: see **New senders (roster requests)** below.\n\n### Inbound channels\n\n- **Slack** (`integrations.slack_bot`) — async Bolt app (`AsyncApp`) embedded in the lifespan, hearing Slack one of two ways: socket mode (`AsyncSocketModeHandler`, with `SLACK_APP_TOKEN`) or, with only `SLACK_SIGNING_SECRET`, the Events API over HTTP at `POST /webhook/slack` (`integrations.slack_events`), where the route checks each request's signature and age (and a 1 MB cap) before Bolt sees it, so unsigned traffic never reaches Bolt's logging; it then takes each signed request once, answering an identical replay (same signature) or Slack's re-signed retry of an `event_id` it already took with an empty 200 that never reaches Bolt (an in-memory, per-process set kept for twice the signature window and capped in size; keys are forgotten if Bolt fails, so a retry of a failed delivery still runs), and Bolt acknowledges at once while the listener runs. Either way a repeated event id is dropped (Slack resends what it thinks went unacknowledged), as is an event delivered for another workspace. Responds to `@mention`s, DMs, and thread continuations, with per-conversation session memory (see **Conversation state** below). Text only: there is no interactivity endpoint and no Block Kit, so nothing Slack sends carries a button.\n- **Discord** (`integrations.discord_bot`) — discord.py gateway embedded in the lifespan; per-thread auto-titling, session-scoped memory, author attribution, configurable `@mention` thread promotion.\n- **Telegram** — webhook gating + per-chat history. Replies (and every outbound Telegram message) go out as Telegram's HTML subset (`utils.markdown_telegram`: markdown-it-py with raw HTML and images off, text escaped), so the Executive's Markdown shows as formatting; links show as their text and target in plain text and never become tags, so quoted text can't hide where one goes; a chunk Telegram refuses is sent again as plain text.\n- **Google Chat** — webhook + service-account auth. It resolves no approval gates and has no roster gate (the webhook authenticates Google, not the sender), and it never populates the session's trusted alert ids, so `ack_alert`'s trust check — which now runs on every session rather than only those declaring an `origin_channel` — refuses there by default, and its `<channel>` block says plainly that a sign-off cannot be answered from it. It does look its sender up on People by the Google account email on the signed event, but hands that entry only to the department gate (`Session.gate_sender_person_id`): the principal's own sends and edits go, a teammate's meet their department's authority, and anyone else's wait for approval. It is never `caller_person_id`, so it grants nothing else.\n- **Email** (`integrations.email_poller`) — MCP poll loop over the Executive's own mailbox — Gmail via `workspace-mcp` or Outlook via `ms-365-mcp-server`, chosen by `EMAIL_PROVIDER` (see *Workspace providers* below); it starts only once the MCP gateway is up, never surfaces Reply-To redirects, filters auto-replies. Its sessions carry `origin_channel=\"email\"`: the untrusted-content policy (`orchestrator.content_trust`) reads that tag to tell mail from the principal's own surfaces — left empty, as it once was, every stranger's body reached the decision extractor as the principal's words. The mail goes into the turn inside an `<untrusted_content source=\"email\" author=\"<sender>\" author_verified=\"no\">` block that says it carries none of the principal's authority, with the framing line and any `[POLICY]` notice outside it; mail from the principal's primary address that Gmail authenticated (`dmarc=pass`) is their own words — but only their new text goes in unwrapped: when the mail quotes or forwards another message (`_new_text_lines` cut something), the message as received follows in an `<untrusted_content source=\"email_quoted\">` block, since a stranger's text they replied to or passed on is not theirs. While the Executive is paused (`scheduler.pause`) it skips each poll and leaves the inbox unread, so held mail is processed on the first poll after resume; the chat adapters above are not paused. The poller handles one message at a time, so each Executive turn on an email has a deadline, `EMAIL_TURN_TIMEOUT_S` (300 s): past it the turn is cut off, an `integration_inbound` row with outcome `turn_timeout` records it, and the message is marked read and not run again (it may already have replied). A message whose handling keeps raising is given up after three tries in a run and marked read, rather than retried every poll. Each gateway call it makes is bounded by `MCP_TOOL_TIMEOUT_S` (see Lifecycle). The Executive sees the whole message; peer memory records only `_email_memory_text` — the subject, the sender's new text (cut at the first quoted or forwarded message) and the attachment filenames — parsed from the rendered message with any trailing `--- REPLY ---` block dropped first, without backtracking-prone regexes, since the text is sender-controlled, and only for a rostered sender, the only kind with a peer to record into. The poller's `integration_inbound` row keeps the mail's text for the audit log, the way the reply's `chat_turn` row keeps the Executive's answer: `full.message` is the sender's new text (what web chat keeps for a turn), `full.attachments` the attachment filenames, and `details.preview` the first 120 characters of the new text, so /audit shows what was asked next to what was answered (the summary still reads `Inbound email from <sender>: <subject>`). The whole body with its quoted chain (`full.body`) is kept only on a row private to the principal: the chain is other people's mail — a contact's, on the principal's reply to one — and every signed-in user reads a public row. Each field is cut by its escaped JSON length (20,000 characters of text, 8,000 of attachment names), the measure the logger's 64 KB cap uses, so a long mail in a non-Latin script loses its tail rather than the row's structure. Outbound, the principal briefs and the client-rotation digest are emailed through the same gateway with the configured backend's send tool (`google_workspace__send_gmail_message` or `microsoft_365__send-mail`, via `workspace.registry.send_from_executive`, from the Executive's own mailbox to the principal's address, subject `<brief title> — <date>`, the date in the user's zone) as formatted HTML — rendered from the brief's Markdown with raw HTML and images off, so text quoted from outside shows as text and opening the email loads nothing remote. Email is first when the principal prefers it, and otherwise the backup after every chat channel, tried only when Slack, Discord and Telegram are missing or fail; an in-band error from the tool counts as a failed send and the next channel is tried. An emailed brief is not a DM, so the per-Person outbound guard below does not apply — the gateway's roster egress gate does.\n\n Two senders get their own framing. Mail from one of the principal's **contacts** (a `kind=\"contact\"` People row — see Org) replaces the non-roster `[POLICY]` notice with a contact one: it names them (name and role/company), says not to reply unless the principal asks and not to tell anyone else, and asks for a summary in an alert for the principal instead. Mail from anyone not in People, a contact or a stranger, is held as outside content for its whole turn (`orchestrator.outside_content`): no connected-app write, contact change, follow-up, link, script or workflow, no direct message, only reads and an alert private to the principal. Both this turn and the forwarded-by-principal turn below are marked `Session.private_to_principal`: they can email, DM or invite only the principal, an alert they raise is private to the principal, and they are not offered the tools that reach anyone else or start work outside the turn (`schedule_tools.PRIVATE_TURN_WITHHELD_TOOLS`: broadcasts, meeting bookings, workflows, follow-ups, watches, artifacts, goal updates, skill drafts, connecting a new MCP server), and of the MCP tools only Google Workspace reads and the gated Gmail send (see MCP below). Every audit row about such mail is private to the principal (see Audit Log), the poller's two `integration_inbound` rows included (`_private_to_principal_mail`), so the audit log's other readers see none of it. The poller holds `audit.private_rows` for the whole handling of such a mail, because some rows are written before the turn binds its private session: the knowledge retrieval quotes the mail's From line, subject and opening. The rows themselves read exactly like an outside sender's: the `integration_inbound` row is the non-roster one (`accepted_non_roster`), and the notice opens with the non-roster notice's exact sentence. The poller handles each message with no session bound, so one message's private turn never marks the next message's rows. The turn stays unattributed (`person_id` None — no peer memory, no co-presence), and the gateway refuses mail to a contact on a poller turn anyway. Mail **forwarded by the principal** — the sender resolves to the principal and `_new_text_lines` reports a forwarded message — is wrapped in a `<forwarded_by_principal>` block: summarise it, draft a reply the principal could send (as text in the reply, never sent or saved as a Gmail draft), note any commitment or date, and offer to add the original sender as a contact (confirmed from the web app or the principal's Slack / Discord, since an ordinary email turn cannot change the People list — the one email that can is the principal's tokened reply to a roster-request email, which is parsed before any model turn; see below). The reply still goes to the principal only. The From header is unauthenticated, so this framing grants nothing: a spoofed \"forward\" just gets the real principal a summary.\n\n **An email that got no reply goes to Needs you.** Mail from the team or the principal is answered by the model calling the mailbox's send tool, so a turn can end with nothing sent (a tool refused, the answer only written). The gateway marks on the conversation who each accepted send reached (`Session.mail_sent_to`: Gmail `send_gmail_message` to/cc, Outlook `send-mail` recipients; `mail_replied_ids`: the message an Outlook `reply-mail-message` / `reply-all-mail-message` answered). After the turn the poller (`_note_reply_outcome`) checks the sender, by any of their addresses, or the message id; with no reply it files a card through `integrations.unanswered_mail` (source `unanswered_email`, high, tagged `private:principal` and routed to the principal, so only their own /today shows it), whatever the model did. Repeats in the thread fold into it (one card per thread, occurrence count), and a later turn that does reply resolves it. A reply the poller sees is also logged (`unanswered_mail.record_reply`, a private `integration_outbound` row keyed by thread), and the briefs read both: each INBOUND email from the roster says \"the Executive replied\" only on that evidence, or \"no reply went out\" while its card is open (`open_thread_keys`), so the brief stops telling the principal to answer mail the Executive already answered. Only mail Gmail proved is the principal's (`Session.email_authenticated`) reads \"Your email got no reply\" with its subject and what the Executive wrote, which never reached them; a teammate's card names who is waiting and never their subject or text (their conversation is theirs alone); mail that only claims a teammate's or the principal's address says it could not be proven and carries nothing the sender wrote. A plain-text `Error …` tool result is not counted as a send. Contacts and senders off the team are not answered by design and keep their own paths. Why: the brief read the inbound log and said people were waiting while Needs you, which shows alerts only, stayed empty, since an alert depended on the model choosing `create_alert`.\n\n **Other mail sources** (`integrations.mail_sources`). Mail read from anywhere but the Executive's own mailbox (a hosted inbound address, a relay) follows the same rules through a vendor-neutral hook. Nothing is registered by default and the hook has no settings: a deployment registers a `MailSource` (its loop, an `enabled` check, and how to replay a held message), the lifespan starts the enabled ones, and each message goes to `handle_inbound` as an `InboundMail`: the parsed message, the address it came to, `prove_sender` (DMARC, or SPF and DKIM aligned, as the source can tell), `send_answer`, an optional attachment reader and what a held message keeps. `handle_inbound` runs the poller's own handling (`email_poller._handle_mail`): sender resolution, private-to-principal rows, the teammate's own rows only when proven, untrusted-content wrapping, the principal's proven mail, the forwarded-by-principal framing, hydration and the turn deadline. Because a source mails the answer itself (with the AI line, and an `integration_outbound` row) rather than the model calling a send tool, three things differ: a stranger is held for the principal silently, with no acknowledgement and no turn, and replayed through the source that read it (`replay_held_mail` dispatches on the payload's `mail_source`); a contact's mail, and mail claiming a teammate that nothing proves, is answered to the principal and never to the sender; and roster-request and fact confirmations are answered only from the mailbox they were sent from. A source must be registered to be handled, it does nothing while the Executive is paused (`handle_inbound` returns `PAUSED` and the source keeps the message), a stranger the request queue won't take is logged as not held, and a sender who is neither team nor contact by the time the turn runs gets no answer at all.\n\nSlack, Discord, and Telegram are roster-gated on inbound: an unrostered sender's message never reaches the Executive (`details.outcome=\"rejected_unknown_sender\"`). The gates look up **team members only** — a contact's Slack, Discord or Telegram id is treated as unknown, so a contact can never talk to the bot (nor count as a co-present peer). What happens next is the roster request below — except for a contact, a thread continuation, a Telegram group or an unverified Telegram webhook, which stay silent. Email is not inbound-gated — non-roster mail flows through with a `[POLICY]` notice so triage can classify it. Slack/Discord thread continuations pass the shared `integrations.response_gate` (utility-fast model, biased toward replying). Slack only continues a thread it has replied in: it reads the thread with `conversations_replies` (5 s bound) and looks for its own user id, which `auth_test` resolves at startup. If that lookup fails, mentions and DMs still work and thread continuations stop until a retry succeeds (`slack_bot._resolve_bot_user_id`, at most once a minute, from the channel `message` listener). When Slack doesn't return the thread in time, the thread's stored history (`slack:thread:{channel}:{thread_ts}`, written on every turn the bot answers there) stands in: with history, a rostered sender gets an ephemeral \"I couldn't read this thread just now… @-mention me\" and the drop is audited (`outcome=dropped_thread_unreadable`). A thread the bot never answered in stays silent. A message the gate skips is audited (`outcome=skipped_gate`, with the gate's reason) and gets an :eyes: reaction (`reactions_add`, which needs the bot's `reactions:write` scope; without it the reaction is skipped), so a sender the gate misjudged can see the message was read and @-mention the bot.\n\n**No link previews on replies.** The Executive's replies go out with previews off — Telegram `sendMessage` carries `link_preview_options.is_disabled`, Slack's reply `say` passes `unfurl_links=False` / `unfurl_media=False`, and every Discord reply send passes `suppress_embeds=True`. The direct messages the Executive starts are the same: `send_slack_dm` posts with `unfurl_links=False` / `unfurl_media=False`, and Discord's `send_dm` sets the `SUPPRESS_EMBEDS` flag on each chunk, so a reminder or a brief sent by DM carries no preview either. Otherwise the chat service fetches a link in the text on its own, so a reply that quotes someone's mail (Act as me reads it) could carry data to a sender's server with no click. The web chat does the same for images: `Message.tsx` loads only an image the app itself serves (`lib/markdownImages.loadsInline`) and shows any other as a link.\n\n### Alert triage of chat messages\n\nEvery chat-app message that passes the roster gate (Telegram, Slack, Discord, Google Chat) is also handed to alert triage through `alerts.pipeline.schedule_chat_message_evaluation`. The sender is named by their People record (`full_name`), not by the name they typed into the chat app, so a person whose account there is called something else is never read as a stranger; the chat app's own name (or raw user id) is used only when nobody on the roster matched. The principal's own messages to their Executive are a conversation, not news for their brief, so they are not triaged at all. Triage sees the sender as `sender:` and the room as `channel:`. Google Chat's inbound audit row also carries the matched People id (`sender_person_id`), looked up before the row is written, so the brief can tell the principal's own messages apart by id, never by a display name anyone can set.\n\n### New senders (roster requests)\n\nSomeone who writes in and is not on the People list — and is not one of the principal's contacts — is **held, acknowledged and asked about** instead of dropped (`integrations.roster_intake.intake` over the `people.roster_requests` ledger; lifecycle in Org). Each adapter calls it after its gate:\n\n- **Slack** — a DM or an `@mention` (not a thread continuation: the bot was not addressed there). The name and profile email come from `users_info` (5 s timeout). The acknowledgement goes in the DM, or as an **ephemeral** message for a mention, so nobody else in the channel learns who is and is not on the roster. The held event keeps only a fixed set of keys (text, user, channel, ts, thread, files).\n- **Discord** — a DM or a mention (not a thread the bot merely follows). The acknowledgement goes in the DM, or by DM for a channel mention; `/ask` answers the interaction with an ephemeral acknowledgement first (Discord allows 3 s), then holds the prompt. Its old \"ask the admin to add you\" reply is gone.\n- **Telegram** — only a **private** chat, and only when `TELEGRAM_WEBHOOK_SECRET` is set and valid: Telegram identifies the chat rather than the sender, and without the secret anyone could forge an update. A group, or an unverified webhook, stays silent as before. Attachment file ids are held and downloaded only on replay.\n- **Email** — non-roster mail that is not private to the principal (so never a contact's) and does not look machine-sent (`looks_automated`: a no-reply / notifications / billing-style local part, a `List-Id` / `List-Unsubscribe` / `Auto-Submitted` / bulk `Precedence` header, or a DMARC failure). The mail is **still triaged** by the Executive on this pass; its `[POLICY]` notice now says the sender was already told their message is waiting and the principal was asked who they are, so the model raises no second alert just to add them, and that the email will come back once they are added.\n\nEvery path skips a contact first (`find_person_by_*_id(..., include_contacts=True)`, or the email poller's private-mail rule): a contact has no chat access and gets no request and no acknowledgement, and the team-visible `rejected_unknown_sender` / `accepted_non_roster` rows read the same for a contact as for a stranger.\n\n**The acknowledgement** is one fixed text (`roster_intake.ACK_TEXT` — \"your message arrived … waiting for confirmation\"), never the model and never an echo of what they wrote, so a forged sender gains nothing by triggering it. It is sent at most once per sender per `ROSTER_ACK_WINDOW_DAYS` (7) and at most `ROSTER_ACK_DAILY_CAP` (20) a day across all senders (`claim_ack`, one transaction; a failed send releases its claim). An email acknowledgement is the one send the MCP gateway lets reach an address off the roster: `send_email_ack` sets `mcp_gateway.roster_ack_grant`, a one-shot ContextVar grant that admits a single `send_gmail_message` with exactly the granted recipient (a plain string, no list), subject and body and no other key, then is spent (audited `integration_outbound`, `kind: roster_ack`, private). An email sender is acknowledged only when Gmail authenticated them: once `claim_ack` succeeds, the poller's `send_ack` re-reads the mail as raw MIME and needs Gmail's own topmost `Authentication-Results` reporting `dmarc=pass` for the From domain (`fact_confirmation.sender_authenticated`, fail-closed). The printed headers the poller reads never carry that header, so without the second read a forged From would draw the acknowledgement to whoever it names — backscatter from the Executive's mailbox. An unauthenticated sender makes `send_ack` raise `roster_intake.AckWithheld`: the claim is released, and they are held silently. `authenticated_by_gmail` strips quoted strings and comments before reading the verdict — Gmail copies the envelope sender and DKIM tags into its own stamp, and a quoted local part could otherwise carry a fake `dmarc=pass` — and needs exactly one `dmarc=` verdict reading exactly `dmarc=pass header.from=<domain>` (Gmail may follow it with its own `dara=` resinfo, so its position is not checked). Residual: when Gmail writes no verdict at all (a From domain without DMARC) and echoes an unsanitised `;dmarc=pass header.from=…` elsewhere in its stamp, that echo would read as the verdict; bounded by the acknowledgement caps. A withheld acknowledgement is audited `roster_ack_withheld`. `intake` acknowledges before surfacing the card and telling the principal, and both follow the request's `ack_sent_at`: a withheld, failed or capped acknowledgement reads \"haven't been told anything yet\" on the Today card, in the principal's prompt and in the email `[POLICY]` notice.\n\n**Telling the principal.** A new request puts a private card on the principal's `/today` (see Today) and pushes a prompt on their delivery plan — preferred chat DM, then the others, then email — for a chat sender or an email sender on the company's own domain; an outside email sender waits on the card, as does everything past `ROSTER_REQUEST_DAILY_CAP` (30) pushes a day (the same cap bounds how many requests open a day; a declined sender is not raised again for 30 days). A chat prompt can be answered in place (\"that's Annamarie, add her to the team\"). An email prompt carries a one-time token (`RR-` + 20 base32 characters, stored hashed); the poller checks every inbound mail for one **before** triage (`try_email_roster_answer`): the reply must come from the principal's primary address exactly (not an alias, not the company-domain rule), carry the token of a pending request, not be an automatic reply, and not fail DMARC where the header is visible; and is parsed by `parse_decision`'s `roster_identity` shape — anything else falls through to the ordinary path. The token is hidden (`RR-[hidden]`) in every other Google Workspace result the gateway returns — the confirmation sits in the Executive's Sent folder, and any turn could otherwise read it — except the poller's own fetch of an inbound message (`mcp_gateway.reveal_roster_tokens`); a token-bearing mail that is not an answer is scrubbed before triage.\n\n**Replay.** Once the principal answers (web card, chat tool, email reply) — or a People-page / `upsert_person` write makes the sender match someone (`after_roster_write`) — the held messages are replayed through the adapter that received them (`register_replayer`: Slack re-runs the held event, Discord and Telegram their held text, email re-fetches the message from Gmail and handles it as mail from a known sender), oldest first, now attributed to the new Person. A teammate gets every held message; a new contact only held email (it takes the private contact path; held chat is dropped); a decline drops everything. Replays run in a **fresh `contextvars.Context`**: the answer may have come from the principal's own verified turn, and a stranger's message must never be read with the principal's session — and their contacts — still bound.\n\n### Standing facts by email (confirm by reply)\n\nThe principal can ask for a standing fact, a retirement or a company-profile edit by email, and the fact tools check it exactly as in chat (the own-words gates run on `_email_memory_text`, the sender's new text, not the quoted chain or attachments). An email's From line proves nothing, though, and a standing fact is read by every later prompt as the principal's own account. So an emailed change is **held, never applied**, until the principal's own mailbox confirms it (`integrations.fact_confirmation`, `memory.facts.fact_confirmations`):\n\n- **Who may ask.** The poller stamps every email turn with `Session.email_from` (the bare lowercased From address) and `email_authenticated`. The text the poller reads never carries `Authentication-Results` (workspace-mcp prints a fixed set of headers), so for mail claiming the principal's primary address it reads the message again as raw MIME (`fact_confirmation.sender_authenticated`) and requires Gmail's own stamp: the **topmost** `Authentication-Results` header (Gmail adds it on receipt, above anything the sender wrote), authserv-id `mx.google.com`, reporting `dmarc=pass` for the From address's domain, with the raw From matching (`authenticated_by_gmail`). It fails closed: no header, `dmarc=none`, a temporary error or a failed read all leave the turn unauthenticated. Mail from a teammate other than the principal is read the same way, before its inbound audit row is written: authenticated, the whole handling of it is theirs alone in the audit log (`rows_for_person`, see Audit) and the turn reads their own mail as them (`Session.email_sender_authenticated`); unauthenticated, it keeps the ordinary rule. Mail from anyone else costs no second read and is never authenticated. `fact_tools._gate` admits an email turn only from the principal's **primary** address, exactly (no alias, no company-domain rule), authenticated, and not private to the principal (mail they forwarded stays refused, as do contacts, teammates and unknown senders).\n- **The hold.** The tool returns `awaiting_confirmation` (no action chip, and the model is told to say nothing has changed). `request_confirmation` stores the change with the SHA-256 of a fresh one-time token (`FC-` + 20 base32 characters, 100 bits; 7-day expiry; at most 10 waiting at once) and emails the token to the principal's roster address, outside any turn's outbound context. A profile edit is dry-run first, so one that cannot apply is reported in the turn, before any email goes out. If the email fails, nothing is held.\n- **Keeping the token from any model.** The tool result never carries it, and `mcp_gateway.hide_roster_tokens` now scrubs `FC-` tokens as well as `RR-` ones (`FC-[hidden]`) from every Google Workspace result except the poller's own fetch of an inbound message. Act as me's reads of the principal's own Gmail, where the confirmation email lands, hide them too (`delegation.gmail.parse_message` and the thread search), so the drafting model never sees a live token either.\n- **The reply.** `_handle_one_email` hands every message to `try_email_fact_confirmation` right after the roster-answer check, before any model turn. It acts only on a reply from the principal's primary address carrying the token of a **pending** confirmation. A made-up, spent, cancelled or expired reference matches nothing and falls through to the ordinary path with the token hidden, so no old or forged token can make the Executive email the principal. A reply with a live token is read again as raw MIME (`read_raw`) and must pass the same Gmail DMARC check as the request; one that doesn't (or whose raw read fails) is refused, the change keeps waiting, and the principal is told. Then an **automatic reply** is consumed quietly — no answer, no model turn, the change keeps waiting: the printed headers catch a Gmail vacation reply (`Precedence: bulk`), and the raw headers catch what they don't show (`automatic_reply`: `Auto-Submitted` other than `no`, `X-Auto-Response-Suppress` and similar, `Precedence: auto_reply`, an out-of-office subject), since an Exchange out-of-office echoes the token from the principal's own address and may well say \"I'll confirm on my return\". The raw message starts at the tool's exact separator line (`\\n\\n--- RAW MIME ---\\n`), so a sender-written Subject imitating it cannot supply the headers. CONFIRM (or yes / approve) applies the change through `fact_tools.apply_confirmed`, the same apply step chat uses. CANCEL (or no) drops it, and an unclear reply leaves it waiting. The principal gets a one-line result either way. A compare-and-set on the row means two replies can apply it only once.\n- **Audit.** Private `fact_confirmation` rows record held / applied / cancelled / refused. The applied change also writes the fact tools' usual private rows, with `source_channel=\"email\"` as its provenance.\n\n### Checking a channel is set up\n\nSettings → Setup status (`GET /setup/status`, `api/setup_checks.py`) gives each channel a light and a plain-language fix. It tests the credentials with one free read-only call — Slack `auth.test`; Telegram `getMe`, then `getWebhookInfo` (is a webhook registered, is it this app's `/webhook/telegram`, did a delivery fail in the past day); Discord `users/@me`, only while the bot is still connecting — and reads what the lifespan left on `app.state`: the Slack socket's `is_connected()`, the Discord bot's `is_ready()` together with its gateway socket being open (discord.py stays ready while it reconnects after a drop), or the exception its task stopped with (`LoginFailure`, `PrivilegedIntentsRequired`), and the MCP gateway. A listening Slack is amber while the listener hasn't resolved its own user id (`slack_bot.bot_user_id()`), since thread continuations are off until it does. Because inbound is roster-gated, a connected Slack, Discord or Telegram is amber while nobody on the roster has its id (`slack_user_id`, `discord_user_id`, `telegram_chat_id`), or when its latest `integration_inbound` row is a `Rejected: …` from the past day whose sender still isn't on the roster — the page shows the sender's id, never message text. Local login with no `TELEGRAM_WEBHOOK_SECRET` is red for Telegram, since the local-login gate turns its webhook away. Google Chat and Gmail are checked from configuration: a numeric project number and a readable service-account key; the OAuth client (or service-account key) the workspace-mcp child signs in with. Gmail is also amber when startup priming could not find every pinned Google tool (`MCPGateway.prime_pinned_tools`, whose result the gateway keeps on `pinned_tools`): the row names a few of the missing tools and counts the rest, and points at the `MCPGateway` log lines. It is amber too while that probe has not finished, and when the probe itself failed — the one check that reads green is the one that ran and found everything, so a crashed probe is never silently fine. The row speaks for the whole `google_workspace` server, so a missing Docs or Drive tool shows up under Email (Gmail).\n\nA channel setting written `KEY= # note` in a `.env` file arrives as the note's text, because python-dotenv strips only a comment that follows a value. `Settings` reads such a value as unset for the Slack, Telegram, Discord and Google Chat credentials, so the line no longer switches a channel on with its own comment as the token. `TELEGRAM_WEBHOOK_SECRET` is the exception, because read as unset a junk secret would turn the webhook's check off. It is kept instead, and since Telegram can only ever send 1–256 of `A-Z a-z 0-9 _ -` (what `setWebhook` accepts), a secret outside that set — a leftover comment, a pasted `<value from Step 2>` — could only be matched by someone who guessed it: while it is set the webhook refuses every update, neither the local-login gate nor the roster tools count it as proof (`Settings.telegram_webhook_secret_valid`), and Setup status shows it red (`.env.example` shipped four such lines; the notes now sit on their own lines).\n\n### Conversation state\n\nEvery adapter keys a deterministic `session_id` off the conversation surface and replays that session's stored turns into `Session.conversation_history`, so a follow-up (\"yes, go ahead\") lands with the question still in context. Slack's ids are `slack:dm:{user}`, `slack:thread:{channel}:{thread_ts}`, and `slack:channel:{channel}:{user}` for a mention that starts a thread; because the bot's reply roots a Slack thread at that message's `ts`, the turn is double-written to that thread's session too, so the first continuation inside it is not cold. A reply inside a thread THAT PERSON ROOTED also offers the parent `slack:channel:{channel}:{user}` id when matching an approval gate, since a gate raised on the mention recorded that session while the answer arrives under the thread's. The root-author check is load-bearing: widening on \"threaded and not a DM\" alone offered one person's channel session inside any thread in that channel, so a remark they made to a colleague could resolve their open gate and post the run's title into that colleague's thread. Discord has the same shape — its auto-thread router promotes a mention reply into a bot-owned thread — and the same alias. An @-mention inside a DM is handled once, by the DM path: Slack fires both events, and taking both forked the conversation across two session ids. The same id is the audit grouping key and the scope passed to `format_for_prompt`. A per-session `asyncio.Lock` serializes turns within one conversation — the inflight semaphore caps fan-out across the workspace, which does nothing to stop two messages in the same thread from both reading history before either writes it. Persistence happens after the reply is sent and its failure is logged, never surfaced: the user already has their answer.\n\n**Conversations within a chat app.** A Telegram chat, a Slack or Discord DM and a person's @mentions in one channel (`slack:channel:…`, `discord:channel:…`) are each one endless stream, so they are cut into conversations (`memory.conversations`, shared helpers in `integrations/conversations.py`). Each adapter computes the stream's base id as before and asks `conversation_for` which conversation a message belongs to: the newest, unless the stream has been quiet for two hours (`CONVERSATION_GAP`), when the next one starts. The first conversation keeps the bare base id; later ones add `~2`, `~3`, … (`memory.conversation_ids`). A whole message of `/new`, \"new chat\" or \"new conversation\" starts a fresh one instead of a turn and is answered with the name of the one it ended; the new row has no messages and stays off the Chats page until its first turn. After a conversation's first exchange `title_after_turn` names it in the background with `utils.chat_topics.name_chat` (the first words of the message if that fails), as a web chat's first turn does: the same call files it under one of its owner's chat topics, so a Telegram or Slack conversation sits beside the web chats about the same matter in the Chats page's Topic view. Threads (`slack:thread:…`, `discord:thread:…`), email and every other id are left whole. What has to see the whole stream compares base ids: the inbound resolver, so an approval asked before a cut is answered after it, and the session-scoped decisions and advice `format_for_prompt` renders. At boot `split_existing_streams` cuts history saved before this by the same rule, once (`app_migrations`), titling each part from its first message and carrying a read-mail lock to every part. An adapter installed outside the package adds its streams with `conversation_ids.register_rolling` and cuts its own old history once, with its own migration name and an `only` filter for its base ids, because the built-in sweep may already have run without it.\n\nThis was absent on Slack until #136. Every message built a fresh `Session` and minted a per-*message* id (`thread_ts` falls back to the message's own `ts`, so a DM never repeated one), which meant a multi-turn confirmation could not work: the Executive asked whether to send a briefing to Slack, the user said yes, and the next turn had no record of the question.\n\n### What the model is told about the channel\n\nChat adapters pass a `<channel>` block (`integrations.channel_context`) in the **user turn** — never a cached system block. It names the surface, states that the person cannot see the app's cards or buttons, and draws the line the assistant kept crossing: briefing proposals and alerts are actioned on the briefing page; a proposal that books something can only be approved there; a workflow sign-off the Executive is explicitly waiting on *can* be answered in the conversation. The principal's DMs on Slack, Discord and Telegram also receive the open-alert digest (`briefing.context.format_open_alerts_for_prompt`) as the `<briefing>` block, gated to DMs because the board is company-wide and a shared channel must not pull it in. That digest is the ONLY trusted source of an `alert_id` for `ack_alert`. The briefing page's `[Discuss mode — alert_id=N]` primer is a pointer to which item is under discussion, not authority on its own: the server accepts that id only if it is also on the live board it derived itself. An id appearing anywhere else, including inside an alert's own body, is not trusted: alerts are minted from inbound email and chat, so their bodies are attacker-controlled. Two mechanisms enforce that rather than one prompt rule. Every field the digest interpolates is collapsed to a single line, because a newline in an attacker-written headline, suggested action, tag or review note would otherwise forge a whole extra `[N]` line — a fabricated instruction to clear somebody else's alert. And the live board the server derived is recorded on the session, so `ack_alert` refuses any id outside it — on EVERY session, web included; the web previously had no check at all. The recorded set is the whole live board (the cap `/today` renders as cards), not just the rows the digest printed, so a card past the digest's 30-row render cap is still ackable rather than sending the principal back to the page. Be precise about what this buys: it stops an id that is invented, closed, snoozed or expired, including one quoted out of an attacker-written alert body. It does NOT stop the model being argued into acking the wrong LIVE card — one alert's body can still make a case about another id that is genuinely open. Scoping trust to the single item under discussion would need the primer id carried server-side, which it is not.\n\n### Handler failures\n\nAn adapter's catch-all replies \"I encountered an error processing your request.\" On Slack that used to be the whole story — one uncorrelated log line, no audit row, and an unguarded error-send that could itself escape into Bolt. It now logs with the session, sender, channel, thread and mode, and writes an `integration_inbound` row with `details.outcome=\"handler_error\"`, joining the inbound row under the same `session_id`. Upstream, a single crashing tool handler no longer takes the turn down at all: the orchestrator's tool gathers use `return_exceptions=True`, hand the model an error `tool_result`, and audit it with `ok=false` (cancellation is re-raised, not swallowed).\n\n### Attachments\n\n`integrations.attachments` handles web chat, Discord, Telegram, Slack and Google Chat. Images become Anthropic vision blocks; documents (PDF/DOCX/TXT/MD/CSV) are inlined into the turn that carried them — inside an `<untrusted_content source=\"attachment\" author=\"<name>\">` block (`content_trust.wrap_untrusted`, whose closing tag the text cannot forge), under an `[Attached: <name>]` label, which the open-loop pass reads as \"not the speaker's words\" and the decision extractor strips before it reads the turn — and indexed into the ChromaDB `inbound_attachments` collection. 20 MB/file cap; web chat uses `POST /chat/upload`.\n\n**Scanned PDFs** are read, not reported empty. A PDF with no text layer goes through `knowledge.pdf_reader`: with `PDF_PROVIDER_READING=true` (opt-in, off by default) the deployment's own model reads it through its provider's PDF support (Anthropic natively, OpenRouter's `file-parser`, a local server only with `LOCAL_PDF_INPUT`); otherwise, and as the fallback, local OCR (pypdfium2 + RapidOCR, offline, no key) — so every deployment converts them. The label then reads `(converted from scanned pages)`, and an unreadable one says why. The index takes the text already extracted for the turn, so a scan is converted once. A file a channel delivered (everything here except `POST /chat/upload`, where the signed-in user sends it) converts at most `PDF_INBOUND_MAX_PAGES` (30) pages and draws on a rolling `PDF_INBOUND_PAGES_PER_HOUR` (300) budget shared by all senders, so sending scans cannot run up unbounded model spend or CPU.\n\nPer channel:\n- **Slack** — a `file_share` message (previously dropped outright for its `subtype`) is handled like any message; files download only after the roster gate and the response gate, with the bot token sent only to `https://files.slack.com/` (needs the `files:read` scope). History and peer memory record the words plus `(Attached files: …)`, never a document's text.\n- **Google Chat** — uploaded attachments download through `media.download` with the reply credentials (`chat.bot`), checked against the 20 MB cap per chunk, 5 per message; an attachment-only message is no longer dropped. The webhook authenticates Google, not the sender, so files are read only when the event's `user.email` is on the People roster (a team member); anyone else's files are named to the Executive, never downloaded. A Drive file shared into a message is left to the Drive tools, with its id.\n- **Email** — the poller (`integrations.email_attachments`) downloads up to 5 readable attachments of the message itself via `get_gmail_attachment_content` — workspace-mcp in stdio mode saves the file and answers `Saved to: <path>`, which must start its line, be the last such line and end in the answer's `Saved filename:` (the answer echoes the sender-chosen attachment name first, and a name carrying `Saved to: /…` must not redirect the read), then resolve inside the tool download folders — and appends their text to the turn (15k chars each). Only for a sender the principal knows (team, contact, principal); a stranger's files stay a list. It runs outside the model loop, so it works on private turns without adding the attachment tool to `PRIVATE_TURN_MCP_TOOLS`.\n- Anything else (a Drive PDF, a skipped attachment) — the Executive's `read_document` tool.\n\nIndexed chunks are keyed on `attachment:<bare filename>` and tagged `type=attachment`. An attachment's name is chosen by whoever sent the message and the name is the chunk-id namespace, so without the prefix an inbound `strategy-2026.md` would upsert over the curated company document of that name. The prefix separates inbound content from curated uploads and keeps provenance visible; it does not separate senders from one another.\n\nIsolation is the **collection**: `retriever.retrieve` never queries `inbound_attachments` at all, so an attachment cannot resurface as company knowledge in a later, unrelated turn. Attachment processing is roster-gated on Discord too — it previously ran before the gate, so an unrostered sender's file was downloaded and indexed before their message was dropped. These rows still have no operator surface: they are never written to `company/docs/`, so `GET /documents` does not list them.\n\nThis replaced a domain-based scheme that did not work. The chunks lived in `company_docs` under a domain outside the specialist set, on the premise that an unrecognised domain matched no filter. It matched every one — `ChromaDBStore.query` attaches a `where` clause only when a domain filter is present, and an Executive-level retrieval passes none — so attachments came back under “From your company documents”, top-ranked and indistinguishable from a curated upload. Legacy rows are migrated across on boot.\n\n### MCP gateway & outbound\n\nMCP runs in **both directions**. As a *client*, `orchestrator.mcp_gateway.MCPGateway` proxies MCP servers (Gmail, Calendar, Drive, Outlook mail and calendar — whatever `mcp_servers.json` configures) as Executive tools, with egress gating on Gmail recipients, Calendar attendees, Drive share grantees, and Microsoft 365 recipients/attendees against the roster (and a refusal of public / whole-domain Drive sharing). The Gmail gate also accepts only a fixed set of argument keys, so workspace-mcp's `reply_all` (recipients taken from the thread, never checked) and `forward_message_id` / `include_forwarded_attachments` (forwarding any inbox message) are refused; a reply is `thread_id` plus an explicit, roster-checked `to`. Three more refusals close paths around those gates: every Apps Script tool (code running as the Executive's account, outside the gates, and since workspace-mcp 1.29.0 schedulable to keep running); any argument that makes the server fetch a URL (`fileUrl` / `file_url` on the Drive and import tools, a Gmail attachment given as a `url`), since the fetch can carry data out in its query string before any recipient gate matters; and text Google would mail to someone the roster never checked (`rsvp_comment` to an event's organizer, an out-of-office `decline_message` to whoever invites the Executive). Every gate reads its arguments by normalized spelling: workspace-mcp 1.29.0 renames a camelCase key such as `Attendees`, `userGoogleEmail` or `rsvpComment` to the real parameter, so a gate matching the exact key would never see it. Arguments that are not a JSON object are refused for the same reason. Google-side fetches are refused too: any key ending in `url` / `uri` at any depth whose value has a URL scheme (a Slides image or page background, a Docs or Forms image; a document hyperlink and a meeting link are stored, not fetched, and pass, as does a Drive file id), (a value is a URL after the characters a URL parser strips are removed, and `//host` counts), and on every tool that can write cells — the Sheets tools and the Drive create / update / import tools, which turn CSV into a Sheet — any string anywhere holding a formula call that fetches (`IMPORTDATA`, `IMPORTXML`, `IMPORTHTML`, `IMPORTFEED`, `IMAGE`), JSON-encoded or mid-CSV included: a string argument that encodes JSON is read as the server decodes it (one too large to read is refused), text is also scanned with character references decoded and comments / CDATA removed, and an upload that would become a native Sheet may only be text `content` — a `base64_content` or server-side `file_path` upload there is refused, since an XLSX hides its formulas behind zip members and XML encodings; a PNG to Drive or a DOCX to Docs is untouched. Not covered, unverified: whether Drive's HTML / Markdown import fetches an `<img src>` when it converts `content` into a Doc. A `manage_event` call that names no attendees is sent with `send_updates=\"none\"`, so the event's existing guests are not emailed text the gate never checked. A delete is sent the same way, except the typed `cancel_calendar_event` of a meeting the Executive booked, which keeps its cancellation notice. Google Docs, Sheets, Slides, Forms and Drive writes run only on files and folders the Executive's own Google account owns (`_check_google_file_write`, read through `get_drive_file_permissions` at call time, fail-closed; only a name starting with a read verb skips it), as OneDrive writes do. Someone added to People in the current turn is left out of the allow-list until the next turn. The allow-list (`_egress_sets`, built by `_roster_allow_set` as a `people.identity.RosterAllow`) is every team member's email and email aliases plus the Executive's own address, always, and — for a teammate — any address on one of the company's own domains whose local part (`+tag` dropped) matches theirs, the same rule inbound mail is matched by; a **contact's** email joins it only when `people_tools.contacts_reachable_now()` is true — a turn the principal started on a verified surface (web chat, their own Slack or Discord, a verified private Telegram chat), or inside `grant_contact_egress()` (the decisions approve route, when the approver is the principal). On any other turn — an inbound email, a teammate, the scheduler, a workflow, the alert review — a contact's address is refused exactly like a stranger's, so the refusal cannot reveal that it belongs to a contact (contacts are private to the principal). The single exception to the roster rule is the fixed roster-request acknowledgement above, under its one-shot `roster_ack_grant`. A turn about the principal's private mail (`Session.private_to_principal`) narrows the list to the principal's own address and the Executive's. Such a turn may call only the MCP tools in `schedule_tools.PRIVATE_TURN_MCP_TOOLS`: Google Workspace reads (`search_gmail_messages`, `get_gmail_message_content`, `get_events`, `list_calendars`, `query_freebusy`, and the Drive, Docs and Sheets reads such as `search_drive_files`, `get_drive_file_content`, `get_doc_content` and `read_sheet_values`) and the two Gmail tools this gate narrows to the principal (`send_gmail_message`, `draft_gmail_message`). It is an exact allow-list, not a server: workspace-mcp runs at the tier `WORKSPACE_MCP_TOOL_TIER` names, `complete` by default, where a Google Chat message to a space, a Docs, Sheets or Drive write into a file already shared with others, `manage_event` on a shared calendar (its gate checks attendees and pins notifications, nothing else) reaches people with no recipient check; and every other server has none at all (a Slack or Notion server, the default `fetch` server, whose URL can carry the turn's content, a server loaded at runtime). Its `search_tools` results show only the allowed tools (`workflows.tool_catalog.filter_search_results`; output it cannot parse reads as no match), and a `call_tool` naming anything else is refused with an error tool_result and an audit row private to the principal (`schedule_tools.private_turn_withholds`), a missing name included. `search_tools` and `call_tool` stay offered, so the tool list and its cached prefix do not change. The typed calendar tool (`_resolve_attendees`) and the chat DM tools (`message_person`, `send_telegram_message`, `send_discord_dm` and their person-id recovery) apply the same rule — a contact's id reads as an unknown one off the principal's turn — and a private turn may DM or invite only the principal (`PRIVATE_TURN_REFUSAL` otherwise); `message_person` never falls back to a \"Needs you\" alert for a contact, who cannot sign in to see it. The Google Workspace server (`workspace-mcp`) behind those Gmail/Calendar/Drive tools runs **co-located inside the API** as a stdio child of the gateway — fitting the single-tenant model (one install = one company = one exec Google account), so there's no separate service to operate. It's baked into the API image and launched by `docker/workspace-mcp-launch.sh`, which selects single-user OAuth (token persisted at `/data/google_credentials`) or service-account domain-wide delegation from `GWORKSPACE_AUTH_MODE`. The optional `WORKSPACE_MCP_TOOLS` (comma-separated service names, default `all`) limits which Google services it loads. The gateway forwards the Google secrets to the child via `_FORWARDED_ENV_VARS`. Every `google_workspace__*` call acts as the Executive's own account. workspace-mcp takes the acting account per call (`user_google_email`) and nothing used to check it, so under domain-wide delegation a model-chosen address could open anyone's mailbox in the domain; `mcp_gateway._check_acting_account` now refuses a value naming any other address — before every other gate, with an `integration_outbound_blocked` audit row. An absent value stays allowed (the server's own account).\n\n**What the model is told is connected.** `MCPGateway.start()` records the configured server names (`server_names`), and the Executive renders them with the channel settings into block 0's *Connected Systems* section (`prompts.connected_systems`; see the caching section). While Google is connected that section pins the Google tool names the Executive uses constantly (`GOOGLE_TOOL_MANIFEST`, narrowed by `connected_systems.google_tool_manifest` to the services and tier actually loaded) and tells it to call them with `call_tool` directly, with no `search_tools` round trip. The narrowing is the point: a name pinned for a service workspace-mcp never imported is not in the index, so the model calls it, receives extensible-mcp's “has not been discovered via search_tools” refusal, and has no way to square that with its own instructions. extensible-mcp only runs a tool one of the session's searches has returned, and remembers it for the session's life, so the gateway does that discovery itself: the lifespan starts `MCPGateway.prime_pinned_tools()` in the background once the gateway is up with `google_workspace` configured (an exact-name search per pinned tool, the way `workflows.tool_catalog.resolve` does it, over the same narrowed set the prompt advertises — `connected_systems.pinned_google_tools`, so priming never probes a service that was not loaded). A name neither the prompt nor priming can account for is logged once, naming both causes: excluded by `WORKSPACE_MCP_TOOLS` / `WORKSPACE_MCP_TOOL_TIER`, or renamed by workspace-mcp since the pin. A pinned call that still comes back with extensible-mcp's \"has not been discovered via search_tools\" refusal, for example before priming finished, is discovered and retried once. That happens after every gate has passed the same arguments, and only for pinned names: any other tool still needs the model's own search, and nothing here widens what a call may do, including the private-turn allow-list.\n\n**Microsoft 365** is the Outlook twin: `@softeria/ms-365-mcp-server` (a Node package, pinned) is installed in a throwaway Node build stage and only the `node` binary plus the package are copied into the API image, launched by `docker/ms365-mcp-launch.sh` as the `microsoft_365` entry with an **explicit tool allow-list** (`--enabled-tools`, an anchored regex) rather than the upstream `mail,calendar` preset — that preset also registers inbox forwarding rules, mailbox settings (external auto-reply), calendar sharing and event forwarding, which can address people the gateway never sees. Exactly the Outlook mail + calendar tools and the OneDrive tools are exposed (`microsoft_365__send-mail`, `microsoft_365__create-calendar-event`, `microsoft_365__search-onedrive-files`, …; hyphenated Graph endpoint aliases, proxied verbatim), and every admitted tool is either roster-gated or carries no recipient; the gate also covers the excluded writers in case an operator widens the list. Both servers can be configured at once. Auth is the MSAL device-code flow against the operator's own Entra app registration (`MS365_MCP_CLIENT_ID` is required; the server's built-in public client is refused); the refresh token persists at `/data/ms365_credentials` and is seeded once with `ms365-mcp-launch.sh --login` from inside the container — the server has a native device-code CLI, so there is no mint script and nothing to copy. The launcher scrubs the literal `$VAR` placeholders extensible-mcp leaves for unset variables (otherwise MSAL would be handed `$MS365_MCP_TENANT_ID` as an authority), and `MS365_MCP_EXPECTED_USERNAME` pins the bound mailbox. The egress gate for this family walks Graph's nested shapes (`body.Message.toRecipients[].emailAddress.address`, `body.attendees[]…`) — every email-shaped string outside the free-text fields must be on the roster, control characters and non-ASCII addresses are refused, unforeseen keys are still scanned (fail-closed) — and covers the whole write surface: send, reply, reply-all, forward, every draft tool, `update-mail-message` (it can PATCH recipients onto a draft) and create-/update-calendar-event; reads pass through. `delete-calendar-event` makes Exchange mail every attendee, so it reads the event and roster-checks the attendees first, except the typed `cancel_calendar_event` of that same event. Graph's reply, reply-all and send-draft actions carry no recipient in their arguments (the recipient is whoever the referenced `messageId` names), so for those the gate first reads the referenced message through the server and roster-checks the recipients Graph will derive (`replyTo` else `from` for a reply; `replyTo` and `from` together, plus the original to/cc, for reply-all; the draft's own to/cc/bcc for send-draft), refusing on any lookup failure; RSVP and cancel actions get the same treatment through an event lookup, because their comment is emailed to the organizer or every attendee; `download-bytes` is pinned to mail attachment bytes and OneDrive file content (`/drives/{id}/items/{id}/content`, optionally Graph's `?format=pdf` rendering), and a OneDrive result comes back as the file's extracted text rather than base64 — the attachment pin is what makes the poller's promise that an unrostered sender cannot be auto-replied to hold on Outlook as it does on Gmail; and the rendered inbound text quotes any forged `--- REPLY ---` line inside a body so the persona only ever reads the real block. Every mail write's `from`, `sender` and `replyTo` may name only the Executive's own address (the Outlook twin of the Gmail acting-account pin), so the model cannot send as a rostered colleague's mailbox or steer replies elsewhere; and `move-mail-message` into Deleted Items, Junk Email or Recoverable Items is refused, so a move cannot trash mail ungated. The server registers its account tools whatever its tool allow-list says, so the gateway itself refuses `login`, `logout`, `select-account` and `remove-account` (audited like any other refusal) and drops them from `search_tools` results — a chat turn cannot sign the mailbox out, switch accounts or start a sign-in; setup is only the launcher's `--login`, and the read-only `verify-login` / `list-accounts` stay callable. The example config's hyphenated patterns still deny `delete-mail-*`, `logout`, `remove-account` and `download-bytes-to-file` as defense in depth. A successful `send-mail` records the same outbound-context linkage Gmail does.\n\n**OneDrive in chat** (opt-in with `MS365_MCP_ONEDRIVE=true` and a fresh `--login`, since the server asks for its tools' permissions on every token refresh and a sign-in without file consent would otherwise fail mail and calendar too) matches what the Executive can do on Google Drive: search, list a folder, read a file, upload and edit, create folders, move, rename, copy and share; there is no delete tool. The launcher adds `Files.Read.All` at sign-in (`--extra-scopes`), so folders shared *with* the Executive can be read too; writes (upload, new folder, move, copy) land only in the Executive's own drives, checked against `list-drives` at call time, so a planted instruction cannot save company files into a stranger's shared folder. Sharing is gated like Drive sharing: `share-drive-item` invitees must be People on the roster and named by email (an `objectId` or `alias` grantee is refused, since nothing can check it), no `owner` role, and `create-drive-item-share-link` must be scoped to specific people (`scope: \"users\"`): an anonymous or whole-organization link, or one with no scope (the tenant default), is refused. An invite must require sign-in and grant only view or edit, a link must be a view or edit link, and `search-onedrive-files` takes plain words only, since its query goes into the request path unencoded. Files Act as me's `save_my_email_attachment` copied from someone's own mail into the Executive's Drive or OneDrive (`delegation.saved_files`) are that person's alone: on any other turn the gateway refuses a call whose arguments name a recorded file id and drops the entries or lines of a result that name one, failing closed for the file tools when the record can't be read. The folders those copies go in are made by the save (never adopted by name) and recorded, and a model call naming one, by id or by an OneDrive path through it, is refused on every turn, the owner's too, with their ids hidden from results. That tool's own calls are the only Drive and OneDrive writes a turn that read the owner's mail may make: built in code, admitted past the lockdown as those exact objects (`code_built_call`), and still checked by every gate above.\n\nAs a *server*, `openexecutive.mcp_server` exposes OE's own company context and specialist council to external MCP clients at `/mcp` — the inverse direction; see the dedicated **MCP Server** section. The gateway launches extensible-mcp as a `uvx` subprocess whose fastembed tool-search index uses an embedding model baked into the API image and loaded offline, so it no longer re-downloads that model from the Hugging Face Hub on every cold start. extensible-mcp is pinned twice over: to a commit, which fixes its own code, and with `--exclude-newer`, which fixes the resolution of its dependencies — without the cutoff uvx re-resolves them against PyPI on every networked start, so a new release of any of them would reach running deployments on restart. Both live in `_EXTENSIBLE_MCP_LAUNCH_ARGS` in `orchestrator/mcp_gateway.py`, the Dockerfile's pre-warm uses the same arguments (a unit test enforces the match), so an image whose pre-warm succeeded starts the gateway with no network. The pre-warm is best-effort (`|| true`): an image built while GitHub was unreachable fetches the pinned commit on its first start instead. Updating the gateway is a deliberate bump of the commit and cutoff; `uv` itself is not pinned. Because the MCP stdio client does not inherit the parent environment, `MCPGateway.start()` explicitly forwards the embedding-cache/offline env vars (`FASTEMBED_CACHE_PATH`, `HF_HUB_OFFLINE`, …) into the child.\n\n**Emailing an artifact.** A Gmail send or draft may carry `attachments=[{\"artifact_id\": \"alert:12\", \"as\"?: \"docx\"}]`. `call_tool` runs the recipient gate first; only if it passes does `_expand_artifact_attachments` replace each such entry with the rendered file (`content` base64 + `filename` + `mime_type`, workspace-mcp's own attachment shape), produced by `artifact_records.render_artifact_file` — the same renderer as `/artifacts/{id}/download`. Only artifact rows resolve (never an arbitrary alert), links have no file, and an entry mixing `artifact_id` with other keys is refused. A stringified or single-object `attachments` is normalised first, so an artifact entry can never reach workspace-mcp unexpanded (it would silently drop it). At most 5 distinct artifacts per email (repeats are dropped) and 15 MB rendered in total; rendering runs off the event loop via `asyncio.to_thread`. A refusal writes `artifact_attachment_refused`; a successful send writes `artifact_attached` — both carry the recipients. Other attachment entries pass through unchanged. The same expansion serves the Microsoft 365 mail writes: the entry becomes a Graph `#microsoft.graph.fileAttachment` (`name`, `contentType`, `contentBytes`) placed where Graph expects it for that tool (`body.Message.attachments` for `send-mail`, reply, forward and the createReply drafts; `body.attachments` for `create-draft-email`), whether the model put it at the top level or inside the message; an entry anywhere else, one on `update-mail-message` or `send-draft-message` (their requests cannot carry attachments), or one behind a body that is not an object is refused rather than forwarded unexpanded.\n\n**Enablement, and why it degrades instead of dying.** `MCP_ENABLED` left unset is inferred from the presence of `mcp_servers_config_path` — dropping an `mcp_servers.json` next to `profile.yaml` turns MCP on with no further configuration. An **explicit** setting always wins in both directions: `MCP_ENABLED=false` keeps MCP off with the file still in place. It did not: `_resolve_mcp` tested `not self.mcp_enabled`, which cannot tell \"never set\" from \"set to false\", so the file's presence silently overrode the operator. The file is probed through `config.mcp_config_file_present`, never `Path.exists` directly — that re-raises an EACCES on a parent directory, and from inside a validator that comes out of `Settings()` itself, which `api/main.py` calls at module level. The check now reads `model_fields_set` (the fields the env actually supplied) and stores that on a private attr behind the read-only `mcp_auto_enabled` property, because the validator's own assignment joins that set and would otherwise make every auto-enable look explicit downstream.\n\nStartup is **best-effort**, in `main._start_mcp_gateway`. Two checks come before the subprocess: MCP off is a no-op, and a config defining no servers under `mcpServers` is logged and skipped — extensible-mcp's own loader raises on that and exits, and because the child is already gone the only thing that surfaces is anyio's \"Attempted to exit cancel scope in a different task\" from `stdio_client` unwinding, a traceback naming nothing about configuration. The start is also bounded (120s, generous because that child may still clone extensible-mcp on a cold start if the image's pre-warm failed): `ClientSession` carries no `read_timeout_seconds`, so `initialize()` waits forever on a child that is *alive but silent*, and an unbounded wait is a lifespan that never yields — the same healthcheck-never-passes symptom, which no `except` can see. A gateway that fails anyway is logged at ERROR with the config path, the servers it named, and whether the config file or an explicit `MCP_ENABLED` turned MCP on, then torn down under its own timeout; the API boots **without MCP tools and without the email poller** rather than refusing to boot. The guard catches `BaseException`, not `Exception`, re-raising a bare `CancelledError` first: the original failure came from anyio, which wraps a task group's failures in `BaseExceptionGroup` as soon as one is a `BaseException` — and that group is not an `Exception`, so `except Exception` would miss the very shape this contains. The teardown is contained too, since it runs from inside that `except` and would otherwise replace the actionable log with the crash it prevents. `configured_server_names` never raises either, and deliberately catches broadly: it reads an operator-owned path during startup, where an exception is the crash loop rather than a bug report — `Path.is_file` re-raises an EACCES on a parent directory, and `json.loads` answers deeply-nested input with `RecursionError`, which is not a `ValueError`. It tests `is_file()` so a directory or a symlink to a FIFO is never opened, and caps the read at 1 MiB. That exception used to propagate out of the lifespan and kill the container — under `restart: unless-stopped`, a crash loop whose only outward symptom was a healthcheck that never passed. Outbound tools: per-Person DMs (`send_slack_dm`, `send_discord_dm`, `send_telegram_message`) plus room-targeted `send_department_message` and `send_company_broadcast`. All three per-Person DMs refuse a recipient id that matches no non-archived Person row (`schedule_tools._dm_recipient_on_roster`), which is what stops untrusted content in a turn — inbound mail, a chat message, a knowledge document — from directing a DM at an arbitrary workspace member. `send_slack_dm` previously consulted the roster only when the turn was already private to the principal, so on an ordinary turn it applied no roster check at all while its Discord and Telegram siblings did; the room-targeted tools are deliberately ungated, since those channels are team-visible. The per-Person DMs are additionally rate-limited and de-duplicated by the outbound anti-spam guard (below).\n\n### Outbound anti-spam guard\n\nEvery per-Person DM passes a deterministic guard (`orchestrator.outbound_guard.check_outbound_allowed`) after the roster gate and recipient-id recovery but before the network send — the single chokepoint **all** proactive DM paths reach (ad-hoc chat sends, the scheduler's followup/nudge dispatch, principal-brief delivery, the reflection turn, and research-finding routing). On a violation it returns a human-readable reason and the handler **suppresses** the send (`{\"status\":\"suppressed\",\"reason\":…}`), writes a `tool_invocation` audit row with `suppressed=true`, and writes **no** `done` activity row — so a blocked attempt never counts toward its own rate cap, and the Executive can read the reason and hold or `schedule_followup` for the recipient's next window. Three controls: **content dedup** (a near-identical message — whitespace/case-normalized, first 160 chars — already sent to the same recipient within `OUTBOUND_DEDUP_WINDOW_MINUTES`, default 360); a **per-recipient rate cap** (`OUTBOUND_MAX_PER_RECIPIENT_PER_WINDOW`, default 5, over `OUTBOUND_RATE_WINDOW_MINUTES`, default 60); and **quiet hours / availability** (`OUTBOUND_RESPECT_QUIET_HOURS`, default on — refuse while the recipient is on leave or outside their `people.channel` availability windows, surfacing the next open window). Delivery history is read from the existing `status='done'` `scheduled_actions` rows (`episodic.recent_sends_for_channel_ref`), so there is no new table. The guard is **fail-open**: any internal lookup error returns \"allow\", so it can never turn a working send into a crash or a silently-dropped message. Principal briefs and the internal heartbeat kinds use the `__internal__` channel and never reach these handlers, so they are unaffected. Once the guard allows a send, the handlers apply the recipient's own notification settings to the Executive's own (tagged) outreach: in their quiet hours, or when they chose *In my briefs*, the DM is stored and returned as `{\"status\":\"held\"}` rather than sent, and goes when quiet hours end or with their next brief (`outbound_guard.check_hold`; see Org).\n\n### AI disclosure\n\nWhat the Executive sends says it is an AI assistant (`orchestrator.disclosure`), added by plain code so a reply the model writes can't leave it out. **Mail** from its own mailbox gets a line under the body, by default \"<EXEC_DISPLAY_NAME> is an AI assistant working for <company>. To reach a person, reply and ask, or write to <principal's address>.\": the MCP gateway adds it to every Gmail send and draft and every Outlook send, reply, forward and draft (`mcp_gateway._with_disclosure`) **after** every outbound gate has passed and only on what goes to the server, so the gates, the outbound-context record and the audit see the model's own words, and `send_from_executive` gets it the same way. It counts as already there only when it is the last line that shows (in a quoted earlier message or hidden in markup it doesn't), and a send of an existing draft and mail whose every recipient is the principal go as they are. HTML that could hide what follows (an unclosed comment, a style or script block, text styled out of sight: `disclosure.hides_what_follows`) is refused, so the line can't be hidden after it; the model is told to send plain text. The roster acknowledgement to a new sender, the one send to an address nobody checked, gets `BARE_MAIL_LINE` (\"This message was sent by an AI assistant.\"), which names no one, like the acknowledgement itself. **Chat** gets a shorter line (\"<name> · AI assistant\", in italics) on the Executive's replies in Slack, Telegram, Discord and Google Chat and on its own DMs and room posts (`send_slack_dm`, `send_discord_dm`, `send_telegram_message`, `broadcast_tools._dispatch`), but only on the first message in a conversation and again after 24 hours without one (`with_chat_line`, kept in memory, so a restart shows it once more); session history keeps the reply without it. `AI_DISCLOSURE` (default on) turns it off; `AI_DISCLOSURE_MAIL_TEXT` / `AI_DISCLOSURE_CHAT_TEXT` reword the lines, and a wording that doesn't say \"AI\" is ignored for the built-in one. It fails open: a line that can't be built is left off, never a send refused. Replies sent *as a person* under Act as me are the delegation section's (**AI line on replies**).\n\n### Calendar & video links\n\nThe Executive books meetings through two typed tools over the configured calendar backend (`CALENDAR_PROVIDER`: Google Calendar via `manage_event`, or Outlook via `create-calendar-event` — see *Workspace providers*). `create_calendar_event` schedules a **future** meeting (propose→approve by default, or auto-execute once that decision class is promoted) and may be used proactively when a stalled goal warrants a sync. `create_instant_meeting` spins up an **impromptu call starting now**, auto-executing without the approval step and skipping the business-hours/horizon caps, so the Executive can hand back a join link immediately. Because nothing approves it, an instant meeting, and `cancel_calendar_event` too, runs only when someone on the team asked on a surface that verified who they are (the principal, or a rostered teammate in the app or their own chat); a turn an inbound email started gets a refusal to pass on instead, and a team-mode `create_calendar_event` the operations department would auto-execute is proposed instead. Both attach a video-meeting link by default (`add_video_link`; opt out for in-person) — a **Google Meet** link read from `manage_event`'s plain-text reply (which also carries the event id, inside the event link's `eid`), or a **Microsoft Teams** link from `onlineMeeting.joinUrl` — surfaced to the caller plus persisted on the decision ledger as `meet_link`. The tool descriptions are static, backend-neutral text, so the cached tool block never depends on settings; the pre-rename `add_google_meet` key is still honoured for old ledger rows. Either way the caps that matter still hold — roster membership, principal-protection, max attendees, and a daily booking ceiling. A proposal raised in the web chat by the person who approves it (the principal, or its approver when it isn't the principal's private booking) says `approve_here`; its `action_taken` chip then carries the `decision_id`, and the chat shows the approval card (Approve, Edit, Dismiss) under the reply as well as on the briefing — answering either clears both. A booked meeting whose event id was never read can't be cancelled from the app: both cancel paths refuse rather than report a cancel that left it on the calendar.\n\n**Around-the-meeting participation.** The Executive doesn't join the call as a live voice; instead, on every successful booking it schedules a best-effort post-meeting follow-up (~5 min after the end) that DMs a human attendee asking for a quick recap — key decisions and action items. The reply flows back through the same cross-session DM context linkage described below, so the Executive can act on it (summarize, follow up) in a later turn. No meeting-transcript or Drive integration is required.\n\n### Workspace providers\n\nThe Executive can *discover* any mail or calendar tool the gateway exposes, but three code paths call a fixed backend with no model in the loop and used to spell Gmail tool names inline: the inbound mailbox poller (list unread → fetch → mark read), alert email dispatch plus the scheduler's email send-tool hint, and the typed booking tools plus the approval-time conflict check. `integrations.workspace` puts those behind two Protocols (`MailProvider`, `CalendarProvider`) with one module per backend (`google.py`, `microsoft.py`) and a registry keyed on `EMAIL_PROVIDER` / `CALENDAR_PROVIDER` — separate switches (Outlook mail with a Google calendar is legitimate), both defaulting to `google`, so an existing install changes nothing until an operator opts in. The Google backend is the old inline code moved verbatim; tests pin its argument dicts byte-for-byte. The Microsoft backend polls only the Inbox folder (`list-mail-folder-messages` with `isRead eq false`, never the all-folders listing that includes Junk), converts Graph's HTML bodies to text with a real parser, lists a message's attachments so the names appear in the same `N. name (mime, size KB)` shape Gmail's text uses (and reach peer memory), marks read with `update-mail-message`, sends through `send-mail`'s nested shape, books with `isOnlineMeeting` + `onlineMeetingProvider=teamsForBusiness`, cancels with `delete-calendar-event`, and answers the advisory conflict check from the Executive's **own** calendar view (delegated permissions cannot read attendees' free/busy — narrower than Google's `query_freebusy`).\n\nEvery backend renders an inbound message into the same `Subject:` / `From:` / `To:` / `Cc:` + `--- BODY ---` text the persona already expects, and the poller adds a `--- REPLY ---` block naming the exact reply tool and threading ids for *that* message (Gmail: `send_gmail_message` + `thread_id`; Outlook: `reply-mail-message` + `messageId`) after the mail's `<untrusted_content>` block, never inside it. The block rides in the user turn — which is what lets the cached persona say \"use the reply tool in the REPLY block\" instead of naming a vendor tool — and the scheduler's proactive-email trigger names the backend's send tool the same way. Providers never raise on a malformed backend response (they return empty / `None` / `{\"error\": …}`), so one bad cycle never kills a loop, and a chosen backend whose MCP server is missing from `mcp_servers.json` is logged at startup and skipped by the poller: fail-soft, never a boot failure. The poller's newer checks run on that rendered text for both backends (contacts and private turns, roster requests and their emailed answers, the audit row), with three Outlook differences that fail closed: no sender is ever authenticated (the `dmarc=pass` read is Gmail's), so there is no acknowledgement to an unknown sender, no emailed fact confirmation and no principal-authenticated mail; attachments stay a list (the download is Gmail's); and the brief's calendar block is skipped (its listing is Google Calendar's). The code's own emails to the principal (roster prompts, fact confirmations, scheduled deliveries) go through `workspace.registry.send_from_executive`, and `runner.email_ready` follows `EMAIL_PROVIDER`. A private turn's allow-list (`schedule_tools.PRIVATE_TURN_MCP_TOOLS`) and Act as me's mail-touched reads include the Outlook twins of the Gmail and Calendar tools, and roster answer tokens are hidden from Microsoft 365 results as from Google's.\n\n### Cross-session DM context\n\nWhen the principal says \"DM Alex about X\" in one session, OE sends the DM and — if a live conversation is active and the recipient is not one of the principal's contacts (a contact cannot DM the bot, and quoting the principal's conversation into their email reply's unattended turn would put it in the audit log) — records an `outbound_context` linkage row (recipient, full outbound text, originating session id). Email is covered too but recorded one layer deeper — there is no `send_email` tool, so the linkage is written in `orchestrator.mcp_gateway` after a successful `google_workspace__send_gmail_message` or `microsoft_365__send-mail`, one row per `to`/`cc` recipient keyed by the bare lowercased address (OE's own address skipped). When Alex later replies on the 1:1 DM path — or by email — the shared helper `integrations.inbound_hydration.hydrate_user_message` (called by the Discord, Telegram, and Slack handlers, and by the email poller keyed on the sender address) looks up the most-recent `open` linkage for that sender within 72h and prepends an `<outbound_reply_context>` block — the outbound text plus a backstory excerpt from the originating session — to the message handed to `Executive.chat()`. So OE knows what the reply is about instead of starting from an empty per-person session. The block is context for the LLM turn only: peer memory strips it before recording what the person said (`strip_outbound_reply_context`, applied in `sync_turn`, `sync_department_turn` and to the prefetch query), so the Executive's own DM is never attributed to the person who replied to it. The block lands in the user turn (caching rule) and is injected into a copy only — the pristine reply is persisted to history. The linkage is one-shot (consumed on first matched reply, race-safe) so an unrelated later DM isn't re-hydrated. This is deterministic and independent of the per-person `peer_memory` (Honcho) layer.\n\nEvery adapter that persists a turn (Slack, Discord, Telegram, and the web route) records the message's **resolved sender** on `chat_messages.sender_person_id` — the rostered Person the adapter matched, or NULL for an unrostered sender — independently of the session owner, which falls back to the principal on Discord and Telegram so those threads stay visible. Attunement's open loops and feedback rely on this so an outsider's words are never read as someone on the roster's.\n\n### OneDrive folder sync\n\nThe Microsoft twin of the Drive folder sync below (`knowledge.onedrive_sync`, `ONEDRIVE_SYNC_ENABLED`; setup in `docs/onedrive_sync_setup.md`). It copies the files in `ONEDRIVE_SYNC_FOLDERS` (`<drive id>/<item id>` pairs; `openexecutive onedrive-folder <link>` resolves a sharing link) into the isolated `onedrive_docs` collection on its own heartbeat, and shows them on the knowledge page as \"OneDrive\" rows with a **Sync now** button. Microsoft has no service account that sees only what is shared with it (app-only Graph access covers the whole tenant), so it reads as the Executive's own Microsoft 365 sign-in, and the folder list is the scope. It never stores a credential: each tick asks the launcher for a token (`ms365-mcp-launch.sh --access-token`, which runs `docker/ms365-access-token.mjs` through the server's own token cache and will only mint file-read tokens), keeps it in memory, and sends it only to Graph. `knowledge.onedrive_client` issues GETs only, follows a paging link only back to Graph, and fetches a file's pre-authenticated download link without the token; errors never carry that link. PowerPoint and older Office formats are read through Graph's PDF rendering.\n\n### Google Drive folder sync\n\nThe synced files show on the knowledge page's Company documents list as \"Google Drive\" rows (sync time, last edit in Drive, an Open in Drive link and a text view), and the page's source card shows the last run, any sign-in error or count of files that failed to sync, and a **Sync now** button that runs one tick on demand.\n\n\nSeparate from the Drive tools the gateway proxies. The optional folder sync (`knowledge.drive_sync`, `DRIVE_SYNC_ENABLED`; setup in `docs/drive_sync_setup.md`) copies the files in `DRIVE_SYNC_FOLDER_IDS` into the isolated `drive_docs` knowledge collection on a scheduler heartbeat, so the Executive knows those folders without searching Drive live (see RAG). It calls the Drive v3 API directly (`knowledge.drive_client`, `httpx`) as a **service account** with the `drive.readonly` scope (`DRIVE_SYNC_SERVICE_ACCOUNT_FILE`), not as the Executive's own account through workspace-mcp. Google enforces the folder scope, because the account sees only what is shared with it, and the sync can change nothing. Structured JSON means no display text to parse, and every file or folder id is checked against `[A-Za-z0-9_-]{1,128}` before it goes into a URL or a query. The two paths meet in two places. A synced chunk carries its Drive file id and sync time, so the Executive can open the live file with its own `get_drive_file_content`. The setup doc says to share each synced folder with the Executive's account too, so that live open works.\n\n### Confluence space sync\n\nThe optional Confluence sync (`knowledge.confluence_sync`, `CONFLUENCE_SYNC_ENABLED`; setup in `docs/confluence_sync_setup.md`) copies the pages of the spaces in `CONFLUENCE_SYNC_SPACE_KEYS` into the isolated `confluence_wiki` knowledge collection on a scheduler heartbeat, so the Executive knows the company wiki without a tool call (see RAG). It works with Confluence Cloud and Server/Data Center: `knowledge.confluence_client` calls the v1 REST API both serve, directly with `httpx`, signing in with a personal access token (Server/DC) or a username and API token (Cloud). It reads only, never follows a redirect (so the token stays on the configured site), streams responses with a 20 MB cap, and checks page ids and space keys before they reach a URL or a CQL query. The URL must be `https://` unless `CONFLUENCE_SYNC_ALLOW_HTTP` is set, and `CONFLUENCE_SSL_VERIFY` takes `true`, `false` or a CA bundle path for a private certificate authority. With `CONFLUENCE_SYNC_PUBLIC_HOSTS_ONLY` (off by default, for an install where whoever sets the URL must not reach the backend's own network) every request resolves the site's host, refuses it when any address is not public (loopback, private, link-local, shared), and connects to the checked address with the site's name kept for the Host header and the TLS certificate check, directly rather than through a proxy. `confluence_client.config_problem` is the same settings check the app runs at start, for a caller that writes these settings on someone's behalf.\n\nIt is separate from a Confluence MCP server such as mcp-atlassian, which a deployment can add to `mcp_servers.json` for live reads and edits in chat. The two share the env names `CONFLUENCE_URL`, `CONFLUENCE_PERSONAL_TOKEN`, `CONFLUENCE_USERNAME`, `CONFLUENCE_API_TOKEN` and `CONFLUENCE_SSL_VERIFY`, so one set of values serves both, and a synced chunk carries its page id so the Executive can open the live page with such a tool. A Confluence token is a user's, and what the sync reads becomes retrievable by everyone who talks to the Executive, so the space list is required and pages with a read restriction (their own or a parent's) are skipped unless `CONFLUENCE_SYNC_SKIP_RESTRICTED=false`. That keeps any existing member's token safe to use, without a dedicated licence. Manual runs: `openexecutive sync-confluence` / `purge-confluence`.\n\n### Your own Gmail or Outlook (Act as me)\n\nA second, separate mail connection, for **Act as me** (see **Act as Me (Delegation)**): a person's *own* mailbox, which `delegation.gmail.DelegateGmail` reads and drafts into over the Gmail REST API. It is never registered with the MCP gateway, so the model can reach it only through the typed `ghostwrite_email` handler — never by tool name through `call_tool`. The credential is one file per person in `DELEGATION_GOOGLE_CREDENTIALS_DIR` (default `company/delegation_google/`, `/data/delegation_google` in Docker), minted on a computer with a browser by `scripts/connect-own-gmail.py --email <you>` with the Executive's own OAuth client and the scopes `gmail.readonly` and `gmail.compose` — the same seed-it-yourself flow as the Executive's token, since the API serves no OAuth callback. It never lives in `WORKSPACE_MCP_CREDENTIALS_DIR`, where workspace-mcp picks a credential by address.\n\nEvery use re-checks with Google that the credential opens the mailbox on the person's People entry, and refuses outright when that address is the Executive's own: a shared mailbox would make everything the Executive writes look like theirs. Drafts are threaded (`In-Reply-To`, `References` of whole ids ending with the parent, `threadId`) and stamped `X-OE-Ghostwritten`; the only send is `drafts.send` of an existing draft by id, when the person taps Send on its reply card (`delegation.reply_send`). A Gmail rate limit, even as a 403, is an error to retry rather than a reconnect. The voice learner and the thread shown to the ghostwriter keep only each sender's own words through `email_poller.sender_new_text`, the poller's quoted-reply stripper made public. Setup status shows it as **Your own mailbox (Act as me)**.\n\nThe same file can instead hold an Outlook sign-in (`\"provider\": \"microsoft\"`), minted by `scripts/connect-own-outlook.py --email <you>` with a device-code sign-in on the Executive's own Entra app (`MS365_MCP_CLIENT_ID`, `MS365_MCP_TENANT_ID`, default `common`) and the delegated scopes `User.Read`, `Mail.ReadWrite`, `Mail.Send` and `offline_access`. `delegation.gmail.gmail_for` then hands back `delegation.outlook.DelegateOutlook`, which talks to Microsoft Graph directly — never the Microsoft 365 MCP server the Executive's own Outlook uses — with the same methods and the same one send: Graph's `send` on an existing draft, with no body. Microsoft rotates the refresh token on use and the new one is written back into the file. A sender counts as verified only from the topmost `Authentication-Results`, the one Exchange wrote, and only mail in their Sent Items counts as theirs.","mermaid": "flowchart TD\n Channels[\"Slack / Discord<br/>Telegram / GChat / Email\"]\n Resolve[\"find_person_by_*_id\"]\n Gate[\"roster gate\"]\n Drop[\"drop\"]\n Hold[\"roster request<br/>(hold + fixed ack,<br/>ask the principal)\"]\n Exec[\"Executive.chat()\"]\n Attach[\"attachments<br/>(vision / inbound_attachments)\"]\n MCP[\"MCP gateway\"]\n GW[\"Google Workspace<br/>(workspace-mcp child)\"]\n M365[\"Microsoft 365<br/>(ms-365-mcp-server child:<br/>Outlook + OneDrive)\"]\n WP[\"workspace providers<br/>(poller / alerts / booking)\"]\n Guard[\"outbound anti-spam guard<br/>(dedup / rate cap / quiet hours)\"]\n Out[\"DM / department<br/>/ broadcast tools\"]\n Channels --> Resolve\n Resolve --> Gate\n Gate -- \"unknown sender\" --> Hold\n Hold -- \"approved: replay\" --> Exec\n Hold -- \"contact / declined\" --> Drop\n Gate -- \"Person\" --> Exec\n Gate --> Attach\n Attach --> Exec\n Exec --> MCP\n MCP -- \"roster egress gate\" --> GW\n MCP -- \"roster egress gate\" --> M365\n WP -- \"EMAIL_PROVIDER / CALENDAR_PROVIDER\" --> MCP\n WP --> Exec\n Exec --> Guard\n Guard -- \"suppress\" --> Drop\n Guard -- \"allow\" --> Out\n Out --> Channels\n Own[(\"Principal's own Gmail<br/>(Act as me: REST, drafts only)\")]\n Exec -- \"ghostwrite_email\" --> Own\n class Channels entry\n class Resolve compute\n class Gate compute\n class Drop external\n class Hold compute\n class Exec hot\n class Attach compute\n class MCP external\n class GW external\n class M365 external\n class WP compute\n class Guard compute\n class Out compute\n class Own external",- "generated_at": "2026-10-16T21:00:00Z"+ "generated_at": "2026-10-17T14:37:21.820135+00:00"}diff --git a/packages/core/openexecutive/architecture/prebuilt/memory.json b/packages/core/openexecutive/architecture/prebuilt/memory.jsonindex e51a74ac..262f434a 100644--- a/packages/core/openexecutive/architecture/prebuilt/memory.json+++ b/packages/core/openexecutive/architecture/prebuilt/memory.json@@ -1,7 +1,7 @@{"section_id": "memory","title": "Memory System",- "markdown": "The Executive's durable memory is an episodic SQLite store at `./episodic_memory.db`, managed by `openexecutive.memory.episodic`. It holds four tables:\n\n- `decisions` — choices made, with `domain`, `summary`, `rationale`, `outcome`, and `tags`. `outcome` is filled in when the principal says how a decision turned out — the `record_decision_outcome` chat tool (principal on a verified surface only) or the Memories page. The weekly review reads this table twice: the week's decisions (`decisions_since`) and up to three older than 30 days with no outcome yet (`decisions_awaiting_outcome`), which it asks about.\n- `initiatives` — tracked efforts with a `status` and `summary` (idempotent upserts).\n- `advice_given` — query/advice pairs per domain.\n- `scheduled_actions` — a dispatch queue, treated separately from recall memory. `cancel_scheduled_action` guards its UPDATE on `status = 'pending'`, so a cancel never overwrites a row the scheduler claimed a moment earlier.\n\n### What gets extracted, and when\n\n`episodic.extract_and_store` runs after a turn and asks a utility-fast model for decisions, initiatives and advice. Every candidate must carry a `user_commitment_quote` that appears verbatim in the principal's own message (`_is_valid_user_commitment`) — the turn's speaker text (`memory_text` when the entry point supplies one, else the prompt), so a quoted Executive email or a briefing card's body inside the prompt cannot satisfy it — the model has repeatedly tried to log the Executive's *recommendations* as the user's commitments, and that quote is the hard gate against it.\n\nA turn reaches the extractor if `should_extract(speaker_text, session=...)` is true, which means only that the principal said something on a surface that proved it was them — there is deliberately **no length floor**. There used to be one, on the combined user+assistant length, and on a live tenant it selected almost exactly the wrong turns: 9 of 16 exchanges were blocked, and the 9 held every instruction the principal gave, while the 7 admitted were long analytical exchanges with no commitment in them. The extractor ran 13 times and stored nothing.\n\nMoving that floor to the user's side would relocate the bug, not fix it. The canonical executive decision is a long analysis answered with \"Approve option B.\" (17 chars) or \"Do B.\" (5), and any floor high enough to skip \"Done\" (4) also skips those — \"Do B.\" and \"Done\" differ by one character and mean opposite things. Length cannot separate a decision from an acknowledgement; the verbatim-quote check can, so `_is_valid_user_commitment` is the gate that decides. The price is one utility-fast call on turns that propose nothing.\n\nThat quote check is only meaningful when `user_message` holds the **principal's** words, and on a chat channel it does not — `Executive.chat()` is reached from Slack, Discord, Telegram, Google Chat and the email poller. A teammate's line would be written to `decisions` with no speaker attached, indistinguishable from the principal's own; an inbound email body is text the sender chose, so a self-quote is free. Removing the length floor is what makes this bite — short channel traffic used to fall under it incidentally — so `should_extract` asks the untrusted-content policy (`orchestrator.content_trust.principal_speaking`) whether the principal is speaking. It names the principal's surfaces rather than inferring them: the web chat (signed in as the principal — or, on an install with no principal on the People page yet, a request that carried no sign-in; a signed-in email on nobody's entry, such as an archived teammate still allowed to sign in, is not the principal), the CLI (`Session.from_cli`), the principal's own Slack or Discord or a private Telegram chat with a valid webhook secret (`people_tools.is_principal_on_verified_surface`), and email from the principal's primary address that Gmail's own `Authentication-Results` marks `dmarc=pass` (`Session.email_authenticated`). Everything else fails closed: a teammate (on the web too), an unrostered sender, the principal's address on mail Gmail did not authenticate, Google Chat, the MCP server (its caller names themselves), unattended runs, and an unreadable roster. The rule used to be \"no `origin_channel` means the principal's own surface\", and the email poller left `origin_channel` empty, so every stranger's email ran through the extractor with its body — headers, quoted chain and all — as the principal's words, and whatever it stored rendered on every later turn. The poller now tags its sessions `origin_channel=\"email\"`, and the gate no longer reads an empty channel as trust.\n\nThe extractor also reads only the words **outside** every `<untrusted_content>` block (`schedule_extraction` runs `content_trust.strip_untrusted` first): an attached document's text is inlined in that block, so a sentence the principal did not type can never be quoted back as their commitment, and a turn that is nothing but an attachment is not extracted at all.\n\nEach pass writes a `memory_extraction` audit row — in a `finally`, so a pass that crashed is recorded too, with the exception type as its `failure` reason: how many items the model proposed, how many were stored, a `malformed` count so a pass where the model returned only garbage does not read as one that found nothing, and a `{kind, reason}` record per drop — `bad_quote` and `missing_field` for an item the model proposed, `not_a_list`, `item_not_a_dict` and `payload_not_a_dict` for a shape that was never a usable item. Every proposed item is either stored or dropped, so `proposed == stored + item drops` is the arithmetic that says whether anything was lost silently. The tool payload is not schema-checked anywhere, so a malformed shape is counted as a drop rather than raised — it used to abort the whole pass, discarding the other two kinds with it and suppressing the row, which read exactly like \"extraction never ran\". Without it, \"the model found nothing\" and \"the model found things and every one was rejected\" are indistinguishable from outside the database — which is why the failure above survived undetected and took a SQLite session on the tenant to find. A `proposed>0, stored=0` streak is the signal to watch.\n\nThe validator rejects a paraphrase, and the model paraphrases: on one install two of three real commitments were lost that way, the quote beginning \"SVN's engagement covers only …\" where the person had typed something else. So a `bad_quote` drop earns exactly one corrective call. The model is shown the rejected items and the quotes it gave, told to copy the span character-for-character (typos and casing included) or return empty arrays, and the tool is forced where the provider supports tool choice. Every retry item is validated first; a still-invalid one adds no second drop and is counted `still_invalid`. A valid item is then classified in order: its label matches a pending drop record → a recovery, stored and the record released; else its quote (terminal punctuation ignored) already supports a stored item of that kind → a re-send, ignored and counted `repeated`, so a model that re-sends everything cannot double-count `stored`; else a new proposal, stored and counted — a reworded label cannot be told from a different item, and crediting it would erase the very `bad_quote` census the row exists to show, so its original drop stands. Recovery is checked before re-send because two commitments can rest on one sentence. Malformed shapes at any level — a kind that is not a list, an item or payload that is not a dict, a response with no tool call — are counted `malformed`, so a retry that returned garbage does not read like one that obediently returned nothing. The row's `retry` block (`rejected`, `recovered`, `repeated`, `still_invalid`, `malformed`, `failure`) is always present, zeros when nothing was rejected; `rejected` is set from the complete drop list when the row is written, so neither a store failure before the retry nor a cancellation during it can zero it. The arithmetic above still holds after the retry. An exception on the retry is recorded as the retry's own `failure` and leaves the first pass's results untouched; the cost is one utility-model call, only on turns that dropped something. `memory_extraction` is a declared event type, so the audit page's filter can select it.\n\n### Standing facts (corrections that persist everywhere)\n\nA fifth table, `facts` (`openexecutive.memory.facts`, created on first write), holds facts and corrections the principal stated and asked to keep — \"Maple House is 48 units, not 52\". Before it, a chat correction's only durable home was Honcho peer memory: optional, best-effort (its prefetch times out or errors under load), re-injected only into that person's later chat turns, and never read by the briefs, the scheduled runs or the alert review. The episodic extractor cannot hold one either: it stores only decisions backed by a commitment quote, and a fact is not a commitment.\n\n- **Written from chat, by the principal or an attributed teammate.** `remember_fact` stores one (subject, statement, optional wrong value) and `forget_fact` retires one. The principal on a verified surface may do both. A teammate on the People list (a `team` row, not archived, not a contact) on a verified surface (the web app signed in, their own Slack or Discord; `fact_tools._teammate_speaker`) may call `remember_fact` only; email, Google Chat and unrostered senders are refused. Both tools are withheld from every unattended run and every turn private to the principal. Every call, `forget_fact` included (retiring a fact changes what later prompts treat as true just as writing one does), also needs `source_quote`: at least two words and eight characters, found in what the speaker typed this turn (`delegation.settings.own_words` over the pinned `TurnDelegation.speaker_text`). The `<outbound_reply_context>` backstory a Slack or Discord reply is hydrated with is stripped first, and a message with an attachment is refused outright. The quote alone only proves the principal asked, so everything `remember_fact` stores and renders (the statement, the subject shown as `[fact N] subject:`, and a previous value shown as `(corrects: …)`) is tied to their words too. An omitted previous value falls back to the replaced fact's own statement. Every figure must be a number they wrote, compared at its magnitude: `$180k` matches `180,000`, but `180m` never lets `$180k` through. Every name must also appear in what they typed: a capitalised word, or any word holding a non-ASCII letter, other than the statement's very first word (a statement is one fact, so splitting a document's names into one-word sentences exempts nothing). So must every month, weekday or quarter. A name the model writes in lower case is not caught: the gate narrows what a real quote can carry in; it does not prove a paraphrase. A real quote therefore cannot carry a document's figure, name or date in with it (\"Cedar Court's lease expires in March\" after \"remember what the lease doc says\"), while a paraphrase of what they said still passes. So the model cannot store its own inference, a document's figure or text quoted back at the principal as something they said. Every audit row the tools write, and the chat loop's `skill:` dispatch row for them (whose input quotes the principal verbatim), is private to the principal (`executive._private_tool_row`). Those rows tie a fact to the principal's session and turn, which `GET /memories/facts` hides from teammates, and a teammate can read any non-private audit row. The handlers run in a worker thread (`asyncio.to_thread`, which carries the turn's context), and the chat and committee paths, the alert review, the morning brief's synthesis and the end-of-day, weekly-review and reflection workflows read the block the same way, so SQLite, the profile file and its lock never block the event loop the SSE streams share. The principal's own email may ask too: the change is checked the same way, then held until they confirm it by replying to a one-time token sent to their own address (see Integrations → Standing facts by email).\n- **Provenance and attribution.** Each row keeps the quote, the channel (`web` or the adapter), `session_id`, `turn_id`, the recording person and the time, plus `recorded_by_role` (`principal` or `teammate`) and, for a teammate, `recorded_by_name` as the People list had it. Rows written before these columns existed read as the principal's (`_migrate` adds the columns on the first write; the read-only render tolerates a DB that has none).\n- **One active fact per subject.** A new row supersedes any active row with the same folded subject key, or the id named in `replaces_fact_id`, in one transaction. The old row stays as `superseded` (with `superseded_by`), and the new one is stored as a `correction` carrying what it replaced. Retiring sets `retired` with a reason. **The principal outranks a teammate:** a teammate's write that would replace an active fact the principal set (by subject or `replaces_fact_id`) raises `PrincipalFactConflict`, and the tool stores it as `proposed` instead, naming the fact it would replace (`replaces_fact_id`); teammates replace each other's facts freely, and the principal replaces anyone's. **\"Needs my approval\"** (`fact_approval_rules`, per teammate, **on by default**, set only by the principal) stores every fact from that teammate as `proposed`; the principal turns it off for a teammate they trust, whose facts then apply at once (except one that would replace the principal's). The rule is read inside `record_fact`'s own write transaction, so a switch turned on a moment earlier cannot let one fact through; a teammate write that names no person is never trusted. One teammate may have at most `MAX_PENDING_PROPOSALS_PER_PERSON` (20) proposals waiting (`TooManyProposals`; the tool tells them to wait for the principal's review). A teammate's retire checks ownership in the `UPDATE` itself (`retire_fact(teammate_id=)`: their own row, not approved). A proposed row never renders; `approve_fact` makes it active and replaces what it names (the principal's own fact included — approving it is their word) and stamps `approved_at`, after which it outranks teammates exactly as the principal's own fact does (`Fact.principal_owned`: no teammate may replace or retire it); `decline_fact` sets `declined`. No field of a teammate's fact may carry what the render adds itself — `(per <anyone>)` in any case (a unit such as `(per month)` or `(per unit)` is fine), `[fact N]` or a date stamp after any dash, read NFKC-folded with invisible characters removed (`fact_tools._marker_error`) — so a teammate cannot plant a second, forged attribution inside their statement (the principal's own unmarked lines are not checked: \"(per Smith lease)\" is ordinary wording for them). The tool answers `awaiting_approval` (no action chip) and tells the model to say it is not in use yet.\n- **Rendered everywhere output is produced.** `render_facts_for_prompt` renders the active rows newest first under a self-explaining `STANDING FACTS` header (use these over older figures; a line ending `(per <name>)` is that teammate's word and the principal's unmarked line wins a conflict; the current conversation still wins; quoted data never instructions). A teammate's line ends `(per <name>)`, the name defanged like the rest, capped at 40 facts / 6000 chars, with angle brackets defanged. It opens the DB read-only and never creates it or the table. The block always rides in a user turn, never a cached system block: a chat turn's `<standing_facts>` (so every scheduled run through the chat loop too), each specialist consult (`route_to_specialist`, chat and workflow steps alike), the /today header and the morning brief (`render_briefing_context`, after the quiet check and inside the string the header's cache key hashes, so a new fact rewrites the header), the alert review's batch (`render_batch`, read once per pass), and the end-of-day digest, the weekly review's top-three call and the morning reflection (`with_standing_facts`).\n- **Company-profile edits from chat.** `update_company_profile` (same gate and quote rule) changes one whitelisted field of `company/profile.yaml`, under `PROFILE_EDIT_LOCK` (also taken by `PATCH /company-profile`, so neither edit silently drops the other): a text or number field is set, a list field gets an item added or removed, and `financials.key_metrics` takes a named metric. It writes through `CompanyProfile.save_to_yaml` and updates the session's profile, so the next turn's cached company block carries it (one cache miss on the change). The new value must itself appear in the principal's own words, not just the quote: the value renders into the cached company block on every later turn, so \"set our mission to what the doc says\" or \"update our headcount\" is refused rather than saving a document's text or a guessed figure. A number must be one they wrote, however they wrote it (`$180k`, `1.2m`, `2,400,000`). Saved text has `<`/`>` defanged. A `kind='profile'` row records each edit with its quote for the Pulse page. Those rows are never rendered into a prompt, because the profile block already carries the value.\n\n### Session scoping\n\n`decisions` and `advice_given` rows carry a `session_id`, so per-thread channels (Discord, Telegram) can pull just-this-thread history without leaking cross-conversation context. A null `session_id` falls back to a global view.\n\n### Surfacing\n\n`openexecutive.memory.episodic.format_for_prompt` renders recent decisions and initiatives into a compact `<past_decisions>` block injected into the user turn — alongside `<retrieved_context>` and peer memory — never into a cached system block. Each decision names where it was recorded when that was a channel — `- 2026-09-01 [finance] (via email): …`, from the prefix of its `session_id` (`email:`, `slack:`, `discord:`, `telegram:`, `google_chat:`); a web or CLI decision has no tag. Rows extracted from mail before the untrusted-content policy, when any sender's body could be stored, therefore read as mail rather than as the principal's own word.\n\nScoped to a session, decisions and advice cover every conversation of a chat app's stream (`memory.conversation_ids.family_clause`): a Telegram chat or a DM is cut into conversations after two quiet hours or a /new (`memory.conversations`), and what an earlier conversation decided still renders in the next.\n\nThe chat route also injects a `<briefing>` block into the same user turn: a compact digest of the current open (unread) alerts, built by `openexecutive.briefing.context.format_open_alerts_for_prompt` (company-wide, `status=\"unread\"`, mirroring `/today`). This is what lets the Executive discuss a briefing item the principal clicked or named on `/today` (e.g. \"Gulf Coast Port Cyberattack\"). It is resolved in parallel with the other context fetches, omitted when there are no open alerts, and never placed in a cached system block.\n\nOn the Pulse page the Memory section shows the three lists as Decisions, Initiatives and Advice tabs, then a **Corrections** tab (`GET /memories/facts`: active standing facts and profile edits with their quote, channel and — for a teammate's — their name; proposals first under \"Waiting for your approval\" with **Approve** / **Decline** for the principal; the replaced, retired and declined history folded away; **Retire** on any fact for the principal and on their own not-yet-approved one for a teammate; and, for the principal, a per-teammate \"needs my approval\" switch), and a **History** tab for the person's own Always in the loop notes (see below). The header's Memories tile counts the three lists. What peer memory has learned about the signed-in person is theirs alone, so it is not on Pulse: it is on **Settings → About you** (see the peer memory section).\n\nThe same user turn carries a `<drive_memory>` block when the conversation has touched Google Drive (`openexecutive.memory.drive_reads`). Drive is reached only as live Google Workspace calls inside a turn and history keeps only prose, so without it a file found one turn was gone the next. `MCPGateway.call_tool` hands each `search_drive_files` and `get_drive_file_content` result to `record_drive_result`, which keeps, per session, every file found or opened (file id, name, type, link, and for an opened file its first 600 characters) and every search that matched nothing, with its query. `format_drive_memory` lists the 20 most recent files, so \"the file you found earlier\" resolves to a file id the Executive reopens rather than searching again, and the queries that found nothing (dropped once the same query later finds something). Rows are keyed on the session *and* the speaker, and shown only to that speaker in that session, because one session can span several people (an email thread, a Slack or Discord thread). Nothing is recorded or shown without a bound `current_session` and a rostered speaker, on a turn private to the principal, or on one that touched the speaker's own mailbox (Act as me). workspace-mcp writes file names into its output unescaped, so a name containing a newline can forge a result line. Only a Drive-shaped file id, type and `docs`/`drive.google.com` link are therefore kept; any other line is dropped, and the name is always quoted as the file's own content, not instructions. Each speaker keeps at most 100 files and 100 searches per session, older rows are pruned on write, and `session_store.delete_session` drops them all.\n\nA conversation can also become its owner's alone. When Act as me first reads the speaker's own mailbox in it, `session_store.mark_mail_private` sets `sessions.mail_private` (creating the row with its owner when a channel adapter hasn't written it yet), and from then on only the session's owner may open, continue or delete it — the principal included, when it is a team member's (`chat._session_access`). It is never cleared. Beside it `sessions.mail_read_at` keeps how many history messages the conversation held before the last turn that read the mail (`session_store.mail_read_at`; NULL on rows marked before the column): Act as me's hold on links and scripts in later turns lasts only while that turn is still in the history window (see Act as me). \n\nThe chat list has owner controls on the same row: `sessions.pinned_at` (pinned chats list first) and `sessions.title_locked` (set by `rename_session`, after which `update_session_title`, the automatic title, leaves the name alone). A `session_shares(session_id, person_id, shared_by_person_id, created_at)` row adds one team member to someone's chat (`list_shared_with_person`, `set_shares`, `leave_share`): they read and write in it with its owner, each of their messages saved with their own `sender_person_id`; a `mail_private` chat is never shared or opened that way, and deleting the chat drops its shares. `last_turn_sender` says who wrote the last turn, which is how redo stays with the person who asked. The chat list's preview puts `You:` only before the caller's own words. `rewind_last_turn` deletes a web chat's last turn (the last reply and the user messages after the reply before it) so it can be asked again; the next turn's history is re-read from these rows, so nothing else needs clearing. A search that matched nothing also gains a note in its tool result: say the exact query and that it found nothing, never that the file does not exist. This is a first step: Drive is still not indexed into the company collection.\n\n### System of record\n\nSQL is the system of record; the peer-memory service is a recall layer mirrored from it, not a replacement. When `store_decision` / `store_initiative` / `store_advice` insert a row whose `department` is non-empty and not `\"general\"`, the row is mirrored as a kind-tagged note into that department's peer via `append_department_note`. The mirror fires only after a successful INSERT, is fire-and-forget, and never rolls back the SQL row on peer-memory failure. `scheduled_actions` is never mirrored — it is a queue, not memory.\n\nThe episodic extractor still learns only from the principal's own words. Commitments and asks from everyone else on the roster are tracked as **open loops** (see Attunement) — `scheduled_actions` rows with `kind='open_loop'`, opened and closed by a separate quote-gated pass after each attributed turn. That pass depends on `chat_messages.sender_person_id`, which records who actually wrote each persisted user message. An open loop counts toward `list_awaiting_replies_by_person` only once it is due, and `list_scheduled_actions(exclude_internal=True)` filters `__internal__` rows in SQL so readers that want real sends are not starved by them. `mark_outbound_context_consumed` also resolves the Attunement outcome row for that DM as `replied` — a matched reply is the clearest sign proactive outreach landed — and a real change to an existing initiative (`store_initiative` / `update_initiative`, new status or summary) marks the updater's own check-in nudges `acted` — an update with no known updater, such as `PATCH /memories/initiatives/{id}`, credits nobody.\n\n### Workspace settings\n\nThe same database holds one row of settings that are not memory: `workspace_settings` (`openexecutive.memory.workspace_settings`) — the install's mode (`team` by default, or `solo` for one person using Open Executive just for themselves), the user's IANA time zone, the principal's role (`PrincipalRole`: `role_kind`, `role_title`, `reports_to`, `remit`, `measured_on`, all nullable; only solo mode reads it), and the company's own email domains (`company_domains`, a JSON list, or NULL to derive them from the principal's primary address — `people.identity` matches a teammate by local part on them; `validate_company_domains` lowercases, dedupes and sorts, allows at most 10 plain DNS names and refuses a free-mail provider's, and a stored value that no longer validates reads as NULL). It is a table of its own rather than a company-profile field because onboarding rebuilds the profile from scratch. Every read is fresh and read-only (a missing file or table reads as the defaults; a table from before the role or `company_domains` columns reads them as unset and is migrated additively by the next init or write). A read error (a locked database, say) also reads as the defaults, so `get_workspace` then says team; `read_stored_mode` is the strict read of the mode alone — None when the row cannot be read or holds no valid mode — for the scheduler's weekly-review check, which must not take a failed read for team. A session may carry an explicit `workspace_mode` override; otherwise the mode is read fresh at the start of each turn and pinned on the session for that turn only (`Session.turn_workspace_mode`, via `pin_turn_workspace_mode`), so every tool handler in the turn sees the mode its persona and tools were built in. `effective_workspace_mode` reads override, then the pin, then the setting; `effective_principal_role` reads a session's `principal_role` override, then the role pinned for the turn (`Session.turn_principal_role`, via `pin_turn_principal_role`), then the stored role. See Org for what solo changes and Scheduler for the time zone.\n\n### Act as me\n\n`initialize_db` also creates Act as me's per-person tables (`delegation.schema.ensure_schema`): `delegation_settings`, `delegation_voice` and `delegation_voice_history`. They hold a setting and a writing profile rather than memory, and nothing in them is mirrored to peer memory. A turn that touched the speaker's own mailbox teaches no memory: the episodic, open-loop and working-style passes are skipped along with the Honcho peer and department syncs, since its reply quotes a draft built from other people's mail. See **Act as Me (Delegation)**.\n\n### Always in the loop (notes of what you said)\n\nA person can keep private, dated notes of what they said, in chat with the Executive and in email replies it drafted for them: what they promised, agreed, declined, answered, asked for or shared. The switch is per person (\"Keep track of what happens\", `history_person_settings.reply_notes`, off by default, one switch for every channel). Any team member on the People list may turn it on (`history.can_keep_notes`: kind `team`, not archived, the principal included); Act as me isn't needed, though notes from email replies only come through it.\n\n- **Where notes come from: chat.** After each chat turn, on both the single-voice and the committee path, the Executive's post-turn block calls `memory.history_chat.schedule_chat_notes` next to the open-loop and style passes, except on a turn that touched the speaker's mailbox. It reads only what the speaker typed this turn (`delegation.settings.own_words`: no backstory an adapter added, nothing when a file came with it), never the reply and never anyone else's message: every channel calls the Executive with the one speaker's message, and what other people say to each other is never read. It runs only for a speaker the turn verified (`history_chat.verified_speaker`): the turn's `caller_person_id` is them, nobody started it by email or runs it unattended or for them, and the surface proved who they are (the web chat signed in or a local install, the principal or a team member on their own Slack or Discord, a private Telegram chat behind a valid webhook secret, or a channel whose adapter verified the sender itself and set `Session.speaker_verified`). A shared Slack or Discord thread counts: the notes stay private and are read back only where nobody else can see them. A message under 40 characters is skipped, and each person gets at most 40 passes a day, counted in `history_chat_passes` so the cap holds across workers and restarts. The pass uses a constant `CHAT_PROMPT` (requests to the assistant, questions and small talk are not notes), the same `record_notes` tool and the same `check_note` gate with the message as both body and allowed words; the note's channel is the inbound channel or `web`, its conversation the session id, and it names no counterpart.\n- **Where notes come from: email.** After `delegation.reply_send` sends a reply, it starts `memory.history_notes.note_sent_reply` in the background. The note-taker reads only the words the person sent (`email_poller.sender_new_text` strips quoted mail) and the recipients' names, cut to four words of name characters (`history_notes.short_name`): never the mail being answered, nor the subject, which others in the thread write too, so nothing another person wrote can become a note. One forced `record_notes` call with a constant prompt and no other tools returns at most three notes. Code then drops any note that says more than they did: the `quote` must appear word for word in what they sent, every figure in the summary must be in the quote, every name or date word must be in what they sent or the recipients' names, at least half its other content words must be theirs, the summary carries no link or address, and a `due_date` is kept only for something promised or agreed. Notes record events, never instructions, and carry `trust = high` because they rest on the person's own words.\n- **Whose they are.** Every note is private to its person (`visibility = private`). Nobody else reads it, the principal included; there is no shared note.\n- **How long they last.** The company default is 90 days (`history_settings.retention_days`, the principal's choice of 30, 90, 365 or until forgotten). A person may only choose a shorter time; shortening the company time clamps everyone's choice and re-dates live notes. A pinned note never expires; unpinning restarts its clock, and a later retention change counts from there. Reads skip expired notes and the scheduler's alert sweep deletes them (`history.sweep_expired`).\n- **What a person controls.** Through `/memories/history` they read, search, pin, correct and forget their own notes. On the Pulse page this is the **History** tab, last in the Memory section and shown only to someone with notes to see (signed in and on the People list): each note shows its kind, who it was with, the date, the person's own words, any due date and when it will be forgotten, and its menu holds **Correct** (a side panel; \"Use the original\" clears a correction), **Pin**, **Don't remember this** and **Forget**. \"Don't remember this\" forgets every note from that conversation and adds it to `history_excluded`, so it is never noted again. Settings → **Memory** holds the switch (\"Keep track of what happens\") and a shorter time for their own notes, and the company time, which the principal changes and everyone else reads. A chat note shows the channel alone (\"Slack\", \"Web chat\").\n- **Recall.** `recall_history` (`orchestrator.history_tools`) is offered only on a turn where the speaker may read their notes: verified as above, a team member who may keep notes, in a conversation private to them (`history_chat.private_chat`: the web chat, a Slack or Discord DM, a Telegram chat, or one its adapter marked `Session.private_chat`), with their switch on. Before any note is read the turn is set `touched_mail`, for the principal too, so its rows are private to the speaker, it teaches no memory and the mail lockdown holds from that round on. The conversation is also marked theirs alone (`session_store.mark_mail_private`), so every later turn in it is private the same way (the lockdown is that turn's alone) and, for a team member, the principal can't open it; recall refuses if that can't be stored. Notes come back in a `<history_notes>` block as history to cite: the date, the person's own words first, then how they were noted. With `due: true` it lists only notes with a due date, from a week overdue to two weeks ahead, soonest first (\"what's due today?\").\n- **In the owner's briefs.** The morning brief adds a FROM YOUR NOTES — DUE SOON block (`memory.history_brief.due_soon_block`: what the owner promised, agreed or asked of someone, from a week overdue to a week ahead, in the workspace's local dates) and the end-of-day digest a FROM YOUR NOTES — TODAY block (`noted_today_block`: what they promised, agreed, asked or declined since the last digest, then what is due tomorrow). Both only on the scheduler's delivery to the owner alone (`morning_brief.PRINCIPAL_DELIVERY`), never a run started from chat, whose tool result lands in the turn's shared audit row and peer memory; only when the owner may keep notes and has the switch on (`history_brief.owner_keeping_notes`), and only the owner's own notes. A run that used any is marked `private_to_principal`, so the shared run history keeps `PRIVATE_RUN_ARTIFACT` instead of its text, and the note ids with their state (overdue, today, soon) enter the brief's fingerprint, so one falling due un-suppresses an unchanged brief. Teammates get no brief, so their notes reach them only through recall and reminders.\n- **In Act as me drafts.** The ghostwriter gets a `<writer_noted>` block (`memory.history_drafts.notes_for_draft`): the writer's own notes from earlier Act as me replies that every recipient of the new draft was on, with their switch on. It keeps the draft consistent with them and turns a contradiction into an open question on the card; it never adds anything from them (see Act as me).\n- **Due-today reminders.** `memory.history_reminders.maybe_remind`, called from the scheduler tick every 15 minutes between 09:00 and 18:00 local time, sends each person with the switch on one message on a day something they promised or agreed to by email (`source = approved_reply`) falls due. Chat promises are left to open loops, which the nudge engine already chases. The message says only how many things are due, never what or to whom, and the channel senders' audit rows for it are private to the person (`audit.context.rows_for_person`; the owner's `private_rows`), which also keeps the send off the shared activity rail (`_record_send_to_activity` skips a send whose rows are private). The person asks \"what's due today?\" in a private conversation and `recall_history` answers. It goes to their own Slack or Discord DM, a private Telegram chat (`delivery_order` skips a negative group id, for the owner's briefs too) or their own email (`scheduler.runner.deliver_to_person`), never a shared channel. `history_reminders` holds one row per person per day, claimed before sending and never released, so two workers never both send and a half-failed send is never repeated; a failed one waits for the next due day.\n- **Not peer memory.** Notes never reach Honcho, episodic extraction, standing facts or another person's turn. The tables (`history_notes`, `history_settings`, `history_person_settings`, `history_excluded`, `history_chat_passes`, `history_reminders`, created by `history_schema.ensure_schema` from `initialize_db`) swap with a client slot and are cleared by a factory reset.\n\n### Conversation review (fixing what replies left undone)\n\n`memory.chat_review` looks back over a chat once it has been quiet `CHAT_REVIEW_QUIET_MINUTES` (30) and fixes what the replies left undone: \"I sent it\" answered with \"noted\" and the draft still waiting, \"drop that reminder\" answered with \"sure\" and the reminder still set. The claim check (`orchestrator.claim_check`, see Lifecycle) catches a false claim in the same turn; this catches the rest.\n\n- **What is recorded.** On both the single-voice and the committee path the post-turn block calls `record_turn` with the speaker's own words (`delegation.settings.own_words`), the reply and the tools the turn ran (`_stream_agent_loop(calls_out=)`). Only a verified speaker's turn is kept: the principal on a surface `people_tools` verifies, or a rostered teammate on their own signed-in web chat, Slack or Discord. A channel whose adapter set `Session.speaker_verified` counts as a verified surface here too; an email, an unattended run, a turn private to the principal, one that touched the speaker's mailbox and a message with an attachment are never kept. Rows live in `chat_review_turns` for 7 days, a turn graded a miss (below) for `MISS_KEEP_DAYS` (90); each row also keeps the audit `turn_id` of the turn, so the claim check's row can be joined back to it.\n- **When.** Each kept turn makes sure one `chat_review` `__internal__` action is waiting for the conversation (`channel_ref` = session id), due 30 minutes on. The runner marks it done and calls `run_scheduled`, which schedules a fresh one if a newer turn arrived meanwhile, else reviews the oldest unreviewed turns (at most 20, the rest in a review right after) and marks exactly those reviewed, so a chat is read in parts and never twice. `CHAT_REVIEW_MAX_PER_DAY` (10) caps each person's passes a day (`chat_review_days`), so one person's chats can't use up another's.\n- **The pass.** One small tool loop per person on `CHAT_REVIEW_MODEL` (default `ROUTING_MODEL`), at most 5 rounds and 8 changes, in its own task with a session rebuilt from the recorded surface and caller and a delegation pin holding their words, so each tool runs through the chat tool's own handler and checks: `list_open_loops` / `close_open_loop`, `remember_fact`, `list_followups` / `cancel_followup` / `move_followup`, `leave_out_of_brief`, plus `learn_reply_style` (a working-style rule), `learn_writing_style` (a habit or avoid line in their Act as me voice profile, only for someone who may use it) and `raise_in_brief` (one line for the next brief). Every change carries `source_quote` of at least four of the person's own words (`fact_tools._quote_error`), and the thing it changes (the loop's or follow-up's text, the fact, the brief item or line) must share two words with what they wrote (its only one, for a one-word target) A chat draft's state is left to the brief's own check of the mailbox's Drafts. The replies are shown as `<untrusted_content>` (they quote mail and documents) and tool results not at all, only the tools' names. `leave_out_of_brief` and `raise_in_brief` are the principal's only; dropping a fact and changing a goal are left to chat. It never sends, books, deletes or grants permission to act, and nothing it does is said in chat. One `chat_review` audit row per pass lists the changes.\n- **Grading (looking back at how it went).** Before the fix loop, the same pass grades each turn it reads with one forced-tool call (`grade_turns`) on the review model. The grader sees what the fix loop sees plus one SIGNALS line per turn, joined from where the product already records them (`turn_signals`): a 👍/👎 and its note on the saved reply (`chat_messages`, matched to the recorded reply by its first 120 characters, which also gives the Reflection screen the reply's `message_id`), a reply the person stopped (`stopped`), a turn they took back to ask again (a `session_rewound` audit row after a turn whose reply is no longer in the chat), a claim the reply made that no tool backed (a `claim_check` audit row with the turn's `turn_id`), and a tool whose recorded result reads as an error. Per turn it records `fine`, `miss` or `unclear`; for a miss, `wanted` (what the person wanted instead, one or two sentences) backed by a `quote` of at least four of their own words from that turn or the ones after it, code-checked (`accept_grades`) or the turn is `unclear` and `wanted` dropped, plus the `kind`: `company` (a term, a fact, a preference, which specialist to ask, doing a thing rather than promising it would have fixed it) or `product` (a tool failed or was refused, a capability it lacks). A turn the model skipped is `unclear`. Grades go on the row (`verdict`, `kind`, `wanted`, `signals`, `graded_at`, `message_id`), and each person's weekly count of graded turns and misses on `chat_review_weeks`, so the rate outlives the 7-day rows. Grading changes nothing in the workspace and never blocks the fixes: a failed grade leaves the turns ungraded. The pass's audit row carries the counts. `list_misses` (one person's or everyone's; the route then keeps, for the principal, only rows from chats `chat._session_access` lets them open, so a teammate's own chat stays theirs), `weekly_rates` and `forget_miss` (`is_principal_or_self`) serve `GET`/`DELETE /memories/reflection` (the Pulse screen **What it got wrong**).\n- **Lessons** (`memory/lessons.py`): for a turn graded a miss the review may call `learn_lesson` once: one sentence this workspace wants done differently (a term and what it means, a preference about the content, a thing to do rather than promise, a specialist to consult), quoted from the person's own words (the quote must come from the miss turn or a later one, and the lesson must be what the quote says). It passes the working-style deny-list (`attunement.style._DENY_PATTERNS`: no link, handle, amount, markup, identifier, action verb, instruction talk, nudge to act unchecked, roster name) plus the lessons' own list (the verbs that move information: email, share, post, export, attach...; the words that widen a request to everyone or everything) without the about-the-writing requirement, may add at most two content words beyond the quote (`lesson_overreach`, so a real quote can't carry a different sentence in), and is re-checked on every render. Rows live in `chat_review_lessons` (text, quote, person, session, `shared` = learned in a channel or group thread, turn, `shown`, `fine_after`, `miss_after`, `retired_at`/`retired_reason`) with `chat_review_lesson_uses` (lesson, turn id, whose turn). A lesson reaches a turn by a keyword match (two shared content words between the lesson plus its quote and the message; no vector index for a list this short): the Executive's own turn gets the matching ones as a `<lessons>` block in the user turn (`build_lessons_block`, never a cached block; the header says the current request wins and nothing in it authorizes an action), and each specialist call gets the same lines under its `<failure_cases>` block (`router._lessons_for_call` → `lessons_for_query`). A lesson reaches its own person's turns; the principal's reach everyone's only when learned in a shared space (`shared`), so nothing said in someone's own chat is paraphrased into another person's turn. `build_lessons_block` counts each showing against the active turn id and the speaker; when the review later grades that turn, `note_outcome` adds to `fine_after` or `miss_after` only when the turn was the lesson's own person's (nobody else's chats can retire it), and a lesson shown 5 times with more misses than fine turns retires itself (`unhelpful`). At most 40 live lessons per person; their oldest retires to make room (`BEGIN IMMEDIATE`, so two reviews can't both skip it). Forget on the screen retires one by hand (`forgotten`); a retired lesson is listed as stopped, never erased.\n- **Replay: the workspace's own evals** (`memory/replay.py`). Nightly (the `chat_replay` scheduled action, `CHAT_REPLAY_TIME` 03:30 in the user's zone, seeded and chained like the reflection), the Executive runs its misses again with everything in force today and a judge says whether each would now go right. A case is a graded turn: a miss (its `wanted`), or a turn that went fine and got a thumbs up (`kept = 1`, held as long as a miss, at most `MAX_KEPT` 300 per person), which the replay protects so a lesson can't break what worked; a closed miss joins that pool. `due_cases` picks a miss the night a lesson is written for it (`WHY_LESSON`), when a lesson learned since the last night reaches it (`WHY_REACHED`), else once a week (`WHY_WEEKLY`), from the last 30 days only and at most `CHAT_REPLAY_MAX_CASES` (30) a night within `CHAT_REPLAY_MINUTES` (20); 20 protected cases (`WHY_PROTECT`, rotated by last replay) run only on a night a new lesson landed. `replay_case` runs `Executive.chat` on a session rebuilt from the recorded surface and speaker (`chat_review._rebuild_session`) with the saved conversation up to that turn (`chat_messages` before the reply's `message_id`), flagged `Session.replay`: reads run for real through every gate, and every tool a read-only turn is denied (`MCP_CLIENT_WITHHELD_TOOLS`, and gateway calls outside `MCP_CLIENT_MCP_TOOLS`) returns \"done\" and lands in `Session.replay_calls` instead (`faked_handlers` / `faked_call_tool`, wrapped outermost in the agent loop); scripts, Python jobs, `load_mcp_server`, Act as me's tools, `recall_history` and extension tools are not offered at all; nothing a replay does is kept (no extraction, open loops, style, notes, review or Honcho mirror, and `build_lessons_block(count=False)` counts no showing). The judge (`CHAT_REPLAY_JUDGE_MODEL`, else `EVAL_JUDGE_MODEL`, else Sonnet; `evals.judges.judge_message`) reads the original date, the person's words and the conversation before, what they wanted (or the reply they liked), today's reply and the recorded actions, and answers `{passed, time_bound, notes}`, intent and action rather than figures; an unreadable answer is a fail. The gate (`_settle`): a miss that passes is `closed` with `closed_at`; a time-bound one becomes `evidence` and is not replayed again; a lesson for a miss that still fails on `LESSON_FAILS` (2) judged replays after it was learned retires (`replay`); a protected case that fails reopens a closed miss and counts a strike against each new lesson of the same person that reached it (a teammate's turn never retires the principal's shared lessons), which retires at `PROTECT_FAILS` (2) such strikes, so one judged turn, or one message written to fail the judge, is not enough. A case that didn't run (an error, the `CASE_SECONDS` timeout) is recorded with `ran = 0` and settles nothing. The judge's input is scrubbed like outside content (`content_trust._scrub`) with the prompt's own tag names renamed inside it. Every replay is a `chat_review_replays` row (the reply and recorded calls; dropped with its turn when a miss or chat is forgotten or purged, `chat_review._prune_replays`) and a `chat_review` audit row (actor `chat_replay`); each night a `chat_review_replay_runs` row, written before the first case (so a second runner sees nothing new) and filled in after, which is also what \"new since the last night\" means. The nightly Executive carries the scheduler's MCP gateway, so the reads a miss needs run as they did. The Reflection screen's number, \"of the N things that went wrong in the last 30 days, M would go right today\" (`summary_for`, over the misses the caller sees), and each miss's last replay come from these columns on `chat_review_turns` (`replay_state`, `replayed_at`, `closed_at`, `replay_count`, `replay_notes`). Off with `CHAT_REPLAY_ENABLED=false` or when the review itself is off.\n\n## Decision ledger\n\n`openexecutive.memory.decision_ledger` keeps one `decision_instances` row per gated action — a meeting the Executive proposes to book, an Act as me reply card — with how it was resolved, so each class has a reliability record. Every status change is a compare-and-set. A tap with an outside effect (sending an email) claims the row first (`claim_for_execution`, proposed → executing), so of two taps only one acts, and finishes it as `approved_unchanged`, `approved_with_edit` or `failed`, or hands it back (`release_claim`). A row whose class acted on its own with nobody tapping — `gate_mode` `auto_execute`, as Act as me's **Handle it for me** replies are — finishes as `executed` instead, with no resolver, so a reliability read never counts it as an approval. A send whose result is unclear stays `executing` for a reconciler and is never retried. A row still waiting can have its payload changed only by compare-and-set (`update_open_payload`, on `proposed` and, when given, on the payload as it was read): that is how an Act as me reply card takes the person's edit, or records the draft made for it at Send.",+ "markdown": "The Executive's durable memory is an episodic SQLite store at `./episodic_memory.db`, managed by `openexecutive.memory.episodic`. It holds four tables:\n\n- `decisions` — choices made, with `domain`, `summary`, `rationale`, `outcome`, and `tags`. `outcome` is filled in when the principal says how a decision turned out — the `record_decision_outcome` chat tool (principal on a verified surface only) or the Memories page. The weekly review reads this table twice: the week's decisions (`decisions_since`) and up to three older than 30 days with no outcome yet (`decisions_awaiting_outcome`), which it asks about.\n- `initiatives` — tracked efforts with a `status` and `summary` (idempotent upserts).\n- `advice_given` — query/advice pairs per domain.\n- `scheduled_actions` — a dispatch queue, treated separately from recall memory. `cancel_scheduled_action` guards its UPDATE on `status = 'pending'`, so a cancel never overwrites a row the scheduler claimed a moment earlier.\n\n### What gets extracted, and when\n\n`episodic.extract_and_store` runs after a turn and asks a utility-fast model for decisions, initiatives and advice. Every candidate must carry a `user_commitment_quote` that appears verbatim in the principal's own message (`_is_valid_user_commitment`) — the turn's speaker text (`memory_text` when the entry point supplies one, else the prompt), so a quoted Executive email or a briefing card's body inside the prompt cannot satisfy it — the model has repeatedly tried to log the Executive's *recommendations* as the user's commitments, and that quote is the hard gate against it.\n\nA turn reaches the extractor if `should_extract(speaker_text, session=...)` is true, which means only that the principal said something on a surface that proved it was them — there is deliberately **no length floor**. There used to be one, on the combined user+assistant length, and on a live tenant it selected almost exactly the wrong turns: 9 of 16 exchanges were blocked, and the 9 held every instruction the principal gave, while the 7 admitted were long analytical exchanges with no commitment in them. The extractor ran 13 times and stored nothing.\n\nMoving that floor to the user's side would relocate the bug, not fix it. The canonical executive decision is a long analysis answered with \"Approve option B.\" (17 chars) or \"Do B.\" (5), and any floor high enough to skip \"Done\" (4) also skips those — \"Do B.\" and \"Done\" differ by one character and mean opposite things. Length cannot separate a decision from an acknowledgement; the verbatim-quote check can, so `_is_valid_user_commitment` is the gate that decides. The price is one utility-fast call on turns that propose nothing.\n\nThat quote check is only meaningful when `user_message` holds the **principal's** words, and on a chat channel it does not — `Executive.chat()` is reached from Slack, Discord, Telegram, Google Chat and the email poller. A teammate's line would be written to `decisions` with no speaker attached, indistinguishable from the principal's own; an inbound email body is text the sender chose, so a self-quote is free. Removing the length floor is what makes this bite — short channel traffic used to fall under it incidentally — so `should_extract` asks the untrusted-content policy (`orchestrator.content_trust.principal_speaking`) whether the principal is speaking. It names the principal's surfaces rather than inferring them: the web chat (signed in as the principal — or, on an install with no principal on the People page yet, a request that carried no sign-in; a signed-in email on nobody's entry, such as an archived teammate still allowed to sign in, is not the principal), the CLI (`Session.from_cli`), the principal's own Slack or Discord or a private Telegram chat with a valid webhook secret (`people_tools.is_principal_on_verified_surface`), and email from the principal's primary address that Gmail's own `Authentication-Results` marks `dmarc=pass` (`Session.email_authenticated`). Everything else fails closed: a teammate (on the web too), an unrostered sender, the principal's address on mail Gmail did not authenticate, Google Chat, the MCP server (its caller names themselves), unattended runs, and an unreadable roster. The rule used to be \"no `origin_channel` means the principal's own surface\", and the email poller left `origin_channel` empty, so every stranger's email ran through the extractor with its body — headers, quoted chain and all — as the principal's words, and whatever it stored rendered on every later turn. The poller now tags its sessions `origin_channel=\"email\"`, and the gate no longer reads an empty channel as trust.\n\nThe extractor also reads only the words **outside** every `<untrusted_content>` block (`schedule_extraction` runs `content_trust.strip_untrusted` first): an attached document's text is inlined in that block, so a sentence the principal did not type can never be quoted back as their commitment, and a turn that is nothing but an attachment is not extracted at all.\n\nEach pass writes a `memory_extraction` audit row — in a `finally`, so a pass that crashed is recorded too, with the exception type as its `failure` reason: how many items the model proposed, how many were stored, a `malformed` count so a pass where the model returned only garbage does not read as one that found nothing, and a `{kind, reason}` record per drop — `bad_quote` and `missing_field` for an item the model proposed, `not_a_list`, `item_not_a_dict` and `payload_not_a_dict` for a shape that was never a usable item. Every proposed item is either stored or dropped, so `proposed == stored + item drops` is the arithmetic that says whether anything was lost silently. The tool payload is not schema-checked anywhere, so a malformed shape is counted as a drop rather than raised — it used to abort the whole pass, discarding the other two kinds with it and suppressing the row, which read exactly like \"extraction never ran\". Without it, \"the model found nothing\" and \"the model found things and every one was rejected\" are indistinguishable from outside the database — which is why the failure above survived undetected and took a SQLite session on the tenant to find. A `proposed>0, stored=0` streak is the signal to watch.\n\nThe validator rejects a paraphrase, and the model paraphrases: on one install two of three real commitments were lost that way, the quote beginning \"SVN's engagement covers only …\" where the person had typed something else. So a `bad_quote` drop earns exactly one corrective call. The model is shown the rejected items and the quotes it gave, told to copy the span character-for-character (typos and casing included) or return empty arrays, and the tool is forced where the provider supports tool choice. Every retry item is validated first; a still-invalid one adds no second drop and is counted `still_invalid`. A valid item is then classified in order: its label matches a pending drop record → a recovery, stored and the record released; else its quote (terminal punctuation ignored) already supports a stored item of that kind → a re-send, ignored and counted `repeated`, so a model that re-sends everything cannot double-count `stored`; else a new proposal, stored and counted — a reworded label cannot be told from a different item, and crediting it would erase the very `bad_quote` census the row exists to show, so its original drop stands. Recovery is checked before re-send because two commitments can rest on one sentence. Malformed shapes at any level — a kind that is not a list, an item or payload that is not a dict, a response with no tool call — are counted `malformed`, so a retry that returned garbage does not read like one that obediently returned nothing. The row's `retry` block (`rejected`, `recovered`, `repeated`, `still_invalid`, `malformed`, `failure`) is always present, zeros when nothing was rejected; `rejected` is set from the complete drop list when the row is written, so neither a store failure before the retry nor a cancellation during it can zero it. The arithmetic above still holds after the retry. An exception on the retry is recorded as the retry's own `failure` and leaves the first pass's results untouched; the cost is one utility-model call, only on turns that dropped something. `memory_extraction` is a declared event type, so the audit page's filter can select it.\n\n### Standing facts (corrections that persist everywhere)\n\nA fifth table, `facts` (`openexecutive.memory.facts`, created on first write), holds facts and corrections the principal stated and asked to keep — \"Maple House is 48 units, not 52\". Before it, a chat correction's only durable home was Honcho peer memory: optional, best-effort (its prefetch times out or errors under load), re-injected only into that person's later chat turns, and never read by the briefs, the scheduled runs or the alert review. The episodic extractor cannot hold one either: it stores only decisions backed by a commitment quote, and a fact is not a commitment.\n\n- **Written from chat, by the principal or an attributed teammate.** `remember_fact` stores one (subject, statement, optional wrong value) and `forget_fact` retires one. The principal on a verified surface may do both. A teammate on the People list (a `team` row, not archived, not a contact) on a verified surface (the web app signed in, their own Slack or Discord; `fact_tools._teammate_speaker`) may call `remember_fact` only; email, Google Chat and unrostered senders are refused. Both tools are withheld from every unattended run and every turn private to the principal. Every call, `forget_fact` included (retiring a fact changes what later prompts treat as true just as writing one does), also needs `source_quote`: at least two words and eight characters, found in what the speaker typed this turn (`delegation.settings.own_words` over the pinned `TurnDelegation.speaker_text`). The `<outbound_reply_context>` backstory a Slack or Discord reply is hydrated with is stripped first, and a message with an attachment is refused outright. The quote alone only proves the principal asked, so everything `remember_fact` stores and renders (the statement, the subject shown as `[fact N] subject:`, and a previous value shown as `(corrects: …)`) is tied to their words too. An omitted previous value falls back to the replaced fact's own statement. Every figure must be a number they wrote, compared at its magnitude: `$180k` matches `180,000`, but `180m` never lets `$180k` through. Every name must also appear in what they typed: a capitalised word, or any word holding a non-ASCII letter, other than the statement's very first word (a statement is one fact, so splitting a document's names into one-word sentences exempts nothing). So must every month, weekday or quarter. A name the model writes in lower case is not caught: the gate narrows what a real quote can carry in; it does not prove a paraphrase. A real quote therefore cannot carry a document's figure, name or date in with it (\"Cedar Court's lease expires in March\" after \"remember what the lease doc says\"), while a paraphrase of what they said still passes. So the model cannot store its own inference, a document's figure or text quoted back at the principal as something they said. Every audit row the tools write, and the chat loop's `skill:` dispatch row for them (whose input quotes the principal verbatim), is private to the principal (`executive._private_tool_row`). Those rows tie a fact to the principal's session and turn, which `GET /memories/facts` hides from teammates, and a teammate can read any non-private audit row. The handlers run in a worker thread (`asyncio.to_thread`, which carries the turn's context), and the chat and committee paths, the alert review, the morning brief's synthesis and the end-of-day, weekly-review and reflection workflows read the block the same way, so SQLite, the profile file and its lock never block the event loop the SSE streams share. The principal's own email may ask too: the change is checked the same way, then held until they confirm it by replying to a one-time token sent to their own address (see Integrations → Standing facts by email).\n- **Provenance and attribution.** Each row keeps the quote, the channel (`web` or the adapter), `session_id`, `turn_id`, the recording person and the time, plus `recorded_by_role` (`principal` or `teammate`) and, for a teammate, `recorded_by_name` as the People list had it. Rows written before these columns existed read as the principal's (`_migrate` adds the columns on the first write; the read-only render tolerates a DB that has none).\n- **One active fact per subject.** A new row supersedes any active row with the same folded subject key, or the id named in `replaces_fact_id`, in one transaction. The old row stays as `superseded` (with `superseded_by`), and the new one is stored as a `correction` carrying what it replaced. Retiring sets `retired` with a reason. **The principal outranks a teammate:** a teammate's write that would replace an active fact the principal set (by subject or `replaces_fact_id`) raises `PrincipalFactConflict`, and the tool stores it as `proposed` instead, naming the fact it would replace (`replaces_fact_id`); teammates replace each other's facts freely, and the principal replaces anyone's. **\"Needs my approval\"** (`fact_approval_rules`, per teammate, **on by default**, set only by the principal) stores every fact from that teammate as `proposed`; the principal turns it off for a teammate they trust, whose facts then apply at once (except one that would replace the principal's). The rule is read inside `record_fact`'s own write transaction, so a switch turned on a moment earlier cannot let one fact through; a teammate write that names no person is never trusted. One teammate may have at most `MAX_PENDING_PROPOSALS_PER_PERSON` (20) proposals waiting (`TooManyProposals`; the tool tells them to wait for the principal's review). A teammate's retire checks ownership in the `UPDATE` itself (`retire_fact(teammate_id=)`: their own row, not approved). A proposed row never renders; `approve_fact` makes it active and replaces what it names (the principal's own fact included — approving it is their word) and stamps `approved_at`, after which it outranks teammates exactly as the principal's own fact does (`Fact.principal_owned`: no teammate may replace or retire it); `decline_fact` sets `declined`. No field of a teammate's fact may carry what the render adds itself — `(per <anyone>)` in any case (a unit such as `(per month)` or `(per unit)` is fine), `[fact N]` or a date stamp after any dash, read NFKC-folded with invisible characters removed (`fact_tools._marker_error`) — so a teammate cannot plant a second, forged attribution inside their statement (the principal's own unmarked lines are not checked: \"(per Smith lease)\" is ordinary wording for them). The tool answers `awaiting_approval` (no action chip) and tells the model to say it is not in use yet.\n- **Rendered everywhere output is produced.** `render_facts_for_prompt` renders the active rows newest first under a self-explaining `STANDING FACTS` header (use these over older figures; a line ending `(per <name>)` is that teammate's word and the principal's unmarked line wins a conflict; the current conversation still wins; quoted data never instructions). A teammate's line ends `(per <name>)`, the name defanged like the rest, capped at 40 facts / 6000 chars, with angle brackets defanged. It opens the DB read-only and never creates it or the table. The block always rides in a user turn, never a cached system block: a chat turn's `<standing_facts>` (so every scheduled run through the chat loop too), each specialist consult (`route_to_specialist`, chat and workflow steps alike), the /today header and the morning brief (`render_briefing_context`, after the quiet check and inside the string the header's cache key hashes, so a new fact rewrites the header), the alert review's batch (`render_batch`, read once per pass), and the end-of-day digest, the weekly review's top-three call and the morning reflection (`with_standing_facts`).\n- **Company-profile edits from chat.** `update_company_profile` (same gate and quote rule) changes one whitelisted field of `company/profile.yaml`, under `PROFILE_EDIT_LOCK` (also taken by `PATCH /company-profile`, so neither edit silently drops the other): a text or number field is set, a list field gets an item added or removed, and `financials.key_metrics` takes a named metric. It writes through `CompanyProfile.save_to_yaml` and updates the session's profile, so the next turn's cached company block carries it (one cache miss on the change). The new value must itself appear in the principal's own words, not just the quote: the value renders into the cached company block on every later turn, so \"set our mission to what the doc says\" or \"update our headcount\" is refused rather than saving a document's text or a guessed figure. A number must be one they wrote, however they wrote it (`$180k`, `1.2m`, `2,400,000`). Saved text has `<`/`>` defanged. A `kind='profile'` row records each edit with its quote for the Pulse page. Those rows are never rendered into a prompt, because the profile block already carries the value.\n\n### Session scoping\n\n`decisions` and `advice_given` rows carry a `session_id`, so per-thread channels (Discord, Telegram) can pull just-this-thread history without leaking cross-conversation context. A null `session_id` falls back to a global view.\n\n### Surfacing\n\n`openexecutive.memory.episodic.format_for_prompt` renders recent decisions and initiatives into a compact `<past_decisions>` block injected into the user turn — alongside `<retrieved_context>` and peer memory — never into a cached system block. Each decision names where it was recorded when that was a channel — `- 2026-09-01 [finance] (via email): …`, from the prefix of its `session_id` (`email:`, `slack:`, `discord:`, `telegram:`, `google_chat:`); a web or CLI decision has no tag. Rows extracted from mail before the untrusted-content policy, when any sender's body could be stored, therefore read as mail rather than as the principal's own word.\n\nScoped to a session, decisions and advice cover every conversation of a chat app's stream (`memory.conversation_ids.family_clause`): a Telegram chat or a DM is cut into conversations after two quiet hours or a /new (`memory.conversations`), and what an earlier conversation decided still renders in the next.\n\nThe chat route also injects a `<briefing>` block into the same user turn: a compact digest of the current open (unread) alerts, built by `openexecutive.briefing.context.format_open_alerts_for_prompt` (company-wide, `status=\"unread\"`, mirroring `/today`). This is what lets the Executive discuss a briefing item the principal clicked or named on `/today` (e.g. \"Gulf Coast Port Cyberattack\"). It is resolved in parallel with the other context fetches, omitted when there are no open alerts, and never placed in a cached system block.\n\nOn the Pulse page the Memory section shows the three lists as Decisions, Initiatives and Advice tabs, then a **Corrections** tab (`GET /memories/facts`: active standing facts and profile edits with their quote, channel and — for a teammate's — their name; proposals first under \"Waiting for your approval\" with **Approve** / **Decline** for the principal; the replaced, retired and declined history folded away; **Retire** on any fact for the principal and on their own not-yet-approved one for a teammate; and, for the principal, a per-teammate \"needs my approval\" switch), and a **History** tab for the person's own Always in the loop notes (see below). The header's Memories tile counts the three lists. What peer memory has learned about the signed-in person is theirs alone, so it is not on Pulse: it is on **Settings → About you** (see the peer memory section).\n\nThe same user turn carries a `<drive_memory>` block when the conversation has touched Google Drive (`openexecutive.memory.drive_reads`). Drive is reached only as live Google Workspace calls inside a turn and history keeps only prose, so without it a file found one turn was gone the next. `MCPGateway.call_tool` hands each `search_drive_files` and `get_drive_file_content` result to `record_drive_result`, which keeps, per session, every file found or opened (file id, name, type, link, and for an opened file its first 600 characters) and every search that matched nothing, with its query. `format_drive_memory` lists the 20 most recent files, so \"the file you found earlier\" resolves to a file id the Executive reopens rather than searching again, and the queries that found nothing (dropped once the same query later finds something). Rows are keyed on the session *and* the speaker, and shown only to that speaker in that session, because one session can span several people (an email thread, a Slack or Discord thread). Nothing is recorded or shown without a bound `current_session` and a rostered speaker, on a turn private to the principal, or on one that touched the speaker's own mailbox (Act as me). workspace-mcp writes file names into its output unescaped, so a name containing a newline can forge a result line. Only a Drive-shaped file id, type and `docs`/`drive.google.com` link are therefore kept; any other line is dropped, and the name is always quoted as the file's own content, not instructions. Each speaker keeps at most 100 files and 100 searches per session, older rows are pruned on write, and `session_store.delete_session` drops them all.\n\nA conversation can also become its owner's alone. When Act as me first reads the speaker's own mailbox in it, `session_store.mark_mail_private` sets `sessions.mail_private` (creating the row with its owner when a channel adapter hasn't written it yet), and from then on only the session's owner may open, continue or delete it — the principal included, when it is a team member's (`chat._session_access`). It is never cleared. Beside it `sessions.mail_read_at` keeps how many history messages the conversation held before the last turn that read the mail (`session_store.mail_read_at`; NULL on rows marked before the column): Act as me's hold on links and scripts in later turns lasts only while that turn is still in the history window (see Act as me). \n\nThe chat list has owner controls on the same row: `sessions.pinned_at` (pinned chats list first) and `sessions.title_locked` (set by `rename_session`, after which `update_session_title`, the automatic title, leaves the name alone). Chats are also grouped by topic for their owner (`memory/chat_topics.py`): a `chat_topics(id, owner_person_id, name, kept, pinned_at, created_at)` row per topic, unique per owner and name (any case), and `sessions.topic_id` with `sessions.topic_source` (NULL = not looked at, `auto` = chosen by the model, `owner` = filed by the owner and never refiled). The one utility-fast call that titles a new chat (`utils/chat_topics.name_chat`, from the web chat and the chat-app conversations) also picks its topic, reusing one of the owner's 60 most recent topic names or making a new one. Only when the owner alone has written in the chat: a channel or group conversation, a shared chat, or one where someone else wrote first is titled without the owner's topic names in the prompt (another writer could steer the title into repeating them) and is filed later by the backfill, whose answer only the owner sees. Each call is bounded by the utility-fast timeout (60 s for a backfill batch). Only a turn that makes a new topic costs a second short call, over the topic names alone, which merges it into an existing topic that means the same unless the owner has `kept` it (renamed, pinned, merged into or filed a chat under it). Chats from before, or whose naming failed, are filed from their titles in batches of 80 the first time the owner opens the Topic view (`backfill`; a failure waits 10 minutes). Topics left with no chat are dropped when listed. A `session_shares(session_id, person_id, shared_by_person_id, created_at)` row adds one team member to someone's chat (`list_shared_with_person`, `set_shares`, `leave_share`): they read and write in it with its owner, each of their messages saved with their own `sender_person_id`; a `mail_private` chat is never shared or opened that way, and deleting the chat drops its shares. `last_turn_sender` says who wrote the last turn, which is how redo stays with the person who asked. The chat list's preview puts `You:` only before the caller's own words. `rewind_last_turn` deletes a web chat's last turn (the last reply and the user messages after the reply before it) so it can be asked again; the next turn's history is re-read from these rows, so nothing else needs clearing. A search that matched nothing also gains a note in its tool result: say the exact query and that it found nothing, never that the file does not exist. This is a first step: Drive is still not indexed into the company collection.\n\n### System of record\n\nSQL is the system of record; the peer-memory service is a recall layer mirrored from it, not a replacement. When `store_decision` / `store_initiative` / `store_advice` insert a row whose `department` is non-empty and not `\"general\"`, the row is mirrored as a kind-tagged note into that department's peer via `append_department_note`. The mirror fires only after a successful INSERT, is fire-and-forget, and never rolls back the SQL row on peer-memory failure. `scheduled_actions` is never mirrored — it is a queue, not memory.\n\nThe episodic extractor still learns only from the principal's own words. Commitments and asks from everyone else on the roster are tracked as **open loops** (see Attunement) — `scheduled_actions` rows with `kind='open_loop'`, opened and closed by a separate quote-gated pass after each attributed turn. That pass depends on `chat_messages.sender_person_id`, which records who actually wrote each persisted user message. An open loop counts toward `list_awaiting_replies_by_person` only once it is due, and `list_scheduled_actions(exclude_internal=True)` filters `__internal__` rows in SQL so readers that want real sends are not starved by them. `mark_outbound_context_consumed` also resolves the Attunement outcome row for that DM as `replied` — a matched reply is the clearest sign proactive outreach landed — and a real change to an existing initiative (`store_initiative` / `update_initiative`, new status or summary) marks the updater's own check-in nudges `acted` — an update with no known updater, such as `PATCH /memories/initiatives/{id}`, credits nobody.\n\n### Workspace settings\n\nThe same database holds one row of settings that are not memory: `workspace_settings` (`openexecutive.memory.workspace_settings`) — the install's mode (`team` by default, or `solo` for one person using Open Executive just for themselves), the user's IANA time zone, the principal's role (`PrincipalRole`: `role_kind`, `role_title`, `reports_to`, `remit`, `measured_on`, all nullable; only solo mode reads it), and the company's own email domains (`company_domains`, a JSON list, or NULL to derive them from the principal's primary address — `people.identity` matches a teammate by local part on them; `validate_company_domains` lowercases, dedupes and sorts, allows at most 10 plain DNS names and refuses a free-mail provider's, and a stored value that no longer validates reads as NULL). It is a table of its own rather than a company-profile field because onboarding rebuilds the profile from scratch. Every read is fresh and read-only (a missing file or table reads as the defaults; a table from before the role or `company_domains` columns reads them as unset and is migrated additively by the next init or write). A read error (a locked database, say) also reads as the defaults, so `get_workspace` then says team; `read_stored_mode` is the strict read of the mode alone — None when the row cannot be read or holds no valid mode — for the scheduler's weekly-review check, which must not take a failed read for team. A session may carry an explicit `workspace_mode` override; otherwise the mode is read fresh at the start of each turn and pinned on the session for that turn only (`Session.turn_workspace_mode`, via `pin_turn_workspace_mode`), so every tool handler in the turn sees the mode its persona and tools were built in. `effective_workspace_mode` reads override, then the pin, then the setting; `effective_principal_role` reads a session's `principal_role` override, then the role pinned for the turn (`Session.turn_principal_role`, via `pin_turn_principal_role`), then the stored role. See Org for what solo changes and Scheduler for the time zone.\n\n### Act as me\n\n`initialize_db` also creates Act as me's per-person tables (`delegation.schema.ensure_schema`): `delegation_settings`, `delegation_voice` and `delegation_voice_history`. They hold a setting and a writing profile rather than memory, and nothing in them is mirrored to peer memory. A turn that touched the speaker's own mailbox teaches no memory: the episodic, open-loop and working-style passes are skipped along with the Honcho peer and department syncs, since its reply quotes a draft built from other people's mail. See **Act as Me (Delegation)**.\n\n### Always in the loop (notes of what you said)\n\nA person can keep private, dated notes of what they said, in chat with the Executive and in email replies it drafted for them: what they promised, agreed, declined, answered, asked for or shared. The switch is per person (\"Keep track of what happens\", `history_person_settings.reply_notes`, off by default, one switch for every channel). Any team member on the People list may turn it on (`history.can_keep_notes`: kind `team`, not archived, the principal included); Act as me isn't needed, though notes from email replies only come through it.\n\n- **Where notes come from: chat.** After each chat turn, on both the single-voice and the committee path, the Executive's post-turn block calls `memory.history_chat.schedule_chat_notes` next to the open-loop and style passes, except on a turn that touched the speaker's mailbox. It reads only what the speaker typed this turn (`delegation.settings.own_words`: no backstory an adapter added, nothing when a file came with it), never the reply and never anyone else's message: every channel calls the Executive with the one speaker's message, and what other people say to each other is never read. It runs only for a speaker the turn verified (`history_chat.verified_speaker`): the turn's `caller_person_id` is them, nobody started it by email or runs it unattended or for them, and the surface proved who they are (the web chat signed in or a local install, the principal or a team member on their own Slack or Discord, a private Telegram chat behind a valid webhook secret, or a channel whose adapter verified the sender itself and set `Session.speaker_verified`). A shared Slack or Discord thread counts: the notes stay private and are read back only where nobody else can see them. A message under 40 characters is skipped, and each person gets at most 40 passes a day, counted in `history_chat_passes` so the cap holds across workers and restarts. The pass uses a constant `CHAT_PROMPT` (requests to the assistant, questions and small talk are not notes), the same `record_notes` tool and the same `check_note` gate with the message as both body and allowed words; the note's channel is the inbound channel or `web`, its conversation the session id, and it names no counterpart.\n- **Where notes come from: email.** After `delegation.reply_send` sends a reply, it starts `memory.history_notes.note_sent_reply` in the background. The note-taker reads only the words the person sent (`email_poller.sender_new_text` strips quoted mail) and the recipients' names, cut to four words of name characters (`history_notes.short_name`): never the mail being answered, nor the subject, which others in the thread write too, so nothing another person wrote can become a note. One forced `record_notes` call with a constant prompt and no other tools returns at most three notes. Code then drops any note that says more than they did: the `quote` must appear word for word in what they sent, every figure in the summary must be in the quote, every name or date word must be in what they sent or the recipients' names, at least half its other content words must be theirs, the summary carries no link or address, and a `due_date` is kept only for something promised or agreed. Notes record events, never instructions, and carry `trust = high` because they rest on the person's own words.\n- **Whose they are.** Every note is private to its person (`visibility = private`). Nobody else reads it, the principal included; there is no shared note.\n- **How long they last.** The company default is 90 days (`history_settings.retention_days`, the principal's choice of 30, 90, 365 or until forgotten). A person may only choose a shorter time; shortening the company time clamps everyone's choice and re-dates live notes. A pinned note never expires; unpinning restarts its clock, and a later retention change counts from there. Reads skip expired notes and the scheduler's alert sweep deletes them (`history.sweep_expired`).\n- **What a person controls.** Through `/memories/history` they read, search, pin, correct and forget their own notes. On the Pulse page this is the **History** tab, last in the Memory section and shown only to someone with notes to see (signed in and on the People list): each note shows its kind, who it was with, the date, the person's own words, any due date and when it will be forgotten, and its menu holds **Correct** (a side panel; \"Use the original\" clears a correction), **Pin**, **Don't remember this** and **Forget**. \"Don't remember this\" forgets every note from that conversation and adds it to `history_excluded`, so it is never noted again. Settings → **Memory** holds the switch (\"Keep track of what happens\") and a shorter time for their own notes, and the company time, which the principal changes and everyone else reads. A chat note shows the channel alone (\"Slack\", \"Web chat\").\n- **Recall.** `recall_history` (`orchestrator.history_tools`) is offered only on a turn where the speaker may read their notes: verified as above, a team member who may keep notes, in a conversation private to them (`history_chat.private_chat`: the web chat, a Slack or Discord DM, a Telegram chat, or one its adapter marked `Session.private_chat`), with their switch on. Before any note is read the turn is set `touched_mail`, for the principal too, so its rows are private to the speaker, it teaches no memory and the mail lockdown holds from that round on. The conversation is also marked theirs alone (`session_store.mark_mail_private`), so every later turn in it is private the same way (the lockdown is that turn's alone) and, for a team member, the principal can't open it; recall refuses if that can't be stored. Notes come back in a `<history_notes>` block as history to cite: the date, the person's own words first, then how they were noted. With `due: true` it lists only notes with a due date, from a week overdue to two weeks ahead, soonest first (\"what's due today?\").\n- **In the owner's briefs.** The morning brief adds a FROM YOUR NOTES — DUE SOON block (`memory.history_brief.due_soon_block`: what the owner promised, agreed or asked of someone, from a week overdue to a week ahead, in the workspace's local dates) and the end-of-day digest a FROM YOUR NOTES — TODAY block (`noted_today_block`: what they promised, agreed, asked or declined since the last digest, then what is due tomorrow). Both only on the scheduler's delivery to the owner alone (`morning_brief.PRINCIPAL_DELIVERY`), never a run started from chat, whose tool result lands in the turn's shared audit row and peer memory; only when the owner may keep notes and has the switch on (`history_brief.owner_keeping_notes`), and only the owner's own notes. A run that used any is marked `private_to_principal`, so the shared run history keeps `PRIVATE_RUN_ARTIFACT` instead of its text, and the note ids with their state (overdue, today, soon) enter the brief's fingerprint, so one falling due un-suppresses an unchanged brief. Teammates get no brief, so their notes reach them only through recall and reminders.\n- **In Act as me drafts.** The ghostwriter gets a `<writer_noted>` block (`memory.history_drafts.notes_for_draft`): the writer's own notes from earlier Act as me replies that every recipient of the new draft was on, with their switch on. It keeps the draft consistent with them and turns a contradiction into an open question on the card; it never adds anything from them (see Act as me).\n- **Due-today reminders.** `memory.history_reminders.maybe_remind`, called from the scheduler tick every 15 minutes between 09:00 and 18:00 local time, sends each person with the switch on one message on a day something they promised or agreed to by email (`source = approved_reply`) falls due. Chat promises are left to open loops, which the nudge engine already chases. The message says only how many things are due, never what or to whom, and the channel senders' audit rows for it are private to the person (`audit.context.rows_for_person`; the owner's `private_rows`), which also keeps the send off the shared activity rail (`_record_send_to_activity` skips a send whose rows are private). The person asks \"what's due today?\" in a private conversation and `recall_history` answers. It goes to their own Slack or Discord DM, a private Telegram chat (`delivery_order` skips a negative group id, for the owner's briefs too) or their own email (`scheduler.runner.deliver_to_person`), never a shared channel. `history_reminders` holds one row per person per day, claimed before sending and never released, so two workers never both send and a half-failed send is never repeated; a failed one waits for the next due day.\n- **Not peer memory.** Notes never reach Honcho, episodic extraction, standing facts or another person's turn. The tables (`history_notes`, `history_settings`, `history_person_settings`, `history_excluded`, `history_chat_passes`, `history_reminders`, created by `history_schema.ensure_schema` from `initialize_db`) swap with a client slot and are cleared by a factory reset.\n\n### Conversation review (fixing what replies left undone)\n\n`memory.chat_review` looks back over a chat once it has been quiet `CHAT_REVIEW_QUIET_MINUTES` (30) and fixes what the replies left undone: \"I sent it\" answered with \"noted\" and the draft still waiting, \"drop that reminder\" answered with \"sure\" and the reminder still set. The claim check (`orchestrator.claim_check`, see Lifecycle) catches a false claim in the same turn; this catches the rest.\n\n- **What is recorded.** On both the single-voice and the committee path the post-turn block calls `record_turn` with the speaker's own words (`delegation.settings.own_words`), the reply and the tools the turn ran (`_stream_agent_loop(calls_out=)`). Only a verified speaker's turn is kept: the principal on a surface `people_tools` verifies, or a rostered teammate on their own signed-in web chat, Slack or Discord. A channel whose adapter set `Session.speaker_verified` counts as a verified surface here too; an email, an unattended run, a turn private to the principal, one that touched the speaker's mailbox and a message with an attachment are never kept. Rows live in `chat_review_turns` for 7 days, a turn graded a miss (below) for `MISS_KEEP_DAYS` (90); each row also keeps the audit `turn_id` of the turn, so the claim check's row can be joined back to it.\n- **When.** Each kept turn makes sure one `chat_review` `__internal__` action is waiting for the conversation (`channel_ref` = session id), due 30 minutes on. The runner marks it done and calls `run_scheduled`, which schedules a fresh one if a newer turn arrived meanwhile, else reviews the oldest unreviewed turns (at most 20, the rest in a review right after) and marks exactly those reviewed, so a chat is read in parts and never twice. `CHAT_REVIEW_MAX_PER_DAY` (10) caps each person's passes a day (`chat_review_days`), so one person's chats can't use up another's.\n- **The pass.** One small tool loop per person on `CHAT_REVIEW_MODEL` (default `ROUTING_MODEL`), at most 5 rounds and 8 changes, in its own task with a session rebuilt from the recorded surface and caller and a delegation pin holding their words, so each tool runs through the chat tool's own handler and checks: `list_open_loops` / `close_open_loop`, `remember_fact`, `list_followups` / `cancel_followup` / `move_followup`, `leave_out_of_brief`, plus `learn_reply_style` (a working-style rule), `learn_writing_style` (a habit or avoid line in their Act as me voice profile, only for someone who may use it) and `raise_in_brief` (one line for the next brief). Every change carries `source_quote` of at least four of the person's own words (`fact_tools._quote_error`), and the thing it changes (the loop's or follow-up's text, the fact, the brief item or line) must share two words with what they wrote (its only one, for a one-word target) A chat draft's state is left to the brief's own check of the mailbox's Drafts. The replies are shown as `<untrusted_content>` (they quote mail and documents) and tool results not at all, only the tools' names. `leave_out_of_brief` and `raise_in_brief` are the principal's only; dropping a fact and changing a goal are left to chat. It never sends, books, deletes or grants permission to act, and nothing it does is said in chat. One `chat_review` audit row per pass lists the changes.\n- **Grading (looking back at how it went).** Before the fix loop, the same pass grades each turn it reads with one forced-tool call (`grade_turns`) on the review model. The grader sees what the fix loop sees plus one SIGNALS line per turn, joined from where the product already records them (`turn_signals`): a 👍/👎 and its note on the saved reply (`chat_messages`, matched to the recorded reply by its first 120 characters, which also gives the Reflection screen the reply's `message_id`), a reply the person stopped (`stopped`), a turn they took back to ask again (a `session_rewound` audit row after a turn whose reply is no longer in the chat), a claim the reply made that no tool backed (a `claim_check` audit row with the turn's `turn_id`), and a tool whose recorded result reads as an error. Per turn it records `fine`, `miss` or `unclear`; for a miss, `wanted` (what the person wanted instead, one or two sentences) backed by a `quote` of at least four of their own words from that turn or the ones after it, code-checked (`accept_grades`) or the turn is `unclear` and `wanted` dropped, plus the `kind`: `company` (a term, a fact, a preference, which specialist to ask, doing a thing rather than promising it would have fixed it) or `product` (a tool failed or was refused, a capability it lacks). A turn the model skipped is `unclear`. Grades go on the row (`verdict`, `kind`, `wanted`, `signals`, `graded_at`, `message_id`), and each person's weekly count of graded turns and misses on `chat_review_weeks`, so the rate outlives the 7-day rows. Grading changes nothing in the workspace and never blocks the fixes: a failed grade leaves the turns ungraded. The pass's audit row carries the counts. `list_misses` (one person's or everyone's; the route then keeps, for the principal, only rows from chats `chat._session_access` lets them open, so a teammate's own chat stays theirs), `weekly_rates` and `forget_miss` (`is_principal_or_self`) serve `GET`/`DELETE /memories/reflection` (the Pulse screen **What it got wrong**).\n- **Lessons** (`memory/lessons.py`): for a turn graded a miss the review may call `learn_lesson` once: one sentence this workspace wants done differently (a term and what it means, a preference about the content, a thing to do rather than promise, a specialist to consult), quoted from the person's own words (the quote must come from the miss turn or a later one, and the lesson must be what the quote says). It passes the working-style deny-list (`attunement.style._DENY_PATTERNS`: no link, handle, amount, markup, identifier, action verb, instruction talk, nudge to act unchecked, roster name) plus the lessons' own list (the verbs that move information: email, share, post, export, attach...; the words that widen a request to everyone or everything) without the about-the-writing requirement, may add at most two content words beyond the quote (`lesson_overreach`, so a real quote can't carry a different sentence in), and is re-checked on every render. Rows live in `chat_review_lessons` (text, quote, person, session, `shared` = learned in a channel or group thread, turn, `shown`, `fine_after`, `miss_after`, `retired_at`/`retired_reason`) with `chat_review_lesson_uses` (lesson, turn id, whose turn). A lesson reaches a turn by a keyword match (two shared content words between the lesson plus its quote and the message; no vector index for a list this short): the Executive's own turn gets the matching ones as a `<lessons>` block in the user turn (`build_lessons_block`, never a cached block; the header says the current request wins and nothing in it authorizes an action), and each specialist call gets the same lines under its `<failure_cases>` block (`router._lessons_for_call` → `lessons_for_query`). A lesson reaches its own person's turns; the principal's reach everyone's only when learned in a shared space (`shared`), so nothing said in someone's own chat is paraphrased into another person's turn. `build_lessons_block` counts each showing against the active turn id and the speaker; when the review later grades that turn, `note_outcome` adds to `fine_after` or `miss_after` only when the turn was the lesson's own person's (nobody else's chats can retire it), and a lesson shown 5 times with more misses than fine turns retires itself (`unhelpful`). At most 40 live lessons per person; their oldest retires to make room (`BEGIN IMMEDIATE`, so two reviews can't both skip it). Forget on the screen retires one by hand (`forgotten`); a retired lesson is listed as stopped, never erased.\n- **Replay: the workspace's own evals** (`memory/replay.py`). Nightly (the `chat_replay` scheduled action, `CHAT_REPLAY_TIME` 03:30 in the user's zone, seeded and chained like the reflection), the Executive runs its misses again with everything in force today and a judge says whether each would now go right. A case is a graded turn: a miss (its `wanted`), or a turn that went fine and got a thumbs up (`kept = 1`, held as long as a miss, at most `MAX_KEPT` 300 per person), which the replay protects so a lesson can't break what worked; a closed miss joins that pool. `due_cases` picks a miss the night a lesson is written for it (`WHY_LESSON`), when a lesson learned since the last night reaches it (`WHY_REACHED`), else once a week (`WHY_WEEKLY`), from the last 30 days only and at most `CHAT_REPLAY_MAX_CASES` (30) a night within `CHAT_REPLAY_MINUTES` (20); 20 protected cases (`WHY_PROTECT`, rotated by last replay) run only on a night a new lesson landed. `replay_case` runs `Executive.chat` on a session rebuilt from the recorded surface and speaker (`chat_review._rebuild_session`) with the saved conversation up to that turn (`chat_messages` before the reply's `message_id`), flagged `Session.replay`: reads run for real through every gate, and every tool a read-only turn is denied (`MCP_CLIENT_WITHHELD_TOOLS`, and gateway calls outside `MCP_CLIENT_MCP_TOOLS`) returns \"done\" and lands in `Session.replay_calls` instead (`faked_handlers` / `faked_call_tool`, wrapped outermost in the agent loop); scripts, Python jobs, `load_mcp_server`, Act as me's tools, `recall_history` and extension tools are not offered at all; nothing a replay does is kept (no extraction, open loops, style, notes, review or Honcho mirror, and `build_lessons_block(count=False)` counts no showing). The judge (`CHAT_REPLAY_JUDGE_MODEL`, else `EVAL_JUDGE_MODEL`, else Sonnet; `evals.judges.judge_message`) reads the original date, the person's words and the conversation before, what they wanted (or the reply they liked), today's reply and the recorded actions, and answers `{passed, time_bound, notes}`, intent and action rather than figures; an unreadable answer is a fail. The gate (`_settle`): a miss that passes is `closed` with `closed_at`; a time-bound one becomes `evidence` and is not replayed again; a lesson for a miss that still fails on `LESSON_FAILS` (2) judged replays after it was learned retires (`replay`); a protected case that fails reopens a closed miss and counts a strike against each new lesson of the same person that reached it (a teammate's turn never retires the principal's shared lessons), which retires at `PROTECT_FAILS` (2) such strikes, so one judged turn, or one message written to fail the judge, is not enough. A case that didn't run (an error, the `CASE_SECONDS` timeout) is recorded with `ran = 0` and settles nothing. The judge's input is scrubbed like outside content (`content_trust._scrub`) with the prompt's own tag names renamed inside it. Every replay is a `chat_review_replays` row (the reply and recorded calls; dropped with its turn when a miss or chat is forgotten or purged, `chat_review._prune_replays`) and a `chat_review` audit row (actor `chat_replay`); each night a `chat_review_replay_runs` row, written before the first case (so a second runner sees nothing new) and filled in after, which is also what \"new since the last night\" means. The nightly Executive carries the scheduler's MCP gateway, so the reads a miss needs run as they did. The Reflection screen's number, \"of the N things that went wrong in the last 30 days, M would go right today\" (`summary_for`, over the misses the caller sees), and each miss's last replay come from these columns on `chat_review_turns` (`replay_state`, `replayed_at`, `closed_at`, `replay_count`, `replay_notes`). Off with `CHAT_REPLAY_ENABLED=false` or when the review itself is off.\n\n## Decision ledger\n\n`openexecutive.memory.decision_ledger` keeps one `decision_instances` row per gated action — a meeting the Executive proposes to book, an Act as me reply card — with how it was resolved, so each class has a reliability record. Every status change is a compare-and-set. A tap with an outside effect (sending an email) claims the row first (`claim_for_execution`, proposed → executing), so of two taps only one acts, and finishes it as `approved_unchanged`, `approved_with_edit` or `failed`, or hands it back (`release_claim`). A row whose class acted on its own with nobody tapping — `gate_mode` `auto_execute`, as Act as me's **Handle it for me** replies are — finishes as `executed` instead, with no resolver, so a reliability read never counts it as an approval. A send whose result is unclear stays `executing` for a reconciler and is never retried. A row still waiting can have its payload changed only by compare-and-set (`update_open_payload`, on `proposed` and, when given, on the payload as it was read): that is how an Act as me reply card takes the person's edit, or records the draft made for it at Send.","mermaid": "flowchart TD\n Store[\"store_decision / store_initiative / store_advice\"]\n DB[\"episodic_memory.db<br/>decisions / initiatives<br/>advice_given / scheduled_actions\"]\n Fmt[\"format_for_prompt\"]\n Turn[\"User turn<br/>past_decisions block\"]\n Mirror[\"append_department_note\"]\n Peer[\"Department peer<br/>(Honcho)\"]\n Store --> DB\n DB --> Fmt\n Fmt --> Turn\n Store -->|\"dept set & not general\"| Mirror\n Mirror -->|\"fire-and-forget\"| Peer\n Tool[\"remember_fact / update_company_profile<br/>(principal, verified, quoted)\"]\n Facts[\"facts table<br/>active / superseded / retired\"]\n Every[\"STANDING FACTS block<br/>chat, specialists, briefs,<br/>alert review, workflows\"]\n Tool --> Facts\n Facts -->|\"render_facts_for_prompt\"| Every\n class Store entry\n class DB storage\n class Fmt compute\n class Turn hot\n class Peer external\n\n class Tool entry\n class Facts storage\n class Every hot",- "generated_at": "2026-10-16T21:00:00Z"+ "generated_at": "2026-10-17T14:32:47.334379+00:00"}diff --git a/packages/core/openexecutive/guide/prebuilt/chat.json b/packages/core/openexecutive/guide/prebuilt/chat.jsonindex 202ba210..344e9123 100644--- a/packages/core/openexecutive/guide/prebuilt/chat.json+++ b/packages/core/openexecutive/guide/prebuilt/chat.json@@ -1,7 +1,7 @@{"section_id": "chat","title": "Chat & Briefing",- "markdown": "**What it is:** Where you talk to the Executive in plain language. The app opens on **Home**, a quick read of what's happened across the company and what needs you, and you drop into a chat whenever you want to ask or decide something. Every conversation is kept on the **Chats** page.\n\n**What it does:**\n\n- Hold a natural conversation with the Executive, which quietly pulls in whichever specialists a question needs.\n- Keep every chat with its full history, so you can pick up where you left off.\n- Attach files to a message: up to 5 per message, 20 MB each (PNG, JPEG, GIF and WebP images, PDF, Word, text, Markdown, CSV). The Executive reads them for that message.\n- Stop a reply while it is still coming. Whatever has been written is kept and marked *Stopped by you*. (Escape works too.)\n- Add to a reply while it works: type and send, and your message joins the answer in progress (*Sent while it works*, then *👀 Seen, taking it into this answer*).\n- Redo your last turn in a web chat: **Try again** under the last reply asks the same question again, and **Edit** under your last message lets you change it. Sending an edit replaces that message and its answer.\n- Turn on **Committee review** for a question that matters: a slower pass where reviewers challenge the draft answer before you see it.\n- Continue any item on Home straight into a chat thread, with the context already filled in.\n- Choose **Show agent activity** in the **⋯** menu at the top right to watch what's happening behind a reply: which specialists were consulted and which tools ran.\n- See what an answer drew on: click **Sources (N)** under a reply to list the documents and web pages it looked at (your own documents, the built-in knowledge and any web pages), with links where there are any.\n- Copy a reply with **Copy**, and rate it with 👍 (**Helpful**) or 👎 (**Not helpful**).\n\n**How to use:**\n\n1. Click **New chat** at the top of the sidebar (on a phone, the **+** in the middle of the bar at the bottom), or type into the **Ask your Executive anything…** box on Home. Click **Home** any time to get back.\n2. Type your question and press **Enter** to send. **Shift + Enter** starts a new line. When the box is empty, a greyed-out suggested follow-up may appear; press **Tab** or **→** to use it (on a phone, tap **Use suggestion**).\n3. To include a file, click the **+** next to the message box, choose **Attach files or photos** and pick up to 5 files. Drag-and-drop isn't supported in chat. Attachments are read for that message only. To make a document permanently available, add it on the **Knowledge** page.\n4. For a decision that matters, click the **+** next to the message box and choose **Committee review (slower, reviewed)** before sending. A **Committee review on** chip appears above the box. It stays on for each message you send until you click the chip (or choose **Turn off committee review** in the **+** menu). While it works you see *Drafting → Committee review → Revising*.\n5. Changed your mind mid-answer? Click the stop button (next to the message box while a reply is streaming) or press **Esc**.\n6. In an open chat, the **⋯** menu at the top right has **Pin** / **Unpin**, **Rename**, **Share**, **Download** and **Show agent activity**. Deleting is on the **Chats** page.\n7. If part of an answer couldn't be completed (say, the finance side), you still get the rest, with a short note under it. Ask again to fill in the missing part.\n8. When something you asked for needs your approval (a meeting the Executive set up for you to approve, or actions it suggested from your email), its card appears right under the reply: **Approve**, **Edit** (for a meeting: its title, start and end) and **Dismiss**. After **Approve** a meeting's card says *Booked. It's on your calendar.* The same card also waits under **Needs you** on Today until you answer it in either place. Saying *ok* in the chat doesn't book it; tap **Approve**. Things the Executive raises on its own come only to Today.\n\n**Chats page:** click **Chats** in the sidebar (on a phone, **Chats** in the bar at the bottom). It lists every conversation you own: web chats and the ones that came in through Slack, Telegram, Discord, Email and Google Chat. You only see your own chats here, plus the ones someone shared with you.\n\n- **Channel tabs:** **All** and **Web** are always there. A tab for Slack, Telegram, Discord, Email or Google Chat appears once you have a chat from it. Each tab shows its count. Chats from other channels carry the channel's name on the row.\n- **Groups:** chats are grouped into **Pinned**, **Today**, **Yesterday**, **Previous 7 Days**, **Previous 30 Days** and **Older** (collapsed until you click it). Each group shows 20 chats, then **Show N more**. Each row shows the title, when it was last active and how many messages it has.\n- **Search:** type in **Search titles and messages**. It searches the titles and message text of your own chats (up to 50 results). Each result shows *title match* or how many messages matched, with a snippet that highlights your words. Open a result found in its messages and the chat shows a bar with *match 1 of N* and arrows to step through the matches. Search does not cover chats shared with you.\n- **Row ⋯ menu** (your own chats): **Pin** / **Unpin**, **Rename**, **Share**, **Download** and **Delete chat**.\n - **Pin** moves the chat to the **Pinned** group at the top. Only you see your pins.\n - **Rename** gives the chat a name (up to 120 characters). The automatic title never replaces a name you set.\n - **Download** saves the whole chat as a Markdown (.md) file: each message under who wrote it (the person's name or *Executive*), with each reply's sources listed under it.\n - **Delete chat** asks *Delete this chat? This cannot be undone.* Deleting removes the chat and its messages from Open Executive and ends any sharing of it. Messages in Slack, Telegram or Discord stay in those apps.\n- **New chat** at the top right starts a new web chat.\n\n**Sharing a chat:**\n\n- **Who you can share with:** team members on your **People** list. Contacts, archived people and yourself are not offered. If no one else is on your team, the panel says *There's no one else on your team to share with yet.*\n- **How:** in an open chat, choose **Share** in the **⋯** menu or the **Share** button in the bar above the conversation; on the **Chats** page, the chat's row **⋯** menu has **Share** too. The panel *Share this chat with:* says *They join the chat and can write in it with you.* and lists your team with a checkbox each. Tick the people, then click **Save**. It confirms *Shared.* Only the chat's owner can share it. There is no share link: access goes to the named people only.\n- **What they get:** they join the chat and write in it with you. It appears on their **Chats** page under **Shared with you**, with *<your name> added you* and when. They are not notified. Their row **⋯** menu has **Download** and **Leave chat**.\n- **Working in it together:** a bar above the conversation shows everyone's initials and *You and <name>* (or *You and N others*). Each person's message shows their name; your own stay on the right. The Executive sees who wrote each message and answers whoever wrote the latest. Everyone with the chat open sees a new message and the Executive's reply as it is written, and *<name> is typing…* above the message box. One turn runs at a time: while the Executive answers someone else, the box says *The Executive is answering <name>…* and Send waits. A chat left open in a background tab catches up when you come back to it.\n- **What only the owner can do:** rename, pin, rate replies (👍/👎), share, delete. **Try again** and **Edit** work only on your own last message, and not for the people you shared with. They don't see your ratings or your pin.\n- **What stays out of a shared chat:** everyone in it reads every reply, so it is not a private conversation. **Act as me** is off there, the Executive won't read anyone's own mail there, and your private items on Today (your mail, people waiting on you, new senders) are not brought into it.\n- **Sending from a shared chat:** once someone else writes in it, the Executive's next reply won't send email, message people, post to the company or a department, book or cancel meetings, set follow-ups, run or schedule workflows or change contacts, even when that reply is to the chat's owner. It says so, and the owner can ask again in their following message.\n- **Which chats can't be shared:** a chat in which the Executive read or drafted in your own mailbox (**Act as me**) stays yours alone. Saving a share on it fails with *This chat read your own mail, so it stays yours alone.* If a chat you already shared later reads your mail, it disappears from everyone's **Shared with you** list and they can no longer open it. This can't be undone. A conversation from Slack, Telegram, Discord, Email or Google Chat can't be shared: *Only a chat started here can be shared.*\n- **Leaving and removing:** someone you shared with can leave from the **Leave** button in the bar or **Leave chat** in the row menu; you can add them again. To remove people, open **Share**, untick them and click **Save** (with nobody ticked it says *Not shared with anyone.*). Someone removed, or who leaves, sees *You're no longer in this chat.* and later *This chat isn't shared with you any more.* if they open it. Archiving someone on **People** takes them out of every chat. Deleting the chat ends it for everyone (*This chat was deleted.*).\n- **Records:** each change to who is in a chat, including someone leaving, is written to the audit log.\n\n**Example prompts:**\n\n- \"Here's our Q3 board deck. What questions should I expect from the board?\" *(with the PDF attached)*\n- \"Should we raise prices 10% for new customers? I want the finance and marketing view.\" *(with Committee review on)*\n- \"What changed across the company this week that I should know about?\"\n\n*Tip: this is the front door. Almost everything else in the app is something the Executive references or acts on from here.*",+ "markdown": "**What it is:** Where you talk to the Executive in plain language. The app opens on **Home**, a quick read of what's happened across the company and what needs you, and you drop into a chat whenever you want to ask or decide something. Every conversation is kept on the **Chats** page.\n\n**What it does:**\n\n- Hold a natural conversation with the Executive, which quietly pulls in whichever specialists a question needs.\n- Keep every chat with its full history, so you can pick up where you left off.\n- Attach files to a message: up to 5 per message, 20 MB each (PNG, JPEG, GIF and WebP images, PDF, Word, text, Markdown, CSV). The Executive reads them for that message.\n- Stop a reply while it is still coming. Whatever has been written is kept and marked *Stopped by you*. (Escape works too.)\n- Add to a reply while it works: type and send, and your message joins the answer in progress (*Sent while it works*, then *👀 Seen, taking it into this answer*).\n- Redo your last turn in a web chat: **Try again** under the last reply asks the same question again, and **Edit** under your last message lets you change it. Sending an edit replaces that message and its answer.\n- Turn on **Committee review** for a question that matters: a slower pass where reviewers challenge the draft answer before you see it.\n- Continue any item on Home straight into a chat thread, with the context already filled in.\n- Choose **Show agent activity** in the **⋯** menu at the top right to watch what's happening behind a reply: which specialists were consulted and which tools ran.\n- See what an answer drew on: click **Sources (N)** under a reply to list the documents and web pages it looked at (your own documents, the built-in knowledge and any web pages), with links where there are any.\n- Copy a reply with **Copy**, and rate it with 👍 (**Helpful**) or 👎 (**Not helpful**).\n\n**How to use:**\n\n1. Click **New chat** at the top of the sidebar (on a phone, the **+** in the middle of the bar at the bottom), or type into the **Ask your Executive anything…** box on Home. Click **Home** any time to get back.\n2. Type your question and press **Enter** to send. **Shift + Enter** starts a new line. When the box is empty, a greyed-out suggested follow-up may appear; press **Tab** or **→** to use it (on a phone, tap **Use suggestion**).\n3. To include a file, click the **+** next to the message box, choose **Attach files or photos** and pick up to 5 files. Drag-and-drop isn't supported in chat. Attachments are read for that message only. To make a document permanently available, add it on the **Knowledge** page.\n4. For a decision that matters, click the **+** next to the message box and choose **Committee review (slower, reviewed)** before sending. A **Committee review on** chip appears above the box. It stays on for each message you send until you click the chip (or choose **Turn off committee review** in the **+** menu). While it works you see *Drafting → Committee review → Revising*.\n5. Changed your mind mid-answer? Click the stop button (next to the message box while a reply is streaming) or press **Esc**.\n6. In an open chat, the **⋯** menu at the top right has **Pin** / **Unpin**, **Rename**, **Share**, **Download** and **Show agent activity**. Deleting is on the **Chats** page.\n7. If part of an answer couldn't be completed (say, the finance side), you still get the rest, with a short note under it. Ask again to fill in the missing part.\n8. When something you asked for needs your approval (a meeting the Executive set up for you to approve, or actions it suggested from your email), its card appears right under the reply: **Approve**, **Edit** (for a meeting: its title, start and end) and **Dismiss**. After **Approve** a meeting's card says *Booked. It's on your calendar.* The same card also waits under **Needs you** on Today until you answer it in either place. Saying *ok* in the chat doesn't book it; tap **Approve**. Things the Executive raises on its own come only to Today.\n\n**Chats page:** click **Chats** in the sidebar (on a phone, **Chats** in the bar at the bottom). It lists every conversation you own: web chats and the ones that came in through Slack, Telegram, Discord, Email and Google Chat. You only see your own chats here, plus the ones someone shared with you.\n\n- **Channel tabs:** **All** and **Web** are always there. A tab for Slack, Telegram, Discord, Email or Google Chat appears once you have a chat from it. Each tab shows its count. Chats from other channels carry the channel's name on the row.\n- **Groups:** chats are grouped into **Pinned**, **Today**, **Yesterday**, **Previous 7 Days**, **Previous 30 Days** and **Older** (collapsed until you click it). Each group shows 20 chats, then **Show N more**. Each row shows the title, when it was last active and how many messages it has.\n- **Date or Topic:** the **Date** / **Topic** switch beside the search box changes how the list is grouped, and the page remembers your choice. **Topic** groups your chats by what they are about (a hire, a customer, a project), whichever app they came from. Every new chat is filed under a topic when it gets its title. The first time you open **Topic**, your earlier chats are grouped from their titles, and the page says *Grouping your earlier chats by topic…* until that's done. **Pinned** stays at the top. A topic with only one chat, and chats with no lasting topic, go under **Other** (collapsed until you click it).\n- **Topic ⋯ menu:** **Rename topic**, **Merge into…** (moves its chats into another topic), **Pin topic** / **Unpin topic** and **Ungroup** (its chats stay, under **Other**). Renaming a topic to the name of another one merges them. Only you see your topics.\n- **Search:** type in **Search titles and messages**. It searches the titles and message text of your own chats (up to 50 results). Each result shows *title match* or how many messages matched, with a snippet that highlights your words. Open a result found in its messages and the chat shows a bar with *match 1 of N* and arrows to step through the matches. Search does not cover chats shared with you.\n- **Row ⋯ menu** (your own chats): **Pin** / **Unpin**, **Rename**, **Move to topic**, **Share**, **Download** and **Delete chat**.\n - **Move to topic** files the chat under one of your topics, a new one, or **No topic**. Your choice sticks: the Executive never moves that chat again, and a topic you renamed, pinned or moved a chat into is never merged on its own.\n - **Pin** moves the chat to the **Pinned** group at the top. Only you see your pins.\n - **Rename** gives the chat a name (up to 120 characters). The automatic title never replaces a name you set.\n - **Download** saves the whole chat as a Markdown (.md) file: each message under who wrote it (the person's name or *Executive*), with each reply's sources listed under it.\n - **Delete chat** asks *Delete this chat? This cannot be undone.* Deleting removes the chat and its messages from Open Executive and ends any sharing of it. Messages in Slack, Telegram or Discord stay in those apps.\n- **New chat** at the top right starts a new web chat.\n\n**Sharing a chat:**\n\n- **Who you can share with:** team members on your **People** list. Contacts, archived people and yourself are not offered. If no one else is on your team, the panel says *There's no one else on your team to share with yet.*\n- **How:** in an open chat, choose **Share** in the **⋯** menu or the **Share** button in the bar above the conversation; on the **Chats** page, the chat's row **⋯** menu has **Share** too. The panel *Share this chat with:* says *They join the chat and can write in it with you.* and lists your team with a checkbox each. Tick the people, then click **Save**. It confirms *Shared.* Only the chat's owner can share it. There is no share link: access goes to the named people only.\n- **What they get:** they join the chat and write in it with you. It appears on their **Chats** page under **Shared with you**, with *<your name> added you* and when. They are not notified. Their row **⋯** menu has **Download** and **Leave chat**.\n- **Working in it together:** a bar above the conversation shows everyone's initials and *You and <name>* (or *You and N others*). Each person's message shows their name; your own stay on the right. The Executive sees who wrote each message and answers whoever wrote the latest. Everyone with the chat open sees a new message and the Executive's reply as it is written, and *<name> is typing…* above the message box. One turn runs at a time: while the Executive answers someone else, the box says *The Executive is answering <name>…* and Send waits. A chat left open in a background tab catches up when you come back to it.\n- **What only the owner can do:** rename, pin, rate replies (👍/👎), share, delete. **Try again** and **Edit** work only on your own last message, and not for the people you shared with. They don't see your ratings or your pin.\n- **What stays out of a shared chat:** everyone in it reads every reply, so it is not a private conversation. **Act as me** is off there, the Executive won't read anyone's own mail there, and your private items on Today (your mail, people waiting on you, new senders) are not brought into it.\n- **Sending from a shared chat:** once someone else writes in it, the Executive's next reply won't send email, message people, post to the company or a department, book or cancel meetings, set follow-ups, run or schedule workflows or change contacts, even when that reply is to the chat's owner. It says so, and the owner can ask again in their following message.\n- **Which chats can't be shared:** a chat in which the Executive read or drafted in your own mailbox (**Act as me**) stays yours alone. Saving a share on it fails with *This chat read your own mail, so it stays yours alone.* If a chat you already shared later reads your mail, it disappears from everyone's **Shared with you** list and they can no longer open it. This can't be undone. A conversation from Slack, Telegram, Discord, Email or Google Chat can't be shared: *Only a chat started here can be shared.*\n- **Leaving and removing:** someone you shared with can leave from the **Leave** button in the bar or **Leave chat** in the row menu; you can add them again. To remove people, open **Share**, untick them and click **Save** (with nobody ticked it says *Not shared with anyone.*). Someone removed, or who leaves, sees *You're no longer in this chat.* and later *This chat isn't shared with you any more.* if they open it. Archiving someone on **People** takes them out of every chat. Deleting the chat ends it for everyone (*This chat was deleted.*).\n- **Records:** each change to who is in a chat, including someone leaving, is written to the audit log.\n\n**Example prompts:**\n\n- \"Here's our Q3 board deck. What questions should I expect from the board?\" *(with the PDF attached)*\n- \"Should we raise prices 10% for new customers? I want the finance and marketing view.\" *(with Committee review on)*\n- \"What changed across the company this week that I should know about?\"\n\n*Tip: this is the front door. Almost everything else in the app is something the Executive references or acts on from here.*","mermaid": null,- "generated_at": "2026-10-16T16:18:07.478970+00:00"+ "generated_at": "2026-10-17T14:37:21.820135+00:00"}diff --git a/packages/core/openexecutive/integrations/conversations.py b/packages/core/openexecutive/integrations/conversations.pyindex bcc44fbb..4ff1d0e7 100644--- a/packages/core/openexecutive/integrations/conversations.py+++ b/packages/core/openexecutive/integrations/conversations.py@@ -73,16 +73,18 @@ async def _title(session_id: str, user_text: str, reply: str) -> None:get_session_metadata,update_session_title,)- from openexecutive.utils.session_title import generate_session_title+ from openexecutive.utils.chat_topics import name_chatmeta = await asyncio.to_thread(get_session_metadata, session_id)# Only a conversation's first exchange names it; later turns and a title- # someone already gave it are left alone.+ # someone already gave it are left alone. Naming also files it under a+ # topic on its owner's Chats page.if meta is None or int(meta.get("message_count") or 0) != 2:return- title = await generate_session_title(user_text, reply) or first_line_title(user_text)- if title:- await asyncio.to_thread(update_session_title, session_id, title)+ if not await name_chat(session_id, user_text, reply):+ title = first_line_title(user_text)+ if title:+ await asyncio.to_thread(update_session_title, session_id, title)def title_after_turn(session_id: str, user_text: str, reply: str) -> None:diff --git a/packages/core/openexecutive/memory/chat_topics.py b/packages/core/openexecutive/memory/chat_topics.pynew file mode 100644index 00000000..b7659bb7--- /dev/null+++ b/packages/core/openexecutive/memory/chat_topics.py@@ -0,0 +1,300 @@+"""Topics that group one person's chats on their Chats page.++A chat's topic is chosen by the model when the chat is named+(``utils.chat_topics``), and the owner can move a chat, rename, pin, merge or+ungroup a topic. What the owner does sticks: a chat they filed+(``topic_source = 'owner'``) is never retagged, and a topic they touched+(``kept``) is never merged away by the tidy.+"""+from __future__ import annotations++import re+from datetime import UTC, datetime+from pathlib import Path+from typing import Any++from openexecutive.memory.episodic import DB_PATH, _get_conn++# Longest topic name kept; the model is asked for two to four words.+MAX_TOPIC_CHARS = 40+# Topics shown to the model when it picks one: the ones used most recently.+PROMPT_TOPICS = 60+++def clean_topic_name(raw: str | None) -> str | None:+ """One line, no quotes or end punctuation, capped. None when nothing is+ left, or the model said no topic fits."""+ if not raw:+ return None+ name = re.sub(r"\s+", " ", raw).strip().strip("\"'").rstrip(".!?,:;").strip()+ name = "".join(c for c in name if c.isprintable())[:MAX_TOPIC_CHARS].strip()+ if not name or name.lower() in {"none", "-", "n/a", "other"}:+ return None+ return name+++def _now() -> str:+ return datetime.now(UTC).isoformat()+++def topic_names(owner: int, db_path: Path = DB_PATH) -> list[str]:+ """The owner's topic names, most recently used first, for the prompt."""+ with _get_conn(db_path) as conn:+ rows = conn.execute(+ """+ SELECT t.name FROM chat_topics t+ LEFT JOIN sessions s ON s.topic_id = t.id+ WHERE t.owner_person_id = ?+ GROUP BY t.id+ ORDER BY MAX(COALESCE(s.updated_at, t.created_at)) DESC+ LIMIT ?+ """,+ (owner, PROMPT_TOPICS),+ ).fetchall()+ return [str(r["name"]) for r in rows]+++def _topic_id(conn: Any, owner: int, name: str, kept: bool) -> tuple[int, bool]:+ # OR IGNORE: the backfill and a new chat's naming may make the same+ # topic at once; the second just finds the first's.+ made = conn.execute(+ "INSERT OR IGNORE INTO chat_topics (owner_person_id, name, kept, created_at) "+ "VALUES (?, ?, ?, ?)",+ (owner, name, 1 if kept else 0, _now()),+ ).rowcount > 0+ row = conn.execute(+ "SELECT id FROM chat_topics WHERE owner_person_id = ? AND name = ?",+ (owner, name),+ ).fetchone()+ if kept and not made:+ conn.execute("UPDATE chat_topics SET kept = 1 WHERE id = ?", (row["id"],))+ return int(row["id"]), made+++def set_auto_topic(+ session_id: str,+ owner: int,+ name: str | None,+ db_path: Path = DB_PATH,+ *,+ only_untagged: bool = False,+) -> tuple[int | None, bool]:+ """File a chat under the model's topic (made if new; None = none fits).+ A chat the owner filed is left as it is, and with ``only_untagged`` so is+ any chat already filed. Returns the topic id and whether+ the topic was just made; (None, False) when nothing changed or none fits.+ One transaction, so a list running meanwhile never drops the new topic+ as empty."""+ with _get_conn(db_path) as conn:+ row = conn.execute(+ "SELECT topic_source FROM sessions WHERE session_id = ? AND caller_person_id = ?",+ (session_id, owner),+ ).fetchone()+ if row is None or row["topic_source"] == "owner":+ return None, False+ # The backfill fills only chats still waiting: a new chat's own naming+ # may have filed it while the batch call ran.+ if only_untagged and row["topic_source"] is not None:+ return None, False+ topic_id, made = _topic_id(conn, owner, name, False) if name else (None, False)+ conn.execute(+ "UPDATE sessions SET topic_id = ?, topic_source = 'auto' WHERE session_id = ?",+ (topic_id, session_id),+ )+ return topic_id, made+++def file_session(+ session_id: str,+ owner: int,+ *,+ topic_id: int | None = None,+ name: str | None = None,+ db_path: Path = DB_PATH,+) -> bool:+ """The owner puts their chat under one of their topics (by id, or by a+ name, made if new) or under none. Kept so. False when the topic id isn't+ theirs."""+ with _get_conn(db_path) as conn:+ if name:+ topic_id, _ = _topic_id(conn, owner, name, True)+ elif topic_id is not None:+ if conn.execute(+ "SELECT 1 FROM chat_topics WHERE id = ? AND owner_person_id = ?",+ (topic_id, owner),+ ).fetchone() is None:+ return False+ conn.execute("UPDATE chat_topics SET kept = 1 WHERE id = ?", (topic_id,))+ conn.execute(+ "UPDATE sessions SET topic_id = ?, topic_source = 'owner' WHERE session_id = ?",+ (topic_id, session_id),+ )+ return True+++def topic_id_by_name(owner: int, name: str, db_path: Path = DB_PATH) -> int | None:+ with _get_conn(db_path) as conn:+ row = conn.execute(+ "SELECT id FROM chat_topics WHERE owner_person_id = ? AND name = ?",+ (owner, name),+ ).fetchone()+ return int(row["id"]) if row is not None else None+++def owned_topic(owner: int, topic_id: int, db_path: Path = DB_PATH) -> dict[str, Any] | None:+ with _get_conn(db_path) as conn:+ row = conn.execute(+ "SELECT id, name, kept, pinned_at FROM chat_topics WHERE id = ? AND owner_person_id = ?",+ (topic_id, owner),+ ).fetchone()+ return dict(row) if row is not None else None+++def list_topics(owner: int, db_path: Path = DB_PATH) -> list[dict[str, Any]]:+ """The owner's topics that hold a chat: pinned first, then by their+ newest chat. Topics left empty (their chats deleted or moved) go."""+ with _get_conn(db_path) as conn:+ conn.execute(+ "DELETE FROM chat_topics WHERE owner_person_id = ? AND id NOT IN "+ "(SELECT topic_id FROM sessions WHERE topic_id IS NOT NULL)",+ (owner,),+ )+ rows = conn.execute(+ """+ SELECT t.id, t.name, t.kept, t.pinned_at, COUNT(s.session_id) AS chat_count,+ MAX(s.updated_at) AS updated_at+ FROM chat_topics t JOIN sessions s ON s.topic_id = t.id+ WHERE t.owner_person_id = ? AND s.caller_person_id = ?+ GROUP BY t.id+ ORDER BY t.pinned_at IS NULL, t.pinned_at DESC, updated_at DESC+ """,+ (owner, owner),+ ).fetchall()+ out: list[dict[str, Any]] = []+ for r in rows:+ item: dict[str, Any] = {+ "id": int(r["id"]),+ "name": str(r["name"]),+ "kept": bool(r["kept"]),+ "chat_count": int(r["chat_count"]),+ }+ if r["pinned_at"]:+ item["pinned_at"] = r["pinned_at"]+ out.append(item)+ return out+++def rename_topic(owner: int, topic_id: int, name: str, db_path: Path = DB_PATH) -> int | None:+ """Rename the owner's topic. A name another of their topics has merges+ this one into it. Returns the topic the chats are under now, None when+ there is no such topic."""+ if owned_topic(owner, topic_id, db_path) is None:+ return None+ with _get_conn(db_path) as conn:+ other = conn.execute(+ "SELECT id FROM chat_topics WHERE owner_person_id = ? AND name = ? AND id != ?",+ (owner, name, topic_id),+ ).fetchone()+ if other is not None:+ merge_topics(owner, topic_id, int(other["id"]), db_path)+ with _get_conn(db_path) as conn:+ conn.execute("UPDATE chat_topics SET kept = 1 WHERE id = ?", (other["id"],))+ return int(other["id"])+ with _get_conn(db_path) as conn:+ conn.execute(+ "UPDATE chat_topics SET name = ?, kept = 1 WHERE id = ?", (name, topic_id)+ )+ return topic_id+++def keep_topic(owner: int, topic_id: int, db_path: Path = DB_PATH) -> None:+ with _get_conn(db_path) as conn:+ conn.execute(+ "UPDATE chat_topics SET kept = 1 WHERE id = ? AND owner_person_id = ?",+ (topic_id, owner),+ )+++def pin_topic(owner: int, topic_id: int, pinned: bool, db_path: Path = DB_PATH) -> bool:+ with _get_conn(db_path) as conn:+ cur = conn.execute(+ "UPDATE chat_topics SET pinned_at = CASE WHEN ? THEN COALESCE(pinned_at, ?) END, "+ "kept = CASE WHEN ? THEN 1 ELSE kept END "+ "WHERE id = ? AND owner_person_id = ?",+ (1 if pinned else 0, _now(), 1 if pinned else 0, topic_id, owner),+ )+ return cur.rowcount > 0+++def merge_topics(owner: int, source_id: int, into_id: int, db_path: Path = DB_PATH) -> bool:+ """Move every chat under ``source_id`` to ``into_id`` and drop the+ source. Both must be the owner's. A chat keeps who filed it."""+ if source_id == into_id:+ return owned_topic(owner, into_id, db_path) is not None+ if owned_topic(owner, source_id, db_path) is None or owned_topic(owner, into_id, db_path) is None:+ return False+ with _get_conn(db_path) as conn:+ conn.execute("UPDATE sessions SET topic_id = ? WHERE topic_id = ?", (into_id, source_id))+ conn.execute("DELETE FROM chat_topics WHERE id = ?", (source_id,))+ return True+++def ungroup_topic(owner: int, topic_id: int, db_path: Path = DB_PATH) -> bool:+ """Drop the owner's topic; its chats go under no topic and stay there."""+ if owned_topic(owner, topic_id, db_path) is None:+ return False+ with _get_conn(db_path) as conn:+ conn.execute(+ "UPDATE sessions SET topic_id = NULL, topic_source = 'owner' WHERE topic_id = ?",+ (topic_id,),+ )+ conn.execute("DELETE FROM chat_topics WHERE id = ?", (topic_id,))+ return True+++def owner_only(session_id: str, owner: int, db_path: Path = DB_PATH) -> bool:+ """Whether only the owner has written in this chat and it is shared with+ no one, so a prompt may carry the owner's topic names and its title may+ show them: anyone else could steer the call into echoing them."""+ with _get_conn(db_path) as conn:+ if conn.execute(+ "SELECT 1 FROM session_shares WHERE session_id = ? LIMIT 1", (session_id,)+ ).fetchone() is not None:+ return False+ other = conn.execute(+ "SELECT 1 FROM chat_messages WHERE session_id = ? AND role = 'user' "+ "AND sender_person_id IS NOT NULL AND sender_person_id != ? LIMIT 1",+ (session_id, owner),+ ).fetchone()+ return other is None+++def has_untagged(owner: int, db_path: Path = DB_PATH) -> bool:+ """Whether any of the owner's chats with a message waits for a topic."""+ with _get_conn(db_path) as conn:+ row = conn.execute(+ """+ SELECT 1 FROM sessions s+ WHERE s.caller_person_id = ? AND s.topic_source IS NULL+ AND EXISTS (SELECT 1 FROM chat_messages m WHERE m.session_id = s.session_id)+ LIMIT 1+ """,+ (owner,),+ ).fetchone()+ return row is not None+++def untagged_sessions(owner: int, db_path: Path = DB_PATH) -> list[dict[str, str]]:+ """The owner's chats no one has looked at for a topic yet, newest first,+ leaving out ones with no message (a chat-app /new not used yet)."""+ with _get_conn(db_path) as conn:+ rows = conn.execute(+ """+ SELECT s.session_id, s.title FROM sessions s+ WHERE s.caller_person_id = ? AND s.topic_source IS NULL+ AND EXISTS (SELECT 1 FROM chat_messages m WHERE m.session_id = s.session_id)+ ORDER BY s.updated_at DESC+ """,+ (owner,),+ ).fetchall()+ return [{"session_id": str(r["session_id"]), "title": str(r["title"])} for r in rows]diff --git a/packages/core/openexecutive/memory/episodic.py b/packages/core/openexecutive/memory/episodic.pyindex 34aa502e..c19e83ca 100644--- a/packages/core/openexecutive/memory/episodic.py+++ b/packages/core/openexecutive/memory/episodic.py@@ -515,6 +515,40 @@ def initialize_db(db_path: Path | None = None) -> None:except sqlite3.OperationalError as exc:if "duplicate column" not in str(exc).lower():raise+ # Chat topics (memory/chat_topics.py): the topic a chat is grouped+ # under on its owner's Chats page, and who put it there. NULL source =+ # not looked at yet; 'auto' = the model chose (topic_id NULL = none+ # fits); 'owner' = the owner moved or ungrouped it, never retagged.+ if "topic_id" not in _sessions_existing:+ try:+ conn.execute("ALTER TABLE sessions ADD COLUMN topic_id INTEGER")+ except sqlite3.OperationalError as exc:+ if "duplicate column" not in str(exc).lower():+ raise+ if "topic_source" not in _sessions_existing:+ try:+ conn.execute("ALTER TABLE sessions ADD COLUMN topic_source TEXT")+ except sqlite3.OperationalError as exc:+ if "duplicate column" not in str(exc).lower():+ raise+ # One person's topics. `kept` = the owner named, pinned or filed a chat+ # under it, so it shows even with one chat and is never merged away.+ conn.execute(+ """+ CREATE TABLE IF NOT EXISTS chat_topics (+ id INTEGER PRIMARY KEY AUTOINCREMENT,+ owner_person_id INTEGER NOT NULL,+ name TEXT NOT NULL COLLATE NOCASE,+ kept INTEGER NOT NULL DEFAULT 0,+ pinned_at TEXT,+ created_at TEXT NOT NULL,+ UNIQUE (owner_person_id, name)+ )+ """+ )+ conn.execute(+ "CREATE INDEX IF NOT EXISTS idx_sessions_topic ON sessions(topic_id)"+ )# Who a chat's owner shared it with, to read (session_store.share_session).conn.execute("""diff --git a/packages/core/openexecutive/memory/session_store.py b/packages/core/openexecutive/memory/session_store.pyindex 1c6f7f2b..b4e1c1fc 100644--- a/packages/core/openexecutive/memory/session_store.py+++ b/packages/core/openexecutive/memory/session_store.py@@ -221,7 +221,7 @@ def list_sessions(rows = conn.execute("""SELECT s.session_id, s.title, s.created_at, s.updated_at, s.pinned_at,- COUNT(m.id) AS message_count, MAX(m.id) AS last_id+ s.topic_id, COUNT(m.id) AS message_count, MAX(m.id) AS last_idFROM sessions sLEFT JOIN chat_messages m ON m.session_id = s.session_idWHERE s.caller_person_id = ?@@ -255,6 +255,8 @@ def list_sessions(}if row["pinned_at"]:item["pinned_at"] = row["pinned_at"]+ if row["topic_id"] is not None:+ item["topic_id"] = row["topic_id"]msg = last.get(row["last_id"]) if row["last_id"] is not None else None# In a shared chat the last message may be a teammate's: no "You: ".mine = msg is not None and msg["sender_person_id"] in (None, caller_person_id)@@ -339,7 +341,7 @@ def search_sessions(with _get_conn(db_path) as conn:rows = conn.execute("""- SELECT s.session_id, s.title, s.created_at, s.updated_at,+ SELECT s.session_id, s.title, s.created_at, s.updated_at, s.topic_id,(SELECT COUNT(*) FROM chat_messages mWHERE m.session_id = s.session_id) AS message_count,(SELECT COUNT(*) FROM chat_messages m@@ -363,6 +365,8 @@ def search_sessions(for k in ("session_id", "title", "created_at", "updated_at","message_count", "match_count")}+ if row["topic_id"] is not None:+ item["topic_id"] = row["topic_id"]item["snippet"] = Noneif row["match_count"]:hit = conn.execute(@@ -402,7 +406,7 @@ def get_session_metadata(session_id: str, db_path: Path = DB_PATH) -> dict[str,row = conn.execute("""SELECT s.session_id, s.title, s.created_at, s.updated_at, s.pinned_at,- COUNT(m.id) AS message_count+ s.topic_id, COUNT(m.id) AS message_countFROM sessions sLEFT JOIN chat_messages m ON m.session_id = s.session_idWHERE s.session_id = ?@@ -415,6 +419,8 @@ def get_session_metadata(session_id: str, db_path: Path = DB_PATH) -> dict[str,meta = dict(row)if not meta.get("pinned_at"):meta.pop("pinned_at", None)+ if meta.get("topic_id") is None:+ meta.pop("topic_id", None)return metadiff --git a/packages/core/openexecutive/utils/chat_topics.py b/packages/core/openexecutive/utils/chat_topics.pynew file mode 100644index 00000000..1279d1f0--- /dev/null+++ b/packages/core/openexecutive/utils/chat_topics.py@@ -0,0 +1,296 @@+"""The model side of chat topics (store: ``memory.chat_topics``).++- ``name_chat``: a new chat's first exchange gets its title and its topic in+ the one utility-fast call that used to give only the title.+- ``tidy_new_topic``: when that call makes a new topic, one short call over+ the topic names alone checks it against the owner's other topics and merges+ it into one that means the same. No call on a turn that made no topic.+- ``backfill``: chats from before topics (or whose naming failed) are filed+ in batches, from their titles only, the first time the owner opens the+ Topic view.+"""+from __future__ import annotations++import asyncio+import contextlib+import logging+import re+import time+from typing import Any++from openexecutive.memory import chat_topics as store+from openexecutive.utils.session_title import clean_title++logger = logging.getLogger(__name__)++_NAME_SYSTEM = (+ "You name a chat thread and file it under a topic. Reply with exactly two "+ "lines and nothing else:\n"+ "Title: <a concise 4-6 word title>\n"+ "Topic: <topic>\n"+ "For Topic, reuse one of the person's existing topics, written exactly as "+ "listed, when the chat is about the same matter. Otherwise give a new "+ "2-4 word topic naming the matter (a project, deal, hire, customer, "+ "person or area of the business), broad enough that later chats about it "+ "fit too. Write none for small talk or a one-off question with no lasting "+ "matter."+)++_TIDY_SYSTEM = (+ "You keep a person's list of chat topics free of duplicates. You get one "+ "new topic and their other topics. If the new topic is about the same "+ "matter as one of the others, reply with that other topic exactly as "+ "listed. Otherwise reply none. Reply with the topic or none only."+)++_BACKFILL_SYSTEM = (+ "You file a person's chats under topics, from their titles. Reply with one "+ "line per chat, in the form <number>: <topic>, and nothing else. Reuse an "+ "existing topic, written exactly as listed, when a chat is about the same "+ "matter. Otherwise give a new 2-4 word topic naming the matter (a project, "+ "deal, hire, customer, person or area of the business), and put chats "+ "about the same matter under the same topic. Write none for small talk or "+ "a one-off question with no lasting matter."+)++# Titles per backfill call: a few thousand tokens in, one short line each out.+BACKFILL_BATCH = 80+# A batch's reply is longer than a title's, so it gets longer to come back.+BACKFILL_TIMEOUT_S = 60.0+# After a backfill fails, the Topic view doesn't start another for a while.+BACKFILL_RETRY_S = 600.0++_tasks: set[asyncio.Task[Any]] = set()+_backfilling: set[int] = set()+_backfill_failed_at: dict[int, float] = {}+++def _keep(task: asyncio.Task[Any]) -> None:+ _tasks.add(task)+ task.add_done_callback(_tasks.discard)+++def _topic_list(names: list[str]) -> str:+ return "\n".join(f"- {n}" for n in names) if names else "(none yet)"+++async def _ask(+ system: str, content: str, *, max_tokens: int, actor: str, timeout_s: float | None = None+) -> str:+ """One utility-fast call, bounded by ``timeout_s`` (default the+ utility-fast budget) so a hung call can't hold a background task."""+ from openexecutive.agents.utility_fast import get_fast_model+ from openexecutive.audit.usage import log_model_usage+ from openexecutive.config import get_settings+ from openexecutive.providers import get_provider++ model = get_fast_model()+ response = await asyncio.wait_for(+ get_provider(model).messages_create(+ model=model,+ max_tokens=max_tokens,+ system=system,+ messages=[{"role": "user", "content": content}],+ ),+ timeout=timeout_s or get_settings().utility_fast_timeout_s,+ )+ log_model_usage(response, model=model, actor=actor)+ return "".join(+ getattr(b, "text", "") for b in response.content if getattr(b, "type", "") == "text"+ ).strip()+++def parse_title_and_topic(raw: str) -> tuple[str | None, str | None]:+ """``Title: …`` / ``Topic: …`` lines. A reply without the labels is+ taken as a bare title, so a model that ignores the format still names+ the chat."""+ title: str | None = None+ topic: str | None = None+ for line in raw.splitlines():+ label, _, rest = line.partition(":")+ key = label.strip().lower()+ if key == "title" and title is None:+ title = clean_title(rest)+ elif key == "topic" and topic is None:+ topic = store.clean_topic_name(rest)+ if title is None and topic is None and raw.strip():+ title = clean_title(raw.strip().splitlines()[0])+ return title, topic+++async def _title_and_topic(+ user_msg: str, assistant_msg: str, names: list[str]+) -> tuple[str | None, str | None]:+ """The one call that names a chat: its title and its topic."""+ raw = await _ask(+ _NAME_SYSTEM,+ f"EXISTING TOPICS:\n{_topic_list(names)}\n\n"+ f"USER MESSAGE:\n{user_msg[:2000]}\n\n"+ f"EXECUTIVE RESPONSE:\n{assistant_msg[:2000]}",+ max_tokens=48,+ actor="session_title",+ )+ return parse_title_and_topic(raw)+++def _owner_only(session_id: str, owner: int) -> bool:+ from openexecutive.api.routes.chat import _shared_space++ try:+ return not _shared_space(session_id) and store.owner_only(session_id, owner)+ except Exception:+ logger.exception("name_chat: couldn't tell who wrote in the chat")+ return False+++async def name_chat(session_id: str, user_msg: str, assistant_msg: str) -> str | None:+ """Title a chat from its first exchange and file it under a topic.+ Returns the title (None when the call failed; the caller keeps its+ placeholder). A chat with no owner only gets a title."""+ from openexecutive.memory.session_store import get_session_owner, update_session_title+ from openexecutive.utils.session_title import generate_session_title++ # Two small indexed reads, done inline so the call starts on this step:+ # the stop path dispatches naming as a task and must see it under way.+ try:+ _, owner = get_session_owner(session_id)+ except Exception:+ logger.exception("name_chat: couldn't read the chat's owner")+ owner = None+ if owner is not None and not _owner_only(session_id, owner):+ # Someone else wrote here (a channel, a group, a shared chat): name it+ # without the owner's topics in the prompt, and leave filing to the+ # backfill, whose answer only the owner sees.+ owner = None+ if owner is None:+ title = await generate_session_title(user_msg, assistant_msg)+ if title:+ await asyncio.to_thread(update_session_title, session_id, title)+ return title+ try:+ names = store.topic_names(owner)+ title, topic = await _title_and_topic(user_msg, assistant_msg, names)+ except Exception:+ logger.exception("name_chat: failed")+ return None+ if title:+ await asyncio.to_thread(update_session_title, session_id, title)+ topic_id, made = await asyncio.to_thread(store.set_auto_topic, session_id, owner, topic)+ if made and topic_id is not None and len(names) > 0:+ with contextlib.suppress(RuntimeError): # no running loop+ _keep(asyncio.get_running_loop().create_task(tidy_new_topic(owner, topic_id)))+ return title+++async def tidy_new_topic(owner: int, topic_id: int) -> int | None:+ """Merge a just-made topic into one of the owner's others that means the+ same. Returns the topic it was merged into, if any. Leaves it alone once+ the owner has touched it (renamed, pinned, filed a chat under it)."""+ try:+ new = await asyncio.to_thread(store.owned_topic, owner, topic_id)+ if new is None or new["kept"]:+ return None+ others = [n for n in await asyncio.to_thread(store.topic_names, owner)+ if n.lower() != str(new["name"]).lower()]+ if not others:+ return None+ raw = await _ask(+ _TIDY_SYSTEM,+ f"NEW TOPIC: {new['name']}\n\nOTHER TOPICS:\n{_topic_list(others)}",+ max_tokens=24,+ actor="chat_topics",+ )+ match = store.clean_topic_name(raw.splitlines()[0] if raw else "")+ if not match:+ return None+ by_name = {n.lower(): n for n in others}+ if match.lower() not in by_name:+ return None++ def _merge() -> int | None:+ current = store.owned_topic(owner, topic_id)+ if current is None or current["kept"]:+ return None+ into_id = store.topic_id_by_name(owner, by_name[match.lower()])+ if into_id is None:+ return None+ return into_id if store.merge_topics(owner, topic_id, into_id) else None++ return await asyncio.to_thread(_merge)+ except Exception:+ logger.exception("tidy_new_topic: failed")+ return None+++_LINE = re.compile(r"^\s*(\d+)\s*[:.)\-]\s*(.*)$")+++def parse_backfill(raw: str, count: int) -> dict[int, str | None]:+ """``<number>: <topic>`` lines, 1-based, for numbers up to ``count``."""+ out: dict[int, str | None] = {}+ for line in raw.splitlines():+ m = _LINE.match(line)+ if not m:+ continue+ n = int(m.group(1))+ if 1 <= n <= count and n not in out:+ out[n] = store.clean_topic_name(m.group(2))+ return out+++def backfill_running(owner: int) -> bool:+ return owner in _backfilling+++def start_backfill(owner: int) -> bool:+ """Start filing the owner's untagged chats in the background, unless it+ is running already or failed a short while ago. True when it runs."""+ if owner in _backfilling:+ return True+ failed = _backfill_failed_at.get(owner)+ if failed is not None and time.monotonic() - failed < BACKFILL_RETRY_S:+ return False+ try:+ task = asyncio.get_running_loop().create_task(backfill(owner))+ except RuntimeError: # pragma: no cover - no running loop+ return False+ _backfilling.add(owner)+ task.add_done_callback(lambda _t: _backfilling.discard(owner))+ _keep(task)+ return True+++async def backfill(owner: int) -> int:+ """File the owner's untagged chats, newest first, a batch per call.+ Returns how many were filed. A failed call stops the run (the rest wait+ for the next one); a chat the reply skips is filed under no topic, so it+ isn't asked about again."""+ filed = 0+ try:+ pending = await asyncio.to_thread(store.untagged_sessions, owner)+ for at in range(0, len(pending), BACKFILL_BATCH):+ batch = pending[at:at + BACKFILL_BATCH]+ names = await asyncio.to_thread(store.topic_names, owner)+ titles = "\n".join(f"{i}. {c['title'][:120]}" for i, c in enumerate(batch, start=1))+ raw = await _ask(+ _BACKFILL_SYSTEM,+ f"EXISTING TOPICS:\n{_topic_list(names)}\n\nCHATS:\n{titles}",+ max_tokens=16 * len(batch) + 32,+ actor="chat_topics",+ timeout_s=BACKFILL_TIMEOUT_S,+ )+ picks = parse_backfill(raw, len(batch))++ def _file(batch: list[dict[str, str]] = batch, picks: dict[int, str | None] = picks) -> int:+ n = 0+ for i, chat in enumerate(batch, start=1):+ store.set_auto_topic(chat["session_id"], owner, picks.get(i), only_untagged=True)+ n += 1+ return n++ filed += await asyncio.to_thread(_file)+ _backfill_failed_at.pop(owner, None)+ except Exception:+ _backfill_failed_at[owner] = time.monotonic()+ logger.exception("chat_topics.backfill: failed owner=%s", owner)+ return fileddiff --git a/packages/core/openexecutive/utils/session_title.py b/packages/core/openexecutive/utils/session_title.pyindex ace0527d..b66663b2 100644--- a/packages/core/openexecutive/utils/session_title.py+++ b/packages/core/openexecutive/utils/session_title.py@@ -64,14 +64,18 @@ async def generate_session_title(getattr(b, "text", "") for b in response.contentif getattr(b, "type", "") == "text").strip()- if not raw:- return None- cleaned = raw.strip().strip('"').strip("'").rstrip(".!?,:;").strip()- cleaned = re.sub(r"\s+", " ", cleaned).strip()- cleaned = "".join(c for c in cleaned if c.isprintable())- if not cleaned:- return None- return cleaned[:max_len]+ return clean_title(raw, max_len=max_len)except Exception:logger.exception("generate_session_title: failed")return None+++def clean_title(raw: str, *, max_len: int = 60) -> str | None:+ """A model's title as one printable line, without quotes or end+ punctuation, capped at ``max_len``. None when nothing is left."""+ cleaned = raw.strip().strip('"').strip("'").rstrip(".!?,:;").strip()+ cleaned = re.sub(r"\s+", " ", cleaned).strip()+ cleaned = "".join(c for c in cleaned if c.isprintable())+ if not cleaned:+ return None+ return cleaned[:max_len]diff --git a/packages/core/tests/conftest.py b/packages/core/tests/conftest.pyindex cbc5056d..cfb36eca 100644--- a/packages/core/tests/conftest.py+++ b/packages/core/tests/conftest.py@@ -147,3 +147,18 @@ def _no_artifact_indexing(monkeypatch: pytest.MonkeyPatch):"openexecutive.orchestrator.artifact_tools._knowledge_store", lambda: None)yield++[email protected](autouse=True)+def _chat_topics_title_only(monkeypatch: pytest.MonkeyPatch):+ """Naming a chat (utils.chat_topics.name_chat) asks for its title and+ topic in one call. Route it through session_title.generate_session_title,+ looked up at call time, so a test's stub of that keeps naming the chat+ and nothing reaches the provider; no topic is filed.+ test_chat_topics.py restores the real call."""+ from openexecutive.utils import chat_topics, session_title++ async def _title_only(user_msg: str, assistant_msg: str, names: list[str]):+ return await session_title.generate_session_title(user_msg, assistant_msg), None++ monkeypatch.setattr(chat_topics, "_title_and_topic", _title_only)diff --git a/packages/core/tests/unit/test_chat_topics.py b/packages/core/tests/unit/test_chat_topics.pynew file mode 100644index 00000000..84f397d9--- /dev/null+++ b/packages/core/tests/unit/test_chat_topics.py@@ -0,0 +1,377 @@+"""Chat topics: the store (memory/chat_topics.py), the model side+(utils/chat_topics.py: naming, tidy, backfill) and the routes+(api/routes/sessions.py)."""+from __future__ import annotations++import asyncio+import time+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 chat as chat_route+from openexecutive.api.routes import sessions as sessions_route+from openexecutive.memory import chat_topics as store+from openexecutive.memory import episodic, session_store+from openexecutive.people import store as people_store+from openexecutive.utils import chat_topics as model++ALEX = {"x-caller-email": "[email protected]"} # principal+SABIN = {"x-caller-email": "[email protected]"}++[email protected](autouse=True)+def _quiet(monkeypatch: pytest.MonkeyPatch) -> None:+ chat_route._sessions.clear()+ chat_route._session_starters.clear()+ monkeypatch.setattr("openexecutive.audit.log_event", lambda *_a, **_k: None)+ model._backfilling.clear()+ model._backfill_failed_at.clear()+++def db(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:+ monkeypatch.chdir(tmp_path)+ db_path = Path("./episodic_memory.db").resolve()+ monkeypatch.setattr(episodic, "DB_PATH", db_path)+ monkeypatch.setattr(session_store, "DB_PATH", db_path)+ monkeypatch.setattr(people_store, "DB_PATH", tmp_path / "people.db")+ episodic.initialize_db(db_path)+ people_store.initialize_db()+ return db_path+++def people(db: Path) -> dict[str, int]:+ return {+ "alex": people_store.upsert_person(full_name="Alex", is_principal=True, email="[email protected]"),+ "sabin": people_store.upsert_person(full_name="Sabin", email="[email protected]"),+ }+++def client(monkeypatch: pytest.MonkeyPatch) -> Iterator[TestClient]:+ monkeypatch.delenv("BACKEND_SHARED_SECRET", raising=False)+ app = FastAPI()+ app.include_router(sessions_route.router)+ # One event loop for the whole test, as a server has, so the backfill a+ # request starts keeps running after it answers.+ with TestClient(app) as c:+ yield c+++class _Model:+ """Stands in for the utility-fast call: replies in order, records prompts."""++ def __init__(self, *replies: str) -> None:+ self.replies = list(replies)+ self.calls: list[dict[str, Any]] = []++ async def __call__(+ self, system: str, content: str, *, max_tokens: int, actor: str, timeout_s: float | None = None+ ) -> str:+ self.calls.append({"system": system, "content": content, "actor": actor})+ if not self.replies:+ raise RuntimeError("no reply scripted")+ return self.replies.pop(0)+++def fake(monkeypatch: pytest.MonkeyPatch) -> _Model:+ """The real naming call (conftest routes it through the title stub),+ over a scripted model."""+ m = _Model()+ monkeypatch.setattr(model, "_ask", m)+ monkeypatch.setattr(model, "_title_and_topic", _REAL_TITLE_AND_TOPIC)+ return m+++_REAL_TITLE_AND_TOPIC = model._title_and_topic+++def _chat(owner: int, sid: str, title: str = "Placeholder", at: str = "2026-10-01T09:00:00+00:00") -> str:+ session_store.create_session(sid, title, at, caller_person_id=owner)+ session_store.save_message(sid, "user", "question", sender_person_id=owner)+ session_store.save_message(sid, "assistant", "answer")+ with episodic._get_conn() as conn:+ conn.execute("UPDATE sessions SET updated_at = ? WHERE session_id = ?", (at, sid))+ return sid+++def _topic_of(sid: str) -> tuple[int | None, str | None]:+ with episodic._get_conn() as conn:+ row = conn.execute("SELECT topic_id, topic_source FROM sessions WHERE session_id = ?", (sid,)).fetchone()+ return row["topic_id"], row["topic_source"]+++# ── parsing ──────────────────────────────────────────────────────────────+++def test_title_and_topic_lines_are_read() -> None:+ assert model.parse_title_and_topic('Title: "Acme renewal terms."\nTopic: Acme renewal') == (+ "Acme renewal terms", "Acme renewal",+ )+ assert model.parse_title_and_topic("Title: Quick hello\nTopic: none") == ("Quick hello", None)+ # A model that ignores the format still names the chat.+ assert model.parse_title_and_topic("Board deck numbers") == ("Board deck numbers", None)+++def test_backfill_lines_are_read() -> None:+ picks = model.parse_backfill("1: Hiring a sales lead\n2) none\n3. Acme renewal\n9: Out of range\njunk", 3)+ assert picks == {1: "Hiring a sales lead", 2: None, 3: "Acme renewal"}+++def test_topic_names_are_cleaned() -> None:+ assert store.clean_topic_name(" 'Cash and runway.' ") == "Cash and runway"+ assert store.clean_topic_name("None") is None+ assert store.clean_topic_name("x" * 80) == "x" * store.MAX_TOPIC_CHARS+++# ── naming a new chat ────────────────────────────────────────────────────+++def test_a_new_chat_gets_a_title_and_reuses_a_topic(people: dict[str, int], fake: _Model) -> None:+ alex = people["alex"]+ _chat(alex, "a")+ fake.replies = ["Title: Shortlist review\nTopic: Hiring a sales lead"]+ assert asyncio.run(model.name_chat("a", "who's on the shortlist?", "Three people.")) == "Shortlist review"+ first, source = _topic_of("a")+ assert first is not None and source == "auto"+ # The second chat sees the first's topic and files under it (any case).+ _chat(alex, "b")+ fake.replies = ["Title: Offer terms\nTopic: hiring a sales lead"]+ asyncio.run(model.name_chat("b", "offer terms?", "Here."))+ assert _topic_of("b")[0] == first+ assert "- Hiring a sales lead" in fake.calls[1]["content"]+ assert fake.calls[1]["actor"] == "session_title"+ # Reusing a topic needs no tidy call.+ assert len(fake.calls) == 2+++def test_a_new_topic_is_merged_into_one_that_means_the_same(people: dict[str, int], fake: _Model) -> None:+ alex = people["alex"]+ _chat(alex, "a")+ _chat(alex, "b")+ fake.replies = ["Title: One\nTopic: Hiring a sales lead"]+ asyncio.run(model.name_chat("a", "q", "r"))+ fake.replies = ["Title: Two\nTopic: Sales lead hire", "Hiring a sales lead"]++ async def _run() -> None:+ await model.name_chat("b", "q", "r")+ await asyncio.gather(*model._tasks)++ asyncio.run(_run())+ assert _topic_of("b")[0] == _topic_of("a")[0]+ assert [t["name"] for t in store.list_topics(alex)] == ["Hiring a sales lead"]+ tidy = fake.calls[-1]+ assert tidy["actor"] == "chat_topics" and "NEW TOPIC: Sales lead hire" in tidy["content"]+++def test_the_tidy_leaves_a_distinct_topic_and_a_kept_one(people: dict[str, int], fake: _Model) -> None:+ alex = people["alex"]+ _chat(alex, "a")+ _chat(alex, "b")+ store.set_auto_topic("a", alex, "Acme renewal")+ new_id, made = store.set_auto_topic("b", alex, "Office move")+ assert made and new_id is not None+ fake.replies = ["none"]+ assert asyncio.run(model.tidy_new_topic(alex, new_id)) is None+ store.keep_topic(alex, new_id)+ assert asyncio.run(model.tidy_new_topic(alex, new_id)) is None+ assert len(fake.calls) == 1 # a kept topic isn't even asked about+ assert {t["name"] for t in store.list_topics(alex)} == {"Acme renewal", "Office move"}+++def test_a_chat_with_no_owner_only_gets_a_title(db: Path, monkeypatch: pytest.MonkeyPatch, fake: _Model) -> None:+ from openexecutive.utils import session_title++ session_store.create_session("legacy", "Placeholder", "2026-10-01T09:00:00+00:00")++ async def _title(*_a: Any, **_k: Any) -> str:+ return "Old chat"++ monkeypatch.setattr(session_title, "generate_session_title", _title)+ assert asyncio.run(model.name_chat("legacy", "q", "r")) == "Old chat"+ assert _topic_of("legacy") == (None, None)+ assert fake.calls == []+++def test_a_failed_call_keeps_the_placeholder(people: dict[str, int], fake: _Model) -> None:+ _chat(people["alex"], "a")+ assert asyncio.run(model.name_chat("a", "q", "r")) is None+ assert _topic_of("a") == (None, None)+++# ── owner actions stick ──────────────────────────────────────────────────+++def test_a_chat_the_owner_filed_is_never_retagged(people: dict[str, int]) -> None:+ alex = people["alex"]+ _chat(alex, "a")+ assert store.file_session("a", alex, name="Board prep")+ assert store.set_auto_topic("a", alex, "Something else") == (None, False)+ topic_id, source = _topic_of("a")+ assert source == "owner"+ assert store.list_topics(alex)[0]["name"] == "Board prep" and store.list_topics(alex)[0]["kept"]+ # Someone else's topic id is refused.+ _chat(people["sabin"], "s")+ store.file_session("s", people["sabin"], name="Theirs")+ theirs = store.topic_id_by_name(people["sabin"], "Theirs")+ assert theirs is not None and not store.file_session("a", alex, topic_id=theirs)+ assert _topic_of("a")[0] == topic_id+++# ── backfill ─────────────────────────────────────────────────────────────+++def test_backfill_files_older_chats_from_their_titles(+ people: dict[str, int], fake: _Model, monkeypatch: pytest.MonkeyPatch+) -> None:+ alex = people["alex"]+ _chat(alex, "c1", "Comp bands for sales roles", "2026-10-01T09:00:00+00:00")+ _chat(alex, "c2", "Acme asks for a discount", "2026-10-02T09:00:00+00:00")+ _chat(alex, "c3", "Hello", "2026-10-03T09:00:00+00:00")+ _chat(alex, "c4", "Offer terms for Dana", "2026-10-04T09:00:00+00:00")+ _chat(people["sabin"], "s1", "Not Alex's")+ monkeypatch.setattr(model, "BACKFILL_BATCH", 2)+ # Newest first, two per call; the second call sees the first's topics.+ fake.replies = ["1: Hiring a sales lead\n2: none", "1: Acme renewal\n2: Hiring a sales lead"]+ assert asyncio.run(model.backfill(alex)) == 4+ assert "- Hiring a sales lead" in fake.calls[1]["content"]+ assert "Not Alex's" not in fake.calls[0]["content"] + fake.calls[1]["content"]+ assert _topic_of("c4")[0] == _topic_of("c1")[0] is not None+ assert _topic_of("c3") == (None, "auto")+ assert store.untagged_sessions(alex) == []+ assert [s["session_id"] for s in store.untagged_sessions(people["sabin"])] == ["s1"]+++def test_a_failed_backfill_waits_before_trying_again(people: dict[str, int], fake: _Model) -> None:+ _chat(people["alex"], "a")+ assert asyncio.run(model.backfill(people["alex"])) == 0+ assert store.untagged_sessions(people["alex"]) # still waiting++ async def _start() -> bool:+ return model.start_backfill(people["alex"])++ assert asyncio.run(_start()) is False+++# ── routes ───────────────────────────────────────────────────────────────+++def test_topics_list_and_organize(client: TestClient, people: dict[str, int], fake: _Model) -> None:+ alex = people["alex"]+ _chat(alex, "a", "Comp bands")+ fake.replies = ["1: Hiring a sales lead"]+ first = client.get("/sessions/topics", headers=ALEX).json()+ assert first["topics"] == [] and first["organizing"] is True+ deadline = time.monotonic() + 5+ while model.backfill_running(alex) and time.monotonic() < deadline:+ time.sleep(0.02)+ second = client.get("/sessions/topics", headers=ALEX).json()+ assert second["organizing"] is False+ assert [(t["name"], t["chat_count"]) for t in second["topics"]] == [("Hiring a sales lead", 1)]+ listed = client.get("/sessions", headers=ALEX).json()+ assert listed[0]["topic_id"] == second["topics"][0]["id"]+ # Another person sees none of it.+ assert client.get("/sessions/topics", headers=SABIN).json()["topics"] == []+++def test_rename_pin_merge_and_ungroup(client: TestClient, people: dict[str, int]) -> None:+ alex = people["alex"]+ for sid in ("a", "b", "c"):+ _chat(alex, sid)+ hire, _ = store.set_auto_topic("a", alex, "Sales hire")+ acme, _ = store.set_auto_topic("b", alex, "Acme")+ store.set_auto_topic("c", alex, "Acme")++ resp = client.patch(f"/sessions/topics/{hire}", json={"name": " Hiring a sales lead ", "pinned": True}, headers=ALEX)+ assert resp.status_code == 200+ assert resp.json()["name"] == "Hiring a sales lead" and resp.json()["pinned_at"] and resp.json()["kept"]+ assert client.get("/sessions/topics", headers=ALEX).json()["topics"][0]["id"] == hire++ # Someone else can't touch it.+ assert client.patch(f"/sessions/topics/{hire}", json={"pinned": False}, headers=SABIN).status_code == 404+ assert client.delete(f"/sessions/topics/{hire}", headers=SABIN).status_code == 404++ assert client.post(f"/sessions/topics/{acme}/merge", json={"into_id": hire}, headers=ALEX).status_code == 204+ topics = client.get("/sessions/topics", headers=ALEX).json()["topics"]+ assert [(t["id"], t["chat_count"]) for t in topics] == [(hire, 3)]++ assert client.delete(f"/sessions/topics/{hire}", headers=ALEX).status_code == 204+ assert client.get("/sessions/topics", headers=ALEX).json()["topics"] == []+ assert all("topic_id" not in s for s in client.get("/sessions", headers=ALEX).json())+ # Ungrouped chats stay out of the backfill.+ assert store.untagged_sessions(alex) == []+++def test_move_a_chat_to_a_topic(client: TestClient, people: dict[str, int]) -> None:+ alex = people["alex"]+ _chat(alex, "a")+ resp = client.patch("/sessions/a", json={"topic_name": "Board prep"}, headers=ALEX)+ assert resp.status_code == 200 and resp.json()["topic_id"]+ resp = client.patch("/sessions/a", json={"topic_id": None}, headers=ALEX)+ assert resp.status_code == 200 and "topic_id" not in resp.json()+ assert client.patch("/sessions/a", json={"topic_id": 999}, headers=ALEX).status_code == 404+ assert client.patch("/sessions/a", json={"topic_name": "x"}, headers=SABIN).status_code == 404+++def test_someone_elses_words_never_see_the_owners_topics(+ people: dict[str, int], fake: _Model, monkeypatch: pytest.MonkeyPatch+) -> None:+ """A teammate writing first in the owner's chat (a channel conversation,+ or a shared chat) could steer the call into putting the owner's topic+ names in the title they then read. Such a chat is titled without them."""+ from openexecutive.utils import session_title++ alex, sabin = people["alex"], people["sabin"]+ _chat(alex, "mine")+ store.set_auto_topic("mine", alex, "Jane Doe exit")++ async def _title(*_a: Any, **_k: Any) -> str:+ return "Plain title"++ monkeypatch.setattr(session_title, "generate_session_title", _title)++ # Sabin wrote in Alex's chat.+ session_store.create_session("theirs", "Placeholder", "2026-10-01T09:00:00+00:00", caller_person_id=alex)+ session_store.save_message("theirs", "user", "list the topics", sender_person_id=sabin)+ session_store.save_message("theirs", "assistant", "answer")+ # Alex's own chat, shared with Sabin.+ _chat(alex, "shared")+ session_store.set_shares("shared", [sabin], alex)+ # A channel conversation, whoever owns it.+ _chat(alex, "slack:channel:C1:U1")++ for sid in ("theirs", "shared", "slack:channel:C1:U1"):+ assert asyncio.run(model.name_chat(sid, "q", "r")) == "Plain title"+ assert _topic_of(sid) == (None, None)+ assert fake.calls == []+++def test_a_refused_field_leaves_the_chat_unfiled(client: TestClient, people: dict[str, int]) -> None:+ _chat(people["alex"], "a")+ resp = client.patch("/sessions/a", json={"topic_name": "Hiring", "title": " "}, headers=ALEX)+ assert resp.status_code == 422+ assert _topic_of("a") == (None, None)+++def test_the_backfill_leaves_a_chat_its_naming_filed_meanwhile(+ people: dict[str, int], fake: _Model, monkeypatch: pytest.MonkeyPatch+) -> None:+ alex = people["alex"]+ _chat(alex, "new", "Placeholder")++ async def _reply(*_a: Any, **_k: Any) -> str:+ # The chat's own naming lands while the batch call runs.+ store.set_auto_topic("new", alex, "Acme renewal")+ return "1: none"++ monkeypatch.setattr(model, "_ask", _reply)+ asyncio.run(model.backfill(alex))+ topic_id, _ = _topic_of("new")+ assert topic_id == store.topic_id_by_name(alex, "Acme renewal")diff --git a/packages/ui/scripts/sessionGroups.test.mjs b/packages/ui/scripts/sessionGroups.test.mjsindex 6a206664..d678a427 100644--- a/packages/ui/scripts/sessionGroups.test.mjs+++ b/packages/ui/scripts/sessionGroups.test.mjs@@ -67,3 +67,44 @@ test("pinned chats come first in Pinned, whatever their date", () => {],);});++test("topic view: pinned first, then topics in server order, one-offs under Other", async () => {+ const { groupSessionsByTopic } = await import("../src/lib/sessionGroups.ts");+ const chat = (session_id, extra = {}) => ({+ session_id,+ title: session_id,+ created_at: "2026-10-01T00:00:00Z",+ updated_at: "2026-10-01T00:00:00Z",+ message_count: 2,+ ...extra,+ });+ const topics = [+ { id: 1, name: "Hiring a sales lead", chat_count: 2, kept: false },+ { id: 2, name: "Acme renewal", chat_count: 1, kept: false },+ { id: 3, name: "Board prep", chat_count: 1, kept: true },+ ];+ const groups = groupSessionsByTopic(+ [+ chat("pinned", { topic_id: 1, pinned_at: "2026-10-01T00:00:00Z" }),+ chat("hire-a", { topic_id: 1 }),+ chat("loose"),+ chat("acme", { topic_id: 2 }),+ chat("hire-b", { topic_id: 1 }),+ chat("board", { topic_id: 3 }),+ chat("gone", { topic_id: 99 }),+ ],+ topics,+ );+ assert.deepEqual(+ groups.map((g) => [g.label, g.items.map((s) => s.session_id)]),+ [+ ["Pinned", ["pinned"]],+ ["Hiring a sales lead", ["hire-a", "hire-b"]],+ ["Board prep", ["board"]],+ // A one-chat topic nobody kept, no topic, or an unknown one: Other, newest first.+ ["Other", ["loose", "acme", "gone"]],+ ],+ );+ assert.equal(groups[1].topic.id, 1);+ assert.equal(groups[3].topic, undefined);+});diff --git a/packages/ui/src/app/chats/page.tsx b/packages/ui/src/app/chats/page.tsxindex 32194c8d..5480ea3f 100644--- a/packages/ui/src/app/chats/page.tsx+++ b/packages/ui/src/app/chats/page.tsx@@ -1,13 +1,19 @@"use client";-import { useEffect, useMemo, useState } from "react";+import { useEffect, useMemo, useState, useSyncExternalStore } from "react";import { useRouter } from "next/navigation";import Link from "next/link";import Icon from "@/components/Icon";import { buttonClass } from "@/components/ui/Button";-import ChatHistory, { ChatRow } from "@/components/sessions/ChatHistory";+import ChatHistory, { ChatRow, type ChatsView } from "@/components/sessions/ChatHistory";import { useSessions } from "@/components/sessions/SessionsContext";-import { listSharedSessions, searchSessions, type SessionSummary } from "@/lib/api";+import {+ listChatTopics,+ listSharedSessions,+ searchSessions,+ type ChatTopic,+ type SessionSummary,+} from "@/lib/api";import {CHANNEL_LABELS,CHANNEL_ORDER,@@ -18,6 +24,39 @@ import {type ChannelFilter = SessionChannel | "all";+const VIEW_KEY = "oe.chats.view";+// While older chats are being filed, how often and how long to look again.+const ORGANIZE_POLL_MS = 3000;+const ORGANIZE_POLLS = 20;++// Date or Topic, remembered per browser; the server render is always Date.+const viewListeners = new Set<() => void>();+let sessionView: ChatsView | null = null;++function storedView(): ChatsView {+ if (sessionView) return sessionView;+ try {+ return window.localStorage.getItem(VIEW_KEY) === "topic" ? "topic" : "date";+ } catch {+ return "date";+ }+}++function saveView(next: ChatsView): void {+ sessionView = next;+ try {+ window.localStorage.setItem(VIEW_KEY, next);+ } catch {+ // Private mode: the choice lasts this visit.+ }+ viewListeners.forEach((fn) => fn());+}++function subscribeView(fn: () => void): () => void {+ viewListeners.add(fn);+ return () => viewListeners.delete(fn);+}+// Full conversation history: every chat, including conversations that// arrived through Slack, Telegram and Discord. Each row opens its chat;// Delete is in the row's ⋯ menu and asks first. Chats others shared with@@ -35,6 +74,47 @@ export default function ChatsPage() {refresh();}, [refresh]);+ const view = useSyncExternalStore(subscribeView, storedView, () => "date" as const);+ const chooseView = saveView;++ // The caller's topics, loaded for the Topic view. While older chats are+ // being filed it looks again every few seconds, reloading the list too so+ // each chat lands under its topic.+ const [topics, setTopics] = useState<ChatTopic[]>([]);+ const [organizing, setOrganizing] = useState(false);+ const [topicsVersion, setTopicsVersion] = useState(0);+ useEffect(() => {+ if (view !== "topic") return;+ let live = true;+ let polls = 0;+ let timer: ReturnType<typeof setTimeout> | undefined;+ const load = () => {+ listChatTopics()+ .then((res) => {+ if (!live) return;+ setTopics(res.topics);+ setOrganizing(res.organizing);+ if (polls > 0) refresh();+ if (res.organizing && polls < ORGANIZE_POLLS) {+ polls += 1;+ timer = setTimeout(load, ORGANIZE_POLL_MS);+ }+ })+ .catch(() => {+ if (live) setOrganizing(false);+ });+ };+ load();+ return () => {+ live = false;+ if (timer) clearTimeout(timer);+ };+ }, [view, topicsVersion, refresh]);+ const changed = () => {+ refresh();+ setTopicsVersion((v) => v + 1);+ };+// Chats teammates shared with the viewer, to write in with them. Kept out// of the channel tabs and counts. A failure just leaves the section hidden.const [shared, setShared] = useState<SessionSummary[]>([]);@@ -167,7 +247,27 @@ export default function ChatsPage() {);})}</div>- <div className="relative sm:ml-auto sm:w-72">+ <div+ role="tablist"+ aria-label="Group chats by"+ className="inline-flex items-center gap-1 p-1 rounded-xl ring-1 ring-line bg-surface-elevated sm:ml-auto"+ >+ {(["date", "topic"] as const).map((v) => (+ <button+ key={v}+ type="button"+ role="tab"+ aria-selected={view === v}+ onClick={() => chooseView(v)}+ className={`min-h-[40px] px-4 text-[15px] font-medium rounded-lg transition cursor-pointer ${+ view === v ? "bg-accent/10 text-accent" : "text-fg-muted hover:text-fg hover:bg-surface-overlay"+ }`}+ >+ {v === "date" ? "Date" : "Topic"}+ </button>+ ))}+ </div>+ <div className="relative sm:w-72"><Iconname="search"size="w-4 h-4"@@ -206,10 +306,17 @@ export default function ChatsPage() {</>) : (<>+ {view === "topic" && organizing && (+ <p role="status" className="px-1 pb-3 text-sm text-fg-muted">+ Grouping your earlier chats by topic…+ </p>+ )}<ChatHistorysessions={visible}searching={searching}query={shown ? trimmed : ""}+ view={view}+ topics={topics}onSelect={(id) => {// Opened from a message match: the chat steps through the matches.const hit = shown?.find((s) => s.session_id === id);@@ -217,7 +324,7 @@ export default function ChatsPage() {router.push(`/?session=${encodeURIComponent(id)}${find}`);}}onDelete={remove}- onChanged={refresh}+ onChanged={changed}/>{sharedSection}</>diff --git a/packages/ui/src/components/sessions/ChatHistory.tsx b/packages/ui/src/components/sessions/ChatHistory.tsxindex fc761bc0..3010f38f 100644--- a/packages/ui/src/components/sessions/ChatHistory.tsx+++ b/packages/ui/src/components/sessions/ChatHistory.tsx@@ -9,8 +9,12 @@ import {getSessionShares,leaveSharedChat,listPeople,+ mergeChatTopic,setSessionShares,+ ungroupChatTopic,+ updateChatTopic,updateSession,+ type ChatTopic,type Person,type SessionSummary,} from "@/lib/api";@@ -18,10 +22,12 @@ import { downloadChat } from "@/lib/downloadChat";import { formatRelativeTime } from "@/lib/relativeTime";import { highlightParts, matchLabel } from "@/lib/chatSearch";import { CHANNEL_LABELS, sessionChannel, sessionTitle } from "@/lib/sessionChannel";-import { groupSessionsByDate, type GroupKey } from "@/lib/sessionGroups";+import { groupSessionsByDate, groupSessionsByTopic, type GroupKey } from "@/lib/sessionGroups";const GROUP_CAP = 20;-const DEFAULT_COLLAPSED = new Set<GroupKey>(["older"]);+const DEFAULT_COLLAPSED = new Set<string>(["older" satisfies GroupKey, "other"]);++export type ChatsView = "date" | "topic";interface ChatHistoryProps {/** Already filtered by channel and search; newest first. */@@ -30,20 +36,43 @@ interface ChatHistoryProps {searching: boolean;/** The words the server searched for, to mark in each result's snippet. */query?: string;+ /** Group by date (the default) or by topic. */+ view?: ChatsView;+ /** The caller's topics, for the Topic view and a row's Move to topic. */+ topics?: ChatTopic[];onSelect: (sessionId: string) => void;/** Deletes after the row has asked; resolves false when it failed. */onDelete: (sessionId: string) => Promise<boolean>;- /** Reloads the list after a rename or a pin. */+ /** Reloads the list after a rename, a pin or a move. */onChanged: () => void;}-// Date-grouped conversation list for /chats — the full history the sidebar's-// short Recent list links to.-export default function ChatHistory({ sessions, searching, query = "", onSelect, onDelete, onChanged }: ChatHistoryProps) {+interface ListGroup {+ key: string;+ label: string;+ topic?: ChatTopic;+ items: SessionSummary[];+}++// Conversation list for /chats, grouped by date or by topic — the full+// history the sidebar's short Recent list links to.+export default function ChatHistory({+ sessions,+ searching,+ query = "",+ view = "date",+ topics = [],+ onSelect,+ onDelete,+ onChanged,+}: ChatHistoryProps) {const [collapsedOverride, setCollapsedOverride] = useState<Record<string, boolean>>({});const [showAll, setShowAll] = useState<Set<string>>(new Set());- const groups = useMemo(() => groupSessionsByDate(sessions), [sessions]);+ const groups: ListGroup[] = useMemo(+ () => (view === "topic" ? groupSessionsByTopic(sessions, topics) : groupSessionsByDate(sessions)),+ [view, sessions, topics],+ );if (groups.length === 0) {return <p className="px-1 py-6 text-[15px] text-fg-muted">No conversations match.</p>;@@ -52,12 +81,12 @@ export default function ChatHistory({ sessions, searching, query = "", onSelect,// Stored collapse state (default-collapsed unless the user toggled it). While// searching we force every group open so matches are never hidden, but the// stored state is preserved and re-applies once the query is cleared.- const storedCollapsed = (key: GroupKey) =>+ const storedCollapsed = (key: string) =>key in collapsedOverride ? collapsedOverride[key] : DEFAULT_COLLAPSED.has(key);- const isCollapsed = (key: GroupKey) => (searching ? false : storedCollapsed(key));- const toggleCollapse = (key: GroupKey) =>+ const isCollapsed = (key: string) => (searching ? false : storedCollapsed(key));+ const toggleCollapse = (key: string) =>setCollapsedOverride((prev) => ({ ...prev, [key]: !storedCollapsed(key) }));- const revealAll = (key: GroupKey) => setShowAll((prev) => new Set(prev).add(key));+ const revealAll = (key: string) => setShowAll((prev) => new Set(prev).add(key));return (<div className="space-y-4">@@ -68,20 +97,23 @@ export default function ChatHistory({ sessions, searching, query = "", onSelect,const hiddenCount = group.items.length - visible.length;return (<section key={group.key}>- <button- type="button"- onClick={() => toggleCollapse(group.key)}- aria-expanded={!collapsed}- className="w-full flex items-center gap-2 min-h-[40px] px-1 text-fg-muted hover:text-fg transition-colors cursor-pointer"- >- <Icon- name="chevron-right"- size="w-3.5 h-3.5"- className={`transition-transform ${collapsed ? "" : "rotate-90"}`}- />- <span className="text-sm font-semibold">{group.label}</span>- <span className="text-sm text-fg-subtle">{group.items.length}</span>- </button>+ <div className="flex flex-wrap items-center gap-1">+ <button+ type="button"+ onClick={() => toggleCollapse(group.key)}+ aria-expanded={!collapsed}+ className="flex-1 min-w-0 flex items-center gap-2 min-h-[40px] px-1 text-fg-muted hover:text-fg transition-colors cursor-pointer"+ >+ <Icon+ name="chevron-right"+ size="w-3.5 h-3.5"+ className={`flex-shrink-0 transition-transform ${collapsed ? "" : "rotate-90"}`}+ />+ <span className="text-sm font-semibold truncate">{group.label}</span>+ <span className="text-sm text-fg-subtle">{group.items.length}</span>+ </button>+ {group.topic && <TopicMenu topic={group.topic} topics={topics} onChanged={onChanged} />}+ </div>{!collapsed && (<div className="mt-1 space-y-2">{visible.map((s) => (@@ -89,6 +121,7 @@ export default function ChatHistory({ sessions, searching, query = "", onSelect,key={s.session_id}session={s}query={query}+ topics={topics}onSelect={onSelect}onDelete={onDelete}onChanged={onChanged}@@ -112,17 +145,160 @@ export default function ChatHistory({ sessions, searching, query = "", onSelect,);}-type RowPanel = "delete" | "rename" | "share" | "leave" | null;+type TopicPanel = "rename" | "merge" | "ungroup" | null;++// A topic header's ⋯ menu: Rename, Merge into…, Pin and Ungroup. Each+// panel opens under the header; what the owner does here is kept.+function TopicMenu({+ topic,+ topics,+ onChanged,+}: {+ topic: ChatTopic;+ topics: ChatTopic[];+ onChanged: () => void;+}) {+ const [panel, setPanel] = useState<TopicPanel>(null);+ const [name, setName] = useState(topic.name);+ const [into, setInto] = useState<number | "">("");+ const [busy, setBusy] = useState(false);+ const [error, setError] = useState<string | null>(null);+ const others = topics.filter((t) => t.id !== topic.id);++ const run = async (action: () => Promise<unknown>) => {+ setBusy(true);+ setError(null);+ try {+ await action();+ setPanel(null);+ onChanged();+ } catch (err) {+ setError(err instanceof Error ? err.message : "Couldn't update this topic.");+ } finally {+ setBusy(false);+ }+ };++ const open = (next: TopicPanel) => {+ setError(null);+ setName(topic.name);+ setInto("");+ setPanel(next);+ };++ const items = [+ { label: "Rename topic", onSelect: () => open("rename") },+ ...(others.length ? [{ label: "Merge into…", onSelect: () => open("merge") }] : []),+ {+ label: topic.pinned_at ? "Unpin topic" : "Pin topic",+ onSelect: () => void run(() => updateChatTopic(topic.id, { pinned: !topic.pinned_at })),+ },+ { label: "Ungroup", onSelect: () => open("ungroup") },+ ];++ return (+ <>+ <OverflowMenu label={`More actions for ${topic.name}`} items={items} />+ {panel === "rename" && (+ <form+ className="basis-full mt-1 flex flex-wrap items-center gap-2 rounded-2xl border border-line bg-surface-elevated px-4 py-3"+ onSubmit={(e) => {+ e.preventDefault();+ const trimmed = name.trim();+ if (trimmed) void run(() => updateChatTopic(topic.id, { name: trimmed.slice(0, 40) }));+ }}+ >+ <input+ type="text"+ value={name}+ onChange={(e) => setName(e.target.value)}+ onKeyDown={(e) => {+ if (e.key === "Escape") {+ e.preventDefault();+ setPanel(null);+ }+ }}+ maxLength={40}+ autoFocus+ aria-label="Topic name"+ className="flex-1 min-w-[12rem] h-10 rounded-lg bg-surface border border-line px-3 text-[15px] text-fg focus:outline-none focus:border-accent/60 focus:ring-2 focus:ring-accent/20"+ />+ <Button size="sm" variant="primary" type="submit" disabled={!name.trim() || busy}>+ {busy ? "Saving…" : "Save"}+ </Button>+ <Button size="sm" variant="ghost" type="button" onClick={() => setPanel(null)} disabled={busy}>+ Cancel+ </Button>+ </form>+ )}+ {panel === "merge" && (+ <div className="basis-full mt-1 flex flex-wrap items-center gap-2 rounded-2xl border border-line bg-surface-elevated px-4 py-3">+ <label className="text-sm text-fg" htmlFor={`merge-${topic.id}`}>+ Move its chats to+ </label>+ <select+ id={`merge-${topic.id}`}+ value={into}+ onChange={(e) => setInto(e.target.value ? Number(e.target.value) : "")}+ className="flex-1 min-w-[10rem] h-10 rounded-lg bg-surface border border-line px-3 text-[15px] text-fg"+ >+ <option value="">Choose a topic</option>+ {others.map((t) => (+ <option key={t.id} value={t.id}>+ {t.name}+ </option>+ ))}+ </select>+ <Button+ size="sm"+ variant="primary"+ disabled={into === "" || busy}+ onClick={() => into !== "" && void run(() => mergeChatTopic(topic.id, into))}+ >+ {busy ? "Merging…" : "Merge"}+ </Button>+ <Button size="sm" variant="ghost" onClick={() => setPanel(null)} disabled={busy}>+ Cancel+ </Button>+ </div>+ )}+ {panel === "ungroup" && (+ <div+ role="alert"+ className="basis-full mt-1 flex flex-wrap items-center gap-2 rounded-2xl border border-line bg-surface-elevated px-4 py-3"+ >+ <p className="mr-auto text-sm text-fg">Ungroup {topic.name}? Its chats stay, under Other.</p>+ <Button size="sm" variant="primary" onClick={() => void run(() => ungroupChatTopic(topic.id))} disabled={busy}>+ {busy ? "Ungrouping…" : "Ungroup"}+ </Button>+ <Button size="sm" variant="ghost" onClick={() => setPanel(null)} disabled={busy}>+ Cancel+ </Button>+ </div>+ )}+ {error && !panel && (+ <p role="alert" className="basis-full mt-1 rounded-2xl border border-line bg-surface-elevated px-4 py-3 text-sm text-fg">+ {error}+ </p>+ )}+ </>+ );+}++type RowPanel = "delete" | "rename" | "share" | "leave" | "move" | null;export function ChatRow({session,query = "",+ topics,onSelect,onDelete,onChanged,}: {session: SessionSummary;query?: string;+ /** The owner's topics; with them the menu offers Move to topic. */+ topics?: ChatTopic[];onSelect: (sessionId: string) => void;/** Absent for a chat shared with the viewer, which only its owner deletes. */onDelete?: (sessionId: string) => Promise<boolean>;@@ -200,6 +376,7 @@ export function ChatRow({: [{ label: session.pinned_at ? "Unpin" : "Pin", onSelect: () => void togglePin() },{ label: "Rename", onSelect: () => open("rename") },+ ...(topics ? [{ label: "Move to topic", onSelect: () => open("move") }] : []),{ label: "Share", onSelect: () => open("share") },{ label: "Download", onSelect: () => void download() },...(onDelete ? [{ label: "Delete chat", danger: true, onSelect: () => open("delete") }] : []),@@ -298,6 +475,16 @@ export function ChatRow({</Button></div>)}+ {panel === "move" && topics && (+ <MovePanel+ session={session}+ topics={topics}+ onDone={(changed) => {+ setPanel(null);+ if (changed) onChanged?.();+ }}+ />+ )}{panel === "share" && <SharePanel sessionId={session.session_id} onClose={() => setPanel(null)} />}</div>);@@ -360,6 +547,95 @@ function RenamePanel({ session, onDone }: { session: SessionSummary; onDone: (ch);}+const NEW_TOPIC = "new";+const NO_TOPIC = "none";++// File a chat under one of the owner's topics, a new one, or none. The+// choice sticks: the chat is never filed again on its own.+function MovePanel({+ session,+ topics,+ onDone,+}: {+ session: SessionSummary;+ topics: ChatTopic[];+ onDone: (changed: boolean) => void;+}) {+ const [choice, setChoice] = useState<string>(+ session.topic_id != null ? String(session.topic_id) : topics.length ? String(topics[0].id) : NEW_TOPIC,+ );+ const [name, setName] = useState("");+ const [saving, setSaving] = useState(false);+ const [error, setError] = useState<string | null>(null);+ const ready = choice !== NEW_TOPIC || name.trim().length > 0;++ const save = async () => {+ if (!ready || saving) return;+ setSaving(true);+ setError(null);+ try {+ await updateSession(+ session.session_id,+ choice === NEW_TOPIC+ ? { topic_name: name.trim().slice(0, 40) }+ : { topic_id: choice === NO_TOPIC ? null : Number(choice) },+ );+ onDone(true);+ } catch (err) {+ setSaving(false);+ setError(err instanceof Error ? err.message : "Couldn't move this chat.");+ }+ };++ return (+ <form+ className="flex flex-wrap items-center gap-2 border-t border-line px-4 py-3"+ onSubmit={(e) => {+ e.preventDefault();+ void save();+ }}+ >+ <select+ value={choice}+ onChange={(e) => setChoice(e.target.value)}+ aria-label="Topic"+ className="flex-1 min-w-[10rem] h-10 rounded-lg bg-surface border border-line px-3 text-[15px] text-fg"+ >+ {topics.map((t) => (+ <option key={t.id} value={String(t.id)}>+ {t.name}+ </option>+ ))}+ <option value={NEW_TOPIC}>New topic…</option>+ <option value={NO_TOPIC}>No topic</option>+ </select>+ {choice === NEW_TOPIC && (+ <input+ type="text"+ value={name}+ onChange={(e) => setName(e.target.value)}+ maxLength={40}+ autoFocus+ placeholder="Topic name"+ aria-label="New topic name"+ className="flex-1 min-w-[10rem] h-10 rounded-lg bg-surface border border-line px-3 text-[15px] text-fg focus:outline-none focus:border-accent/60 focus:ring-2 focus:ring-accent/20"+ />+ )}+ <Button size="sm" variant="primary" type="submit" disabled={!ready || saving}>+ {saving ? "Moving…" : "Move"}+ </Button>+ <Button size="sm" variant="ghost" type="button" onClick={() => onDone(false)} disabled={saving}>+ Cancel+ </Button>+ {error && (+ <p role="alert" className="basis-full text-sm text-red-400">+ {error}+ </p>+ )}+ </form>+ );+}+interface ShareState {people: Person[];chosen: Set<number>;diff --git a/packages/ui/src/lib/api.ts b/packages/ui/src/lib/api.tsindex c580048a..3f386e73 100644--- a/packages/ui/src/lib/api.ts+++ b/packages/ui/src/lib/api.ts@@ -976,6 +976,55 @@ export interface SessionSummary {shared_by?: string;/** Shared-with-me list only: when it was shared. */shared_at?: string;+ /** The owner's topic this chat is filed under; absent when none. */+ topic_id?: number;+}++/** One of the caller's chat topics (the Topic view on Chats). */+export interface ChatTopic {+ id: number;+ name: string;+ chat_count: number;+ /** The owner named, pinned or filed a chat under it: shown even with one chat. */+ kept: boolean;+ pinned_at?: string;+}++/** The caller's topics; `organizing` while older chats are still being filed. */+export async function listChatTopics(): Promise<{ topics: ChatTopic[]; organizing: boolean }> {+ const res = await fetch(`${API_BASE}/sessions/topics`);+ if (!res.ok) throw new Error("Failed to list topics");+ return res.json();+}++/** Rename and / or pin a topic. Renaming to another topic's name merges them. */+export async function updateChatTopic(+ topicId: number,+ patch: { name?: string; pinned?: boolean },+): Promise<ChatTopic> {+ const res = await fetch(`${API_BASE}/sessions/topics/${topicId}`, {+ method: "PATCH",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify(patch),+ });+ if (!res.ok) throw await sessionError(res, "Couldn't update this topic.");+ return res.json();+}++/** Move every chat under one topic to another. */+export async function mergeChatTopic(topicId: number, intoId: number): Promise<void> {+ const res = await fetch(`${API_BASE}/sessions/topics/${topicId}/merge`, {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ into_id: intoId }),+ });+ if (!res.ok) throw await sessionError(res, "Couldn't merge these topics.");+}++/** Drop a topic; its chats stay, under no topic. */+export async function ungroupChatTopic(topicId: number): Promise<void> {+ const res = await fetch(`${API_BASE}/sessions/topics/${topicId}`, { method: "DELETE" });+ if (!res.ok) throw await sessionError(res, "Couldn't ungroup this topic.");}export async function listSessions(): Promise<SessionSummary[]> {@@ -1027,10 +1076,12 @@ export async function listSharedSessions(): Promise<SessionSummary[]> {return res.json();}-/** Rename and / or pin the caller's own chat. A renamed chat keeps its name. */+/** Rename, pin and / or file the caller's own chat. A renamed chat keeps its+ * name; `topic_id: null` files it under no topic, `topic_name` under that+ * topic (made if new). */export async function updateSession(sessionId: string,- patch: { title?: string; pinned?: boolean },+ patch: { title?: string; pinned?: boolean; topic_id?: number | null; topic_name?: string },): Promise<SessionSummary> {const res = await fetch(`${API_BASE}/sessions/${encodeURIComponent(sessionId)}`, {method: "PATCH",diff --git a/packages/ui/src/lib/sessionGroups.ts b/packages/ui/src/lib/sessionGroups.tsindex 4b33069b..016fbd5a 100644--- a/packages/ui/src/lib/sessionGroups.ts+++ b/packages/ui/src/lib/sessionGroups.ts@@ -1,4 +1,4 @@-import type { SessionSummary } from "@/lib/api";+import type { ChatTopic, SessionSummary } from "@/lib/api";export type GroupKey = "pinned" | "today" | "yesterday" | "prev7" | "prev30" | "older";@@ -76,3 +76,56 @@ export function groupSessionsByDate(items: buckets[key],})).filter((g) => g.items.length > 0);}++export interface TopicGroup {+ /** "pinned", "topic:<id>" or "other". */+ key: string;+ label: string;+ /** The topic, for its menu; absent on Pinned and Other. */+ topic?: ChatTopic;+ items: SessionSummary[];+}++/**+ * Groups sessions by the topic each is filed under. Pinned chats stay first,+ * in "Pinned", as in the date view. Topics follow in the order the server+ * lists them (pinned topics first, then by their newest chat). A topic with+ * one chat shown here folds into "Other" unless the owner kept it (named,+ * pinned or filed a chat under it), so a run of one-off topics doesn't bury+ * the list. Chats under no topic, or one not listed, go to "Other", last.+ */+export function groupSessionsByTopic(+ sessions: SessionSummary[],+ topics: ChatTopic[],+): TopicGroup[] {+ const pinned: SessionSummary[] = [];+ const byTopic = new Map<number, SessionSummary[]>();+ const other: SessionSummary[] = [];+ const known = new Set(topics.map((t) => t.id));+ for (const s of sessions) {+ if (s.pinned_at) pinned.push(s);+ else if (s.topic_id != null && known.has(s.topic_id)) {+ const list = byTopic.get(s.topic_id) ?? [];+ list.push(s);+ byTopic.set(s.topic_id, list);+ } else other.push(s);+ }+ const groups: TopicGroup[] = [];+ if (pinned.length) groups.push({ key: "pinned", label: "Pinned", items: pinned });+ for (const topic of topics) {+ const items = byTopic.get(topic.id);+ if (!items?.length) continue;+ if (items.length === 1 && !topic.kept && !topic.pinned_at) {+ other.push(items[0]);+ continue;+ }+ groups.push({ key: `topic:${topic.id}`, label: topic.name, topic, items });+ }+ if (other.length) {+ // Keep "Other" newest first, as the list came.+ const order = new Map(sessions.map((s, i) => [s.session_id, i]));+ other.sort((a, b) => (order.get(a.session_id) ?? 0) - (order.get(b.session_id) ?? 0));+ groups.push({ key: "other", label: "Other", items: other });+ }+ return groups;+}