AI-powered virtual executive team — a single coherent executive persona backed by 8 specialist agents (FastAPI + Next.js).
feat(chat): pin, rename, share, export and redo the last turn (#471)
Rufus8068e43144ca
diff --git a/packages/core/openexecutive/api/models.py b/packages/core/openexecutive/api/models.pyindex 040a5c9d..e4c84ac3 100644--- a/packages/core/openexecutive/api/models.py+++ b/packages/core/openexecutive/api/models.py@@ -285,6 +285,14 @@ class SessionSummary(BaseModel):# Set on the plain list: the chat's last message as one line, "You: "# before the person's own words, for a list that says what each chat is.preview: str | None = None+ # When its owner pinned it to the top of their list; absent when not.+ pinned_at: str | None = None+ # A chat someone shared with the caller (`GET /sessions/shared-with-me`,+ # or opened by id): it is theirs to read, not to write in, `shared_by`+ # names its owner and `shared_at` says when.+ read_only: bool | None = None+ shared_by: str | None = None+ shared_at: str | None = Noneclass TargetCustomerData(BaseModel):diff --git a/packages/core/openexecutive/api/routes/sessions.py b/packages/core/openexecutive/api/routes/sessions.pyindex 631b08e4..df25e81f 100644--- a/packages/core/openexecutive/api/routes/sessions.py+++ b/packages/core/openexecutive/api/routes/sessions.py@@ -1,5 +1,6 @@from __future__ import annotations+import contextlibimport timefrom typing import Any, Literal@@ -9,17 +10,30 @@ from pydantic import BaseModel, Fieldfrom openexecutive.api.models import SessionSummaryfrom openexecutive.api.routes import chat as chat_routefrom openexecutive.api.routes.chat import (+ _acquire_session_turn,+ _is_channel_namespaced,+ _release_session_turn,_resolve_caller_person_id,_session_access,forget_session,)+from openexecutive.memory import chat_exportfrom openexecutive.memory.session_store import (delete_session,get_session_metadata,+ get_session_owner,+ is_shared_with,list_sessions,+ list_shared_with_person,load_messages,+ rename_session,+ rewind_last_turn,search_sessions,+ session_mail_private,set_message_feedback,+ set_pinned,+ set_shares,+ shared_with,)router = APIRouter()@@ -58,22 +72,267 @@ def _require_session_access(request: Request, session_id: str) -> int | None:return caller[email protected]("/sessions/{session_id}", response_model=SessionSummary)+def _require_read_access(request: Request, session_id: str) -> bool:+ """404 unless the caller may read this session. True when they may only+ read it: its owner shared it with them (``set_shares``), and it never read+ its owner's own mail. Anyone who may use it (``_require_session_access``)+ gets False."""+ caller = _resolve_caller_person_id(request)+ if _session_access(request, session_id, caller) == "allowed":+ return False+ if caller is not None and is_shared_with(session_id, caller) and not session_mail_private(session_id):+ return True+ raise HTTPException(status_code=404, detail="Session not found")+++def _require_owner(request: Request, session_id: str) -> int:+ """404 unless the caller owns this chat (the principal owns an ownerless+ legacy one); returns their id. Pinning, naming, sharing and redoing a+ turn are the owner's, not the principal's on someone else's chat."""+ caller = _require_session_access(request, session_id)+ exists, owner = get_session_owner(session_id)+ if caller is None or not exists:+ raise HTTPException(status_code=404, detail="Session not found")+ if owner == caller:+ return caller+ if owner is None and session_id not in chat_route._session_starters:+ # An ownerless legacy chat is the principal's, but not one someone+ # the roster can't resolve is talking in right now.+ from openexecutive.people.store import get_person++ person = get_person(caller)+ if person is not None and person.is_principal and not person.archived:+ return caller+ raise HTTPException(status_code=404, detail="Session not found")+++def _owner_rows(session_id: str, owner: int | None) -> contextlib.AbstractContextManager[None]:+ """Audit rows about a chat stay as private as the chat: a teammate's own,+ or one that read its owner's mail, is its owner's alone, as every row its+ turns wrote is (``chat._session_access``)."""+ from openexecutive.audit.context import rows_for_person++ if chat_route._teammates_own(owner) or session_mail_private(session_id):+ return rows_for_person(owner)+ return contextlib.nullcontext()+++def _person_name(person_id: int | None) -> str | None:+ if person_id is None:+ return None+ from openexecutive.people.store import get_person++ person = get_person(int(person_id))+ return person.full_name if person is not None else None+++ "/sessions/shared-with-me",+ response_model=list[SessionSummary],+ response_model_exclude_none=True,+)+def get_shared_sessions(request: Request) -> list[SessionSummary]:+ """Chats other people shared with the caller, to read, newest first, each+ with who shared it (``shared_by``) and when (``shared_at``)."""+ caller = _resolve_caller_person_id(request)+ if caller is None:+ return []+ out: list[SessionSummary] = []+ for row in list_shared_with_person(caller):+ out.append(SessionSummary(+ session_id=row["session_id"],+ title=row["title"],+ created_at=row["created_at"],+ updated_at=row["updated_at"],+ message_count=row["message_count"],+ shared_by=_person_name(row["owner_person_id"]) or "Someone on your team",+ shared_at=row["shared_at"],+ read_only=True,+ ))+ return out++[email protected]("/sessions/{session_id}", response_model=SessionSummary, response_model_exclude_none=True)def get_session(session_id: str, request: Request) -> SessionSummary:- _require_session_access(request, session_id)+ read_only = _require_read_access(request, session_id)meta = get_session_metadata(session_id)if meta is None:raise HTTPException(status_code=404, detail="Session not found")- return SessionSummary(**meta)+ summary = SessionSummary(**meta)+ if read_only:+ # Only the owner pins, so a reader never sees the owner's pin.+ _, owner = get_session_owner(session_id)+ summary.pinned_at = None+ summary.read_only = True+ summary.shared_by = _person_name(owner) or "Someone on your team"+ return summary@router.get("/sessions/{session_id}/messages")def get_session_messages(session_id: str, request: Request) -> list[dict]:- _require_session_access(request, session_id)+ read_only = _require_read_access(request, session_id)meta = get_session_metadata(session_id)if meta is None:raise HTTPException(status_code=404, detail="Session not found")- return load_messages(session_id)+ messages = load_messages(session_id)+ if read_only:+ # The owner's ratings are theirs.+ for msg in messages:+ msg.pop("feedback", None)+ return messages+++class SessionUpdate(BaseModel):+ """Rename and / or pin a chat. A field left out is left as it is."""++ title: str | None = Field(default=None, min_length=1, max_length=120)+ pinned: bool | None = None++[email protected]("/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 it+ after) 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")+ rename_session(session_id, title)+ if body.pinned is not None:+ set_pinned(session_id, body.pinned)+ meta = get_session_metadata(session_id)+ if meta is None:+ raise HTTPException(status_code=404, detail="Session not found")+ return SessionSummary(**meta)+++class ShareEntry(BaseModel):+ person_id: int+ full_name: str+ shared_at: str+++class SharesUpdate(BaseModel):+ """Everyone the chat should be shared with; anyone not listed is unshared."""++ person_ids: list[int] = Field(default_factory=list, max_length=100)+++def _share_list(session_id: str) -> list[ShareEntry]:+ out: list[ShareEntry] = []+ for row in shared_with(session_id):+ name = _person_name(row["person_id"])+ if name is not None:+ out.append(ShareEntry(person_id=row["person_id"], full_name=name, shared_at=row["shared_at"]))+ return out++[email protected]("/sessions/{session_id}/shares", response_model=list[ShareEntry])+def get_session_shares(session_id: str, request: Request) -> list[ShareEntry]:+ """Who the owner shared this chat with."""+ _require_owner(request, session_id)+ return _share_list(session_id)++[email protected]("/sessions/{session_id}/shares", response_model=list[ShareEntry])+def put_session_shares(session_id: str, body: SharesUpdate, request: Request) -> list[ShareEntry]:+ """Share the chat, to read, with exactly these team members.++ Team members only (not contacts, not archived, not the owner). A chat+ that read its owner's own mail (Act as me) is never shared: 409."""+ owner = _require_owner(request, session_id)+ person_ids = sorted(set(body.person_ids))+ if person_ids and session_mail_private(session_id):+ raise HTTPException(+ status_code=409,+ detail="This chat read your own mail, so it stays yours alone.",+ )+ from openexecutive.people.store import get_person++ for pid in person_ids:+ person = get_person(pid)+ if person is None or person.archived or person.kind != "team" or pid == owner:+ raise HTTPException(status_code=422, detail=f"Can't share with person {pid}")+ added, removed = set_shares(session_id, person_ids, owner)+ if added or removed:+ from openexecutive.audit import log_event++ with _owner_rows(session_id, owner):+ log_event(+ "session_shared",+ f"Chat shared with {len(person_ids)} people (+{len(added)} -{len(removed)})",+ session_id=session_id,+ actor="user",+ details={"by_person_id": owner, "added": added, "removed": removed},+ )+ return _share_list(session_id)++[email protected]("/sessions/{session_id}/export")+def export_session(session_id: str, request: Request) -> Response:+ """The chat as a Markdown file, for anyone who may read it."""+ _require_read_access(request, session_id)+ meta = get_session_metadata(session_id)+ if meta is None:+ raise HTTPException(status_code=404, detail="Session not found")+ _, owner = get_session_owner(session_id)+ text = chat_export.to_markdown(meta, owner_person_id=owner)+ return Response(+ content=text,+ media_type="text/markdown; charset=utf-8",+ headers={+ "Content-Disposition": f'attachment; filename="{chat_export.file_name(meta["title"])}"'+ },+ )+++class RewindRequest(BaseModel):+ """The id of the reply being replaced, which must still be the chat's last."""++ last_message_id: int+++class RewindResponse(BaseModel):+ """The words of the turn just removed, to send again (Try again) or as+ the starting point of an edit."""++ message: str++[email protected]("/sessions/{session_id}/rewind", response_model=RewindResponse)+async def rewind_session(session_id: str, body: RewindRequest, request: Request) -> RewindResponse:+ """Take back the chat's last turn so the owner can ask it again, as it+ was (Try again) or edited. The page then sends the message as a normal+ turn, through the same gates as any other.++ Web chats only: a Slack, Telegram or Discord conversation also lives in+ that app, where the reply can't be taken back. 409 while a turn is+ answering in this chat, or when the page's last reply is no longer the+ chat's last (another tab moved on)."""+ owner = _require_owner(request, session_id)+ if _is_channel_namespaced(session_id):+ raise HTTPException(status_code=409, detail="Only a chat started here can be redone.")+ lock = await _acquire_session_turn(session_id, 0.5)+ if lock is None:+ raise HTTPException(status_code=409, detail="The Executive is still answering in this chat.")+ try:+ asked = rewind_last_turn(session_id, body.last_message_id)+ finally:+ _release_session_turn(session_id, lock)+ if asked is None:+ raise HTTPException(status_code=409, detail="This chat has moved on. Reload it and try again.")+ from openexecutive.audit import log_event++ with _owner_rows(session_id, owner):+ log_event(+ "session_rewound",+ f"Last turn taken back (reply {body.last_message_id})",+ session_id=session_id,+ actor="user",+ details={"last_message_id": body.last_message_id, "messages": len(asked)},+ )+ return RewindResponse(message="\n\n".join(asked))@router.delete("/sessions/{session_id}", status_code=status.HTTP_204_NO_CONTENT)diff --git a/packages/core/openexecutive/architecture/architecture-facts.yaml b/packages/core/openexecutive/architecture/architecture-facts.yamlindex cae695fe..3a88a545 100644--- a/packages/core/openexecutive/architecture/architecture-facts.yaml+++ b/packages/core/openexecutive/architecture/architecture-facts.yaml@@ -2324,6 +2324,26 @@ memory:session_store.delete_session drops the rows. Complements, not replaces,the folder sync (knowledge collections: DRIVE): a synced folder is knownwithout a search; this remembers whatever else a conversation read.+ chat_controls: |+ The owner's controls on a saved chat (api/routes/sessions.py). Pin+ (sessions.pinned_at; pinned chats list first) and rename+ (sessions.title_locked: session_store.update_session_title, the automatic+ title, never overwrites a name the owner gave). Share, read-only, with+ named team members (session_shares; PUT /sessions/{id}/shares sets the+ exact list; contacts, the archived and the owner refused). A reader may+ open, list (GET /sessions/shared-with-me) and export the chat and nothing+ else; every write route keeps the usual owner check. A mail_private chat+ (Act as me read the owner's mail) is never shared and stops being+ readable by earlier readers. Export (memory/chat_export.py) is Markdown+ with each message under its writer's People name or Executive and the+ reply's sources. Try again and Edit both call POST+ /sessions/{id}/rewind, which, under the conversation's turn lock and+ only while the given reply is still the chat's last row, deletes the+ last turn and returns the person's words; the page resends them (or the+ edit) as an ordinary /chat turn through the same gates. Web chats only:+ a chat-app conversation's reply also lives in that app. The page asks+ first when the reply being redone already did something (action chips),+ since the new turn could do it again.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 d5fd7561..8d88caf1 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/{id}`, `GET /sessions/{id}/messages`, `DELETE /sessions/{id}`, `POST /sessions/{id}/messages/{message_id}/feedback`, `GET /sessions/{id}/followup` | List, read and delete saved chat sessions (assistant messages carry their row `id` and any `feedback`). The list is scoped to the caller, 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. |\n| `today` | `GET /today`, `GET /today/activity`, `GET /today/activity/daily`, `GET /today/brief-delivery`, `GET /today/value`, `GET /today/top-three`, `GET /today/weekly-review` | Morning-brief aggregation, recent-action rail, Pulse heartbeat heatmap (per-day activity counts), and the owner's Your month tally (`GET /today/value?period=month|week&offset=N`: counted lines beside the period before plus the finished reports, owner only, 403 otherwise; see Today). `GET /today` carries the viewer's cached \"What's going on\" `narrative` with `narrative_generated_at` (when it was written) and `narrative_stale` (a fresher one is being written — the page re-polls; see Today). A proposal backed by a roster request carries `roster_request` (the new sender's server-derived details and held-message previews; the principal's only) and is answered through the `people` routes below. `brief-delivery` returns the latest morning brief or end-of-day digest that didn't reach the owner, as `{brief, at, problem, fix, readable}` in plain language (`readable` is false when it couldn't be written, so there is nothing to read), or null — null while briefs go out, once the cause is fixed, while the scheduler is off, and for anyone but the owner (`chat._caller_is_principal_or_unclaimed`); it carries no address or channel id. `top-three` and `weekly-review` feed the solo Briefing's own cards and answer only in solo mode and only to the principal (`workflows._caller_is_the_principal`: a principal match or no caller header, never an unclaimed roster); anyone else, and team mode, get null. `top-three` returns `{items: [{key, kind, text, why, slot}]}` — the morning brief's top three from the same code (`build_top_three(principal_due_soon())`), `slot` a free block like `10:00–11:00`, `\"\"` when none is left, null when no calendar was read — and is kept off `GET /today` because its calendar read may take up to 4 s. `weekly-review` returns the latest completed `weekly_review` run as `{run_id, completed_at, period, top_three, excerpt}` (next week's top three as plain text; `excerpt` when that list is empty), or null when none has completed. |\n| `people` | `GET\\|POST\\|PATCH /people`, `POST /people/{id}/archive`, `GET /people/requests`, `GET /people/requests/{id}`, `POST /people/requests/{id}/approve`, `POST /people/requests/{id}/decline`, `GET\\|POST /people/{id}/open-loops` (a `POST` tells the owner once and returns `notified`: `sent` with the channel, `held`, `not_reached` or `skipped`; see Attunement), `POST /open-loops/{loop_id}/close`, `GET /people/{id}/outreach`, `GET\\|PUT\\|DELETE /people/{id}/attunement` | Roster CRUD and scope lookups. Every `Person` carries `kind` (`team` / `contact`). `GET /people` lists team members only unless `?include_contacts=true` (the People page asks for both; the department-head and workflow pickers keep the default); `POST` / `PATCH` accept `kind`, and a principal contact is a 422 either way. They also take `email_aliases` (other addresses the person writes from, at most 10; on `PATCH` the full list replaces the current one, omitted leaves it): an alias matches their mail and may be emailed but never signs in; a malformed one is a 422, and an alias — or a new primary `email` — that is already someone else's address or alias is a 409. Every `POST` / `PATCH` then closes any pending roster request whose sender now matches someone and replays its held messages. Adding, editing and archiving (`POST`, `PATCH`, `/archive`) are the principal's only, or anyone's while no one is principal yet so a first setup can add its owner (`chat._caller_is_principal_or_unclaimed`, the check behind `PUT /workspace`; a request with no `x-caller-email`, such as the CLI or local login, counts as the principal). Anyone else, a person editing their own row included, gets 403 before the person lookup, so it can't probe which ids exist. Contacts are private to the principal (`caller_is_principal`: the signed-in email is the principal's, or no `x-caller-email`; stricter than the owner rule above, so while no one is principal nobody is): for anyone else `include_contacts` is ignored, a contact's id is a 404 on `GET /people/{id}` and open-loops (exactly as for a missing id; `PATCH` and archive are already a 403 for them), and creating a contact or turning someone into one is a 403, even on a first setup with no principal yet. `GET /people/me` returns `{person_id, is_principal}` so the UI offers contacts to the principal only. `GET /people/by-scope/{token}` never returns a contact. Archiving a person closes their open loops. The open-loop routes list what a person owes (soonest due first) and close one (`reason`: done / not_needed / cancelled) — both the principal's or the owner's only (403 otherwise, via `people.store.is_principal_or_self`). `POST /people/{id}/open-loops` `{task, due_date?}` assigns that person a task (201 with the loop; `due_date` is a local date, due 17:00 in the user's timezone, clamped to 60 days, default 2 days): any active team member may assign anyone on the team, 403 for anyone else; 409 for an archived person, a contact (as seen by the principal), a person at the open-loop cap, a duplicate or open loops turned off; 422 for an empty task. Nobody is messaged at assignment — the owner is chased once it is due. `/outreach` returns, per kind of proactive outreach over 30 days, `sent` / `replied` / `acted` / `ignored` / `pending` (voided DMs are excluded) — same access rule, checked before the person lookup so it can't probe which ids exist. `/attunement` reads, replaces (`rules`: up to 4 strings, or omitted to only set `locked`) or resets the person's working-style rules — same access rule, 404 for an archived person; `PUT` rejects a rule that is not purely about style with 422. Archiving a person also drops their working style and frees their aliases. The **roster-request** routes (declared before `/people/{person_id}`) are the principal's alone (`caller_is_principal`; anyone else gets 404, as for a missing id): `GET /people/requests?status=pending|approved|linked|declined|expired|superseded|all` lists up to 100 (`id`, `channel`, `channel_ref`, sanitised `display_name`, `profile_email`, `on_company_domain`, `suggested_kind`, `suggested_person_id` / `_name`, `status`, `resolved_person_id` / `_kind`, `message_count`, timestamps, `ack_sent`, and `previews` of the held messages while pending — shown to the principal, never to a model); `approve` takes either `link_person_id` (+ `replace_channel_id`) or `full_name` + `kind` (no default: 422 without both) + optional `role`; `decline` takes no body. An answered request is a 409, a chat id or address already on someone else is a 409; the held messages are replayed (or dropped) in the background. |\n| `departments` | `GET\\|POST\\|PATCH\\|DELETE /departments`, `.../goals` | Department state and per-department goals. `PATCH /departments/{slug}` also takes `watched_entities` (≤50 names, `[]` clears) — the entities the research watch policy may add watches for and route to this department. A `cadences` spec that does not parse is rejected with a 422 (empty means no cadence, i.e. the check-in is off); a changed `check_in` cancels the pending check-in and queues the next one on the new schedule. `GET` and `PATCH /departments/{slug}` return the department state plus `next_check_in_at` (ISO UTC of the pending check-in, `null` when it is off, the workspace is solo or none is queued); the list route does not carry it. A new `head_person_id` must be a team member: an unknown id and one of the principal's contacts get the same name-free 422 (`person_id N is not on the team.`), so the route — open to any signed-in user — never reveals that a contact exists; an unchanged head is not re-checked. `POST .../goals` requires only `key_result`: a missing or blank `period_value` is filled with the current period for `period_type` in the user's zone (the same label `create_goal` uses), and `target` defaults to empty. `PATCH .../goals/{id}` rejects a blank `key_result` or `period_value` with a 422; `target` may be cleared. |\n| `agents` | `GET /agents`, `GET /agents/models`, `GET /agents/models/options`, `GET /agents/presets`, `POST /agents/presets/{id}`, `PATCH /agents/{id}`, `POST /agents/{id}/test` | Specialist metadata and Council overrides. `/agents/models` is the flat model allowlist the PATCH validator uses; `/agents/models/options` returns the same ids in the same order, each tagged with `provider`, `provider_label`, `route` (`direct` / `openrouter` / `local`) and a display `label`, for the Council's Provider → Model picker. `AgentDetail` carries `instructions` (additional instructions, appended after `prompt`, which stays the built-in prompt or its replacement); `PATCH` and `/test` accept `instructions` (max 4,000 chars, blank clears it). `GET /agents/presets` lists the Fast, Balanced and Thorough quality presets (each with `available` and the resolved `model` for this install) plus `active` (null when the council is Custom), `base` and `custom_agents`; `POST /agents/presets/{id}` applies one by writing per-agent model and deep-reasoning overrides and returns the same shape (404 unknown preset, 409 when the install allows none of its models). Each `AgentMeta` carries `visibility` (`core` or `internal`) so the Council's simple view can list core agents first. |\n| `personas` | `GET\\|PUT\\|POST\\|DELETE /personas` | Executive persona definitions. |\n| `alerts` | `POST /alerts/{id}/approve`, `GET /alerts/approvals/{id}`, `POST /alerts/{id}/ack`, `POST /alerts/bulk-ack`, `POST /alerts/{id}/snooze`, `POST /alerts/{id}/reopen`, `POST /alerts/review` | Groom the briefing queue. `approve` (body `{edited_body?}`, 202) carries a proposal card out on the server and records who approved it and when (`alerts.approvals`, see Today): it queues the scheduled action a department-gated card held, or runs one Executive turn as the approver in a new chat (`session_id`). 409 for a card already approved or closed, a decision-backed card (approved at `/decisions`), a roster request or a drafted artifact; 403 unless the caller is the card's routed person or the principal (an unrouted card is the principal's); 429 when the caller already has three background turns running. `GET /alerts/approvals/{id}` reads one back (`running`, then `done` / `failed` with `outcome`) for its approver, the card's person or the principal (404 for anyone else). `snooze` (`until`, an ISO time up to 30 days ahead; `null` clears it, the Undo) hides an `unread` card until then by setting `snoozed_until` (409 on a closed card or a roster request); the TTL then counts from the snooze, so a card snoozed past its TTL still comes back. `ack` (`read`/`ack`/`dismissed`, optional `mute_topic`) also teaches a watch-sourced alert's watch (`trust_score`); `bulk-ack` takes explicit `alert_ids` and/or `older_than_days` + `category` (exempt sources skipped); `reopen` is the Undo for a `resolved` / `expired` / `dismissed` alert (never `ack` or an artifact / decision row; back to `unread` with every review stamp cleared and its TTL anchor refreshed, so it is live again even if older than its TTL); `review` runs the Executive's relevance review on demand (ignores the interval; still honours `ALERT_REVIEW_ENABLED`, the per-pass caps, the single-flight lock and per-alert idempotency) and returns the move counts. `bulk-ack` caps ids at 500, needs `older_than_days >= 1`, and applies watch feedback per row; `mute_topic` must be one of the alert's tags or a scoped `external:` / `department:` pattern. Alerts still surface only through the briefing (`/today` reads the live view) — there is no list, prefs, mutes, or live-stream endpoint. |\n| `artifacts` | `GET /artifacts`, `GET /artifacts/{id}`, `GET /artifacts/{id}/download?as=`, `POST /artifacts/{id}/archive`, `POST /artifacts/{id}/restore`, `DELETE /artifacts/{id}` | Browsable deliverables in any format — Markdown, HTML, Word, Excel, or a link into a connected app — with `format`, `downloads`, `external_url`, `supersedes_id` and, for an extension's kind of document, `collection` / `collection_label` on every summary (`orchestrator.extensions`; archive, restore and delete tell the collection first and answer 502 if it refuses). `download` renders the file (Word/Excel built at request time from the stored text; any Markdown artifact, workflow output included, can export `?as=docx`) and is always an attachment with `nosniff` and a sandbox CSP. Every route answers for the signed-in caller (`artifact_records.Viewer`): a drafted artifact is its owner's alone (`alerts.owner_person_id`, the person whose conversation published it; none = the principal's), a workflow output follows its run (`persistence.run_visible_to`), and anything the caller may not see is a 404 like a missing id, the principal included. `POST /alerts/{id}/ack` and `/reopen` answer 404 for someone else's drafted artifact the same way. |\n| `decisions` | `GET /decisions`, `POST /decisions/{id}/{approve,reject,cancel}`, `GET`/`PUT /decisions/classes/meeting_scheduling`, `GET /audit/reliability` | Approval-gated decision instances (e.g. calendar bookings). What approve/reject/cancel do is per class (`DECISION_CLASSES`, one `DecisionClassSpec` each; meeting booking books on approve and deletes on cancel; `delegation_reply`, an inbox reply card, is its approver's alone (`approver_only`) — hidden from everyone else, the principal included when it is a team member's — sends its Gmail draft on approve and, after a reject, deletes the draft unless it was edited; `department_action`, a team member's chat send or edit their department held (see Org), is the principal's and its approver's alone (`principal_and_approver`), makes that exact call on approve and audits `department_action_done` / `_failed` / `_declined`), and an instance of a class with no spec gets 409 instead of being carried out as another. Only the principal, or the person the decision went to for approval (`approver_person_id`), may approve, reject or cancel it. Anyone else gets 403, and a decision nobody was asked about, or one private to the principal, is the principal's alone. The resolver is recorded as `resolver_person_id`, and a reject that loses the race to another answer is a 409. `GET /audit/reliability` is the principal's alone (403 otherwise), because it counts private decisions too. A proposed booking is surfaced on the briefing as a companion alert; approve/reject/cancel here also clear that alert. An approval whose caller resolves to the principal runs the booking inside `grant_contact_egress()`, so a meeting the principal proposed with a contact can be created. Such a booking's payload is marked `private`: it is proposed to the principal, left out of anyone else's `GET /decisions`, and a 404 for them on `GET /decisions/{id}` and every action route. Reviewed in the briefing — there is no separate proposals page. The class routes read and set how meetings are handled: both return `{decision_class: \"meeting_scheduling\", mode: \"propose\" \\| \"auto_execute\"}` (default `propose`); the `PUT` body is `{mode}`, principal-only (403 otherwise, open before a principal exists — but then only `propose` can be set: `auto_execute` is a 409 until a non-archived principal is on the roster), 422 on any other mode, and a change writes a `decision_class_mode_changed` audit row. In solo mode the class mode decides a booking, and `auto_execute` applies only to a turn the principal started on a verified surface — any other turn gets a proposal. |\n| `delegation` | `GET`/`PUT /delegation`, `GET`/`PUT`/`DELETE /delegation/voice`, `POST /delegation/voice/learn`, `POST /delegation/voice/describe`, `POST /delegation/voice/signature`, `PUT /delegation/inbox`, `POST /delegation/inbox/check`, `GET /delegation/replies`, `PUT /delegation/replies/{id}/text`, `GET /delegation/actions`, `PUT /delegation/handle-it`, `PUT /delegation/disclosure`, `PUT /delegation/training`, `DELETE /delegation/learned/{id}`, `GET /delegation/handled`, `PUT /delegation/team` | Act as me — the **caller's own** delegation only; nobody sets it for anyone else. It answers the principal, and a team member once the owner lets them; anyone else gets 403 `not_available_yet`. `GET /delegation` returns `{enabled, gmail: {status, message, email, connect_command, outlook_connect_command, provider}, inbox: {enabled, status, message, watch_since, last_poll_at, checking}, handle_it: {enabled, mode, available, sent_today, lead, lead_available}, training: {replies, follow_ups, actions, drafts, learned}, disclosure: {enabled, handle_it, approved_sends, line}, team}`, where `team` is the owner's switch for the principal while `DELEGATION_TEAM_MEMBERS` allows it — `{enabled, members: [{person_id, name, enabled, inbox, drafts_30d, sent_30d}]}`, counts only — and `null` otherwise. `PUT /delegation/handle-it` takes `{enabled?, mode?}` (`mode` is `careful`, `balanced` or `bold`; anything else is a 422 `bad_mode`) from a caller the API knows is that person — 403 `not_yours`, 409 `caller_signing_required` with only the shared secret — and turning it on needs Act as me and Draft replies to my inbox on (409 `act_as_me_off` / `inbox_off`); `GET /delegation/handled` returns `{replies: [{decision_id, sent_at, to_name, to_email, subject, body, open_questions, gmail_link, source}]}`, the caller's replies and follow-ups (`source` `follow_up`) sent on its own in the last 7 days; a card on `GET /delegation/replies` carries `source` the same way, `can_allow` while Replies (Follow-ups, on a follow-up) is in training, and `learns_style` while Drafts is. `PUT /delegation/disclosure` takes `{handle_it?, approved_sends?}` (any other field is a 422), the caller's own switches for the AI line on replies sent as them (`disclosure.enabled` is the install's `AI_DISCLOSURE`); turning one on needs no signed sign-in, turning one off does (409 `caller_signing_required`), and a change is audited as `delegation_disclosure_changed`. `PUT /delegation/training` takes `{replies?, follow_ups?, actions?, drafts?}` (any other field is a 422) and returns the `GET /delegation` shape; putting Replies or Follow-ups in, or Suggested actions out, needs no signed sign-in, anything else does (409 `caller_signing_required`), and putting Replies or Follow-ups in turns Take the lead as you off (`PUT /delegation/take-the-lead` on answers 409 `in_training` while they are). `training.learned` is `[{id, label, setting, example, uses, created_at}]`, what the caller allowed or kept in training (`setting` `replies`, `follow_ups`, `actions` or `drafts`; the kept example, or \"\"); `DELETE /delegation/learned/{id}` removes one of the caller's own (404 for anyone else's). `PUT /delegation/team` takes `{enabled}` from the principal alone (403 `principal_only`; 409 `not_available` when the install doesn't allow it). The Gmail `status` is `connected`, `not_configured`, `needs_reconnect`, `mismatch`, `no_email`, `shared_mailbox` or `error`, checked live with Google on each call. `PUT` takes `{enabled}` (any other field is a 422); turning it on needs the caller's own Gmail connected, otherwise a 409 whose code says why (`gmail_not_connected`, `gmail_needs_reconnect`, `gmail_mismatch`, `no_email`, `shared_mailbox`, `gmail_error`). The voice routes show, learn (from the caller's sent mail, one pass at a time — a 409 `in_progress`, `locked`, `too_soon`, `not_enough_mail`, `no_profile` or `changed` when it was locked or edited while learning, or a Gmail code), write it from the caller's own description (`POST /delegation/voice/describe` with `{description}`: one model call applies their words to the profile they have and returns it with a short `sample_reply`, saving nothing, so they review it and save it with `PUT`; a 409 `empty`, `too_long`, `in_progress`, `too_many` past 10 an hour or `no_profile`; no mailbox needed), edit and lock, and reset \"How I write\": a typed field that fails validation is a 422 `invalid_voice` listing each `rejected` field, and `clear_exemplars` / `clear_signature` drop those. `POST /delegation/voice/signature` reads the signature from the caller's Gmail settings again and changes nothing else (a locked profile stays locked), with the same Gmail codes as learning: a 409 when their mailbox isn't connected, it refuses the sign-in or the check itself fails (`gmail_error`), and a 502 `gmail_error` when reading the signature fails. On an Outlook mailbox it is a 409 `signature_unavailable`, since Outlook gives apps no signature to read, and the stored one is left alone. A caller `can_delegate` refuses — anyone but the principal, for now — gets 403 `not_available_yet`, which hides the Settings card. A request with no `x-caller-email` is a 403 `sign_in_required` unless the API runs under local login — a header-less call is not a sign-in (the caller is read through `api/caller.py`, as on every principal-only route). `PUT /delegation/inbox` takes `{enabled}` and turns **Draft replies to my inbox** on or off, returning the same shape as `GET /delegation`: on needs Act as me on (409 `act_as_me_off`) and the mailbox connected (the Gmail codes above, which keep their names for an Outlook mailbox too), and turning Act as me off turns it off too. `POST /delegation/inbox/check` starts a scan now in the background and answers 202 with the `inbox` state (409 `inbox_off` or `in_progress`). `GET /delegation/replies` returns `{cards: [...]}`, the caller's open reply cards from the database alone (no Gmail call): the decision id, the sender's name, address, relation and whether it was verified, the subject, when it arrived, what they wrote, the draft's recipients, subject and body, `open_questions`, `flags` and a Gmail link built from a fixed prefix. **Send** is `POST /decisions/{id}/approve`: it sends the card's draft exactly as it is in Gmail, after checking again that the caller is its owner — which on a server needs signed callers (409 `caller_signing_required` otherwise) — that both switches are on (`inbox_off`), no client slot is active (`client_slot`), the Gmail is connected (the Gmail codes), the draft is still there and unanswered (`draft_gone`, `you_replied`) and its recipients are allowed (`no_recipients`, `too_many_recipients`, `executive_recipient`, `not_from_you`). Recipients that changed, or a newer message in the thread, answer 409 `{code: \"confirm\", message, reasons, recipients}`; approving again with `edits: {recipients: <the list shown>, thread_moved_on: true}` is the second yes. **Send + allow** adds `edits.allow: true`: 422 `cant_allow` unless Replies (Follow-ups, on a follow-up card) is in training, 409 `learned_full` when their list is full, both before anything is sent; `edits.example: true` keeps a draft edited in the mailbox as how they write to that person while Drafts is in training. A draft edited in Gmail between those checks and the send is not sent (`draft_changed`). A double tap sends once (`already_handled`); Gmail refusing answers 429 `rate_limited` or 502 `gmail_error` with nothing sent, and a send Gmail didn't confirm answers 502 `send_unconfirmed` and is settled by the next inbox scan. Dismiss is `POST /decisions/{id}/reject`. `GET /delegation/actions` returns `{cards: [...]}`, the caller's own approval cards (`delegation_actions`): the decision id, when it was made, a one-line `why`, and each action's `index`, `kind` (`invite`, `message`, `add_contact`), `summary` and `text` (a message as it will be sent, or a meeting's description). **Approve** is `POST /decisions/{id}/approve` with `edits: {only: [indexes]}` (and `allow: true` for Approve + allow while Suggested actions is in training: 422 `cant_allow` otherwise or when nothing on it can be allowed, 409 `learned_full`; a card carries `can_allow`); it needs the card's own person signed in (403 `not_yours`, 409 `caller_signing_required`), Act as me on (409 `act_as_me_off`) and a card under a week old (409 `expired`), runs once (409 `already_handled`), and returns the decision with `final_payload_json.results`: per action `done`, `waiting` (sent to whoever approves meetings), `failed` with why, or `skipped`. Every change writes a private audit row. |\n| `history` | `GET /memories/history` (`?q=`), `PUT /memories/history/settings`, `PATCH`/`DELETE /memories/history/{id}`, `POST /memories/history/{id}/forget-conversation` | Always in the loop: the **caller's own** notes and switches only, resolved as for Act as me (a signed-in person on the roster, or the principal under local login; otherwise 403 `sign_in_required` / `not_on_roster`). `GET` returns `{notes, reply_notes, retention_days, effective_retention_days, company_retention_days, retention_choices, can_keep_notes, can_note_replies, can_set_company_retention, share_work_style, can_share_work_style}` (`can_keep_notes`: a team member on the People list may turn notes on; `can_note_replies`: they can use Act as me, so email replies are noted too; `share_work_style`: their own \"Share my work style with the team\" switch, `can_share_work_style`: a team member in a team workspace). `PUT` turns notes on only for someone who may keep them, and `share_work_style` on only for someone who may share it (403 `not_available` for either; turning either off always works), takes a person's retention only when shorter than the company's (422 `invalid_setting`), and the company retention only from the principal (403 `principal_only`). `PATCH` pins or corrects a note; `DELETE` forgets it; `forget-conversation` is \"Don't remember this\". A note that isn't the caller's is 404. Every change is audited privately to its person. |\n| `notifications` | `GET /notifications/settings`, `PUT /notifications/settings` | Settings → Notifications: the **caller's own** settings only, resolved as for the notes (a signed-in person on the People list, or the principal under local login; otherwise 403 `sign_in_required` / `not_on_roster`). `GET` returns `{quiet_hours: {enabled, start, end, days}, delivery, urgent_through, timezone, effective_timezone, held_count, gets_briefs, updated_at}` — `days` is `every_day` or `weekdays`, `delivery` `instant` or `digest`, `timezone` the zone they chose (`\"\"` for the workspace's), `held_count` how many messages wait for their quiet hours or brief (counted, never listed), `gets_briefs` whether they are the principal. `PUT` takes `{quiet_hours, delivery, urgent_through, timezone}` and replaces them (extra fields, equal start and end, a bad time or an unknown zone → 422); switching `digest` → `instant` makes what waited for the brief go now. Audited as `notification_settings_changed`. See Org. |\n| `audit` | `GET /audit/logs`, `GET /audit/logs/{id}`, `GET /audit/sessions/{id}`, `GET /audit/usage`, `POST /audit/log` | Durable audit trail of side effects. `/audit/sessions/{id}` adds a per-session token cost summary; `/audit/usage` aggregates token usage and OpenRouter cost across all sessions (totals, by day, by model, and by source — the part of the system that made the calls — including server-side web-search counts), plus `scripts`: how many `run_script` scripts ran (and worked, and in workflows), the tool calls they made, their time, and `turns_avoided` — an upper bound on the model turns those calls would otherwise have needed (each call past a script's first) — and `python_jobs`: how many Python jobs ran (and worked, ran a kept Custom tool, took a chat attachment), their time, CPU, largest peak memory and bytes in and out, and the tokens and charge of the turns that ran one. The Token usage page shows it as a Scripts section. Rows private to the principal (`private_to_principal`: a turn about their private mail, or a row naming one of their contacts on their own turn) are theirs alone: for any other caller, resolved as for `/alerts`, the usage totals leave them out. Once a principal is on the roster, anyone else reads only their own rows (a teammate's own turns, their Act as me work) in the list, by id and in a session, and the principal reads those as actions only — what was done, when and in whose conversation, with the text, details and `full` left out, and no text search over them; any other row's id is a 404, and a session shows only the rows the caller reads. |\n| `architecture` | `GET /architecture/sections`, `.../sections/{id}` | This documentation surface. |\n| `guide` | `GET /guide/sections`, `.../sections/{id}` | Plain-language user-guide content surface — mirrors `architecture` (static, version-controlled files; no LLM on the serving path). |\n| `health` | `GET /health`, `GET /health/honcho` | Liveness probes. Only `/health` is unauthenticated; `/health/honcho` sits behind the gate like everything else, because the exemption is an exact-path set. `/health` also carries `google_tools_missing`, the pinned Google tools startup priming could not find: `[]` once it has checked and they are all there, a list of names when a workspace-mcp rename or the configured services and tool tier left one out, and `null` for no answer — Google Workspace is not configured, or the probe has not finished or it failed. Only `[]` asserts they are present. It also carries `gateway`, the MCP gateway's state from its supervisor (`orchestrator.gateway_boot`): `state` is `off` (MCP not enabled), `no_servers` (enabled, the config names none), `starting` (an attempt is running), `up` or `down` (every attempt so far failed; `next_retry_at` is the next one), with `attempts`, `up_since` and `email_poller` (whether the poller that rides on the gateway runs); the failure's own text stays out, since the route is open to anyone, and goes to the log and the owner's notice on Home. A hosted instance whose gateway never came up used to answer `ok` here with no email going out or in. Only `[]` asserts the tools are present, so a probe that died cannot read as healthy; Setup status says which of the three `null` means. |\n| `version` | `GET /version` | The running version, the latest release on GitHub and `update_available`, for Settings → About. The GitHub answer is cached 6h, only a semver `tag_name` is used and the release link is built from it; `UPDATE_CHECK_ENABLED=false` skips the call and still returns the running version. No in-app updater: upgrading is host-side (`docs/deployment.md#upgrading`). |\n| `setup_status` | `GET /setup/status` | Settings → Setup status: one light per part of the install — AI model, company setup, owner, the Executive's address, API protection, Gmail, your own mailbox (Act as me), Slack, Discord, Telegram, Google Chat, the scheduler, the daily brief (when and where it goes) and Honcho — as `{checked_at, checks: [{id, label, state, summary, fix, link, last_activity}]}`, where `state` is `ok`, `warn`, `error` or `off` (optional and not set up), `fix` says what to do in plain language, `link` is an in-app page that helps (`/people`, `/onboard`) and `last_activity` is the channel's latest `integration_inbound` audit time. It tests live, with at most one free read-only call per service, each bounded to 5 s: Anthropic `models.list` (so an organisation key missing `ANTHROPIC_WORKSPACE_ID` shows up), Slack `auth.test`, Telegram `getMe` and `getWebhookInfo`, Discord `users/@me` only while the bot is still connecting, and — once the owner's own Gmail credential exists — Google's token refresh and Gmail `users/me/profile`. It also reads the listeners the lifespan leaves on `app.state` (Slack's socket, the Discord bot and its task, the MCP gateway), the scheduler heartbeat and the pause switch. When `google_workspace` is configured, the lifespan also starts `MCPGateway.prime_pinned_tools()` in the background (held on `app.state.mcp_prime_task`, cancelled at shutdown), so the pinned Google tools named in the prompt are callable without a search. With `DRIVE_SYNC_ENABLED` the lifespan also bootstraps the `drive_sync_scan` heartbeat beside Notion's (see Scheduler); the Drive folder sync has no HTTP route, only the `openexecutive sync-drive` / `purge-drive` CLI. With `CONFLUENCE_SYNC_ENABLED` it bootstraps the `confluence_sync_scan` heartbeat the same way; that sync is run by hand with `openexecutive sync-confluence` / `purge-confluence`. Sample values copied from `.env.example` are named as such without being sent anywhere. No token reaches a response or a log line: probes report a status code, a service's short error code or an exception's class name. Requests within 5 s of a run get that run's answer and concurrent requests share one run (kept per app on `app.state`), so the button can't become a stream of calls to those services. Gated like every other route; the UI adds a sign-in light of its own, from its own settings. |\n| `documents` | `POST\\|GET\\|DELETE /documents`, `GET /documents/{filename}`, `GET /documents/sources`, `POST /documents/sources/{drive\\|onedrive\\|notion}/sync`, `GET /documents/{drive\\|onedrive\\|notion}`, `GET /documents/{drive\\|onedrive\\|notion}/{id}` | Upload, list, view extracted text, and delete indexed company docs. `GET /documents` rows carry `source: \"upload\"` and the `domain` the upload was indexed under. The connected-source routes back the knowledge page's single Company documents list: `/documents/sources` gives each source's `{id, label, enabled, syncing, last_run, last_error, interval_minutes, file_count}`; `/documents/drive`, `/documents/onedrive` and `/documents/notion` list synced files from the sync state (`{enabled, last_run, last_error, files: [{id, name, url, modified_at, synced_at, indexed}]}`; a Drive row also carries `unreadable_reason`, why a file with `indexed: false` has no text — e.g. a scan OCR could not read — or null); `/documents/{drive\\|onedrive\\|notion}/{id}` returns the stored text (a OneDrive id is `<drive id>:<item id>`) for an id on record (the path comes from the state, never the caller). They are read-only — a synced file is removed where it lives. `POST …/sync` starts one tick of the same sync the scheduler runs as a background task (202); 409 when the source is not connected or a tick is already running (every sync holds a per-process run lock, so a manual run never overlaps the heartbeat; the route also keeps its own started task per source and re-checks just before starting one, so two simultaneous requests start one tick, not two), 429 with `Retry-After` within 60 s of the last successful run or of the end of the last tick in this process, failed ones included, so a failing or slow source can't be re-run back-to-back. The page's text view never loads images from synced content (a remote image would be a read beacon for whoever edits the shared folder). Upload is keyed on the filename, so re-uploading a document replaces its chunks rather than duplicating them, and `DELETE` removes the rows as well as the file. `domain` must be one of the nine specialist domains (including `sales`) or `general`; anything else is a 400 rather than a 200 that indexes where no specialist can retrieve. A scanned PDF is converted (`knowledge.pdf_reader`) before it is indexed and in the text view, as are scanned PDFs in `POST /chat/upload` and the client / onboarding intake uploads. The upload is streamed to disk 1 MB at a time and refused with a 413 once it passes 50 MB, and the file is parsed in a short-lived child process (see the RAG section), so a large document does not stay in the API process's memory. A Word or Excel file that cannot be parsed, or whose parse runs out of time, is a 422 with a readable reason. When every parser is busy, the response is a 503 with `Retry-After`. |\n| `executive` | `GET /executive/status`, `POST /executive/pause`, `POST /executive/resume` | Operator pause switch for all autonomous work (scheduler, Gmail poller, workflow resumer); inbound chat and DMs stay live. Status returns `{paused, paused_at, paused_by, reason, held_actions, can_resume}` — `held_actions` counts due `pending` rows that fire on resume. `pause` takes an optional `reason` (≤200 chars) and is idempotent (re-pausing keeps the original start and reason); `paused_by` is the UI proxy's `x-caller-email`, else `api`. Behind the shared-secret middleware — not `SCHEDULED_ADMIN_TOKEN`, which the UI cannot send. Any caller may pause; `resume` is principal-only (`is_principal_or_self`, 403 otherwise; open while no principal is rostered; a header-less caller resolves to the principal as in `chat`), and status carries `can_resume` for the viewer so the UI hides Resume from everyone else. |\n| `workspace` | `GET /workspace`, `PUT /workspace` | Solo/team mode, the user's time zone and the principal's role (`memory.workspace_settings`). Both return `{mode, timezone, effective_timezone, role_kind, role_title, reports_to, remit, measured_on, company_domains, company_domains_custom}` — `timezone` is what the user set (null when unset), `effective_timezone` the zone in effect (`timezone`, else `USER_TIMEZONE`, else UTC), and each role field is null until set. `PUT` is a partial update: only the fields sent change; `mode` is `solo` or `team` (not null), `timezone` an IANA zone, or null/blank to clear it; `role_kind` is `owner`, `in_house`, `independent` or `other`, and `role_title` / `reports_to` / `remit` / `measured_on` are free text (trimmed, at most 120 / 120 / 500 / 300 characters), each null or blank to clear it; an unknown zone, a bad mode or role kind, an over-long role field or an unknown field is a 422 and changes nothing. Switching to solo cancels every pending department check-in, switching to team re-schedules them, and a new zone re-times the pending briefs and reflection; a role change has no side effects (the next turn reads it). `company_domains` is the company's own email domains (a teammate matches by local part on them — see Org): `GET` returns the ones in effect (the stored list, or the domain of the principal's primary address, with `company_domains_custom` false) only to the same caller the role is shown to, `[]` for anyone else; `PUT` takes a list (at most 10 plain domain names, never a free-mail provider's — 422 otherwise, the value never quoted) or null / `[]` to go back to deriving them, and a change is audited with the new list. Each change writes a `workspace_settings_changed` audit row (a role change adds `details.role_fields_changed`, the names of the fields that changed — never their text). The role is the principal's: `GET` returns it only to a caller `PUT` would accept and reads it as nulls for anyone else. `PUT` is the principal's alone (`is_principal_or_self`, 403 otherwise; a header-less caller resolves to the principal as in `chat`) and open while no principal is rostered, so first-run setup can pick a mode. Both work before onboarding — unlike `company-profile`, nothing here needs a profile. |\n| `scheduled` | `GET\\|DELETE` scheduled actions (`?status=…&order=asc\\|desc`) | Pending and fired scheduled actions; `order` flips the `run_at` sort (asc=soonest-first for the upcoming queue, desc=most-recent-first for terminal-status history). `DELETE /scheduled/{id}` cancels a `pending` row (409 otherwise). Like pause it only stops work, so any signed-in user may — the UI proxy's `x-caller-email` is trusted when the request also carries the `BACKEND_SHARED_SECRET` `x-api-key` — as may a matching `X-Admin-Token` (`SCHEDULED_ADMIN_TOKEN`) or a loopback caller with no token set; otherwise 401 (token set) or 503. Audited as `scheduled_action_cancelled`. |\n| `watchlist` | `GET\\|POST\\|PATCH\\|DELETE /watchlist`, `POST /watchlist/{slug}/approve`, `POST /watchlist/{slug}/decline` | External-monitoring watchlist + signals. Rows carry `origin` (`manual` \\| `executive` \\| `research` \\| `research_proposed`); `approve` turns a research suggestion (`research_proposed`, `dry_run`) into a live watch, `decline` `{reason: not_relevant \\| too_noisy \\| wrong_source}` removes it and records the decline (or, for `too_noisy`, keeps it live at a high floor), both 409 unless the row is a pending suggestion; `DELETE ?reason=` on a research-origin row records the decline too. |\n| `workflows` | `GET /workflows`, `POST /workflows/{name}/runs`, `GET\\|POST\\|PUT\\|DELETE /workflows/custom`, `GET\\|DELETE /workflows/custom/{name}/targets`, `POST /workflows/runs/{run_id}/decision`, `POST /workflows/runs/{run_id}/rerun`, `GET /workflows/tools/search?q=`, `GET /workflows/tools/describe?names=` | Workflow catalog, run management, and user-created (dynamic) workflow CRUD. `rerun` queues a failed scheduled run (a department check-in, a saved workflow on a cadence) once more, due now (see Scheduler); the principal may, and for a saved workflow the person it delivers to; 409 for a run that did not fail, one started from `/jobs` (\"Start this one again from its page\") or one already queued again. Custom definitions come back with a server-managed `owner_person_id` (the creator — the web caller on `POST`, set on insert only; a client-sent value is ignored), who is asked to approve a workflow's first write to a new target. `GET /workflows/custom/{name}/targets` lists the targets its tool steps may write to without asking and `DELETE …/targets?value=` forgets one. `POST /workflows/{name}/runs` is a 403 (\"Only the principal can run this workflow.\"), audited, before any run row exists, when the workflow is one only the principal may start in the workspace's mode (`weekly_review` always, `morning_brief` in solo) and the caller is not the principal. A request with no `x-caller-email` counts as the principal; with no principal on the roster, no signed-in caller does. This governs starting a run only. A run started by hand (this endpoint, or `run_workflow` / research in chat) records its starter as `owner_person_id` and is theirs alone: `GET /workflows/runs` lists the team's (scheduled, no owner) runs plus the caller's own and the ones waiting on them, and `GET` / `DELETE /workflows/runs/{run_id}` and `POST /workflows/runs/{run_id}/decision` are a 404 for anyone else's, the principal included. A signed-in email that is on nobody's People entry cannot start one (403), and a run whose starter can't be read is refused (503); its steps read and draft documents as the starter only. `POST /workflows/runs/{run_id}/decision` with `{decision: \"approve\"|\"reject\"}` answers a run awaiting a yes/no sign-off from the web app — 403 unless the caller is the person it waits on or the principal, 409 if it isn't awaiting or needs a written reply — through the same `apply_resolution` a chat reply uses. Custom create/update also rejects (422) any action-step tool that does not resolve, and so does `POST /workflows/custom/{name}/activate` when turning a workflow **on** — that click is the approval for a tool workflow chat saved switched off (turning off is never checked). Turning on a workflow with action steps requires the body `{is_active: true, definition}` carrying the definition the user reviewed; if the stored one differs (ignoring `is_active` and timestamps) it returns 409, and the switch itself is a compare-and-set on the validated revision (`dynamic_store.activate_if_unchanged`, keyed on `updated_at`), so a save that lands while the tool check awaits the gateway — even from another process — is a 409 too, so only what was shown gets switched on. `GET /workflows/custom` lists inactive definitions too; `GET /workflows/{name}` 404s for them. The two `tools` endpoints return `{tools: [{name, description, read_only, source}]}` for the advanced editor's tool picker and the review card; `read_only` is true only when the name says it reads (a label, not a control). The run stream adds a `progress` event (`step_id`, `summary`) while an action step uses tools. Each catalog entry (`WorkflowMeta`) carries `is_custom`, `background` (true for the system-run built-ins the UI files under “System”) and `quick` (true for a Quick workflow, one per playbook nothing else follows, named `quick_<playbook>`). The run endpoint streams SSE; its `awaiting_human` event carries `delivery` (`self` \\| `sent` \\| `suppressed` \\| `alerted` \\| `failed`) alongside `person_id` / `question` / `awaiting_until`, because the outbound guard or an unreachable approver means the question may never have been asked — a client must not render “waiting on them” for those. A paused run ends the stream with neither `done` nor `error`, so that `awaiting_human` frame carries `terminal: true` to say so explicitly, plus `resumable` — whether the run continues by itself once answered or stops at the gate. `GET /workflows/runs/{run_id}` returns the run row with the resume payload replaced by a small `resume_progress` summary (`gate_step_id`, `completed_step_ids`, or `null`): the payload holds every completed step's full text, and the run-detail page polls this endpoint while a run is unfinished. |\n| `knowledge` | `/knowledge/builtin`, `/external`, `/search` | MBA knowledge base and external sources. `/search` is the introspection parallel of `retriever.retrieve` and mirrors its filters — including the `general` catch-all on the company collection — so the panel cannot report a specialist seeing nothing that it does retrieve in chat. It accepts `general` in `domain_filter` for the same reason. `/search` applies the same review gate as `retrieve()` — withheld (pending or rejected) built-in, external and failure rows are dropped, so the panel never advertises knowledge the Executive cannot use; it degrades to unfiltered rather than failing if review state is unreadable. `POST /knowledge/builtin` refuses a name already held by shipped content, and `POST|DELETE /knowledge/failures` now register and deregister for review — without that a user-authored failure case study had no review row, so no SME decision could block it. |\n| `skills` | `/skills`, `/skills/search`, `/skills/{name}/restore` | Skill registry (the UI's **Playbooks**) CRUD and search. `PUT` on a built-in saves a company customization that shadows it; `DELETE` returns `{name, outcome}` — `deleted`, `reverted` (customization removed, built-in back) or `hidden` (built-in hidden for this company); `restore` un-hides; `GET /skills?include_hidden=true` lists hidden built-ins. List and detail carry `used_by` — `[{name, title, is_custom}]` of the workflows that follow the playbook (switched-off custom ones included) (`WorkflowMeta.playbooks` is the other direction). |\n| `evals` | `/evals/scenarios`, `/evals/runs` | Eval scenarios and run results. `POST /evals/runs` is a 403 when a workflow scenario names a workflow that only the principal may start in the mode it runs in (the weekly review; the morning brief in solo) and the caller is not the principal — the Jobs page's rule for starting a run; stored results are read under the existing `/evals/runs` rules. |\n| `memories` | `/memories/{decisions,initiatives,advice}`, `GET /memories/facts`, `POST /memories/facts/{fact_id}/{retire,approve,decline}`, `GET /memories/facts/approval`, `PUT /memories/facts/approval/{person_id}`, `GET /memories/people`, `GET /memories/people/{person_id}/conclusions` | Episodic-memory record management; the standing facts the Pulse Corrections tab reads (`{facts: [...], can_retire, retirable_ids, can_review}`; each fact carries `recorded_by_role` / `recorded_by_name`; `?include_inactive=` default true, honoured for the principal only; anyone else gets the active rows plus their own `proposed` ones, with the provenance (`session_id`, `turn_id`, `recorded_by_person_id`, `retired_reason`, and `source_quote` except on their own facts) blanked, never retired, replaced or declined text; `?limit=` 1–500) and their retire (the principal any fact, a teammate only one they recorded that the principal has not approved — else 403; the audit row names the teammate; 404 for an unknown or `profile` row, 409 when no longer active; writes a private `fact_retired` audit row); approve / decline a teammate's `proposed` fact (principal only, else 403; 409 when it is not proposed; private `fact_reviewed` row); and the per-teammate \"needs my approval\" switch (on by default; `GET` lists `[{person_id, full_name, needs_approval}]` for every active team member but the principal, `true` for anyone not yet set; `PUT` takes `{needs_approval}`, 404 for anyone else; both principal only; private `fact_approval_changed` row); plus the read-only peer-memory overview the Pulse People tab reads (`{status: ok|disabled|error, people: [...], conclusion_total}`; `?recent=` 1–50, default 5) and one person's full conclusion list, paged newest first (`{status, person_id, items, page, size, total, has_more}`; `?page=` ≥1, `?size=` 1–100, default 50; 404 when the person has no peer). Peer memory is each person's own: the overview holds only the caller's entry (none for a caller off the roster; `conclusion_total` counts only theirs), the principal included, and `/conclusions` for anyone but the caller is a 404. |\n| `review` | `/review/items`, `/review/stats`, `/review/trusted-defaults`, `POST /review/curate`, `POST /review/bulk-approve` | Knowledge review queue and annotations. Shipped knowledge registers as a trusted default (`approved` with a NULL `reviewed_at`), so the queue starts empty; `curate` (`{domain, action: start|stop}`, domain required) opts one domain in or out, and `trusted-defaults` returns domain → unreviewed count. `bulk-approve` takes a non-empty `domain`, `item_ids` (max 500) or `all_pending: true`, and 400s with no selector; it returns `{approved_count, item_ids}`. |\n| `onboarding` | `/onboard/interview/understand`, `/onboard/interview/start`, `/onboard/interview/message`, `/onboard/interview/draft`, `/onboard/interview/{id}`, `/onboard/interview/commit` | Conversational company setup. The `onboarding_interviewer` agent asks clarifying questions, then emits a draft profile + people + departments. **Nothing is persisted until `POST /onboard/interview/commit`** — the interview itself never writes. `start` is multipart (description + optional deck/one-pager uploads). `commit` answers 403 when the draft would make a different person the owner and the caller is not the current owner (setup demotes the old principal, and any signed-in user can open it). It also takes an optional `owner_email` — the principal's sign-in email, which the review screen pre-fills from the signed-in user — checked before anything is written (422 if it is malformed, already another person's, or would replace the principal's existing email — setup only fills in a missing one; 403 if the caller is not the owner and it is not the address they signed in with, since the roster is the sign-in allow-list) and saved on the principal's People row, so the owner's chats resolve to them from the first turn. |\n| `workflow_designer` | `POST /workflows/designer/start`, `POST /workflows/designer/edit`, `POST /workflows/designer/message`, `POST /workflows/designer/draft`, `GET /workflows/designer/{session_id}` | The conversational New workflow wizard, and editing a saved workflow by conversation. `/edit` (`{name}`) opens a session on a saved custom workflow with no model call: the stored definition is the starting draft, and every response then carries `editing` (its name) and `original` (the stored definition as the session opened on it); drafts keep that name and its on/off state whatever the model writes (404 for an unknown workflow). The UI saves one with `POST /workflows/custom/{name}/save-edit` (`{session_id, definition}`): the server saves the session's own draft, never a client-sent body, and only when it equals the `definition` the user reviewed (a later message is a 409, so the click saves only what was shown); it re-validates it, keeps the stored on/off state, and writes only if the stored workflow is still the version the conversation opened on — otherwise 409, as it is for a session about another workflow or one with nothing drafted yet. It sits under `/workflows/custom` so anything that limits writes to custom workflows covers it too. The `workflow_designer` agent asks clarifying questions (`phase: \"question\"`, with `hint` and up to four suggested `options`), then returns `phase: \"draft\"` with `draft.definition` (exactly the body `POST /workflows/custom` takes), `summary`, and `assumptions`; every response carries the `transcript`. **Nothing is persisted here** — sessions are in memory, and the UI saves through `POST /workflows/custom`. Errors are fixed strings (422 over the 8,000-char message cap or the transcript cap, 404 for an expired session, 409 while another turn on the same session is still running, 502/504 for model failure or timeout). Mounted ahead of the `workflows` router. |\n| `python_jobs` | `GET /python-jobs/{job_id}/{name}` | A result file a Python job (`run_python_job`) wrote, the principal's alone (403 otherwise), served as a download (`Content-Disposition: attachment`, `Content-Security-Policy: sandbox`, `nosniff`, `Cache-Control: no-store`); 404 for a bad id or name or a file past its 7 days. |\n| `saved_tools` | `GET /saved-tools`, `GET\\|PUT /saved-tools/{name}`, `POST /saved-tools/{name}/rollback` | The scripts the Executive saved as tools (Settings → Advanced → Saved tools), the owner's alone (403 otherwise). The list gives each tool's name, description, on/off, current version, `kind` (`script` or `python`, a kept Python job) and the tools it calls, plus whether `SAVED_TOOLS_ENABLED` is on; the detail adds the script, every version and the last 20 runs. `PUT {enabled?, workflows?, version?}` turns one on or off (off also turns it off for workflows, so turning it back on never re-arms unattended runs), and turns the named `version` — the one the owner looked at, never whatever is current by then — on for workflows (or workflows off); a Python tool never turns on for workflows (409) — turning workflows on lets more run unattended, so it needs a request tied to the owner (signed sign-ins or local login, as Take the lead's switches do; 409 otherwise); `rollback {version}` makes that version the one that runs. Both are audited as `saved_tool_changed`. The Executive saves tools itself through `run_script`; there is no create route. |\n| `onboarding` (fallback) | `/onboard/start`, `/onboard/answer`, `/onboard/status/{id}` | The original 12-step form wizard, kept as a fallback (UI at `/onboard?mode=form`) and used by the `openexecutive onboard` CLI. Its final answer saves the profile and adds people with their emails and a principal, so once there is an owner only they can send it (403, and the session rolls back so the owner can still finish it). `/onboard/start` reads the workspace mode once for the session: solo skips the Team Size, Team Members and Fractional Executives steps. Each status response's `current_step` / `total_steps` count only the steps that session asks, and `optional` says whether the current step can be skipped. |\n| `company-profile` | `GET\\|PATCH /company-profile` | Structured company profile. |\n| `alerts` (private cards) | `POST /alerts/{id}/ack`, `/reopen`, `/alerts/bulk-ack` | An alert tagged `private:principal` (see Today) is a 404 on ack and reopen for anyone but the principal, and their bulk sweep skips it. A roster-request card (source `roster_request`) is a 409 on `ack` even for the principal — it is answered at `/people/requests/{id}`, since acking would leave the sender waiting with nothing to show it — and, as an exempt source, `bulk-ack` and `reopen` skip it. |\n| `auth` | `GET /auth/allowed-emails` | Non-archived **team members** with an email, offered to the UI's sign-in gate — a contact is never on it, so adding a client to reach them by email no longer lets them sign in. The gate takes the **union** of this roster and its own `ALLOWED_EMAILS` env list, so env entries always work (and are checked first, short-circuiting the fetch) and roster entries are additive — a roster change can never revoke a configured operator. With local login (`make dev` with Google sign-in not set up — the UI then listens on 127.0.0.1 only) the UI signs in without an email, sends no `x-caller-email`, and the backend resolves the caller to the principal, as it does for the CLI. |\n| `fixtures` | `/fixtures`, `/fixtures/{name}/load` | Demo-company fixture load/reset/snapshot. `POST /fixtures/reset` leaves no departments, like a new install (`departments_seeded` is always 0). |\n| `clients` | `/clients`, `/clients/generate`, `/clients/cockpit`, `/clients/save`, `/clients/{slug}/activate` | Client-company slots — multi-client mode for fractional use; create from current/blank/AI-generated intake draft (pasted notes and/or file attachments, multipart on `/clients/generate`), save-back switching, engagement metadata (PATCH), cross-client cockpit, delete. See the Client Companies section. |\n| webhooks | `POST /webhook/telegram`, `POST /webhook/google-chat`, `POST /webhook/slack` | Inbound integration callbacks (self-verified). `/webhook/slack` answers 503 unless `SLACK_SIGNING_SECRET` is set. |\n| MCP server | `POST\\|GET /mcp` | Open Executive exposed as an MCP server (Streamable-HTTP). Not a router — a mounted FastMCP sub-app. Same shared-secret gate (`x-api-key`); exposes company context as resources and the specialist council as tools. See the MCP Server section. |\n\n**Take the lead** (`api/routes/take_the_lead.py`): `GET /take-the-lead` returns the As the Executive switch, its six Ask first switches (`{kind, label, hint, on}`, the hint a plain line on what each one catches), the company's rules, whether this server can tie a change to the owner (`available`), and whether the Executive is paused. `PUT /take-the-lead` takes `{enabled?, ask_first?}`, and `POST /take-the-lead/rules` / `DELETE /take-the-lead/rules/{id}` add or remove a company rule (`{kind: person|domain|words|amount, value}`, 422 on a bad one). All four are the principal's alone (403). Anything that lets more happen on its own (turning it on, turning an Ask first off, removing a rule) needs a caller the API can tie to them (`delegation.verified.caller_refusal`, else 409). `GET /today/activity` adds `took_the_lead` rows (what Take the lead did, named, not quoted) and, for the caller alone, `sent_as_you` rows for what Handle it for me sent as them. Under `/delegation`: `PUT /delegation/take-the-lead {enabled}` is Take the lead as you (the owner's only for now; turning it on turns Handle it for me on), and `GET|POST /delegation/take-the-lead/rules` and `DELETE …/rules/{id}` manage the caller's own rules. `HandleItOut` gains `lead` and `lead_available`. A `take_the_lead_action` decision is approved or rejected through the existing `/decisions/{id}/approve|reject`. Training: the response also carries `training` (In training: everything waits unless allowed), `learned` (`{id, label, feature, example, uses, created_at}`: what it was allowed, the edit kept as an example by field) and `suggested` (`{key, label, approvals}`); `PUT` takes `training?` too, and leaving training while on needs the same provable owner as turning it on. `POST /take-the-lead/learned {key}` allows a current suggestion (404 for anything else; provable owner), `DELETE /take-the-lead/learned/{id}` makes it ask first again. `learned` also lists the owner's own Act as me senders (`feature` `act_as_me`), never anyone else's, and Remove works on those too. On a `take_the_lead_action` card, `POST /decisions/{id}/approve` takes `edits.input` (the card's editable fields, 422 for any other; the principal's alone, 403 for an area approver) and `edits.allow: true` (a training card only, 422 otherwise; the principal from a provable request, 403 otherwise), finishing `approved_with_edit` when a field changed.",+ "markdown": "The FastAPI surface lives in `openexecutive.api.main`, which mounts one router per topic. A shared-secret middleware gates every request via an `x-api-key` header, except `/health` and the `/webhook/*` callbacks (which carry their own verification). With local login (`OE_LOCAL_LOGIN=1`, which only `make dev` sets, and only while neither Google nor SSO sign-in is set up) a second middleware answers 403 to any request whose raw `Host` is not `localhost`, `127.0.0.1` or `[::1]` (except a webhook that verifies its caller: Google Chat and Slack always, Telegram only with a `TELEGRAM_WEBHOOK_SECRET` Telegram can send), and to any write whose `Sec-Fetch-Site` is present and not `same-origin`/`none`. The UI signs that owner in with no password and this API usually has no secret, so without it a web page in the owner's browser could drive the API as the principal — by DNS-rebinding its own hostname to 127.0.0.1, or by posting a plain form from another site or localhost port. CORS is restricted to the UI origins in `BACKEND_ALLOWED_ORIGINS`, plus the `make dev` UI on `localhost:3000` only when `OE_PUBLIC_DEPLOYMENT` is unset, so a public instance never answers a localhost page with credentials. The gate is off when `BACKEND_SHARED_SECRET` is unset — intended for local development only — so any internet-reachable deployment sets `OE_PUBLIC_DEPLOYMENT`, and `create_app()` then refuses to boot without the secret rather than serving an unauthenticated API.\n\n**Who is calling** is read in one place, `api/caller.py`, which answers with a `Caller` kind and email; a test fails on any other read of an `x-caller-*` header. By default (`open`) it is the `x-caller-email` the UI proxy stamps from the sign-in, trusted because whoever holds the shared secret is trusted as the proxy, and a request with none runs as the principal. **Signed callers** remove that trust. With `CALLER_ASSERTION_PUBLIC_KEYS` set, the proxy signs every request with an Ed25519 key only the UI holds, and a third middleware checks the `x-caller-assertion` header:\n\n- **What it covers.** It is good for one method, the exact path and query, at most 120 seconds, and one use. The API keeps used ids in memory.\n- **What it names.** A `user`, by email, or the `operator`: local login, which runs as the principal.\n- **No caller header at all** is a `service`, for scripts or MCP clients holding only the secret. It is never the principal, not even on an install with no owner yet, so it can't save a first setup.\n- **Anything else is a 401.** That includes an `x-caller-email` without an assertion (`caller_assertion_required`), and a bad, expired, reused or mismatched assertion (`caller_assertion_invalid`).\n\nPublic keys that can't be read stop the boot, rather than fall back to trusting the header. `scripts/make-caller-keys.py` makes the pair, and `scripts/mint-caller-assertion.py` signs one request for curl. The API holds only public keys. Setup's API-protection check warns while a shared secret is set without them.\n\nEndpoints grouped by router:\n\n| Router | Key endpoints | Purpose |\n|---|---|---|\n| `chat` | `POST /chat`, `POST /chat/stop`, `POST /chat/add`, `POST /chat/background` | SSE stream of a live Executive turn, with a `: keepalive` comment every `CHAT_STREAM_KEEPALIVE_S` while the turn is quiet. `POST /chat/background` starts a new chat that the server answers to the end with nobody connected (a phone approving a card, then closing the app): it answers `202` with the new `session_id` once the same caller, access and quota checks as `/chat` pass, the turn saves itself as a `/chat` turn does, and one caller may have three running at once (`429` beyond that). `POST /chat/add` hands the running turn a message the person typed while it works; the turn takes it at its next step and the stream names it in a `message_added` event, and a second `POST /chat` on the same conversation waits for the first to finish. The request body optionally carries `page_context` (route, page title, guide section id, and a form descriptor with current values) — sent only by the Ask OE side panel so the Executive can explain the current page or propose form values. When the Executive calls its `propose_form_values` tool, the stream emits a `form_patch` event (`{type, form_id, fields, rationale, iteration}`) that the panel applies into the on-screen form as highlighted suggestions; the user reviews and saves through the form's normal submit path. Each round of tool calls also emits an `activity` event (`{type, label, tool, iteration}`) naming what is running — progress only, forwarded verbatim and never persisted with the message, unlike an `action_taken` chip. A `session_id` in the body must be a chat the caller may use (the same ownership rule as `sessions`). If it isn't, the turn runs in a fresh chat instead, so nothing is written into someone else's session and the reply looks the same as for an unknown id. An unknown namespaced id (`slack:…`, `telegram:…` and so on) is ignored and a fresh chat is started, because those ids belong to the channel adapters and claiming one first would make the caller its owner. The client mints a `client_turn_id` and sends it with the turn; `POST /chat/stop` takes that id and halts the turn mid-flight, so the button is live from the moment Send is pressed rather than only once the first SSE byte arrives. A stopped turn emits a `stopped` event and then the usual `done` over the same still-open stream — never an `error` — and whatever streamed so far is persisted and flagged. The endpoint returns 404 both for an unknown id and for another caller's turn, so it cannot be used to probe which turns are live. An optional `memory_text` (1–2000 chars) is what peer memory records as the caller's words instead of `message` — the briefing handoffs send it because their seed quotes the Executive's own card; `POST /chat/upload` derives it from the typed text and filenames. Since it never reaches the transcript, the `chat_turn` audit row keeps it beside `message`. After the reply — a stopped or timed-out one too, before the `stopped` / `error` / `done` frames — a turn that looked at anything sends one `sources` event, `{type, session_id, sources: [{kind, title, url}], unavailable: [area]}`: `kind` is `company`, `knowledge`, `notion`, `research`, `document` or `web`, `url` is only ever an http(s) link or, for an earlier document, `/artifacts/<id>`, at most 12 sources (6 from the web, pages the reply cites first), and `unavailable` names parts of the analysis (\"finance\") whose specialist failed or said nothing every time it was asked. It is persisted with the reply as `chat_messages.sources`. A request that carries `x-caller-email` marks its turn signed in (`Session.web_caller_signed_in`), which Act as me needs on a deployment without local login. |\n| `sessions` | `GET /sessions`, `GET /sessions/shared-with-me`, `GET\\|PATCH /sessions/{id}`, `GET /sessions/{id}/messages`, `DELETE /sessions/{id}`, `POST /sessions/{id}/messages/{message_id}/feedback`, `GET /sessions/{id}/followup`, `GET\\|PUT /sessions/{id}/shares`, `GET /sessions/{id}/export`, `POST /sessions/{id}/rewind` | List, read and delete saved chat sessions (assistant messages carry their row `id` and any `feedback`). The list is scoped to the caller, and each chat carries `preview`: its last message as one plain line, Markdown marks stripped and cut at a word near 120 characters, with `You:` before the person's own words. With `?q=` it is a search: the caller's own chats whose title or message text contains the words (case-insensitive, `LIKE` with wildcards escaped), each with `match_count` (messages that contain them; 0 for a title-only match) and `snippet` (the newest matching message, around the match, prefixed `You:` or `Executive:`). Scoped exactly like the list, so nobody else's conversation can match. The Chats page searches this way and opens a result with `?find=`, so the chat starts on that message and steps through the others. A chat-app conversation started with /new is left off the list until its first turn (`memory.conversations`). Every per-session route checks ownership, because session ids are guessable (`slack:dm:<user id>`, `telegram:<chat id>`): only the session's owner or the principal gets through, and a legacy row with no owner is the principal's alone. A teammate's own chat (a web chat, a DM, a private Telegram chat; not a channel or group conversation, `chat._shared_space`) is theirs alone, the principal included, as their mail with the Executive is. Anyone else gets the same 404 as for an unknown id, so the routes can't be used to find out which chats exist. The one other way in is having started the chat in this process (matched by Person id or verified email, so it survives the caller being added to the roster), which is how a caller the roster can't resolve keeps using their own chat. That record is in memory, so after a restart such an ownerless chat is refused for reads. The principal can continue someone else's ownerless chat without becoming its owner. Deleting a session also drops its in-memory copy, so a later turn naming that id starts fresh. The feedback route records 👍/👎 (`{\"feedback\": \"up\"|\"down\"|null}`) on one assistant reply; only the session's own caller or the principal may rate it. The rater is stored (`feedback_by_person_id`), and a 👎 on a reply to the rater's own message triggers a working-style pass for them (paced; see attunement). The chat stream's `done` event carries `message_id` for the persisted reply. The followup route returns `{\"suggestion\": string|null}` — one suggested next user message, written by the utility-fast model from the last few turns, that the chat composer shows as its greyed placeholder (Tab / → or the inline chip fills it in without sending). It is null unless the session ends on a persisted assistant reply, and null (uncached) when the model fails. Same ownership check as feedback; successful suggestions are cached in-process per (session, reply id). Messages from `GET /sessions/{id}/messages` carry each assistant reply's saved `sources` (the same shape as the chat stream's `sources` event, without `type`), so a reloaded chat shows them again. The owner (not the principal on someone else's chat; the principal for an ownerless one) also has the chat controls. `PATCH` takes `{title?, pinned?}`: a name they give is kept (`sessions.title_locked`, so the automatic title never replaces it) and a pinned chat lists first, newest pin first, with `pinned_at`. `PUT /sessions/{id}/shares {person_ids}` shares it, to read, with exactly those team members (not contacts, the archived or the owner: 422), audited `session_shared`; a chat that read its owner's own mail (`mail_private`) is never shared (409) and stops being readable by those it was shared with before. They get it from `GET /sessions/shared-with-me` (with `read_only`, `shared_by`, `shared_at`) and may read it, its messages (without the owner's ratings) and its export; every other route still treats them as anyone else, so they can't write in it, rate, rename, delete or redo it. `GET /sessions/{id}/export` returns the chat as a Markdown file (`memory.chat_export`: each message under its writer's People name or `Executive`, the reply's sources listed under it). `POST /sessions/{id}/rewind {last_message_id}` takes back the last turn for Try again and Edit: under the conversation's turn lock it deletes the last reply and the messages it answered, but only while that reply is still the chat's last row, and returns those messages' words (`{message}`), which the page sends again as an ordinary `/chat` turn through the usual gates. 409 while a turn is answering, for a stale reply id, and for a chat-app conversation (its reply also lives in Slack, Telegram or Discord); audited `session_rewound`. |\n| `today` | `GET /today`, `GET /today/activity`, `GET /today/activity/daily`, `GET /today/brief-delivery`, `GET /today/value`, `GET /today/top-three`, `GET /today/weekly-review` | Morning-brief aggregation, recent-action rail, Pulse heartbeat heatmap (per-day activity counts), and the owner's Your month tally (`GET /today/value?period=month|week&offset=N`: counted lines beside the period before plus the finished reports, owner only, 403 otherwise; see Today). `GET /today` carries the viewer's cached \"What's going on\" `narrative` with `narrative_generated_at` (when it was written) and `narrative_stale` (a fresher one is being written — the page re-polls; see Today). A proposal backed by a roster request carries `roster_request` (the new sender's server-derived details and held-message previews; the principal's only) and is answered through the `people` routes below. `brief-delivery` returns the latest morning brief or end-of-day digest that didn't reach the owner, as `{brief, at, problem, fix, readable}` in plain language (`readable` is false when it couldn't be written, so there is nothing to read), or null — null while briefs go out, once the cause is fixed, while the scheduler is off, and for anyone but the owner (`chat._caller_is_principal_or_unclaimed`); it carries no address or channel id. `top-three` and `weekly-review` feed the solo Briefing's own cards and answer only in solo mode and only to the principal (`workflows._caller_is_the_principal`: a principal match or no caller header, never an unclaimed roster); anyone else, and team mode, get null. `top-three` returns `{items: [{key, kind, text, why, slot}]}` — the morning brief's top three from the same code (`build_top_three(principal_due_soon())`), `slot` a free block like `10:00–11:00`, `\"\"` when none is left, null when no calendar was read — and is kept off `GET /today` because its calendar read may take up to 4 s. `weekly-review` returns the latest completed `weekly_review` run as `{run_id, completed_at, period, top_three, excerpt}` (next week's top three as plain text; `excerpt` when that list is empty), or null when none has completed. |\n| `people` | `GET\\|POST\\|PATCH /people`, `POST /people/{id}/archive`, `GET /people/requests`, `GET /people/requests/{id}`, `POST /people/requests/{id}/approve`, `POST /people/requests/{id}/decline`, `GET\\|POST /people/{id}/open-loops` (a `POST` tells the owner once and returns `notified`: `sent` with the channel, `held`, `not_reached` or `skipped`; see Attunement), `POST /open-loops/{loop_id}/close`, `GET /people/{id}/outreach`, `GET\\|PUT\\|DELETE /people/{id}/attunement` | Roster CRUD and scope lookups. Every `Person` carries `kind` (`team` / `contact`). `GET /people` lists team members only unless `?include_contacts=true` (the People page asks for both; the department-head and workflow pickers keep the default); `POST` / `PATCH` accept `kind`, and a principal contact is a 422 either way. They also take `email_aliases` (other addresses the person writes from, at most 10; on `PATCH` the full list replaces the current one, omitted leaves it): an alias matches their mail and may be emailed but never signs in; a malformed one is a 422, and an alias — or a new primary `email` — that is already someone else's address or alias is a 409. Every `POST` / `PATCH` then closes any pending roster request whose sender now matches someone and replays its held messages. Adding, editing and archiving (`POST`, `PATCH`, `/archive`) are the principal's only, or anyone's while no one is principal yet so a first setup can add its owner (`chat._caller_is_principal_or_unclaimed`, the check behind `PUT /workspace`; a request with no `x-caller-email`, such as the CLI or local login, counts as the principal). Anyone else, a person editing their own row included, gets 403 before the person lookup, so it can't probe which ids exist. Contacts are private to the principal (`caller_is_principal`: the signed-in email is the principal's, or no `x-caller-email`; stricter than the owner rule above, so while no one is principal nobody is): for anyone else `include_contacts` is ignored, a contact's id is a 404 on `GET /people/{id}` and open-loops (exactly as for a missing id; `PATCH` and archive are already a 403 for them), and creating a contact or turning someone into one is a 403, even on a first setup with no principal yet. `GET /people/me` returns `{person_id, is_principal}` so the UI offers contacts to the principal only. `GET /people/by-scope/{token}` never returns a contact. Archiving a person closes their open loops. The open-loop routes list what a person owes (soonest due first) and close one (`reason`: done / not_needed / cancelled) — both the principal's or the owner's only (403 otherwise, via `people.store.is_principal_or_self`). `POST /people/{id}/open-loops` `{task, due_date?}` assigns that person a task (201 with the loop; `due_date` is a local date, due 17:00 in the user's timezone, clamped to 60 days, default 2 days): any active team member may assign anyone on the team, 403 for anyone else; 409 for an archived person, a contact (as seen by the principal), a person at the open-loop cap, a duplicate or open loops turned off; 422 for an empty task. Nobody is messaged at assignment — the owner is chased once it is due. `/outreach` returns, per kind of proactive outreach over 30 days, `sent` / `replied` / `acted` / `ignored` / `pending` (voided DMs are excluded) — same access rule, checked before the person lookup so it can't probe which ids exist. `/attunement` reads, replaces (`rules`: up to 4 strings, or omitted to only set `locked`) or resets the person's working-style rules — same access rule, 404 for an archived person; `PUT` rejects a rule that is not purely about style with 422. Archiving a person also drops their working style and frees their aliases. The **roster-request** routes (declared before `/people/{person_id}`) are the principal's alone (`caller_is_principal`; anyone else gets 404, as for a missing id): `GET /people/requests?status=pending|approved|linked|declined|expired|superseded|all` lists up to 100 (`id`, `channel`, `channel_ref`, sanitised `display_name`, `profile_email`, `on_company_domain`, `suggested_kind`, `suggested_person_id` / `_name`, `status`, `resolved_person_id` / `_kind`, `message_count`, timestamps, `ack_sent`, and `previews` of the held messages while pending — shown to the principal, never to a model); `approve` takes either `link_person_id` (+ `replace_channel_id`) or `full_name` + `kind` (no default: 422 without both) + optional `role`; `decline` takes no body. An answered request is a 409, a chat id or address already on someone else is a 409; the held messages are replayed (or dropped) in the background. |\n| `departments` | `GET\\|POST\\|PATCH\\|DELETE /departments`, `.../goals` | Department state and per-department goals. `PATCH /departments/{slug}` also takes `watched_entities` (≤50 names, `[]` clears) — the entities the research watch policy may add watches for and route to this department. A `cadences` spec that does not parse is rejected with a 422 (empty means no cadence, i.e. the check-in is off); a changed `check_in` cancels the pending check-in and queues the next one on the new schedule. `GET` and `PATCH /departments/{slug}` return the department state plus `next_check_in_at` (ISO UTC of the pending check-in, `null` when it is off, the workspace is solo or none is queued); the list route does not carry it. A new `head_person_id` must be a team member: an unknown id and one of the principal's contacts get the same name-free 422 (`person_id N is not on the team.`), so the route — open to any signed-in user — never reveals that a contact exists; an unchanged head is not re-checked. `POST .../goals` requires only `key_result`: a missing or blank `period_value` is filled with the current period for `period_type` in the user's zone (the same label `create_goal` uses), and `target` defaults to empty. `PATCH .../goals/{id}` rejects a blank `key_result` or `period_value` with a 422; `target` may be cleared. |\n| `agents` | `GET /agents`, `GET /agents/models`, `GET /agents/models/options`, `GET /agents/presets`, `POST /agents/presets/{id}`, `PATCH /agents/{id}`, `POST /agents/{id}/test` | Specialist metadata and Council overrides. `/agents/models` is the flat model allowlist the PATCH validator uses; `/agents/models/options` returns the same ids in the same order, each tagged with `provider`, `provider_label`, `route` (`direct` / `openrouter` / `local`) and a display `label`, for the Council's Provider → Model picker. `AgentDetail` carries `instructions` (additional instructions, appended after `prompt`, which stays the built-in prompt or its replacement); `PATCH` and `/test` accept `instructions` (max 4,000 chars, blank clears it). `GET /agents/presets` lists the Fast, Balanced and Thorough quality presets (each with `available` and the resolved `model` for this install) plus `active` (null when the council is Custom), `base` and `custom_agents`; `POST /agents/presets/{id}` applies one by writing per-agent model and deep-reasoning overrides and returns the same shape (404 unknown preset, 409 when the install allows none of its models). Each `AgentMeta` carries `visibility` (`core` or `internal`) so the Council's simple view can list core agents first. |\n| `personas` | `GET\\|PUT\\|POST\\|DELETE /personas` | Executive persona definitions. |\n| `alerts` | `POST /alerts/{id}/approve`, `GET /alerts/approvals/{id}`, `POST /alerts/{id}/ack`, `POST /alerts/bulk-ack`, `POST /alerts/{id}/snooze`, `POST /alerts/{id}/reopen`, `POST /alerts/review` | Groom the briefing queue. `approve` (body `{edited_body?}`, 202) carries a proposal card out on the server and records who approved it and when (`alerts.approvals`, see Today): it queues the scheduled action a department-gated card held, or runs one Executive turn as the approver in a new chat (`session_id`). 409 for a card already approved or closed, a decision-backed card (approved at `/decisions`), a roster request or a drafted artifact; 403 unless the caller is the card's routed person or the principal (an unrouted card is the principal's); 429 when the caller already has three background turns running. `GET /alerts/approvals/{id}` reads one back (`running`, then `done` / `failed` with `outcome`) for its approver, the card's person or the principal (404 for anyone else). `snooze` (`until`, an ISO time up to 30 days ahead; `null` clears it, the Undo) hides an `unread` card until then by setting `snoozed_until` (409 on a closed card or a roster request); the TTL then counts from the snooze, so a card snoozed past its TTL still comes back. `ack` (`read`/`ack`/`dismissed`, optional `mute_topic`) also teaches a watch-sourced alert's watch (`trust_score`); `bulk-ack` takes explicit `alert_ids` and/or `older_than_days` + `category` (exempt sources skipped); `reopen` is the Undo for a `resolved` / `expired` / `dismissed` alert (never `ack` or an artifact / decision row; back to `unread` with every review stamp cleared and its TTL anchor refreshed, so it is live again even if older than its TTL); `review` runs the Executive's relevance review on demand (ignores the interval; still honours `ALERT_REVIEW_ENABLED`, the per-pass caps, the single-flight lock and per-alert idempotency) and returns the move counts. `bulk-ack` caps ids at 500, needs `older_than_days >= 1`, and applies watch feedback per row; `mute_topic` must be one of the alert's tags or a scoped `external:` / `department:` pattern. Alerts still surface only through the briefing (`/today` reads the live view) — there is no list, prefs, mutes, or live-stream endpoint. |\n| `artifacts` | `GET /artifacts`, `GET /artifacts/{id}`, `GET /artifacts/{id}/download?as=`, `POST /artifacts/{id}/archive`, `POST /artifacts/{id}/restore`, `DELETE /artifacts/{id}` | Browsable deliverables in any format — Markdown, HTML, Word, Excel, or a link into a connected app — with `format`, `downloads`, `external_url`, `supersedes_id` and, for an extension's kind of document, `collection` / `collection_label` on every summary (`orchestrator.extensions`; archive, restore and delete tell the collection first and answer 502 if it refuses). `download` renders the file (Word/Excel built at request time from the stored text; any Markdown artifact, workflow output included, can export `?as=docx`) and is always an attachment with `nosniff` and a sandbox CSP. Every route answers for the signed-in caller (`artifact_records.Viewer`): a drafted artifact is its owner's alone (`alerts.owner_person_id`, the person whose conversation published it; none = the principal's), a workflow output follows its run (`persistence.run_visible_to`), and anything the caller may not see is a 404 like a missing id, the principal included. `POST /alerts/{id}/ack` and `/reopen` answer 404 for someone else's drafted artifact the same way. |\n| `decisions` | `GET /decisions`, `POST /decisions/{id}/{approve,reject,cancel}`, `GET`/`PUT /decisions/classes/meeting_scheduling`, `GET /audit/reliability` | Approval-gated decision instances (e.g. calendar bookings). What approve/reject/cancel do is per class (`DECISION_CLASSES`, one `DecisionClassSpec` each; meeting booking books on approve and deletes on cancel; `delegation_reply`, an inbox reply card, is its approver's alone (`approver_only`) — hidden from everyone else, the principal included when it is a team member's — sends its Gmail draft on approve and, after a reject, deletes the draft unless it was edited; `department_action`, a team member's chat send or edit their department held (see Org), is the principal's and its approver's alone (`principal_and_approver`), makes that exact call on approve and audits `department_action_done` / `_failed` / `_declined`), and an instance of a class with no spec gets 409 instead of being carried out as another. Only the principal, or the person the decision went to for approval (`approver_person_id`), may approve, reject or cancel it. Anyone else gets 403, and a decision nobody was asked about, or one private to the principal, is the principal's alone. The resolver is recorded as `resolver_person_id`, and a reject that loses the race to another answer is a 409. `GET /audit/reliability` is the principal's alone (403 otherwise), because it counts private decisions too. A proposed booking is surfaced on the briefing as a companion alert; approve/reject/cancel here also clear that alert. An approval whose caller resolves to the principal runs the booking inside `grant_contact_egress()`, so a meeting the principal proposed with a contact can be created. Such a booking's payload is marked `private`: it is proposed to the principal, left out of anyone else's `GET /decisions`, and a 404 for them on `GET /decisions/{id}` and every action route. Reviewed in the briefing — there is no separate proposals page. The class routes read and set how meetings are handled: both return `{decision_class: \"meeting_scheduling\", mode: \"propose\" \\| \"auto_execute\"}` (default `propose`); the `PUT` body is `{mode}`, principal-only (403 otherwise, open before a principal exists — but then only `propose` can be set: `auto_execute` is a 409 until a non-archived principal is on the roster), 422 on any other mode, and a change writes a `decision_class_mode_changed` audit row. In solo mode the class mode decides a booking, and `auto_execute` applies only to a turn the principal started on a verified surface — any other turn gets a proposal. |\n| `delegation` | `GET`/`PUT /delegation`, `GET`/`PUT`/`DELETE /delegation/voice`, `POST /delegation/voice/learn`, `POST /delegation/voice/describe`, `POST /delegation/voice/signature`, `PUT /delegation/inbox`, `POST /delegation/inbox/check`, `GET /delegation/replies`, `PUT /delegation/replies/{id}/text`, `GET /delegation/actions`, `PUT /delegation/handle-it`, `PUT /delegation/disclosure`, `PUT /delegation/training`, `DELETE /delegation/learned/{id}`, `GET /delegation/handled`, `PUT /delegation/team` | Act as me — the **caller's own** delegation only; nobody sets it for anyone else. It answers the principal, and a team member once the owner lets them; anyone else gets 403 `not_available_yet`. `GET /delegation` returns `{enabled, gmail: {status, message, email, connect_command, outlook_connect_command, provider}, inbox: {enabled, status, message, watch_since, last_poll_at, checking}, handle_it: {enabled, mode, available, sent_today, lead, lead_available}, training: {replies, follow_ups, actions, drafts, learned}, disclosure: {enabled, handle_it, approved_sends, line}, team}`, where `team` is the owner's switch for the principal while `DELEGATION_TEAM_MEMBERS` allows it — `{enabled, members: [{person_id, name, enabled, inbox, drafts_30d, sent_30d}]}`, counts only — and `null` otherwise. `PUT /delegation/handle-it` takes `{enabled?, mode?}` (`mode` is `careful`, `balanced` or `bold`; anything else is a 422 `bad_mode`) from a caller the API knows is that person — 403 `not_yours`, 409 `caller_signing_required` with only the shared secret — and turning it on needs Act as me and Draft replies to my inbox on (409 `act_as_me_off` / `inbox_off`); `GET /delegation/handled` returns `{replies: [{decision_id, sent_at, to_name, to_email, subject, body, open_questions, gmail_link, source}]}`, the caller's replies and follow-ups (`source` `follow_up`) sent on its own in the last 7 days; a card on `GET /delegation/replies` carries `source` the same way, `can_allow` while Replies (Follow-ups, on a follow-up) is in training, and `learns_style` while Drafts is. `PUT /delegation/disclosure` takes `{handle_it?, approved_sends?}` (any other field is a 422), the caller's own switches for the AI line on replies sent as them (`disclosure.enabled` is the install's `AI_DISCLOSURE`); turning one on needs no signed sign-in, turning one off does (409 `caller_signing_required`), and a change is audited as `delegation_disclosure_changed`. `PUT /delegation/training` takes `{replies?, follow_ups?, actions?, drafts?}` (any other field is a 422) and returns the `GET /delegation` shape; putting Replies or Follow-ups in, or Suggested actions out, needs no signed sign-in, anything else does (409 `caller_signing_required`), and putting Replies or Follow-ups in turns Take the lead as you off (`PUT /delegation/take-the-lead` on answers 409 `in_training` while they are). `training.learned` is `[{id, label, setting, example, uses, created_at}]`, what the caller allowed or kept in training (`setting` `replies`, `follow_ups`, `actions` or `drafts`; the kept example, or \"\"); `DELETE /delegation/learned/{id}` removes one of the caller's own (404 for anyone else's). `PUT /delegation/team` takes `{enabled}` from the principal alone (403 `principal_only`; 409 `not_available` when the install doesn't allow it). The Gmail `status` is `connected`, `not_configured`, `needs_reconnect`, `mismatch`, `no_email`, `shared_mailbox` or `error`, checked live with Google on each call. `PUT` takes `{enabled}` (any other field is a 422); turning it on needs the caller's own Gmail connected, otherwise a 409 whose code says why (`gmail_not_connected`, `gmail_needs_reconnect`, `gmail_mismatch`, `no_email`, `shared_mailbox`, `gmail_error`). The voice routes show, learn (from the caller's sent mail, one pass at a time — a 409 `in_progress`, `locked`, `too_soon`, `not_enough_mail`, `no_profile` or `changed` when it was locked or edited while learning, or a Gmail code), write it from the caller's own description (`POST /delegation/voice/describe` with `{description}`: one model call applies their words to the profile they have and returns it with a short `sample_reply`, saving nothing, so they review it and save it with `PUT`; a 409 `empty`, `too_long`, `in_progress`, `too_many` past 10 an hour or `no_profile`; no mailbox needed), edit and lock, and reset \"How I write\": a typed field that fails validation is a 422 `invalid_voice` listing each `rejected` field, and `clear_exemplars` / `clear_signature` drop those. `POST /delegation/voice/signature` reads the signature from the caller's Gmail settings again and changes nothing else (a locked profile stays locked), with the same Gmail codes as learning: a 409 when their mailbox isn't connected, it refuses the sign-in or the check itself fails (`gmail_error`), and a 502 `gmail_error` when reading the signature fails. On an Outlook mailbox it is a 409 `signature_unavailable`, since Outlook gives apps no signature to read, and the stored one is left alone. A caller `can_delegate` refuses — anyone but the principal, for now — gets 403 `not_available_yet`, which hides the Settings card. A request with no `x-caller-email` is a 403 `sign_in_required` unless the API runs under local login — a header-less call is not a sign-in (the caller is read through `api/caller.py`, as on every principal-only route). `PUT /delegation/inbox` takes `{enabled}` and turns **Draft replies to my inbox** on or off, returning the same shape as `GET /delegation`: on needs Act as me on (409 `act_as_me_off`) and the mailbox connected (the Gmail codes above, which keep their names for an Outlook mailbox too), and turning Act as me off turns it off too. `POST /delegation/inbox/check` starts a scan now in the background and answers 202 with the `inbox` state (409 `inbox_off` or `in_progress`). `GET /delegation/replies` returns `{cards: [...]}`, the caller's open reply cards from the database alone (no Gmail call): the decision id, the sender's name, address, relation and whether it was verified, the subject, when it arrived, what they wrote, the draft's recipients, subject and body, `open_questions`, `flags` and a Gmail link built from a fixed prefix. **Send** is `POST /decisions/{id}/approve`: it sends the card's draft exactly as it is in Gmail, after checking again that the caller is its owner — which on a server needs signed callers (409 `caller_signing_required` otherwise) — that both switches are on (`inbox_off`), no client slot is active (`client_slot`), the Gmail is connected (the Gmail codes), the draft is still there and unanswered (`draft_gone`, `you_replied`) and its recipients are allowed (`no_recipients`, `too_many_recipients`, `executive_recipient`, `not_from_you`). Recipients that changed, or a newer message in the thread, answer 409 `{code: \"confirm\", message, reasons, recipients}`; approving again with `edits: {recipients: <the list shown>, thread_moved_on: true}` is the second yes. **Send + allow** adds `edits.allow: true`: 422 `cant_allow` unless Replies (Follow-ups, on a follow-up card) is in training, 409 `learned_full` when their list is full, both before anything is sent; `edits.example: true` keeps a draft edited in the mailbox as how they write to that person while Drafts is in training. A draft edited in Gmail between those checks and the send is not sent (`draft_changed`). A double tap sends once (`already_handled`); Gmail refusing answers 429 `rate_limited` or 502 `gmail_error` with nothing sent, and a send Gmail didn't confirm answers 502 `send_unconfirmed` and is settled by the next inbox scan. Dismiss is `POST /decisions/{id}/reject`. `GET /delegation/actions` returns `{cards: [...]}`, the caller's own approval cards (`delegation_actions`): the decision id, when it was made, a one-line `why`, and each action's `index`, `kind` (`invite`, `message`, `add_contact`), `summary` and `text` (a message as it will be sent, or a meeting's description). **Approve** is `POST /decisions/{id}/approve` with `edits: {only: [indexes]}` (and `allow: true` for Approve + allow while Suggested actions is in training: 422 `cant_allow` otherwise or when nothing on it can be allowed, 409 `learned_full`; a card carries `can_allow`); it needs the card's own person signed in (403 `not_yours`, 409 `caller_signing_required`), Act as me on (409 `act_as_me_off`) and a card under a week old (409 `expired`), runs once (409 `already_handled`), and returns the decision with `final_payload_json.results`: per action `done`, `waiting` (sent to whoever approves meetings), `failed` with why, or `skipped`. Every change writes a private audit row. |\n| `history` | `GET /memories/history` (`?q=`), `PUT /memories/history/settings`, `PATCH`/`DELETE /memories/history/{id}`, `POST /memories/history/{id}/forget-conversation` | Always in the loop: the **caller's own** notes and switches only, resolved as for Act as me (a signed-in person on the roster, or the principal under local login; otherwise 403 `sign_in_required` / `not_on_roster`). `GET` returns `{notes, reply_notes, retention_days, effective_retention_days, company_retention_days, retention_choices, can_keep_notes, can_note_replies, can_set_company_retention, share_work_style, can_share_work_style}` (`can_keep_notes`: a team member on the People list may turn notes on; `can_note_replies`: they can use Act as me, so email replies are noted too; `share_work_style`: their own \"Share my work style with the team\" switch, `can_share_work_style`: a team member in a team workspace). `PUT` turns notes on only for someone who may keep them, and `share_work_style` on only for someone who may share it (403 `not_available` for either; turning either off always works), takes a person's retention only when shorter than the company's (422 `invalid_setting`), and the company retention only from the principal (403 `principal_only`). `PATCH` pins or corrects a note; `DELETE` forgets it; `forget-conversation` is \"Don't remember this\". A note that isn't the caller's is 404. Every change is audited privately to its person. |\n| `notifications` | `GET /notifications/settings`, `PUT /notifications/settings` | Settings → Notifications: the **caller's own** settings only, resolved as for the notes (a signed-in person on the People list, or the principal under local login; otherwise 403 `sign_in_required` / `not_on_roster`). `GET` returns `{quiet_hours: {enabled, start, end, days}, delivery, urgent_through, timezone, effective_timezone, held_count, gets_briefs, updated_at}` — `days` is `every_day` or `weekdays`, `delivery` `instant` or `digest`, `timezone` the zone they chose (`\"\"` for the workspace's), `held_count` how many messages wait for their quiet hours or brief (counted, never listed), `gets_briefs` whether they are the principal. `PUT` takes `{quiet_hours, delivery, urgent_through, timezone}` and replaces them (extra fields, equal start and end, a bad time or an unknown zone → 422); switching `digest` → `instant` makes what waited for the brief go now. Audited as `notification_settings_changed`. See Org. |\n| `audit` | `GET /audit/logs`, `GET /audit/logs/{id}`, `GET /audit/sessions/{id}`, `GET /audit/usage`, `POST /audit/log` | Durable audit trail of side effects. `/audit/sessions/{id}` adds a per-session token cost summary; `/audit/usage` aggregates token usage and OpenRouter cost across all sessions (totals, by day, by model, and by source — the part of the system that made the calls — including server-side web-search counts), plus `scripts`: how many `run_script` scripts ran (and worked, and in workflows), the tool calls they made, their time, and `turns_avoided` — an upper bound on the model turns those calls would otherwise have needed (each call past a script's first) — and `python_jobs`: how many Python jobs ran (and worked, ran a kept Custom tool, took a chat attachment), their time, CPU, largest peak memory and bytes in and out, and the tokens and charge of the turns that ran one. The Token usage page shows it as a Scripts section. Rows private to the principal (`private_to_principal`: a turn about their private mail, or a row naming one of their contacts on their own turn) are theirs alone: for any other caller, resolved as for `/alerts`, the usage totals leave them out. Once a principal is on the roster, anyone else reads only their own rows (a teammate's own turns, their Act as me work) in the list, by id and in a session, and the principal reads those as actions only — what was done, when and in whose conversation, with the text, details and `full` left out, and no text search over them; any other row's id is a 404, and a session shows only the rows the caller reads. |\n| `architecture` | `GET /architecture/sections`, `.../sections/{id}` | This documentation surface. |\n| `guide` | `GET /guide/sections`, `.../sections/{id}` | Plain-language user-guide content surface — mirrors `architecture` (static, version-controlled files; no LLM on the serving path). |\n| `health` | `GET /health`, `GET /health/honcho` | Liveness probes. Only `/health` is unauthenticated; `/health/honcho` sits behind the gate like everything else, because the exemption is an exact-path set. `/health` also carries `google_tools_missing`, the pinned Google tools startup priming could not find: `[]` once it has checked and they are all there, a list of names when a workspace-mcp rename or the configured services and tool tier left one out, and `null` for no answer — Google Workspace is not configured, or the probe has not finished or it failed. Only `[]` asserts they are present. It also carries `gateway`, the MCP gateway's state from its supervisor (`orchestrator.gateway_boot`): `state` is `off` (MCP not enabled), `no_servers` (enabled, the config names none), `starting` (an attempt is running), `up` or `down` (every attempt so far failed; `next_retry_at` is the next one), with `attempts`, `up_since` and `email_poller` (whether the poller that rides on the gateway runs); the failure's own text stays out, since the route is open to anyone, and goes to the log and the owner's notice on Home. A hosted instance whose gateway never came up used to answer `ok` here with no email going out or in. Only `[]` asserts the tools are present, so a probe that died cannot read as healthy; Setup status says which of the three `null` means. |\n| `version` | `GET /version` | The running version, the latest release on GitHub and `update_available`, for Settings → About. The GitHub answer is cached 6h, only a semver `tag_name` is used and the release link is built from it; `UPDATE_CHECK_ENABLED=false` skips the call and still returns the running version. No in-app updater: upgrading is host-side (`docs/deployment.md#upgrading`). |\n| `setup_status` | `GET /setup/status` | Settings → Setup status: one light per part of the install — AI model, company setup, owner, the Executive's address, API protection, Gmail, your own mailbox (Act as me), Slack, Discord, Telegram, Google Chat, the scheduler, the daily brief (when and where it goes) and Honcho — as `{checked_at, checks: [{id, label, state, summary, fix, link, last_activity}]}`, where `state` is `ok`, `warn`, `error` or `off` (optional and not set up), `fix` says what to do in plain language, `link` is an in-app page that helps (`/people`, `/onboard`) and `last_activity` is the channel's latest `integration_inbound` audit time. It tests live, with at most one free read-only call per service, each bounded to 5 s: Anthropic `models.list` (so an organisation key missing `ANTHROPIC_WORKSPACE_ID` shows up), Slack `auth.test`, Telegram `getMe` and `getWebhookInfo`, Discord `users/@me` only while the bot is still connecting, and — once the owner's own Gmail credential exists — Google's token refresh and Gmail `users/me/profile`. It also reads the listeners the lifespan leaves on `app.state` (Slack's socket, the Discord bot and its task, the MCP gateway), the scheduler heartbeat and the pause switch. When `google_workspace` is configured, the lifespan also starts `MCPGateway.prime_pinned_tools()` in the background (held on `app.state.mcp_prime_task`, cancelled at shutdown), so the pinned Google tools named in the prompt are callable without a search. With `DRIVE_SYNC_ENABLED` the lifespan also bootstraps the `drive_sync_scan` heartbeat beside Notion's (see Scheduler); the Drive folder sync has no HTTP route, only the `openexecutive sync-drive` / `purge-drive` CLI. With `CONFLUENCE_SYNC_ENABLED` it bootstraps the `confluence_sync_scan` heartbeat the same way; that sync is run by hand with `openexecutive sync-confluence` / `purge-confluence`. Sample values copied from `.env.example` are named as such without being sent anywhere. No token reaches a response or a log line: probes report a status code, a service's short error code or an exception's class name. Requests within 5 s of a run get that run's answer and concurrent requests share one run (kept per app on `app.state`), so the button can't become a stream of calls to those services. Gated like every other route; the UI adds a sign-in light of its own, from its own settings. |\n| `documents` | `POST\\|GET\\|DELETE /documents`, `GET /documents/{filename}`, `GET /documents/sources`, `POST /documents/sources/{drive\\|onedrive\\|notion}/sync`, `GET /documents/{drive\\|onedrive\\|notion}`, `GET /documents/{drive\\|onedrive\\|notion}/{id}` | Upload, list, view extracted text, and delete indexed company docs. `GET /documents` rows carry `source: \"upload\"` and the `domain` the upload was indexed under. The connected-source routes back the knowledge page's single Company documents list: `/documents/sources` gives each source's `{id, label, enabled, syncing, last_run, last_error, interval_minutes, file_count}`; `/documents/drive`, `/documents/onedrive` and `/documents/notion` list synced files from the sync state (`{enabled, last_run, last_error, files: [{id, name, url, modified_at, synced_at, indexed}]}`; a Drive row also carries `unreadable_reason`, why a file with `indexed: false` has no text — e.g. a scan OCR could not read — or null); `/documents/{drive\\|onedrive\\|notion}/{id}` returns the stored text (a OneDrive id is `<drive id>:<item id>`) for an id on record (the path comes from the state, never the caller). They are read-only — a synced file is removed where it lives. `POST …/sync` starts one tick of the same sync the scheduler runs as a background task (202); 409 when the source is not connected or a tick is already running (every sync holds a per-process run lock, so a manual run never overlaps the heartbeat; the route also keeps its own started task per source and re-checks just before starting one, so two simultaneous requests start one tick, not two), 429 with `Retry-After` within 60 s of the last successful run or of the end of the last tick in this process, failed ones included, so a failing or slow source can't be re-run back-to-back. The page's text view never loads images from synced content (a remote image would be a read beacon for whoever edits the shared folder). Upload is keyed on the filename, so re-uploading a document replaces its chunks rather than duplicating them, and `DELETE` removes the rows as well as the file. `domain` must be one of the nine specialist domains (including `sales`) or `general`; anything else is a 400 rather than a 200 that indexes where no specialist can retrieve. A scanned PDF is converted (`knowledge.pdf_reader`) before it is indexed and in the text view, as are scanned PDFs in `POST /chat/upload` and the client / onboarding intake uploads. The upload is streamed to disk 1 MB at a time and refused with a 413 once it passes 50 MB, and the file is parsed in a short-lived child process (see the RAG section), so a large document does not stay in the API process's memory. A Word or Excel file that cannot be parsed, or whose parse runs out of time, is a 422 with a readable reason. When every parser is busy, the response is a 503 with `Retry-After`. |\n| `executive` | `GET /executive/status`, `POST /executive/pause`, `POST /executive/resume` | Operator pause switch for all autonomous work (scheduler, Gmail poller, workflow resumer); inbound chat and DMs stay live. Status returns `{paused, paused_at, paused_by, reason, held_actions, can_resume}` — `held_actions` counts due `pending` rows that fire on resume. `pause` takes an optional `reason` (≤200 chars) and is idempotent (re-pausing keeps the original start and reason); `paused_by` is the UI proxy's `x-caller-email`, else `api`. Behind the shared-secret middleware — not `SCHEDULED_ADMIN_TOKEN`, which the UI cannot send. Any caller may pause; `resume` is principal-only (`is_principal_or_self`, 403 otherwise; open while no principal is rostered; a header-less caller resolves to the principal as in `chat`), and status carries `can_resume` for the viewer so the UI hides Resume from everyone else. |\n| `workspace` | `GET /workspace`, `PUT /workspace` | Solo/team mode, the user's time zone and the principal's role (`memory.workspace_settings`). Both return `{mode, timezone, effective_timezone, role_kind, role_title, reports_to, remit, measured_on, company_domains, company_domains_custom}` — `timezone` is what the user set (null when unset), `effective_timezone` the zone in effect (`timezone`, else `USER_TIMEZONE`, else UTC), and each role field is null until set. `PUT` is a partial update: only the fields sent change; `mode` is `solo` or `team` (not null), `timezone` an IANA zone, or null/blank to clear it; `role_kind` is `owner`, `in_house`, `independent` or `other`, and `role_title` / `reports_to` / `remit` / `measured_on` are free text (trimmed, at most 120 / 120 / 500 / 300 characters), each null or blank to clear it; an unknown zone, a bad mode or role kind, an over-long role field or an unknown field is a 422 and changes nothing. Switching to solo cancels every pending department check-in, switching to team re-schedules them, and a new zone re-times the pending briefs and reflection; a role change has no side effects (the next turn reads it). `company_domains` is the company's own email domains (a teammate matches by local part on them — see Org): `GET` returns the ones in effect (the stored list, or the domain of the principal's primary address, with `company_domains_custom` false) only to the same caller the role is shown to, `[]` for anyone else; `PUT` takes a list (at most 10 plain domain names, never a free-mail provider's — 422 otherwise, the value never quoted) or null / `[]` to go back to deriving them, and a change is audited with the new list. Each change writes a `workspace_settings_changed` audit row (a role change adds `details.role_fields_changed`, the names of the fields that changed — never their text). The role is the principal's: `GET` returns it only to a caller `PUT` would accept and reads it as nulls for anyone else. `PUT` is the principal's alone (`is_principal_or_self`, 403 otherwise; a header-less caller resolves to the principal as in `chat`) and open while no principal is rostered, so first-run setup can pick a mode. Both work before onboarding — unlike `company-profile`, nothing here needs a profile. |\n| `scheduled` | `GET\\|DELETE` scheduled actions (`?status=…&order=asc\\|desc`) | Pending and fired scheduled actions; `order` flips the `run_at` sort (asc=soonest-first for the upcoming queue, desc=most-recent-first for terminal-status history). `DELETE /scheduled/{id}` cancels a `pending` row (409 otherwise). Like pause it only stops work, so any signed-in user may — the UI proxy's `x-caller-email` is trusted when the request also carries the `BACKEND_SHARED_SECRET` `x-api-key` — as may a matching `X-Admin-Token` (`SCHEDULED_ADMIN_TOKEN`) or a loopback caller with no token set; otherwise 401 (token set) or 503. Audited as `scheduled_action_cancelled`. |\n| `watchlist` | `GET\\|POST\\|PATCH\\|DELETE /watchlist`, `POST /watchlist/{slug}/approve`, `POST /watchlist/{slug}/decline` | External-monitoring watchlist + signals. Rows carry `origin` (`manual` \\| `executive` \\| `research` \\| `research_proposed`); `approve` turns a research suggestion (`research_proposed`, `dry_run`) into a live watch, `decline` `{reason: not_relevant \\| too_noisy \\| wrong_source}` removes it and records the decline (or, for `too_noisy`, keeps it live at a high floor), both 409 unless the row is a pending suggestion; `DELETE ?reason=` on a research-origin row records the decline too. |\n| `workflows` | `GET /workflows`, `POST /workflows/{name}/runs`, `GET\\|POST\\|PUT\\|DELETE /workflows/custom`, `GET\\|DELETE /workflows/custom/{name}/targets`, `POST /workflows/runs/{run_id}/decision`, `POST /workflows/runs/{run_id}/rerun`, `GET /workflows/tools/search?q=`, `GET /workflows/tools/describe?names=` | Workflow catalog, run management, and user-created (dynamic) workflow CRUD. `rerun` queues a failed scheduled run (a department check-in, a saved workflow on a cadence) once more, due now (see Scheduler); the principal may, and for a saved workflow the person it delivers to; 409 for a run that did not fail, one started from `/jobs` (\"Start this one again from its page\") or one already queued again. Custom definitions come back with a server-managed `owner_person_id` (the creator — the web caller on `POST`, set on insert only; a client-sent value is ignored), who is asked to approve a workflow's first write to a new target. `GET /workflows/custom/{name}/targets` lists the targets its tool steps may write to without asking and `DELETE …/targets?value=` forgets one. `POST /workflows/{name}/runs` is a 403 (\"Only the principal can run this workflow.\"), audited, before any run row exists, when the workflow is one only the principal may start in the workspace's mode (`weekly_review` always, `morning_brief` in solo) and the caller is not the principal. A request with no `x-caller-email` counts as the principal; with no principal on the roster, no signed-in caller does. This governs starting a run only. A run started by hand (this endpoint, or `run_workflow` / research in chat) records its starter as `owner_person_id` and is theirs alone: `GET /workflows/runs` lists the team's (scheduled, no owner) runs plus the caller's own and the ones waiting on them, and `GET` / `DELETE /workflows/runs/{run_id}` and `POST /workflows/runs/{run_id}/decision` are a 404 for anyone else's, the principal included. A signed-in email that is on nobody's People entry cannot start one (403), and a run whose starter can't be read is refused (503); its steps read and draft documents as the starter only. `POST /workflows/runs/{run_id}/decision` with `{decision: \"approve\"|\"reject\"}` answers a run awaiting a yes/no sign-off from the web app — 403 unless the caller is the person it waits on or the principal, 409 if it isn't awaiting or needs a written reply — through the same `apply_resolution` a chat reply uses. Custom create/update also rejects (422) any action-step tool that does not resolve, and so does `POST /workflows/custom/{name}/activate` when turning a workflow **on** — that click is the approval for a tool workflow chat saved switched off (turning off is never checked). Turning on a workflow with action steps requires the body `{is_active: true, definition}` carrying the definition the user reviewed; if the stored one differs (ignoring `is_active` and timestamps) it returns 409, and the switch itself is a compare-and-set on the validated revision (`dynamic_store.activate_if_unchanged`, keyed on `updated_at`), so a save that lands while the tool check awaits the gateway — even from another process — is a 409 too, so only what was shown gets switched on. `GET /workflows/custom` lists inactive definitions too; `GET /workflows/{name}` 404s for them. The two `tools` endpoints return `{tools: [{name, description, read_only, source}]}` for the advanced editor's tool picker and the review card; `read_only` is true only when the name says it reads (a label, not a control). The run stream adds a `progress` event (`step_id`, `summary`) while an action step uses tools. Each catalog entry (`WorkflowMeta`) carries `is_custom`, `background` (true for the system-run built-ins the UI files under “System”) and `quick` (true for a Quick workflow, one per playbook nothing else follows, named `quick_<playbook>`). The run endpoint streams SSE; its `awaiting_human` event carries `delivery` (`self` \\| `sent` \\| `suppressed` \\| `alerted` \\| `failed`) alongside `person_id` / `question` / `awaiting_until`, because the outbound guard or an unreachable approver means the question may never have been asked — a client must not render “waiting on them” for those. A paused run ends the stream with neither `done` nor `error`, so that `awaiting_human` frame carries `terminal: true` to say so explicitly, plus `resumable` — whether the run continues by itself once answered or stops at the gate. `GET /workflows/runs/{run_id}` returns the run row with the resume payload replaced by a small `resume_progress` summary (`gate_step_id`, `completed_step_ids`, or `null`): the payload holds every completed step's full text, and the run-detail page polls this endpoint while a run is unfinished. |\n| `knowledge` | `/knowledge/builtin`, `/external`, `/search` | MBA knowledge base and external sources. `/search` is the introspection parallel of `retriever.retrieve` and mirrors its filters — including the `general` catch-all on the company collection — so the panel cannot report a specialist seeing nothing that it does retrieve in chat. It accepts `general` in `domain_filter` for the same reason. `/search` applies the same review gate as `retrieve()` — withheld (pending or rejected) built-in, external and failure rows are dropped, so the panel never advertises knowledge the Executive cannot use; it degrades to unfiltered rather than failing if review state is unreadable. `POST /knowledge/builtin` refuses a name already held by shipped content, and `POST|DELETE /knowledge/failures` now register and deregister for review — without that a user-authored failure case study had no review row, so no SME decision could block it. |\n| `skills` | `/skills`, `/skills/search`, `/skills/{name}/restore` | Skill registry (the UI's **Playbooks**) CRUD and search. `PUT` on a built-in saves a company customization that shadows it; `DELETE` returns `{name, outcome}` — `deleted`, `reverted` (customization removed, built-in back) or `hidden` (built-in hidden for this company); `restore` un-hides; `GET /skills?include_hidden=true` lists hidden built-ins. List and detail carry `used_by` — `[{name, title, is_custom}]` of the workflows that follow the playbook (switched-off custom ones included) (`WorkflowMeta.playbooks` is the other direction). |\n| `evals` | `/evals/scenarios`, `/evals/runs` | Eval scenarios and run results. `POST /evals/runs` is a 403 when a workflow scenario names a workflow that only the principal may start in the mode it runs in (the weekly review; the morning brief in solo) and the caller is not the principal — the Jobs page's rule for starting a run; stored results are read under the existing `/evals/runs` rules. |\n| `memories` | `/memories/{decisions,initiatives,advice}`, `GET /memories/facts`, `POST /memories/facts/{fact_id}/{retire,approve,decline}`, `GET /memories/facts/approval`, `PUT /memories/facts/approval/{person_id}`, `GET /memories/people`, `GET /memories/people/{person_id}/conclusions` | Episodic-memory record management; the standing facts the Pulse Corrections tab reads (`{facts: [...], can_retire, retirable_ids, can_review}`; each fact carries `recorded_by_role` / `recorded_by_name`; `?include_inactive=` default true, honoured for the principal only; anyone else gets the active rows plus their own `proposed` ones, with the provenance (`session_id`, `turn_id`, `recorded_by_person_id`, `retired_reason`, and `source_quote` except on their own facts) blanked, never retired, replaced or declined text; `?limit=` 1–500) and their retire (the principal any fact, a teammate only one they recorded that the principal has not approved — else 403; the audit row names the teammate; 404 for an unknown or `profile` row, 409 when no longer active; writes a private `fact_retired` audit row); approve / decline a teammate's `proposed` fact (principal only, else 403; 409 when it is not proposed; private `fact_reviewed` row); and the per-teammate \"needs my approval\" switch (on by default; `GET` lists `[{person_id, full_name, needs_approval}]` for every active team member but the principal, `true` for anyone not yet set; `PUT` takes `{needs_approval}`, 404 for anyone else; both principal only; private `fact_approval_changed` row); plus the read-only peer-memory overview the Pulse People tab reads (`{status: ok|disabled|error, people: [...], conclusion_total}`; `?recent=` 1–50, default 5) and one person's full conclusion list, paged newest first (`{status, person_id, items, page, size, total, has_more}`; `?page=` ≥1, `?size=` 1–100, default 50; 404 when the person has no peer). Peer memory is each person's own: the overview holds only the caller's entry (none for a caller off the roster; `conclusion_total` counts only theirs), the principal included, and `/conclusions` for anyone but the caller is a 404. |\n| `review` | `/review/items`, `/review/stats`, `/review/trusted-defaults`, `POST /review/curate`, `POST /review/bulk-approve` | Knowledge review queue and annotations. Shipped knowledge registers as a trusted default (`approved` with a NULL `reviewed_at`), so the queue starts empty; `curate` (`{domain, action: start|stop}`, domain required) opts one domain in or out, and `trusted-defaults` returns domain → unreviewed count. `bulk-approve` takes a non-empty `domain`, `item_ids` (max 500) or `all_pending: true`, and 400s with no selector; it returns `{approved_count, item_ids}`. |\n| `onboarding` | `/onboard/interview/understand`, `/onboard/interview/start`, `/onboard/interview/message`, `/onboard/interview/draft`, `/onboard/interview/{id}`, `/onboard/interview/commit` | Conversational company setup. The `onboarding_interviewer` agent asks clarifying questions, then emits a draft profile + people + departments. **Nothing is persisted until `POST /onboard/interview/commit`** — the interview itself never writes. `start` is multipart (description + optional deck/one-pager uploads). `commit` answers 403 when the draft would make a different person the owner and the caller is not the current owner (setup demotes the old principal, and any signed-in user can open it). It also takes an optional `owner_email` — the principal's sign-in email, which the review screen pre-fills from the signed-in user — checked before anything is written (422 if it is malformed, already another person's, or would replace the principal's existing email — setup only fills in a missing one; 403 if the caller is not the owner and it is not the address they signed in with, since the roster is the sign-in allow-list) and saved on the principal's People row, so the owner's chats resolve to them from the first turn. |\n| `workflow_designer` | `POST /workflows/designer/start`, `POST /workflows/designer/edit`, `POST /workflows/designer/message`, `POST /workflows/designer/draft`, `GET /workflows/designer/{session_id}` | The conversational New workflow wizard, and editing a saved workflow by conversation. `/edit` (`{name}`) opens a session on a saved custom workflow with no model call: the stored definition is the starting draft, and every response then carries `editing` (its name) and `original` (the stored definition as the session opened on it); drafts keep that name and its on/off state whatever the model writes (404 for an unknown workflow). The UI saves one with `POST /workflows/custom/{name}/save-edit` (`{session_id, definition}`): the server saves the session's own draft, never a client-sent body, and only when it equals the `definition` the user reviewed (a later message is a 409, so the click saves only what was shown); it re-validates it, keeps the stored on/off state, and writes only if the stored workflow is still the version the conversation opened on — otherwise 409, as it is for a session about another workflow or one with nothing drafted yet. It sits under `/workflows/custom` so anything that limits writes to custom workflows covers it too. The `workflow_designer` agent asks clarifying questions (`phase: \"question\"`, with `hint` and up to four suggested `options`), then returns `phase: \"draft\"` with `draft.definition` (exactly the body `POST /workflows/custom` takes), `summary`, and `assumptions`; every response carries the `transcript`. **Nothing is persisted here** — sessions are in memory, and the UI saves through `POST /workflows/custom`. Errors are fixed strings (422 over the 8,000-char message cap or the transcript cap, 404 for an expired session, 409 while another turn on the same session is still running, 502/504 for model failure or timeout). Mounted ahead of the `workflows` router. |\n| `python_jobs` | `GET /python-jobs/{job_id}/{name}` | A result file a Python job (`run_python_job`) wrote, the principal's alone (403 otherwise), served as a download (`Content-Disposition: attachment`, `Content-Security-Policy: sandbox`, `nosniff`, `Cache-Control: no-store`); 404 for a bad id or name or a file past its 7 days. |\n| `saved_tools` | `GET /saved-tools`, `GET\\|PUT /saved-tools/{name}`, `POST /saved-tools/{name}/rollback` | The scripts the Executive saved as tools (Settings → Advanced → Saved tools), the owner's alone (403 otherwise). The list gives each tool's name, description, on/off, current version, `kind` (`script` or `python`, a kept Python job) and the tools it calls, plus whether `SAVED_TOOLS_ENABLED` is on; the detail adds the script, every version and the last 20 runs. `PUT {enabled?, workflows?, version?}` turns one on or off (off also turns it off for workflows, so turning it back on never re-arms unattended runs), and turns the named `version` — the one the owner looked at, never whatever is current by then — on for workflows (or workflows off); a Python tool never turns on for workflows (409) — turning workflows on lets more run unattended, so it needs a request tied to the owner (signed sign-ins or local login, as Take the lead's switches do; 409 otherwise); `rollback {version}` makes that version the one that runs. Both are audited as `saved_tool_changed`. The Executive saves tools itself through `run_script`; there is no create route. |\n| `onboarding` (fallback) | `/onboard/start`, `/onboard/answer`, `/onboard/status/{id}` | The original 12-step form wizard, kept as a fallback (UI at `/onboard?mode=form`) and used by the `openexecutive onboard` CLI. Its final answer saves the profile and adds people with their emails and a principal, so once there is an owner only they can send it (403, and the session rolls back so the owner can still finish it). `/onboard/start` reads the workspace mode once for the session: solo skips the Team Size, Team Members and Fractional Executives steps. Each status response's `current_step` / `total_steps` count only the steps that session asks, and `optional` says whether the current step can be skipped. |\n| `company-profile` | `GET\\|PATCH /company-profile` | Structured company profile. |\n| `alerts` (private cards) | `POST /alerts/{id}/ack`, `/reopen`, `/alerts/bulk-ack` | An alert tagged `private:principal` (see Today) is a 404 on ack and reopen for anyone but the principal, and their bulk sweep skips it. A roster-request card (source `roster_request`) is a 409 on `ack` even for the principal — it is answered at `/people/requests/{id}`, since acking would leave the sender waiting with nothing to show it — and, as an exempt source, `bulk-ack` and `reopen` skip it. |\n| `auth` | `GET /auth/allowed-emails` | Non-archived **team members** with an email, offered to the UI's sign-in gate — a contact is never on it, so adding a client to reach them by email no longer lets them sign in. The gate takes the **union** of this roster and its own `ALLOWED_EMAILS` env list, so env entries always work (and are checked first, short-circuiting the fetch) and roster entries are additive — a roster change can never revoke a configured operator. With local login (`make dev` with Google sign-in not set up — the UI then listens on 127.0.0.1 only) the UI signs in without an email, sends no `x-caller-email`, and the backend resolves the caller to the principal, as it does for the CLI. |\n| `fixtures` | `/fixtures`, `/fixtures/{name}/load` | Demo-company fixture load/reset/snapshot. `POST /fixtures/reset` leaves no departments, like a new install (`departments_seeded` is always 0). |\n| `clients` | `/clients`, `/clients/generate`, `/clients/cockpit`, `/clients/save`, `/clients/{slug}/activate` | Client-company slots — multi-client mode for fractional use; create from current/blank/AI-generated intake draft (pasted notes and/or file attachments, multipart on `/clients/generate`), save-back switching, engagement metadata (PATCH), cross-client cockpit, delete. See the Client Companies section. |\n| webhooks | `POST /webhook/telegram`, `POST /webhook/google-chat`, `POST /webhook/slack` | Inbound integration callbacks (self-verified). `/webhook/slack` answers 503 unless `SLACK_SIGNING_SECRET` is set. |\n| MCP server | `POST\\|GET /mcp` | Open Executive exposed as an MCP server (Streamable-HTTP). Not a router — a mounted FastMCP sub-app. Same shared-secret gate (`x-api-key`); exposes company context as resources and the specialist council as tools. See the MCP Server section. |\n\n**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-14T06:43:22Z"+ "generated_at": "2026-10-14T14:31:35Z"}diff --git a/packages/core/openexecutive/architecture/prebuilt/memory.json b/packages/core/openexecutive/architecture/prebuilt/memory.jsonindex 57b48159..de6e40c0 100644--- a/packages/core/openexecutive/architecture/prebuilt/memory.json+++ b/packages/core/openexecutive/architecture/prebuilt/memory.json@@ -1,7 +1,7 @@{"section_id": "memory","title": "Memory System",- "markdown": "The Executive's durable memory is an episodic SQLite store at `./episodic_memory.db`, managed by `openexecutive.memory.episodic`. It holds four tables:\n\n- `decisions` — choices made, with `domain`, `summary`, `rationale`, `outcome`, and `tags`. `outcome` is filled in when the principal says how a decision turned out — the `record_decision_outcome` chat tool (principal on a verified surface only) or the Memories page. The weekly review reads this table twice: the week's decisions (`decisions_since`) and up to three older than 30 days with no outcome yet (`decisions_awaiting_outcome`), which it asks about.\n- `initiatives` — tracked efforts with a `status` and `summary` (idempotent upserts).\n- `advice_given` — query/advice pairs per domain.\n- `scheduled_actions` — a dispatch queue, treated separately from recall memory. `cancel_scheduled_action` guards its UPDATE on `status = 'pending'`, so a cancel never overwrites a row the scheduler claimed a moment earlier.\n\n### What gets extracted, and when\n\n`episodic.extract_and_store` runs after a turn and asks a utility-fast model for decisions, initiatives and advice. Every candidate must carry a `user_commitment_quote` that appears verbatim in the principal's own message (`_is_valid_user_commitment`) — the turn's speaker text (`memory_text` when the entry point supplies one, else the prompt), so a quoted Executive email or a briefing card's body inside the prompt cannot satisfy it — the model has repeatedly tried to log the Executive's *recommendations* as the user's commitments, and that quote is the hard gate against it.\n\nA turn reaches the extractor if `should_extract(speaker_text, session=...)` is true, which means only that the principal said something on a surface that proved it was them — there is deliberately **no length floor**. There used to be one, on the combined user+assistant length, and on a live tenant it selected almost exactly the wrong turns: 9 of 16 exchanges were blocked, and the 9 held every instruction the principal gave, while the 7 admitted were long analytical exchanges with no commitment in them. The extractor ran 13 times and stored nothing.\n\nMoving that floor to the user's side would relocate the bug, not fix it. The canonical executive decision is a long analysis answered with \"Approve option B.\" (17 chars) or \"Do B.\" (5), and any floor high enough to skip \"Done\" (4) also skips those — \"Do B.\" and \"Done\" differ by one character and mean opposite things. Length cannot separate a decision from an acknowledgement; the verbatim-quote check can, so `_is_valid_user_commitment` is the gate that decides. The price is one utility-fast call on turns that propose nothing.\n\nThat quote check is only meaningful when `user_message` holds the **principal's** words, and on a chat channel it does not — `Executive.chat()` is reached from Slack, Discord, Telegram, Google Chat and the email poller. A teammate's line would be written to `decisions` with no speaker attached, indistinguishable from the principal's own; an inbound email body is text the sender chose, so a self-quote is free. Removing the length floor is what makes this bite — short channel traffic used to fall under it incidentally — so `should_extract` asks the untrusted-content policy (`orchestrator.content_trust.principal_speaking`) whether the principal is speaking. It names the principal's surfaces rather than inferring them: the web chat (signed in as the principal — or, on an install with no principal on the People page yet, a request that carried no sign-in; a signed-in email on nobody's entry, such as an archived teammate still allowed to sign in, is not the principal), the CLI (`Session.from_cli`), the principal's own Slack or Discord or a private Telegram chat with a valid webhook secret (`people_tools.is_principal_on_verified_surface`), and email from the principal's primary address that Gmail's own `Authentication-Results` marks `dmarc=pass` (`Session.email_authenticated`). Everything else fails closed: a teammate (on the web too), an unrostered sender, the principal's address on mail Gmail did not authenticate, Google Chat, the MCP server (its caller names themselves), unattended runs, and an unreadable roster. The rule used to be \"no `origin_channel` means the principal's own surface\", and the email poller left `origin_channel` empty, so every stranger's email ran through the extractor with its body — headers, quoted chain and all — as the principal's words, and whatever it stored rendered on every later turn. The poller now tags its sessions `origin_channel=\"email\"`, and the gate no longer reads an empty channel as trust.\n\nThe extractor also reads only the words **outside** every `<untrusted_content>` block (`schedule_extraction` runs `content_trust.strip_untrusted` first): an attached document's text is inlined in that block, so a sentence the principal did not type can never be quoted back as their commitment, and a turn that is nothing but an attachment is not extracted at all.\n\nEach pass writes a `memory_extraction` audit row — in a `finally`, so a pass that crashed is recorded too, with the exception type as its `failure` reason: how many items the model proposed, how many were stored, a `malformed` count so a pass where the model returned only garbage does not read as one that found nothing, and a `{kind, reason}` record per drop — `bad_quote` and `missing_field` for an item the model proposed, `not_a_list`, `item_not_a_dict` and `payload_not_a_dict` for a shape that was never a usable item. Every proposed item is either stored or dropped, so `proposed == stored + item drops` is the arithmetic that says whether anything was lost silently. The tool payload is not schema-checked anywhere, so a malformed shape is counted as a drop rather than raised — it used to abort the whole pass, discarding the other two kinds with it and suppressing the row, which read exactly like \"extraction never ran\". Without it, \"the model found nothing\" and \"the model found things and every one was rejected\" are indistinguishable from outside the database — which is why the failure above survived undetected and took a SQLite session on the tenant to find. A `proposed>0, stored=0` streak is the signal to watch.\n\nThe validator rejects a paraphrase, and the model paraphrases: on one install two of three real commitments were lost that way, the quote beginning \"SVN's engagement covers only …\" where the person had typed something else. So a `bad_quote` drop earns exactly one corrective call. The model is shown the rejected items and the quotes it gave, told to copy the span character-for-character (typos and casing included) or return empty arrays, and the tool is forced where the provider supports tool choice. Every retry item is validated first; a still-invalid one adds no second drop and is counted `still_invalid`. A valid item is then classified in order: its label matches a pending drop record → a recovery, stored and the record released; else its quote (terminal punctuation ignored) already supports a stored item of that kind → a re-send, ignored and counted `repeated`, so a model that re-sends everything cannot double-count `stored`; else a new proposal, stored and counted — a reworded label cannot be told from a different item, and crediting it would erase the very `bad_quote` census the row exists to show, so its original drop stands. Recovery is checked before re-send because two commitments can rest on one sentence. Malformed shapes at any level — a kind that is not a list, an item or payload that is not a dict, a response with no tool call — are counted `malformed`, so a retry that returned garbage does not read like one that obediently returned nothing. The row's `retry` block (`rejected`, `recovered`, `repeated`, `still_invalid`, `malformed`, `failure`) is always present, zeros when nothing was rejected; `rejected` is set from the complete drop list when the row is written, so neither a store failure before the retry nor a cancellation during it can zero it. The arithmetic above still holds after the retry. An exception on the retry is recorded as the retry's own `failure` and leaves the first pass's results untouched; the cost is one utility-model call, only on turns that dropped something. `memory_extraction` is a declared event type, so the audit page's filter can select it.\n\n### Standing facts (corrections that persist everywhere)\n\nA fifth table, `facts` (`openexecutive.memory.facts`, created on first write), holds facts and corrections the principal stated and asked to keep — \"Maple House is 48 units, not 52\". Before it, a chat correction's only durable home was Honcho peer memory: optional, best-effort (its prefetch times out or errors under load), re-injected only into that person's later chat turns, and never read by the briefs, the scheduled runs or the alert review. The episodic extractor cannot hold one either: it stores only decisions backed by a commitment quote, and a fact is not a commitment.\n\n- **Written from chat, by the principal or an attributed teammate.** `remember_fact` stores one (subject, statement, optional wrong value) and `forget_fact` retires one. The principal on a verified surface may do both. A teammate on the People list (a `team` row, not archived, not a contact) on a verified surface (the web app signed in, their own Slack or Discord; `fact_tools._teammate_speaker`) may call `remember_fact` only; email, Google Chat and unrostered senders are refused. Both tools are withheld from every unattended run and every turn private to the principal. Every call, `forget_fact` included (retiring a fact changes what later prompts treat as true just as writing one does), also needs `source_quote`: at least two words and eight characters, found in what the speaker typed this turn (`delegation.settings.own_words` over the pinned `TurnDelegation.speaker_text`). The `<outbound_reply_context>` backstory a Slack or Discord reply is hydrated with is stripped first, and a message with an attachment is refused outright. The quote alone only proves the principal asked, so everything `remember_fact` stores and renders (the statement, the subject shown as `[fact N] subject:`, and a previous value shown as `(corrects: …)`) is tied to their words too. An omitted previous value falls back to the replaced fact's own statement. Every figure must be a number they wrote, compared at its magnitude: `$180k` matches `180,000`, but `180m` never lets `$180k` through. Every name must also appear in what they typed: a capitalised word, or any word holding a non-ASCII letter, other than the statement's very first word (a statement is one fact, so splitting a document's names into one-word sentences exempts nothing). So must every month, weekday or quarter. A name the model writes in lower case is not caught: the gate narrows what a real quote can carry in; it does not prove a paraphrase. A real quote therefore cannot carry a document's figure, name or date in with it (\"Cedar Court's lease expires in March\" after \"remember what the lease doc says\"), while a paraphrase of what they said still passes. So the model cannot store its own inference, a document's figure or text quoted back at the principal as something they said. Every audit row the tools write, and the chat loop's `skill:` dispatch row for them (whose input quotes the principal verbatim), is private to the principal (`executive._private_tool_row`). Those rows tie a fact to the principal's session and turn, which `GET /memories/facts` hides from teammates, and a teammate can read any non-private audit row. The handlers run in a worker thread (`asyncio.to_thread`, which carries the turn's context), and the chat and committee paths, the alert review, the morning brief's synthesis and the end-of-day, weekly-review and reflection workflows read the block the same way, so SQLite, the profile file and its lock never block the event loop the SSE streams share. The principal's own email may ask too: the change is checked the same way, then held until they confirm it by replying to a one-time token sent to their own address (see Integrations → Standing facts by email).\n- **Provenance and attribution.** Each row keeps the quote, the channel (`web` or the adapter), `session_id`, `turn_id`, the recording person and the time, plus `recorded_by_role` (`principal` or `teammate`) and, for a teammate, `recorded_by_name` as the People list had it. Rows written before these columns existed read as the principal's (`_migrate` adds the columns on the first write; the read-only render tolerates a DB that has none).\n- **One active fact per subject.** A new row supersedes any active row with the same folded subject key, or the id named in `replaces_fact_id`, in one transaction. The old row stays as `superseded` (with `superseded_by`), and the new one is stored as a `correction` carrying what it replaced. Retiring sets `retired` with a reason. **The principal outranks a teammate:** a teammate's write that would replace an active fact the principal set (by subject or `replaces_fact_id`) raises `PrincipalFactConflict`, and the tool stores it as `proposed` instead, naming the fact it would replace (`replaces_fact_id`); teammates replace each other's facts freely, and the principal replaces anyone's. **\"Needs my approval\"** (`fact_approval_rules`, per teammate, **on by default**, set only by the principal) stores every fact from that teammate as `proposed`; the principal turns it off for a teammate they trust, whose facts then apply at once (except one that would replace the principal's). The rule is read inside `record_fact`'s own write transaction, so a switch turned on a moment earlier cannot let one fact through; a teammate write that names no person is never trusted. One teammate may have at most `MAX_PENDING_PROPOSALS_PER_PERSON` (20) proposals waiting (`TooManyProposals`; the tool tells them to wait for the principal's review). A teammate's retire checks ownership in the `UPDATE` itself (`retire_fact(teammate_id=)`: their own row, not approved). A proposed row never renders; `approve_fact` makes it active and replaces what it names (the principal's own fact included — approving it is their word) and stamps `approved_at`, after which it outranks teammates exactly as the principal's own fact does (`Fact.principal_owned`: no teammate may replace or retire it); `decline_fact` sets `declined`. No field of a teammate's fact may carry what the render adds itself — `(per <anyone>)` in any case (a unit such as `(per month)` or `(per unit)` is fine), `[fact N]` or a date stamp after any dash, read NFKC-folded with invisible characters removed (`fact_tools._marker_error`) — so a teammate cannot plant a second, forged attribution inside their statement (the principal's own unmarked lines are not checked: \"(per Smith lease)\" is ordinary wording for them). The tool answers `awaiting_approval` (no action chip) and tells the model to say it is not in use yet.\n- **Rendered everywhere output is produced.** `render_facts_for_prompt` renders the active rows newest first under a self-explaining `STANDING FACTS` header (use these over older figures; a line ending `(per <name>)` is that teammate's word and the principal's unmarked line wins a conflict; the current conversation still wins; quoted data never instructions). A teammate's line ends `(per <name>)`, the name defanged like the rest, capped at 40 facts / 6000 chars, with angle brackets defanged. It opens the DB read-only and never creates it or the table. The block always rides in a user turn, never a cached system block: a chat turn's `<standing_facts>` (so every scheduled run through the chat loop too), each specialist consult (`route_to_specialist`, chat and workflow steps alike), the /today header and the morning brief (`render_briefing_context`, after the quiet check and inside the string the header's cache key hashes, so a new fact rewrites the header), the alert review's batch (`render_batch`, read once per pass), and the end-of-day digest, the weekly review's top-three call and the morning reflection (`with_standing_facts`).\n- **Company-profile edits from chat.** `update_company_profile` (same gate and quote rule) changes one whitelisted field of `company/profile.yaml`, under `PROFILE_EDIT_LOCK` (also taken by `PATCH /company-profile`, so neither edit silently drops the other): a text or number field is set, a list field gets an item added or removed, and `financials.key_metrics` takes a named metric. It writes through `CompanyProfile.save_to_yaml` and updates the session's profile, so the next turn's cached company block carries it (one cache miss on the change). The new value must itself appear in the principal's own words, not just the quote: the value renders into the cached company block on every later turn, so \"set our mission to what the doc says\" or \"update our headcount\" is refused rather than saving a document's text or a guessed figure. A number must be one they wrote, however they wrote it (`$180k`, `1.2m`, `2,400,000`). Saved text has `<`/`>` defanged. A `kind='profile'` row records each edit with its quote for the Pulse page. Those rows are never rendered into a prompt, because the profile block already carries the value.\n\n### Session scoping\n\n`decisions` and `advice_given` rows carry a `session_id`, so per-thread channels (Discord, Telegram) can pull just-this-thread history without leaking cross-conversation context. A null `session_id` falls back to a global view.\n\n### Surfacing\n\n`openexecutive.memory.episodic.format_for_prompt` renders recent decisions and initiatives into a compact `<past_decisions>` block injected into the user turn — alongside `<retrieved_context>` and peer memory — never into a cached system block. Each decision names where it was recorded when that was a channel — `- 2026-09-01 [finance] (via email): …`, from the prefix of its `session_id` (`email:`, `slack:`, `discord:`, `telegram:`, `google_chat:`); a web or CLI decision has no tag. Rows extracted from mail before the untrusted-content policy, when any sender's body could be stored, therefore read as mail rather than as the principal's own word.\n\nScoped to a session, decisions and advice cover every conversation of a chat app's stream (`memory.conversation_ids.family_clause`): a Telegram chat or a DM is cut into conversations after two quiet hours or a /new (`memory.conversations`), and what an earlier conversation decided still renders in the next.\n\nThe chat route also injects a `<briefing>` block into the same user turn: a compact digest of the current open (unread) alerts, built by `openexecutive.briefing.context.format_open_alerts_for_prompt` (company-wide, `status=\"unread\"`, mirroring `/today`). This is what lets the Executive discuss a briefing item the principal clicked or named on `/today` (e.g. \"Gulf Coast Port Cyberattack\"). It is resolved in parallel with the other context fetches, omitted when there are no open alerts, and never placed in a cached system block.\n\nOn the Pulse page the Memory section shows the three lists as Decisions, Initiatives and Advice tabs, then a **Corrections** tab (`GET /memories/facts`: active standing facts and profile edits with their quote, channel and — for a teammate's — their name; proposals first under \"Waiting for your approval\" with **Approve** / **Decline** for the principal; the replaced, retired and declined history folded away; **Retire** on any fact for the principal and on their own not-yet-approved one for a teammate; and, for the principal, a per-teammate \"needs my approval\" switch), and a **History** tab for the person's own Always in the loop notes (see below). The header's Memories tile counts the three lists. What peer memory has learned about the signed-in person is theirs alone, so it is not on Pulse: it is on **Settings → About you** (see the peer memory section).\n\nThe same user turn carries a `<drive_memory>` block when the conversation has touched Google Drive (`openexecutive.memory.drive_reads`). Drive is reached only as live Google Workspace calls inside a turn and history keeps only prose, so without it a file found one turn was gone the next. `MCPGateway.call_tool` hands each `search_drive_files` and `get_drive_file_content` result to `record_drive_result`, which keeps, per session, every file found or opened (file id, name, type, link, and for an opened file its first 600 characters) and every search that matched nothing, with its query. `format_drive_memory` lists the 20 most recent files, so \"the file you found earlier\" resolves to a file id the Executive reopens rather than searching again, and the queries that found nothing (dropped once the same query later finds something). Rows are keyed on the session *and* the speaker, and shown only to that speaker in that session, because one session can span several people (an email thread, a Slack or Discord thread). Nothing is recorded or shown without a bound `current_session` and a rostered speaker, on a turn private to the principal, or on one that touched the speaker's own mailbox (Act as me). workspace-mcp writes file names into its output unescaped, so a name containing a newline can forge a result line. Only a Drive-shaped file id, type and `docs`/`drive.google.com` link are therefore kept; any other line is dropped, and the name is always quoted as the file's own content, not instructions. Each speaker keeps at most 100 files and 100 searches per session, older rows are pruned on write, and `session_store.delete_session` drops them all.\n\nA conversation can also become its owner's alone. When Act as me first reads the speaker's own mailbox in it, `session_store.mark_mail_private` sets `sessions.mail_private` (creating the row with its owner when a channel adapter hasn't written it yet), and from then on only the session's owner may open, continue or delete it — the principal included, when it is a team member's (`chat._session_access`). It is never cleared. Beside it `sessions.mail_read_at` keeps how many history messages the conversation held before the last turn that read the mail (`session_store.mail_read_at`; NULL on rows marked before the column): Act as me's hold on links and scripts in later turns lasts only while that turn is still in the history window (see Act as me). A search that matched nothing also gains a note in its tool result: say the exact query and that it found nothing, never that the file does not exist. This is a first step: Drive is still not indexed into the company collection.\n\n### System of record\n\nSQL is the system of record; the peer-memory service is a recall layer mirrored from it, not a replacement. When `store_decision` / `store_initiative` / `store_advice` insert a row whose `department` is non-empty and not `\"general\"`, the row is mirrored as a kind-tagged note into that department's peer via `append_department_note`. The mirror fires only after a successful INSERT, is fire-and-forget, and never rolls back the SQL row on peer-memory failure. `scheduled_actions` is never mirrored — it is a queue, not memory.\n\nThe episodic extractor still learns only from the principal's own words. Commitments and asks from everyone else on the roster are tracked as **open loops** (see Attunement) — `scheduled_actions` rows with `kind='open_loop'`, opened and closed by a separate quote-gated pass after each attributed turn. That pass depends on `chat_messages.sender_person_id`, which records who actually wrote each persisted user message. An open loop counts toward `list_awaiting_replies_by_person` only once it is due, and `list_scheduled_actions(exclude_internal=True)` filters `__internal__` rows in SQL so readers that want real sends are not starved by them. `mark_outbound_context_consumed` also resolves the Attunement outcome row for that DM as `replied` — a matched reply is the clearest sign proactive outreach landed — and a real change to an existing initiative (`store_initiative` / `update_initiative`, new status or summary) marks the updater's own check-in nudges `acted` — an update with no known updater, such as `PATCH /memories/initiatives/{id}`, credits nobody.\n\n### Workspace settings\n\nThe same database holds one row of settings that are not memory: `workspace_settings` (`openexecutive.memory.workspace_settings`) — the install's mode (`team` by default, or `solo` for one person using Open Executive just for themselves), the user's IANA time zone, the principal's role (`PrincipalRole`: `role_kind`, `role_title`, `reports_to`, `remit`, `measured_on`, all nullable; only solo mode reads it), and the company's own email domains (`company_domains`, a JSON list, or NULL to derive them from the principal's primary address — `people.identity` matches a teammate by local part on them; `validate_company_domains` lowercases, dedupes and sorts, allows at most 10 plain DNS names and refuses a free-mail provider's, and a stored value that no longer validates reads as NULL). It is a table of its own rather than a company-profile field because onboarding rebuilds the profile from scratch. Every read is fresh and read-only (a missing file or table reads as the defaults; a table from before the role or `company_domains` columns reads them as unset and is migrated additively by the next init or write). A read error (a locked database, say) also reads as the defaults, so `get_workspace` then says team; `read_stored_mode` is the strict read of the mode alone — None when the row cannot be read or holds no valid mode — for the scheduler's weekly-review check, which must not take a failed read for team. A session may carry an explicit `workspace_mode` override; otherwise the mode is read fresh at the start of each turn and pinned on the session for that turn only (`Session.turn_workspace_mode`, via `pin_turn_workspace_mode`), so every tool handler in the turn sees the mode its persona and tools were built in. `effective_workspace_mode` reads override, then the pin, then the setting; `effective_principal_role` reads a session's `principal_role` override, then the role pinned for the turn (`Session.turn_principal_role`, via `pin_turn_principal_role`), then the stored role. See Org for what solo changes and Scheduler for the time zone.\n\n### Act as me\n\n`initialize_db` also creates Act as me's per-person tables (`delegation.schema.ensure_schema`): `delegation_settings`, `delegation_voice` and `delegation_voice_history`. They hold a setting and a writing profile rather than memory, and nothing in them is mirrored to peer memory. A turn that touched the speaker's own mailbox teaches no memory: the episodic, open-loop and working-style passes are skipped along with the Honcho peer and department syncs, since its reply quotes a draft built from other people's mail. See **Act as Me (Delegation)**.\n\n### Always in the loop (notes of what you said)\n\nA person can keep private, dated notes of what they said, in chat with the Executive and in email replies it drafted for them: what they promised, agreed, declined, answered, asked for or shared. The switch is per person (\"Keep track of what happens\", `history_person_settings.reply_notes`, off by default, one switch for every channel). Any team member on the People list may turn it on (`history.can_keep_notes`: kind `team`, not archived, the principal included); Act as me isn't needed, though notes from email replies only come through it.\n\n- **Where notes come from: chat.** After each chat turn, on both the single-voice and the committee path, the Executive's post-turn block calls `memory.history_chat.schedule_chat_notes` next to the open-loop and style passes, except on a turn that touched the speaker's mailbox. It reads only what the speaker typed this turn (`delegation.settings.own_words`: no backstory an adapter added, nothing when a file came with it), never the reply and never anyone else's message: every channel calls the Executive with the one speaker's message, and what other people say to each other is never read. It runs only for a speaker the turn verified (`history_chat.verified_speaker`): the turn's `caller_person_id` is them, nobody started it by email or runs it unattended or for them, and the surface proved who they are (the web chat signed in or a local install, the principal or a team member on their own Slack or Discord, a private Telegram chat behind a valid webhook secret, or a channel whose adapter verified the sender itself and set `Session.speaker_verified`). A shared Slack or Discord thread counts: the notes stay private and are read back only where nobody else can see them. A message under 40 characters is skipped, and each person gets at most 40 passes a day, counted in `history_chat_passes` so the cap holds across workers and restarts. The pass uses a constant `CHAT_PROMPT` (requests to the assistant, questions and small talk are not notes), the same `record_notes` tool and the same `check_note` gate with the message as both body and allowed words; the note's channel is the inbound channel or `web`, its conversation the session id, and it names no counterpart.\n- **Where notes come from: email.** After `delegation.reply_send` sends a reply, it starts `memory.history_notes.note_sent_reply` in the background. The note-taker reads only the words the person sent (`email_poller.sender_new_text` strips quoted mail) and the recipients' names, cut to four words of name characters (`history_notes.short_name`): never the mail being answered, nor the subject, which others in the thread write too, so nothing another person wrote can become a note. One forced `record_notes` call with a constant prompt and no other tools returns at most three notes. Code then drops any note that says more than they did: the `quote` must appear word for word in what they sent, every figure in the summary must be in the quote, every name or date word must be in what they sent or the recipients' names, at least half its other content words must be theirs, the summary carries no link or address, and a `due_date` is kept only for something promised or agreed. Notes record events, never instructions, and carry `trust = high` because they rest on the person's own words.\n- **Whose they are.** Every note is private to its person (`visibility = private`). Nobody else reads it, the principal included; there is no shared note.\n- **How long they last.** The company default is 90 days (`history_settings.retention_days`, the principal's choice of 30, 90, 365 or until forgotten). A person may only choose a shorter time; shortening the company time clamps everyone's choice and re-dates live notes. A pinned note never expires; unpinning restarts its clock, and a later retention change counts from there. Reads skip expired notes and the scheduler's alert sweep deletes them (`history.sweep_expired`).\n- **What a person controls.** Through `/memories/history` they read, search, pin, correct and forget their own notes. On the Pulse page this is the **History** tab, last in the Memory section and shown only to someone with notes to see (signed in and on the People list): each note shows its kind, who it was with, the date, the person's own words, any due date and when it will be forgotten, and its menu holds **Correct** (a side panel; \"Use the original\" clears a correction), **Pin**, **Don't remember this** and **Forget**. \"Don't remember this\" forgets every note from that conversation and adds it to `history_excluded`, so it is never noted again. Settings → **Memory** holds the switch (\"Keep track of what happens\") and a shorter time for their own notes, and the company time, which the principal changes and everyone else reads. A chat note shows the channel alone (\"Slack\", \"Web chat\").\n- **Recall.** `recall_history` (`orchestrator.history_tools`) is offered only on a turn where the speaker may read their notes: verified as above, a team member who may keep notes, in a conversation private to them (`history_chat.private_chat`: the web chat, a Slack or Discord DM, a Telegram chat, or one its adapter marked `Session.private_chat`), with their switch on. Before any note is read the turn is set `touched_mail`, for the principal too, so its rows are private to the speaker, it teaches no memory and the mail lockdown holds from that round on. The conversation is also marked theirs alone (`session_store.mark_mail_private`), so every later turn in it is private the same way (the lockdown is that turn's alone) and, for a team member, the principal can't open it; recall refuses if that can't be stored. Notes come back in a `<history_notes>` block as history to cite: the date, the person's own words first, then how they were noted. With `due: true` it lists only notes with a due date, from a week overdue to two weeks ahead, soonest first (\"what's due today?\").\n- **In the owner's briefs.** The morning brief adds a FROM YOUR NOTES — DUE SOON block (`memory.history_brief.due_soon_block`: what the owner promised, agreed or asked of someone, from a week overdue to a week ahead, in the workspace's local dates) and the end-of-day digest a FROM YOUR NOTES — TODAY block (`noted_today_block`: what they promised, agreed, asked or declined since the last digest, then what is due tomorrow). Both only on the scheduler's delivery to the owner alone (`morning_brief.PRINCIPAL_DELIVERY`), never a run started from chat, whose tool result lands in the turn's shared audit row and peer memory; only when the owner may keep notes and has the switch on (`history_brief.owner_keeping_notes`), and only the owner's own notes. A run that used any is marked `private_to_principal`, so the shared run history keeps `PRIVATE_RUN_ARTIFACT` instead of its text, and the note ids with their state (overdue, today, soon) enter the brief's fingerprint, so one falling due un-suppresses an unchanged brief. Teammates get no brief, so their notes reach them only through recall and reminders.\n- **In Act as me drafts.** The ghostwriter gets a `<writer_noted>` block (`memory.history_drafts.notes_for_draft`): the writer's own notes from earlier Act as me replies that every recipient of the new draft was on, with their switch on. It keeps the draft consistent with them and turns a contradiction into an open question on the card; it never adds anything from them (see Act as me).\n- **Due-today reminders.** `memory.history_reminders.maybe_remind`, called from the scheduler tick every 15 minutes between 09:00 and 18:00 local time, sends each person with the switch on one message on a day something they promised or agreed to by email (`source = approved_reply`) falls due. Chat promises are left to open loops, which the nudge engine already chases. The message says only how many things are due, never what or to whom, and the channel senders' audit rows for it are private to the person (`audit.context.rows_for_person`; the owner's `private_rows`), which also keeps the send off the shared activity rail (`_record_send_to_activity` skips a send whose rows are private). The person asks \"what's due today?\" in a private conversation and `recall_history` answers. It goes to their own Slack or Discord DM, a private Telegram chat (`delivery_order` skips a negative group id, for the owner's briefs too) or their own email (`scheduler.runner.deliver_to_person`), never a shared channel. `history_reminders` holds one row per person per day, claimed before sending and never released, so two workers never both send and a half-failed send is never repeated; a failed one waits for the next due day.\n- **Not peer memory.** Notes never reach Honcho, episodic extraction, standing facts or another person's turn. The tables (`history_notes`, `history_settings`, `history_person_settings`, `history_excluded`, `history_chat_passes`, `history_reminders`, created by `history_schema.ensure_schema` from `initialize_db`) swap with a client slot and are cleared by a factory reset.\n\n## Decision ledger\n\n`openexecutive.memory.decision_ledger` keeps one `decision_instances` row per gated action — a meeting the Executive proposes to book, an Act as me reply card — with how it was resolved, so each class has a reliability record. Every status change is a compare-and-set. A tap with an outside effect (sending an email) claims the row first (`claim_for_execution`, proposed → executing), so of two taps only one acts, and finishes it as `approved_unchanged`, `approved_with_edit` or `failed`, or hands it back (`release_claim`). A row whose class acted on its own with nobody tapping — `gate_mode` `auto_execute`, as Act as me's **Handle it for me** replies are — finishes as `executed` instead, with no resolver, so a reliability read never counts it as an approval. A send whose result is unclear stays `executing` for a reconciler and is never retried. 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). A `session_shares(session_id, person_id, shared_by_person_id, created_at)` row lets one team member read someone's chat (`list_shared_with_person`, `set_shares`); it is read-only, a `mail_private` chat is never shared or read that way, and deleting the chat drops its shares. `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## 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-10T16:30:36Z"+ "generated_at": "2026-10-14T14:31:35Z"}diff --git a/packages/core/openexecutive/memory/chat_export.py b/packages/core/openexecutive/memory/chat_export.pynew file mode 100644index 00000000..3323e1eb--- /dev/null+++ b/packages/core/openexecutive/memory/chat_export.py@@ -0,0 +1,90 @@+"""A chat as a Markdown document, for the Download and Copy buttons+(``GET /sessions/{id}/export``).++Each message under who wrote it (the person's name from People, or the+Executive), with the reply's sources listed under it. What the reply said+is copied as written: it is already Markdown.+"""+from __future__ import annotations++import re+from datetime import datetime+from typing import Any++from openexecutive.memory.session_store import export_rows++EXECUTIVE = "Executive"+_FILE_NAME_MAX = 60+++def _names(person_ids: set[int]) -> dict[int, str]:+ from openexecutive.people.store import get_person++ out: dict[int, str] = {}+ for pid in person_ids:+ try:+ person = get_person(pid)+ except Exception:+ person = None+ if person is not None and person.full_name:+ out[pid] = person.full_name+ return out+++def _day(stamp: str | None) -> str:+ try:+ when = datetime.fromisoformat(str(stamp))+ except (TypeError, ValueError):+ return ""+ return f"{when.day} {when:%B %Y}"+++def _sources_block(sources: dict[str, Any] | None) -> list[str]:+ if not sources:+ return []+ lines: list[str] = []+ for item in sources.get("sources") or []:+ title = str(item.get("title") or item.get("url") or "").strip()+ url = str(item.get("url") or "").strip()+ if not title:+ continue+ lines.append(f"- [{title}]({url})" if url.startswith(("http://", "https://")) else f"- {title}")+ if not lines:+ return []+ return ["", "Sources:", *lines]+++def to_markdown(meta: dict[str, Any], *, owner_person_id: int | None) -> str:+ """The whole chat ``meta`` describes (a ``get_session_metadata`` row)."""+ rows = export_rows(str(meta["session_id"]))+ people = {+ int(r["sender_person_id"]) for r in rows if r["sender_person_id"] is not None+ }+ if owner_person_id is not None:+ people.add(int(owner_person_id))+ names = _names(people)+ owner_name = names.get(owner_person_id) if owner_person_id is not None else None++ out = [f"# {meta['title']}"]+ started = _day(meta.get("created_at"))+ if started:+ out += ["", f"Started {started}"]+ for row in rows:+ sender = row["sender_person_id"]+ if row["role"] == "assistant":+ who = EXECUTIVE+ else:+ who = (names.get(int(sender)) if sender is not None else None) or owner_name or "You"+ out += ["", f"## {who}", "", str(row["content"]).strip()]+ if row["stopped"]:+ out += ["", "_(Stopped before it finished.)_"]+ if row["role"] == "assistant":+ out += _sources_block(row["sources"])+ return "\n".join(out).rstrip() + "\n"+++def file_name(title: str) -> str:+ """A safe download name from the chat's title: letters, digits and+ dashes, ending in ``.md``."""+ slug = re.sub(r"[^A-Za-z0-9]+", "-", title).strip("-").lower()[:_FILE_NAME_MAX].strip("-")+ return f"{slug or 'chat'}.md"diff --git a/packages/core/openexecutive/memory/episodic.py b/packages/core/openexecutive/memory/episodic.pyindex b3ae31a4..9508357c 100644--- a/packages/core/openexecutive/memory/episodic.py+++ b/packages/core/openexecutive/memory/episodic.py@@ -491,6 +491,38 @@ def initialize_db(db_path: Path | None = None) -> None:"WHERE chat_messages.session_id = sessions.session_id) ""WHERE mail_private = 1 AND mail_read_at IS NULL")+ # Chat list controls (session_store.set_pinned / rename_session): when+ # the owner pinned the chat (NULL = not pinned), and 1 once they named+ # it, so the auto-title never writes over their name.+ if "pinned_at" not in _sessions_existing:+ try:+ conn.execute("ALTER TABLE sessions ADD COLUMN pinned_at TEXT")+ except sqlite3.OperationalError as exc:+ if "duplicate column" not in str(exc).lower():+ raise+ if "title_locked" not in _sessions_existing:+ try:+ conn.execute(+ "ALTER TABLE sessions ADD COLUMN title_locked INTEGER NOT NULL DEFAULT 0"+ )+ except sqlite3.OperationalError as exc:+ if "duplicate column" not in str(exc).lower():+ raise+ # Who a chat's owner shared it with, to read (session_store.share_session).+ conn.execute(+ """+ CREATE TABLE IF NOT EXISTS session_shares (+ session_id TEXT NOT NULL,+ person_id INTEGER NOT NULL,+ shared_by_person_id INTEGER,+ created_at TEXT NOT NULL,+ PRIMARY KEY (session_id, person_id)+ )+ """+ )+ conn.execute(+ "CREATE INDEX IF NOT EXISTS idx_session_shares_person ON session_shares(person_id)"+ )# Trust-ledger tables (first-climb autonomy, Build 1+2).# `decision_instances` is the correlation unit: links a proposal, itsdiff --git a/packages/core/openexecutive/memory/session_store.py b/packages/core/openexecutive/memory/session_store.pyindex d99f1b1e..4f35562c 100644--- a/packages/core/openexecutive/memory/session_store.py+++ b/packages/core/openexecutive/memory/session_store.py@@ -38,8 +38,37 @@ def create_session(def update_session_title(session_id: str, title: str, db_path: Path = DB_PATH) -> None:+ """The automatic title (a placeholder, then a generated one). Never+ replaces a name the owner gave the chat (``rename_session``)."""with _get_conn(db_path) as conn:- conn.execute("UPDATE sessions SET title = ? WHERE session_id = ?", (title, session_id))+ conn.execute(+ "UPDATE sessions SET title = ? WHERE session_id = ? AND title_locked = 0",+ (title, session_id),+ )+++def rename_session(session_id: str, title: str, db_path: Path = DB_PATH) -> bool:+ """The owner's own name for a chat, kept from then on. False when there+ is no such chat."""+ with _get_conn(db_path) as conn:+ cur = conn.execute(+ "UPDATE sessions SET title = ?, title_locked = 1 WHERE session_id = ?",+ (title, session_id),+ )+ return cur.rowcount > 0+++def set_pinned(session_id: str, pinned: bool, db_path: Path = DB_PATH) -> bool:+ """Pin a chat to the top of its owner's list, or unpin it. Pinning again+ keeps the first pin's time. False when there is no such chat."""+ now = datetime.now(UTC).isoformat()+ with _get_conn(db_path) as conn:+ cur = conn.execute(+ "UPDATE sessions SET pinned_at = CASE WHEN ? THEN COALESCE(pinned_at, ?) END "+ "WHERE session_id = ?",+ (1 if pinned else 0, now, session_id),+ )+ return cur.rowcount > 0def update_session_timestamp(session_id: str, db_path: Path = DB_PATH) -> None:@@ -127,9 +156,11 @@ def load_messages(session_id: str, db_path: Path = DB_PATH) -> list[dict[str, Anout: list[dict[str, Any]] = []for row in rows:msg: dict[str, Any] = {"role": row["role"], "content": row["content"]}- # The row id lets the UI attach 👍/👎 to a reloaded reply. Only on- # assistant rows, alongside `feedback`, for the same reason as- # `actions` below: untouched user rows keep their exact shape.+ # The row id lets the UI attach 👍/👎 to a reloaded reply, and name+ # the turn it takes back when the person edits their message or asks+ # again (``rewind_last_turn``). Only on assistant rows, alongside+ # `feedback`, for the same reason as `actions` below: untouched user+ # rows keep their exact shape.if row["role"] == "assistant":msg["id"] = row["id"]if row["feedback"]:@@ -166,7 +197,8 @@ def list_sessions(caller_person_id: int,db_path: Path = DB_PATH,) -> list[dict[str, Any]]:- """List sessions owned by `caller_person_id`, newest first.+ """List sessions owned by `caller_person_id`: pinned ones first (newest+ pin first, with ``pinned_at``), then the rest newest first.Legacy rows with caller_person_id IS NULL (created before this columnexisted) are excluded — the comparison `NULL = ?` never matches in@@ -180,13 +212,13 @@ def list_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.pinned_at,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 = ?GROUP BY s.session_id- ORDER BY s.updated_at DESC+ ORDER BY s.pinned_at IS NULL, s.pinned_at DESC, s.updated_at DESC""",(caller_person_id,),).fetchall()@@ -213,6 +245,8 @@ def list_sessions(k: row[k]for k in ("session_id", "title", "created_at", "updated_at", "message_count")}+ if row["pinned_at"]:+ item["pinned_at"] = row["pinned_at"]msg = last.get(row["last_id"]) if row["last_id"] is not None else Noneitem["preview"] = _preview(msg["role"], msg["content"]) if msg is not None else Noneout.append(item)@@ -340,6 +374,7 @@ def delete_session(session_id: str, db_path: Path = DB_PATH) -> bool:return Falsewith _get_conn(db_path) as conn:conn.execute("DELETE FROM chat_messages WHERE session_id = ?", (session_id,))+ conn.execute("DELETE FROM session_shares WHERE session_id = ?", (session_id,))cur = conn.execute("DELETE FROM sessions WHERE session_id = ?", (session_id,))deleted = cur.rowcount > 0delete_session_drive_memory(session_id, db_path)@@ -352,7 +387,7 @@ def get_session_metadata(session_id: str, db_path: Path = DB_PATH) -> dict[str,with _get_conn(db_path) as conn:row = 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.pinned_at,COUNT(m.id) AS message_countFROM sessions sLEFT JOIN chat_messages m ON m.session_id = s.session_id@@ -361,7 +396,12 @@ def get_session_metadata(session_id: str, db_path: Path = DB_PATH) -> dict[str,""",(session_id,),).fetchone()- return dict(row) if row else None+ if row is None:+ return None+ meta = dict(row)+ if not meta.get("pinned_at"):+ meta.pop("pinned_at", None)+ return metadef get_session_owner(session_id: str, db_path: Path = DB_PATH) -> tuple[bool, int | None]:@@ -451,3 +491,160 @@ def session_mail_private(session_id: str, db_path: Path = DB_PATH) -> bool:return Falseraisereturn bool(row is not None and row["mail_private"])+++def rewind_last_turn(+ session_id: str, last_message_id: int, db_path: Path = DB_PATH+) -> list[str] | None:+ """Remove the conversation's last turn: its last reply and the person's+ messages it answered (everything after the reply before it). Returns+ those messages' words, oldest first, for the turn that replaces it.++ ``last_message_id`` must be the id of the conversation's last row and that+ row a reply, so a stale page (another tab already moved the chat on)+ removes nothing. None when it isn't."""+ if not db_path.exists():+ return None+ with _get_conn(db_path) as conn:+ conn.execute("BEGIN IMMEDIATE")+ last = conn.execute(+ "SELECT id, role FROM chat_messages WHERE session_id = ? ORDER BY id DESC LIMIT 1",+ (session_id,),+ ).fetchone()+ if last is None or last["id"] != last_message_id or last["role"] != "assistant":+ return None+ before = conn.execute(+ "SELECT MAX(id) AS id FROM chat_messages "+ "WHERE session_id = ? AND role = 'assistant' AND id < ?",+ (session_id, last_message_id),+ ).fetchone()+ since = int(before["id"]) if before is not None and before["id"] is not None else 0+ asked = conn.execute(+ "SELECT content FROM chat_messages "+ "WHERE session_id = ? AND role = 'user' AND id > ? AND id < ? ORDER BY id",+ (session_id, since, last_message_id),+ ).fetchall()+ conn.execute(+ "DELETE FROM chat_messages WHERE session_id = ? AND id > ? AND id <= ?",+ (session_id, since, last_message_id),+ )+ return [str(row["content"]) for row in asked]+++# Sharing: a chat's owner lets named teammates read it. Read only: they can't+# write in it, and an Act as me conversation is never shared+# (``session_mail_private``; the routes refuse it).+++def shared_with(session_id: str, db_path: Path = DB_PATH) -> list[dict[str, Any]]:+ """Who ``session_id`` is shared with: ``person_id`` and ``shared_at``,+ oldest share first."""+ if not db_path.exists():+ return []+ with _get_conn(db_path) as conn:+ rows = conn.execute(+ "SELECT person_id, created_at FROM session_shares WHERE session_id = ? "+ "ORDER BY created_at, person_id",+ (session_id,),+ ).fetchall()+ return [{"person_id": int(r["person_id"]), "shared_at": r["created_at"]} for r in rows]+++def is_shared_with(session_id: str, person_id: int, db_path: Path = DB_PATH) -> bool:+ if not db_path.exists():+ return False+ with _get_conn(db_path) as conn:+ row = conn.execute(+ "SELECT 1 FROM session_shares WHERE session_id = ? AND person_id = ?",+ (session_id, person_id),+ ).fetchone()+ return row is not None+++def set_shares(+ session_id: str,+ person_ids: list[int],+ shared_by_person_id: int | None,+ db_path: Path = DB_PATH,+) -> tuple[list[int], list[int]]:+ """Share ``session_id`` with exactly ``person_ids``. Returns the ids added+ and the ids removed; someone already on the list keeps their share time."""+ now = datetime.now(UTC).isoformat()+ wanted = set(person_ids)+ with _get_conn(db_path) as conn:+ conn.execute("BEGIN IMMEDIATE")+ have = {+ int(r["person_id"])+ for r in conn.execute(+ "SELECT person_id FROM session_shares WHERE session_id = ?", (session_id,)+ )+ }+ added = sorted(wanted - have)+ removed = sorted(have - wanted)+ for pid in removed:+ conn.execute(+ "DELETE FROM session_shares WHERE session_id = ? AND person_id = ?",+ (session_id, pid),+ )+ for pid in added:+ conn.execute(+ "INSERT INTO session_shares (session_id, person_id, shared_by_person_id, created_at) "+ "VALUES (?, ?, ?, ?)",+ (session_id, pid, shared_by_person_id, now),+ )+ return added, removed+++def list_shared_with_person(person_id: int, db_path: Path = DB_PATH) -> list[dict[str, Any]]:+ """The chats shared with ``person_id``, newest activity first, each with+ its owner (``owner_person_id``) and when it was shared (``shared_at``).+ An Act as me conversation is left out even if it was shared before it+ read mail."""+ if not db_path.exists():+ return []+ with _get_conn(db_path) as conn:+ rows = conn.execute(+ """+ SELECT s.session_id, s.title, s.created_at, s.updated_at,+ s.caller_person_id AS owner_person_id, sh.created_at AS shared_at,+ (SELECT COUNT(*) FROM chat_messages m+ WHERE m.session_id = s.session_id) AS message_count+ FROM session_shares sh+ JOIN sessions s ON s.session_id = sh.session_id+ WHERE sh.person_id = ? AND s.mail_private = 0+ ORDER BY s.updated_at DESC+ """,+ (person_id,),+ ).fetchall()+ return [dict(r) for r in rows]+++def export_rows(session_id: str, db_path: Path = DB_PATH) -> list[dict[str, Any]]:+ """Every message of ``session_id`` with who wrote it, for an export:+ ``role``, ``content``, ``created_at``, ``sender_person_id``, ``stopped``+ and the reply's ``sources`` (decoded, or None)."""+ if not db_path.exists():+ return []+ with _get_conn(db_path) as conn:+ rows = conn.execute(+ "SELECT role, content, created_at, sender_person_id, stopped, sources "+ "FROM chat_messages WHERE session_id = ? ORDER BY id",+ (session_id,),+ ).fetchall()+ out: list[dict[str, Any]] = []+ for row in rows:+ sources = None+ if row["sources"]:+ try:+ sources = json.loads(row["sources"])+ except (ValueError, TypeError):+ sources = None+ out.append({+ "role": row["role"],+ "content": row["content"],+ "created_at": row["created_at"],+ "sender_person_id": row["sender_person_id"],+ "stopped": bool(row["stopped"]),+ "sources": sources if isinstance(sources, dict) else None,+ })+ return outdiff --git a/packages/core/tests/unit/test_session_controls.py b/packages/core/tests/unit/test_session_controls.pynew file mode 100644index 00000000..2b811bae--- /dev/null+++ b/packages/core/tests/unit/test_session_controls.py@@ -0,0 +1,277 @@+"""Pin, rename, share, export and take back the last turn of a chat+(api/routes/sessions.py, memory/session_store.py, memory/chat_export.py)."""+from __future__ import annotations++import json+from collections.abc import AsyncIterator+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 episodic, session_store+from openexecutive.memory.chat_export import file_name+from openexecutive.memory.company_profile import CompanyProfile+from openexecutive.people import store as people_store++ALEX = {"x-caller-email": "[email protected]"} # principal+SABIN = {"x-caller-email": "[email protected]"}+RIYA = {"x-caller-email": "[email protected]"}++[email protected](autouse=True)+def _reset_route_state(monkeypatch: pytest.MonkeyPatch) -> list[tuple[str, dict[str, Any]]]:+ chat_route._sessions.clear()+ chat_route._session_starters.clear()+ events: list[tuple[str, dict[str, Any]]] = []+ monkeypatch.setattr(+ "openexecutive.audit.log_event",+ lambda event_type, *_a, details=None, **_k: events.append((event_type, details or {})),+ )+ return events+++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]"),+ "riya": people_store.upsert_person(full_name="Riya", email="[email protected]"),+ "vendor": people_store.upsert_person(full_name="Vendor", email="[email protected]", kind="contact"),+ }+++def client(monkeypatch: pytest.MonkeyPatch) -> TestClient:+ monkeypatch.delenv("BACKEND_SHARED_SECRET", raising=False)+ monkeypatch.setenv("ANTHROPIC_API_KEY", "test-key")+ from openexecutive.knowledge import retriever+ from openexecutive.onboarding import profile_builder+ from openexecutive.orchestrator import executive as exec_mod+ from openexecutive.utils import session_title++ monkeypatch.setattr(profile_builder, "load_or_create_profile", lambda: CompanyProfile())+ monkeypatch.setattr(retriever, "retrieve", lambda *_a, **_k: "")++ async def _title(*_a: Any, **_k: Any) -> str:+ return "Generated title"++ monkeypatch.setattr(session_title, "generate_session_title", _title)++ class _StubExecutive:+ _THINKING = exec_mod.Executive._THINKING++ def __init__(self, **_kwargs: Any) -> None:+ pass++ async def stream_chat(self, **_kwargs: Any) -> AsyncIterator[str]:+ yield "ok"++ async def stream_chat_with_committee(self, **_kwargs: Any) -> AsyncIterator[str]:+ yield "ok"++ monkeypatch.setattr(exec_mod, "Executive", _StubExecutive)+ app = FastAPI()+ app.include_router(chat_route.router)+ app.include_router(sessions_route.router)+ return TestClient(app)+++def _chat_of(owner: int, sid: str = "web-1", turns: int = 2) -> str:+ session_store.create_session(sid, "Placeholder", "2026-10-01T09:00:00+00:00", caller_person_id=owner)+ for i in range(turns):+ session_store.save_message(sid, "user", f"question {i}", sender_person_id=owner)+ session_store.save_message(+ sid, "assistant", f"answer {i}",+ sources=json.dumps({"sources": [{"kind": "web", "title": "Q3 report", "url": "https://x.test/q3"}],+ "unavailable": []}),+ )+ return sid+++def _last_id(sid: str) -> int:+ return int(session_store.load_messages(sid)[-1]["id"])+++def test_pin_puts_a_chat_first_and_rename_sticks(client: TestClient, people: dict[str, int]) -> None:+ _chat_of(people["alex"], "old")+ _chat_of(people["alex"], "new")+ session_store.update_session_timestamp("new")+ assert [s["session_id"] for s in client.get("/sessions", headers=ALEX).json()] == ["new", "old"]++ resp = client.patch("/sessions/old", json={"pinned": True, "title": " Board prep "}, headers=ALEX)+ assert resp.status_code == 200 and resp.json()["title"] == "Board prep"+ listed = client.get("/sessions", headers=ALEX).json()+ assert [s["session_id"] for s in listed] == ["old", "new"]+ assert listed[0]["pinned_at"] and "pinned_at" not in listed[1]++ # The automatic title never replaces the owner's name.+ session_store.update_session_title("old", "Auto title")+ assert client.get("/sessions/old", headers=ALEX).json()["title"] == "Board prep"+ session_store.update_session_title("new", "Auto title")+ assert client.get("/sessions/new", headers=ALEX).json()["title"] == "Auto title"++ client.patch("/sessions/old", json={"pinned": False}, headers=ALEX)+ assert "pinned_at" not in client.get("/sessions/old", headers=ALEX).json()+ assert client.patch("/sessions/old", json={"title": " "}, headers=ALEX).status_code == 422+++def test_only_the_owner_pins_renames_or_shares(client: TestClient, people: dict[str, int]) -> None:+ _chat_of(people["sabin"], "slack:channel:C1") # a channel chat the principal may open+ assert client.get("/sessions/slack:channel:C1", headers=ALEX).status_code == 200+ assert client.patch("/sessions/slack:channel:C1", json={"pinned": True}, headers=ALEX).status_code == 404+ assert client.put("/sessions/slack:channel:C1/shares", json={"person_ids": []}, headers=ALEX).status_code == 404+ assert client.patch("/sessions/slack:channel:C1", json={"pinned": True}, headers=RIYA).status_code == 404+++def test_a_shared_chat_is_read_only_for_who_it_is_shared_with(+ client: TestClient, people: dict[str, int], _reset_route_state: list[tuple[str, dict[str, Any]]]+) -> None:+ sid = _chat_of(people["sabin"])+ # A teammate's own chat is theirs alone until they share it.+ assert client.get(f"/sessions/{sid}/messages", headers=ALEX).status_code == 404++ resp = client.put(f"/sessions/{sid}/shares", json={"person_ids": [people["alex"]]}, headers=SABIN)+ assert resp.status_code == 200+ assert [s["full_name"] for s in resp.json()] == ["Alex"]+ assert _reset_route_state[-1][0] == "session_shared"+ assert _reset_route_state[-1][1]["added"] == [people["alex"]]++ shared = client.get("/sessions/shared-with-me", headers=ALEX).json()+ assert [(s["session_id"], s["shared_by"], s["read_only"]) for s in shared] == [(sid, "Sabin", True)]+ assert client.get("/sessions/shared-with-me", headers=RIYA).json() == []+ # It is not in Alex's own list.+ assert sid not in [s["session_id"] for s in client.get("/sessions", headers=ALEX).json()]++ meta = client.get(f"/sessions/{sid}", headers=ALEX).json()+ assert meta["read_only"] is True and meta["shared_by"] == "Sabin"+ assert len(client.get(f"/sessions/{sid}/messages", headers=ALEX).json()) == 4+ assert client.get(f"/sessions/{sid}/export", headers=ALEX).status_code == 200++ # Reading is all: no deleting, rating, renaming, redoing or writing in it.+ assert client.delete(f"/sessions/{sid}", headers=ALEX).status_code == 404+ assert client.patch(f"/sessions/{sid}", json={"title": "Mine"}, headers=ALEX).status_code == 404+ assert client.post(+ f"/sessions/{sid}/rewind", json={"last_message_id": _last_id(sid)}, headers=ALEX+ ).status_code == 404+ client.post("/chat", json={"message": "hi", "session_id": sid}, headers=ALEX).read()+ assert len(session_store.load_messages(sid)) == 4++ # Unsharing takes it away.+ client.put(f"/sessions/{sid}/shares", json={"person_ids": []}, headers=SABIN)+ assert client.get(f"/sessions/{sid}/messages", headers=ALEX).status_code == 404+ assert client.get("/sessions/shared-with-me", headers=ALEX).json() == []+++def test_sharing_refuses_contacts_the_owner_and_a_chat_that_read_mail(+ client: TestClient, people: dict[str, int]+) -> None:+ sid = _chat_of(people["sabin"])+ for pid in (people["vendor"], people["sabin"], 9999):+ assert client.put(f"/sessions/{sid}/shares", json={"person_ids": [pid]}, headers=SABIN).status_code == 422+ client.put(f"/sessions/{sid}/shares", json={"person_ids": [people["riya"]]}, headers=SABIN)++ session_store.mark_mail_private(sid, people["sabin"])+ assert client.put(+ f"/sessions/{sid}/shares", json={"person_ids": [people["riya"]]}, headers=SABIN+ ).status_code == 409+ # Shared before it read mail: no longer readable or listed.+ assert client.get(f"/sessions/{sid}/messages", headers=RIYA).status_code == 404+ assert client.get("/sessions/shared-with-me", headers=RIYA).json() == []+++def test_deleting_a_chat_drops_its_shares(client: TestClient, people: dict[str, int]) -> None:+ sid = _chat_of(people["alex"])+ client.put(f"/sessions/{sid}/shares", json={"person_ids": [people["riya"]]}, headers=ALEX)+ assert client.delete(f"/sessions/{sid}", headers=ALEX).status_code == 204+ assert session_store.shared_with(sid) == []+++def test_export_is_markdown_with_names_and_sources(client: TestClient, people: dict[str, int]) -> None:+ sid = _chat_of(people["alex"], turns=1)+ client.patch(f"/sessions/{sid}", json={"title": "Q3 / numbers?"}, headers=ALEX)+ resp = client.get(f"/sessions/{sid}/export", headers=ALEX)+ assert resp.status_code == 200+ assert resp.headers["content-type"].startswith("text/markdown")+ assert 'filename="q3-numbers.md"' in resp.headers["content-disposition"]+ text = resp.text+ assert text.startswith("# Q3 / numbers?\n\nStarted 1 October 2026\n")+ assert "## Alex\n\nquestion 0" in text+ assert "## Executive\n\nanswer 0\n\nSources:\n- [Q3 report](https://x.test/q3)" in text+ assert file_name("!!!") == "chat.md"+++def test_rewind_takes_back_the_last_turn_and_the_next_turn_replaces_it(+ client: TestClient, people: dict[str, int]+) -> None:+ sid = _chat_of(people["alex"])+ session_store.save_message(sid, "user", "question 2", sender_person_id=people["alex"])+ session_store.save_message(sid, "user", "and one more thing", sender_person_id=people["alex"])+ session_store.save_message(sid, "assistant", "answer 2")+ last = _last_id(sid)++ # A stale page (it names an earlier reply) takes nothing back.+ first_reply = int(session_store.load_messages(sid)[1]["id"])+ assert client.post(+ f"/sessions/{sid}/rewind", json={"last_message_id": first_reply}, headers=ALEX+ ).status_code == 409++ resp = client.post(f"/sessions/{sid}/rewind", json={"last_message_id": last}, headers=ALEX)+ assert resp.status_code == 200+ assert resp.json() == {"message": "question 2\n\nand one more thing"}+ assert [m["content"] for m in session_store.load_messages(sid)] == [+ "question 0", "answer 0", "question 1", "answer 1",+ ]++ client.post("/chat", json={"message": "question 2, edited", "session_id": sid}, headers=ALEX).read()+ assert [m["content"] for m in session_store.load_messages(sid)][-2:] == ["question 2, edited", "ok"]+++def test_rewind_is_for_web_chats_only(client: TestClient, people: dict[str, int]) -> None:+ sid = _chat_of(people["alex"], "telegram:42")+ assert client.post(+ f"/sessions/{sid}/rewind", json={"last_message_id": _last_id(sid)}, headers=ALEX+ ).status_code == 409+ assert len(session_store.load_messages(sid)) == 4+++def test_a_teammates_share_and_rewind_rows_are_private_to_them(+ client: TestClient, people: dict[str, int], monkeypatch: pytest.MonkeyPatch+) -> None:+ from openexecutive.audit.context import rows_owner++ owners: list[Any] = []+ monkeypatch.setattr(+ "openexecutive.audit.log_event", lambda *_a, **_k: owners.append(rows_owner())+ )+ sid = _chat_of(people["sabin"])+ client.put(f"/sessions/{sid}/shares", json={"person_ids": [people["riya"]]}, headers=SABIN)+ client.post(f"/sessions/{sid}/rewind", json={"last_message_id": _last_id(sid)}, headers=SABIN)+ assert owners == [people["sabin"], people["sabin"]]+++def test_the_principal_cant_take_over_an_ownerless_chat_someone_is_in(+ client: TestClient, people: dict[str, int]+) -> None:+ sid = _chat_of(people["alex"], "legacy")+ with session_store._get_conn(session_store.DB_PATH) as conn:+ conn.execute("UPDATE sessions SET caller_person_id = NULL WHERE session_id = 'legacy'")+ assert client.patch("/sessions/legacy", json={"pinned": True}, headers=ALEX).status_code == 200+ chat_route._session_starters[sid] = frozenset({"email:[email protected]"})+ assert client.patch("/sessions/legacy", json={"pinned": True}, headers=ALEX).status_code == 404diff --git a/packages/ui/scripts/chatTurns.test.mjs b/packages/ui/scripts/chatTurns.test.mjsnew file mode 100644index 00000000..a8ac8cee--- /dev/null+++ b/packages/ui/scripts/chatTurns.test.mjs@@ -0,0 +1,65 @@+import assert from "node:assert/strict";+import test from "node:test";+import { confirmRedoText, dropLastTurn, lastTurn } from "../src/lib/chatTurns.ts";++const user = (content) => ({ role: "user", content });+const reply = (content, id, actions) => ({ role: "assistant", content, id, ...(actions ? { actions } : {}) });+const WEB = "3f2c9a1e-7d1b-4b8e-9a0c-1f2e3d4c5b6a";++test("a saved last reply can be redone in a web chat", () => {+ const msgs = [user("hi"), reply("hello", 1), user("plan my week"), reply("here", 2)];+ assert.deepEqual(lastTurn(msgs, WEB), {+ replyIndex: 3,+ userIndex: 2,+ replyId: 2,+ canRedo: true,+ didSomething: false,+ });+});++test("the last user message is found past several queued ones", () => {+ const msgs = [user("a"), user("b"), reply("ok", 7)];+ const t = lastTurn(msgs, WEB);+ assert.equal(t.userIndex, 1);+ assert.equal(t.canRedo, true);+});++test("no redo without a session, in a channel chat, or before the reply is saved", () => {+ const msgs = [user("hi"), reply("hello", 1)];+ assert.equal(lastTurn(msgs, null).canRedo, false);+ assert.equal(lastTurn(msgs, "slack:dm:U123").canRedo, false);+ assert.equal(lastTurn(msgs, "telegram:42").canRedo, false);+ const unsaved = lastTurn([user("hi"), { role: "assistant", content: "..." }], WEB);+ assert.equal(unsaved.replyIndex, null);+ assert.equal(unsaved.replyId, null);+ assert.equal(unsaved.canRedo, false);+});++test("a chat ending on the user's message has no reply to redo", () => {+ const t = lastTurn([reply("hello", 1), user("still there?")], WEB);+ assert.equal(t.replyIndex, null);+ assert.equal(t.userIndex, null);+ assert.equal(t.canRedo, false);+ assert.equal(lastTurn([], WEB).canRedo, false);+});++test("a reply with actions did something", () => {+ const msgs = [user("email Sam"), reply("done", 4, [{ tool: "send_email", summary: "Sent an email to Sam" }])];+ assert.equal(lastTurn(msgs, WEB).didSomething, true);+ assert.equal(lastTurn([user("x"), reply("y", 5, [])], WEB).didSomething, false);+});++test("dropLastTurn removes the last reply and the messages it answered", () => {+ const msgs = [user("hi"), reply("hello", 1), user("a"), user("b"), reply("ok", 2)];+ assert.deepEqual(dropLastTurn(msgs), msgs.slice(0, 2));+ assert.deepEqual(dropLastTurn([user("only"), reply("one", 1)]), []);+ assert.deepEqual(dropLastTurn([]), []);+});++test("confirmRedoText names the first action, or says what kind", () => {+ assert.equal(+ confirmRedoText([{ summary: "Sent an email to Sam" }]),+ 'That answer already did something ("Sent an email to Sam"). Doing it again could repeat it. Go ahead?',+ );+ assert.match(confirmRedoText([]), /sent a message, booked a meeting or filed a card/);+});diff --git a/packages/ui/scripts/sessionGroups.test.mjs b/packages/ui/scripts/sessionGroups.test.mjsindex 1ac41fac..6a206664 100644--- a/packages/ui/scripts/sessionGroups.test.mjs+++ b/packages/ui/scripts/sessionGroups.test.mjs@@ -52,3 +52,18 @@ test("an unparseable timestamp falls into Older instead of throwing", () => {const groups = groupSessionsByDate([at("bad", "not-a-date")], NOW);assert.deepEqual(groups.map((g) => g.key), ["older"]);});++test("pinned chats come first in Pinned, whatever their date", () => {+ const pinned = (id, updated) => ({ ...at(id, updated), pinned_at: daysAgo(0) });+ const groups = groupSessionsByDate(+ [at("today", daysAgo(0)), pinned("old-pin", daysAgo(90)), pinned("new-pin", daysAgo(0))],+ NOW,+ );+ assert.deepEqual(+ groups.map((g) => [g.key, g.label, g.items.map((i) => i.session_id)]),+ [+ ["pinned", "Pinned", ["old-pin", "new-pin"]],+ ["today", "Today", ["today"]],+ ],+ );+});diff --git a/packages/ui/src/app/chats/page.tsx b/packages/ui/src/app/chats/page.tsxindex 65e9efd1..02f33271 100644--- a/packages/ui/src/app/chats/page.tsx+++ b/packages/ui/src/app/chats/page.tsx@@ -5,9 +5,9 @@ import { useRouter } from "next/navigation";import Link from "next/link";import Icon from "@/components/Icon";import { buttonClass } from "@/components/ui/Button";-import ChatHistory from "@/components/sessions/ChatHistory";+import ChatHistory, { ChatRow } from "@/components/sessions/ChatHistory";import { useSessions } from "@/components/sessions/SessionsContext";-import { searchSessions, type SessionSummary } from "@/lib/api";+import { listSharedSessions, searchSessions, type SessionSummary } from "@/lib/api";import {CHANNEL_LABELS,CHANNEL_ORDER,@@ -20,7 +20,8 @@ type ChannelFilter = SessionChannel | "all";// 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.+// Delete is in the row's ⋯ menu and asks first. Chats others shared with+// the viewer list apart, under "Shared with you", and open to read.export default function ChatsPage() {const router = useRouter();const { sessions, loaded, error, refresh, remove } = useSessions();@@ -34,6 +35,21 @@ export default function ChatsPage() {refresh();}, [refresh]);+ // Chats teammates shared, to read. Kept out of the channel tabs and counts.+ // A failure just leaves the section hidden.+ const [shared, setShared] = useState<SessionSummary[]>([]);+ useEffect(() => {+ let live = true;+ listSharedSessions()+ .then((list) => {+ if (live) setShared(list);+ })+ .catch(() => {});+ return () => {+ live = false;+ };+ }, []);+const trimmed = query.trim();useEffect(() => {if (!trimmed) return;@@ -84,6 +100,25 @@ export default function ChatsPage() {const searching = trimmed.length > 0;const shownCounts = useMemo(() => (shown ? countByChannel(shown) : counts), [shown, counts]);+ // Hidden while searching: the search covers the viewer's own chats.+ const sharedSection =+ shared.length > 0 && !searching ? (+ <section aria-labelledby="shared-with-you" className="mt-8 first:mt-0">+ <h2 id="shared-with-you" className="px-1 mb-2 text-sm font-semibold text-fg-muted">+ Shared with you <span className="font-normal text-fg-subtle">{shared.length}</span>+ </h2>+ <div className="space-y-2">+ {shared.map((s) => (+ <ChatRow+ key={s.session_id}+ session={s}+ onSelect={(id) => router.push(`/chats/shared/${encodeURIComponent(id)}`)}+ />+ ))}+ </div>+ </section>+ ) : null;+return (<div className="flex flex-col h-full bg-surface text-fg"><main className="flex-1 overflow-y-auto px-4 sm:px-6 py-8">@@ -161,10 +196,14 @@ export default function ChatsPage() {</button></p>) : sessions.length === 0 ? (- <p className="px-1 py-6 text-[15px] text-fg-muted">- No conversations yet. Start one with New chat.- </p>+ <>+ {sharedSection}+ <p className="px-1 py-6 text-[15px] text-fg-muted">+ No conversations yet. Start one with New chat.+ </p>+ </>) : (+ <><ChatHistorysessions={visible}searching={searching}@@ -176,7 +215,10 @@ export default function ChatsPage() {router.push(`/?session=${encodeURIComponent(id)}${find}`);}}onDelete={remove}+ onChanged={refresh}/>+ {sharedSection}+ </>)}</div></main>diff --git a/packages/ui/src/app/chats/shared/[id]/page.tsx b/packages/ui/src/app/chats/shared/[id]/page.tsxnew file mode 100644index 00000000..9900107c--- /dev/null+++ b/packages/ui/src/app/chats/shared/[id]/page.tsx@@ -0,0 +1,84 @@+"use client";++import { useEffect, useState } from "react";+import { useParams } from "next/navigation";+import Link from "next/link";+import Chat from "@/components/Chat";+import { getSession, getSessionMessages, type ChatMessage, type SessionSummary } from "@/lib/api";+import { sessionTitle } from "@/lib/sessionChannel";++type Loaded =+ | { id: string; state: "ok"; session: SessionSummary; messages: ChatMessage[] }+ | { id: string; state: "gone" | "error" };++// A chat a teammate shared with the viewer, to read: the conversation with+// no composer, and a Download button. Opened from "Shared with you" on /chats.+export default function SharedChatPage() {+ const params = useParams();+ const id = typeof params.id === "string" ? decodeURIComponent(params.id) : "";+ // Keyed by the chat it is for, so a different id shows "Loading" until its+ // own answer arrives (no state set synchronously in the effect).+ const [loaded, setLoaded] = useState<Loaded | null>(null);++ useEffect(() => {+ if (!id) return;+ let live = true;+ Promise.all([getSession(id), getSessionMessages(id)])+ .then(([session, messages]) => {+ if (live) setLoaded({ id, state: "ok", session, messages });+ })+ .catch((err: unknown) => {+ if (!live) return;+ const gone = err instanceof Error && err.message === "not_found";+ setLoaded({ id, state: gone ? "gone" : "error" });+ });+ return () => {+ live = false;+ };+ }, [id]);++ const current = loaded && loaded.id === id ? loaded : null;+ const chat = current?.state === "ok" ? current : null;++ return (+ <div className="flex flex-col h-full bg-surface text-fg">+ <div className="border-b border-line px-4 sm:px-6 py-3 flex-shrink-0">+ <div className="max-w-3xl mx-auto min-w-0">+ <Link href="/chats" className="text-sm text-fg-muted hover:text-fg">+ ← Chats+ </Link>+ {current?.state === "ok" && (+ <h1 className="mt-1 text-lg font-semibold text-fg truncate">{sessionTitle(current.session)}</h1>+ )}+ </div>+ </div>+ {!current ? (+ <p className="max-w-3xl mx-auto w-full px-4 sm:px-6 py-8 text-[15px] text-fg-muted">Loading chat…</p>+ ) : current.state === "gone" ? (+ <p className="max-w-3xl mx-auto w-full px-4 sm:px-6 py-8 text-[15px] text-fg-muted">+ This chat isn't shared with you any more.+ </p>+ ) : !chat ? (+ <p className="max-w-3xl mx-auto w-full px-4 sm:px-6 py-8 text-[15px] text-fg-muted">+ Couldn't load this chat. Try again in a moment.+ </p>+ ) : chat.session.read_only ? (+ <div className="flex-1 min-h-0">+ <Chat+ initialMessages={chat.messages}+ initialSessionId={id}+ readOnly={{ sharedBy: chat.session.shared_by ?? "someone on your team" }}+ />+ </div>+ ) : (+ // The viewer's own chat: it opens where they can write in it.+ <p className="max-w-3xl mx-auto w-full px-4 sm:px-6 py-8 text-[15px] text-fg-muted">+ This is your own chat.{" "}+ <Link href={`/?session=${encodeURIComponent(id)}`} className="font-medium text-accent hover:underline">+ Open it+ </Link>+ </p>+ )}+ </div>+ );+}diff --git a/packages/ui/src/app/page.tsx b/packages/ui/src/app/page.tsxindex d14caa5d..9f486497 100644--- a/packages/ui/src/app/page.tsx+++ b/packages/ui/src/app/page.tsx@@ -18,7 +18,9 @@ import { GettingStartedCard, useGettingStarted } from "@/components/onboard/Gettimport { useFirstRunRedirect } from "@/components/onboard/useFirstRunRedirect";import PausedBanner from "@/components/executive/PausedBanner";import OverflowMenu from "@/components/ui/OverflowMenu";-import { ChatMessage, DebugEvent, getSessionMessages } from "@/lib/api";+import { ChatMessage, DebugEvent, getSessionMessages, updateSession } from "@/lib/api";+import { downloadChat } from "@/lib/downloadChat";+import { sessionTitle } from "@/lib/sessionChannel";import Link from "next/link";import { useRouter } from "next/navigation";@@ -247,6 +249,41 @@ export default function HomePage() {<BriefDeliveryNotice notice={deliveryNotice} />) : undefined;+ // The open chat, when it is one of the caller's own saved chats: its+ // Pin, Rename and Download sit in the header's ⋯ menu.+ const openChat =+ mode === "chat" && activeSessionId+ ? sessions.find((s) => s.session_id === activeSessionId)+ : undefined;+ const chatItems = openChat+ ? [+ {+ label: openChat.pinned_at ? "Unpin" : "Pin",+ onSelect: () => {+ updateSession(openChat.session_id, { pinned: !openChat.pinned_at })+ .then(refreshSessions)+ .catch(() => window.alert("Couldn't pin this chat."));+ },+ },+ {+ label: "Rename",+ onSelect: () => {+ const title = window.prompt("Name this chat", sessionTitle(openChat))?.trim();+ if (!title) return;+ updateSession(openChat.session_id, { title: title.slice(0, 120) })+ .then(refreshSessions)+ .catch(() => window.alert("Couldn't rename this chat."));+ },+ },+ {+ label: "Download",+ onSelect: () => {+ downloadChat(openChat.session_id).catch(() => window.alert("Couldn't download this chat."));+ },+ },+ ]+ : [];+// Hold the page while the browser moves to setup.if (redirecting) return <div className="h-full bg-surface" />;@@ -303,6 +340,7 @@ export default function HomePage() {<OverflowMenulabel="Home options"items={[+ ...chatItems,{label: debugOpen ? "Hide agent activity" : "Show agent activity",onSelect: () => setDebugOpen((o) => !o),diff --git a/packages/ui/src/components/Chat.tsx b/packages/ui/src/components/Chat.tsxindex 20b45b35..d1286f8f 100644--- a/packages/ui/src/components/Chat.tsx+++ b/packages/ui/src/components/Chat.tsx@@ -21,9 +21,12 @@ import {FALLBACK_ACTIVITY_LABEL,getFollowupSuggestion,getSuggestedPrompts,+ rewindSession,setMessageFeedback,streamChat,} from "@/lib/api";+import { confirmRedoText, dropLastTurn, lastTurn } from "@/lib/chatTurns";+import { downloadChat } from "@/lib/downloadChat";import { answerSourcesFrom, type AnswerSources } from "@/lib/answerSources";import { matchingMessages } from "@/lib/chatSearch";import { isAbortError, useStoppableTurn } from "@/lib/use-stoppable-turn";@@ -62,6 +65,9 @@ interface ChatProps {// Chats page): the chat starts at the newest message containing them and// steps through the others.initialFind?: string;+ // A chat someone else shared with the viewer: shown to read, with no+ // composer and no rating, Try again or Edit.+ readOnly?: { sharedBy: string };}// The browser's own highlight for found words, where it has one@@ -91,7 +97,7 @@ function endsOnReply(messages: ChatMessage[] | undefined): boolean {const FALLBACK_SUBTITLE ="Pick up where we left off — decisions to revisit, drafts to push forward, people to pull in.";-export default function Chat({ onDebugEvent, initialMessages, initialSessionId, initialInput, autoSubmitInitialInput, initialMemoryText, onTurnComplete, onTurnStart, initialFind }: ChatProps) {+export default function Chat({ onDebugEvent, initialMessages, initialSessionId, initialInput, autoSubmitInitialInput, initialMemoryText, onTurnComplete, onTurnStart, initialFind, readOnly }: ChatProps) {const { data: session } = useSession();const firstName = session?.user?.name?.trim().split(/\s+/)[0];@@ -145,8 +151,16 @@ export default function Chat({ onDebugEvent, initialMessages, initialSessionId,setFind(null);setFindPos(null);};+ // Try again / Edit on the last turn. `editingReplyId` is the reply the+ // edit replaces: once the chat's last reply changes, the edit is over.+ const [editingReplyId, setEditingReplyId] = useState<number | null>(null);+ const [redoing, setRedoing] = useState(false);+ const [redoError, setRedoError] = useState<string | null>(null);+ const [downloadError, setDownloadError] = useState(false);useEffect(() => {+ // A shared chat is only read: nothing to suggest.+ if (readOnly) return;const ctrl = new AbortController();getSuggestedPrompts(ctrl.signal).then((r) => {@@ -163,6 +177,7 @@ export default function Chat({ onDebugEvent, initialMessages, initialSessionId,setIsLoadingPrompts(false);});return () => ctrl.abort();+ // eslint-disable-next-line react-hooks/exhaustive-deps}, []);function clearFollowup() {@@ -187,7 +202,7 @@ export default function Chat({ onDebugEvent, initialMessages, initialSessionId,// Opening an existing session suggests a follow-up to its last reply.// Later session switches are handled in the sync effect below.useEffect(() => {- if (initialSessionId && endsOnReply(initialMessages)) loadFollowup(initialSessionId);+ if (!readOnly && initialSessionId && endsOnReply(initialMessages)) loadFollowup(initialSessionId);return () => followupCtrlRef.current?.abort();// eslint-disable-next-line react-hooks/exhaustive-deps}, []);@@ -318,6 +333,7 @@ export default function Chat({ onDebugEvent, initialMessages, initialSessionId,}const message = (text ?? input).trim();if ((!message && pendingFiles.length === 0) || isLoading) return;+ setRedoError(null);const restored = restoredHandoffRef.current;restoredHandoffRef.current = undefined;const turnMemoryText =@@ -552,6 +568,103 @@ export default function Chat({ onDebugEvent, initialMessages, initialSessionId,setMessageFeedback(sessionId, target.id, value).catch(() => apply(previous));}+ // What the last turn allows. Not while anything is in flight, and never+ // on a chat shared to read.+ const turn = lastTurn(messages, sessionId);+ const canRedo =+ !readOnly && turn.canRedo && !isLoading && !redoing && !streamingContent && queued.length === 0;+ // Not tied to canRedo: the edit stays on while its rewind is in flight.+ const editing = !readOnly && editingReplyId !== null && editingReplyId === turn.replyId;++ // Takes the last turn back on the server, then here. Returns the words it+ // answered, or null when the server refused (the reason shows above the+ // composer and nothing else changes).+ async function takeBackLastTurn(): Promise<string | null> {+ if (!sessionId || turn.replyId === null) return null;+ if (turn.didSomething) {+ const reply = turn.replyIndex !== null ? messages[turn.replyIndex] : undefined;+ if (!window.confirm(confirmRedoText(reply?.actions))) return null;+ }+ setRedoError(null);+ setRedoing(true);+ try {+ const asked = await rewindSession(sessionId, turn.replyId);+ clearFollowup();+ setMessages((prev) => dropLastTurn(prev));+ return asked;+ } catch (err) {+ setRedoError(err instanceof Error ? err.message : "Couldn't redo that answer.");+ return null;+ } finally {+ setRedoing(false);+ }+ }++ // Try again: the same words as a new turn. Sent like a queued follow-up so+ // whatever is in the composer (text, files) stays there.+ async function handleRetry() {+ const asked = await takeBackLastTurn();+ if (asked !== null) void handleSend(asked, undefined, true);+ }++ // Edit: the last message goes back in the composer; sending replaces it+ // and its answer.+ function startEdit() {+ if (turn.replyIndex === null || turn.userIndex === null) return;+ const words = dropLastTurn(messages).length;+ const text = messages+ .slice(words, turn.replyIndex)+ .filter((m) => m.role === "user")+ .map((m) => m.content)+ .join("\n\n");+ setRedoError(null);+ setEditingReplyId(turn.replyId);+ setInput(text);+ requestAnimationFrame(() => {+ const el = textareaRef.current;+ if (!el) return;+ el.focus();+ el.setSelectionRange(text.length, text.length);+ el.style.height = "auto";+ el.style.height = Math.min(el.scrollHeight, 160) + "px";+ });+ }++ function cancelEdit() {+ setEditingReplyId(null);+ setInput("");+ if (textareaRef.current) textareaRef.current.style.height = "auto";+ }++ async function sendEdit() {+ const text = input.trim();+ if (!text) return;+ const asked = await takeBackLastTurn();+ if (asked === null) return;+ setEditingReplyId(null);+ setInput("");+ if (textareaRef.current) textareaRef.current.style.height = "auto";+ // Files picked before the edit stay for the next message.+ void handleSend(text, undefined, true);+ }++ // Enter and the Send button: an edit replaces the last turn.+ function submit() {+ if (redoing) return;+ if (editing) void sendEdit();+ else void handleSend();+ }++ async function handleDownload() {+ if (!sessionId) return;+ setDownloadError(false);+ try {+ await downloadChat(sessionId);+ } catch {+ setDownloadError(true);+ }+ }+// The "still working" line: before the reply starts, and again under the// partial reply whenever the Executive goes quiet to run a tool.const status = turnStatus({@@ -595,7 +708,11 @@ export default function Chat({ onDebugEvent, initialMessages, initialSessionId,}if (e.key === "Enter" && !e.shiftKey) {e.preventDefault();- handleSend();+ submit();+ }+ if (e.key === "Escape" && editing) {+ e.preventDefault();+ cancelEdit();}}@@ -678,7 +795,9 @@ export default function Chat({ onDebugEvent, initialMessages, initialSessionId,</div>)}<div ref={messagesRef} className="max-w-3xl mx-auto px-4 sm:px-6 py-6 sm:py-8">- {isEmpty ? (+ {isEmpty && readOnly ? (+ <p className="py-10 text-center text-[15px] text-fg-muted">This chat is empty.</p>+ ) : isEmpty ? (/* Empty state */<div className="flex flex-col items-center justify-center min-h-[60vh] text-center"><div className="mb-6">@@ -738,10 +857,12 @@ export default function Chat({ onDebugEvent, initialMessages, initialSessionId,sources={msg.role === "assistant" ? msg.sources : undefined}feedback={msg.role === "assistant" ? msg.feedback : undefined}onFeedback={- msg.role === "assistant" && msg.id && sessionId+ !readOnly && msg.role === "assistant" && msg.id && sessionId? (v) => handleFeedback(i, v): undefined}+ onRetry={canRedo && i === turn.replyIndex ? () => void handleRetry() : undefined}+ onEdit={canRedo && !editing && i === turn.userIndex ? startEdit : undefined}/></div>))}@@ -788,9 +909,56 @@ export default function Chat({ onDebugEvent, initialMessages, initialSessionId,</div></div>- {/* Input */}+ {readOnly ? (+ <div className="border-t border-line bg-surface px-4 sm:px-6 py-3 sm:py-4">+ <div className="max-w-3xl mx-auto flex flex-wrap items-center gap-3">+ <p className="mr-auto text-sm text-fg-muted">+ Shared with you by {readOnly.sharedBy}. You can read it but not write in it.+ </p>+ {downloadError && (+ <p role="alert" className="text-sm text-red-400">+ Couldn't download this chat.+ </p>+ )}+ <button+ type="button"+ onClick={() => void handleDownload()}+ disabled={!sessionId}+ className="min-h-[2.5rem] px-3 rounded-lg border border-line text-sm font-medium text-fg hover:bg-surface-overlay disabled:opacity-50 cursor-pointer"+ >+ Download+ </button>+ </div>+ </div>+ ) : (+ /* Input */<div className="border-t border-line bg-surface px-4 sm:px-6 py-3 sm:py-4"><div className="max-w-3xl mx-auto">+ {redoError && (+ <div role="alert" className="mb-2 flex items-start gap-2 rounded-lg border border-line bg-surface-elevated px-3 py-2 text-sm text-fg">+ <span className="mr-auto">{redoError}</span>+ <button+ type="button"+ onClick={() => setRedoError(null)}+ aria-label="Dismiss"+ className="-my-1 inline-flex h-8 w-8 items-center justify-center rounded-md text-fg-muted hover:text-fg hover:bg-surface-overlay cursor-pointer"+ >+ <Icon name="close" size="w-3.5 h-3.5" />+ </button>+ </div>+ )}+ {editing && (+ <div className="mb-2 flex items-center gap-2 rounded-lg border border-accent/40 bg-accent/10 px-3 py-1.5 text-sm text-fg">+ <span className="mr-auto">Editing your last message. Sending replaces it and its answer.</span>+ <button+ type="button"+ onClick={cancelEdit}+ className="min-h-[2rem] px-2 rounded-md font-medium text-fg-muted hover:text-fg hover:bg-surface-overlay cursor-pointer"+ >+ Cancel+ </button>+ </div>+ )}{/* Committee review is switched in the + menu; while it is on, thischip says so and turns it off. */}{committeeEnabled && (@@ -859,7 +1027,8 @@ export default function Chat({ onDebugEvent, initialMessages, initialSessionId,? `Attach files (limit ${MAX_FILES_PER_TURN} per message)`: "Attach files or photos",onSelect: () => fileInputRef.current?.click(),- disabled: isLoading || pendingFiles.length >= MAX_FILES_PER_TURN,+ // An edit replaces the words only.+ disabled: isLoading || editing || pendingFiles.length >= MAX_FILES_PER_TURN,},{label: committeeEnabled ? "Turn off committee review" : "Committee review (slower, reviewed)",@@ -913,9 +1082,9 @@ export default function Chat({ onDebugEvent, initialMessages, initialSessionId,{(!isLoading || input.trim()) && (<buttontype="button"- onClick={() => handleSend()}- disabled={!input.trim() && pendingFiles.length === 0}- aria-label={isLoading ? "Add to what it's working on" : "Send message"}+ onClick={submit}+ disabled={editing ? !input.trim() || redoing : !input.trim() && pendingFiles.length === 0}+ aria-label={isLoading ? "Add to what it's working on" : editing ? "Send edited message" : "Send message"}className="flex-shrink-0 w-11 h-11 rounded-xl bg-accent-strong hover:bg-accent-strong/90 disabled:opacity-30 disabled:cursor-not-allowed transition-all duration-150 flex items-center justify-center cursor-pointer"><Icon name="arrow-send" size="w-4 h-4" className="text-white" />@@ -946,6 +1115,7 @@ export default function Chat({ onDebugEvent, initialMessages, initialSessionId,</p></div></div>+ )}</div>);}diff --git a/packages/ui/src/components/Message.tsx b/packages/ui/src/components/Message.tsxindex c3366ce3..c89e2897 100644--- a/packages/ui/src/components/Message.tsx+++ b/packages/ui/src/components/Message.tsx@@ -38,6 +38,34 @@ interface MessageProps {// Shown under the text while the reply streams, e.g. the "still working"// line when the Executive goes quiet mid-reply to run a tool.status?: ReactNode;+ // The chat's last reply only: take the turn back and ask again.+ onRetry?: () => void;+ // The user's last message only: put it back in the composer to change.+ onEdit?: () => void;+}++// The small text buttons under a message (Copy, Try again, Edit).+const TOOL_BUTTON =+ "min-h-[2rem] px-2 rounded-md text-xs font-medium text-fg-muted hover:text-fg hover:bg-surface-overlay transition-colors";++function CopyButton({ text }: { text: string }) {+ const [copied, setCopied] = useState(false);+ const copy = () => {+ navigator.clipboard+ .writeText(text)+ .then(() => {+ setCopied(true);+ setTimeout(() => setCopied(false), 1500);+ })+ .catch(() => {+ // No clipboard (an insecure page, or permission refused): nothing to show.+ });+ };+ return (+ <button type="button" onClick={copy} className={TOOL_BUTTON}>+ <span role="status">{copied ? "Copied" : "Copy"}</span>+ </button>+ );}function FeedbackButtons({@@ -70,7 +98,7 @@ function FeedbackButtons({);};return (- <div className="mt-2 flex items-center gap-1" aria-label="Rate this reply">+ <div className="flex items-center gap-1" aria-label="Rate this reply">{button("up", "👍", "Helpful")}{button("down", "👎", "Not helpful")}{value && (@@ -234,6 +262,8 @@ export default function Message({feedback,onFeedback,status,+ onRetry,+ onEdit,}: MessageProps) {// Approval cards this reply left, shown under it (ActionCards).const cardIds = useMemo(@@ -245,10 +275,15 @@ export default function Message({);if (role === "user") {return (- <div className="flex justify-end mb-6">+ <div className="flex flex-col items-end mb-6"><div className="max-w-xl px-4 py-3 rounded-2xl rounded-tr-sm bg-surface-overlay text-fg text-sm leading-relaxed"><p className="whitespace-pre-wrap">{content}</p></div>+ {onEdit && (+ <button type="button" onClick={onEdit} className={`${TOOL_BUTTON} mt-1`}>+ Edit+ </button>+ )}</div>);}@@ -308,8 +343,16 @@ export default function Message({<p className="mt-2 text-xs text-fg-muted">Stopped by you</p>)}- {onFeedback && !isStreaming && (- <FeedbackButtons value={feedback} onChange={onFeedback} />+ {!isStreaming && (content.trim() || onRetry || onFeedback) && (+ <div className="mt-2 flex flex-wrap items-center gap-1">+ {content.trim() && <CopyButton text={content} />}+ {onRetry && (+ <button type="button" onClick={onRetry} className={TOOL_BUTTON}>+ Try again+ </button>+ )}+ {onFeedback && <FeedbackButtons value={feedback} onChange={onFeedback} />}+ </div>)}</div></div>diff --git a/packages/ui/src/components/sessions/ChatHistory.tsx b/packages/ui/src/components/sessions/ChatHistory.tsxindex 60b1d597..d8145efd 100644--- a/packages/ui/src/components/sessions/ChatHistory.tsx+++ b/packages/ui/src/components/sessions/ChatHistory.tsx@@ -1,10 +1,19 @@"use client";-import { useMemo, useState } from "react";+import { useCallback, useEffect, useMemo, useState } from "react";import Icon from "@/components/Icon";import Button from "@/components/ui/Button";import OverflowMenu from "@/components/ui/OverflowMenu";-import type { SessionSummary } from "@/lib/api";+import {+ getPeopleViewer,+ getSessionShares,+ listPeople,+ setSessionShares,+ updateSession,+ type Person,+ type SessionSummary,+} from "@/lib/api";+import { downloadChat } from "@/lib/downloadChat";import { formatRelativeTime } from "@/lib/relativeTime";import { highlightParts, matchLabel } from "@/lib/chatSearch";import { CHANNEL_LABELS, sessionChannel, sessionTitle } from "@/lib/sessionChannel";@@ -23,11 +32,13 @@ interface ChatHistoryProps {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. */+ 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 }: ChatHistoryProps) {+export default function ChatHistory({ sessions, searching, query = "", onSelect, onDelete, onChanged }: ChatHistoryProps) {const [collapsedOverride, setCollapsedOverride] = useState<Record<string, boolean>>({});const [showAll, setShowAll] = useState<Set<string>>(new Set());@@ -73,7 +84,14 @@ export default function ChatHistory({ sessions, searching, query = "", onSelect,{!collapsed && (<div className="mt-1 space-y-2">{visible.map((s) => (- <ChatRow key={s.session_id} session={s} query={query} onSelect={onSelect} onDelete={onDelete} />+ <ChatRow+ key={s.session_id}+ session={s}+ query={query}+ onSelect={onSelect}+ onDelete={onDelete}+ onChanged={onChanged}+ />))}{hiddenCount > 0 && (<button@@ -93,27 +111,37 @@ export default function ChatHistory({ sessions, searching, query = "", onSelect,);}-function ChatRow({+type RowPanel = "delete" | "rename" | "share" | null;++export function ChatRow({session,- query,+ query = "",onSelect,onDelete,+ onChanged,}: {session: SessionSummary;- query: string;+ query?: string;onSelect: (sessionId: string) => void;- onDelete: (sessionId: string) => Promise<boolean>;+ /** Absent for a chat shared with the viewer, which only they can't delete. */+ onDelete?: (sessionId: string) => Promise<boolean>;+ onChanged?: () => void;}) {- // Delete is in the row's ⋯ menu and asks here, in the row, first.- const [confirming, setConfirming] = useState(false);+ // Delete, Rename and Share open a panel here, in the row; the ⋯ menu+ // holds them all.+ const [panel, setPanel] = useState<RowPanel>(null);const [deleting, setDeleting] = useState(false);const [failed, setFailed] = useState(false);+ // What the last quick action (pin, download) couldn't do, if anything.+ const [actionError, setActionError] = useState<string | null>(null);const channel = sessionChannel(session.session_id);+ const readOnly = !!session.read_only;const messages =matchLabel(session.match_count) ??`${session.message_count} message${session.message_count === 1 ? "" : "s"}`;const confirmDelete = async () => {+ if (!onDelete) return;setDeleting(true);setFailed(false);const ok = await onDelete(session.session_id);@@ -124,6 +152,41 @@ function ChatRow({}};+ const togglePin = async () => {+ setActionError(null);+ try {+ await updateSession(session.session_id, { pinned: !session.pinned_at });+ onChanged?.();+ } catch (err) {+ setActionError(err instanceof Error ? err.message : "Couldn't pin this chat.");+ }+ };++ const download = async () => {+ setActionError(null);+ try {+ await downloadChat(session.session_id);+ } catch {+ setActionError("Couldn't download this chat.");+ }+ };++ const open = (next: RowPanel) => {+ setActionError(null);+ setFailed(false);+ setPanel(next);+ };++ const menu = readOnly+ ? [{ label: "Download", onSelect: () => void download() }]+ : [+ { label: session.pinned_at ? "Unpin" : "Pin", onSelect: () => void togglePin() },+ { label: "Rename", onSelect: () => open("rename") },+ { label: "Share", onSelect: () => open("share") },+ { label: "Download", onSelect: () => void download() },+ ...(onDelete ? [{ label: "Delete chat", danger: true, onSelect: () => open("delete") }] : []),+ ];+return (<div className="rounded-2xl border border-line bg-surface-elevated transition-colors hover:border-line-strong"><div className="flex items-center gap-1 pr-2">@@ -141,7 +204,17 @@ function ChatRow({)}</span><span className="block text-sm text-fg-subtle mt-0.5">- {formatRelativeTime(session.updated_at)} · {messages}+ {readOnly ? (+ <>+ Shared by {session.shared_by ?? "someone on your team"} ·{" "}+ {formatRelativeTime(session.shared_at ?? session.updated_at)}+ </>+ ) : (+ <>+ {session.pinned_at && <span className="text-fg-muted">Pinned · </span>}+ {formatRelativeTime(session.updated_at)} · {messages}+ </>+ )}</span>{session.snippet && (<span className="block text-sm text-fg-muted mt-1.5 line-clamp-2 break-words">@@ -157,12 +230,14 @@ function ChatRow({</span>)}</button>- <OverflowMenu- label="More actions for this chat"- items={[{ label: "Delete chat", danger: true, onSelect: () => setConfirming(true) }]}- />+ <OverflowMenu label="More actions for this chat" items={menu} /></div>- {(confirming || failed) && (+ {actionError && (+ <p role="alert" className="border-t border-line px-4 py-3 text-sm text-fg">+ {actionError}+ </p>+ )}+ {(panel === "delete" || failed) && (<div role="alert" className="flex flex-wrap items-center gap-2 border-t border-line px-4 py-3"><p className="mr-auto text-sm text-fg">{failed ? "Couldn't delete this chat. Try again?" : "Delete this chat? This cannot be undone."}@@ -174,7 +249,7 @@ function ChatRow({size="sm"variant="ghost"onClick={() => {- setConfirming(false);+ setPanel(null);setFailed(false);}}disabled={deleting}@@ -183,6 +258,202 @@ function ChatRow({</Button></div>)}+ {panel === "rename" && (+ <RenamePanel+ session={session}+ onDone={(changed) => {+ setPanel(null);+ if (changed) onChanged?.();+ }}+ />+ )}+ {panel === "share" && <SharePanel sessionId={session.session_id} onClose={() => setPanel(null)} />}+ </div>+ );+}++function RenamePanel({ session, onDone }: { session: SessionSummary; onDone: (changed: boolean) => void }) {+ const [title, setTitle] = useState(sessionTitle(session));+ const [saving, setSaving] = useState(false);+ const [error, setError] = useState<string | null>(null);+ const trimmed = title.trim();++ const save = async () => {+ if (!trimmed || saving) return;+ setSaving(true);+ setError(null);+ try {+ await updateSession(session.session_id, { title: trimmed.slice(0, 120) });+ onDone(true);+ } catch (err) {+ setSaving(false);+ setError(err instanceof Error ? err.message : "Couldn't rename 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();+ }}+ >+ <input+ type="text"+ value={title}+ onChange={(e) => setTitle(e.target.value)}+ onKeyDown={(e) => {+ if (e.key === "Escape") {+ e.preventDefault();+ onDone(false);+ }+ }}+ maxLength={120}+ autoFocus+ aria-label="Chat 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={!trimmed || saving}>+ {saving ? "Saving…" : "Save"}+ </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>;+}++// Who the chat is shared with, to read: team members only, never the owner.+// Loaded when the panel opens (it mounts then), keyed by the chat it is for.+function SharePanel({ sessionId, onClose }: { sessionId: string; onClose: () => void }) {+ const [loaded, setLoaded] = useState<ShareState | null>(null);+ const [loadError, setLoadError] = useState(false);+ const [saving, setSaving] = useState(false);+ const [error, setError] = useState<string | null>(null);+ const [saved, setSaved] = useState(false);++ // State is only set once the requests answer, never synchronously here.+ const fetchShares = useCallback(+ (isLive: () => boolean) => {+ Promise.all([listPeople(), getPeopleViewer(), getSessionShares(sessionId)])+ .then(([people, viewer, shares]) => {+ if (!isLive()) return;+ const team = people.filter(+ (p) => p.kind === "team" && !p.archived && p.id !== viewer.person_id,+ );+ setLoaded({ people: team, chosen: new Set(shares.map((s) => s.person_id)) });+ })+ .catch(() => {+ if (isLive()) setLoadError(true);+ });+ },+ [sessionId],+ );+ useEffect(() => {+ let live = true;+ fetchShares(() => live);+ return () => {+ live = false;+ };+ }, [fetchShares]);+ const load = () => {+ setLoadError(false);+ fetchShares(() => true);+ };++ const toggle = (id: number) => {+ setSaved(false);+ setLoaded((prev) => {+ if (!prev) return prev;+ const chosen = new Set(prev.chosen);+ if (chosen.has(id)) chosen.delete(id);+ else chosen.add(id);+ return { ...prev, chosen };+ });+ };++ const save = async () => {+ if (!loaded) return;+ setSaving(true);+ setError(null);+ try {+ const shares = await setSessionShares(sessionId, Array.from(loaded.chosen));+ setLoaded({ ...loaded, chosen: new Set(shares.map((s) => s.person_id)) });+ setSaved(true);+ } catch (err) {+ setError(err instanceof Error ? err.message : "Couldn't share this chat.");+ } finally {+ setSaving(false);+ }+ };++ return (+ <div className="border-t border-line px-4 py-3 space-y-3">+ <p className="text-sm text-fg">Share this chat to read with:</p>+ {loadError ? (+ <p role="alert" className="text-sm text-fg-muted">+ Couldn't load your team.{" "}+ <button type="button" onClick={load} className="font-medium text-accent hover:underline cursor-pointer">+ Try again+ </button>+ </p>+ ) : !loaded ? (+ <p className="text-sm text-fg-muted">Loading your team…</p>+ ) : loaded.people.length === 0 ? (+ <p className="text-sm text-fg-muted">There's no one else on your team to share with yet.</p>+ ) : (+ <ul className="max-h-60 overflow-y-auto space-y-0.5">+ {loaded.people.map((p) => (+ <li key={p.id}>+ <label className="flex items-center gap-3 min-h-[2.5rem] px-2 rounded-lg hover:bg-surface-overlay cursor-pointer">+ <input+ type="checkbox"+ checked={loaded.chosen.has(p.id)}+ onChange={() => toggle(p.id)}+ className="h-4 w-4 flex-shrink-0 accent-[rgb(var(--accent-strong))]"+ />+ <span className="text-[15px] text-fg">{p.full_name}</span>+ {p.role && <span className="text-sm text-fg-subtle truncate">{p.role}</span>}+ </label>+ </li>+ ))}+ </ul>+ )}+ {error && (+ <p role="alert" className="text-sm text-red-400">+ {error}+ </p>+ )}+ <div className="flex flex-wrap items-center gap-2">+ {saved && (+ <p role="status" className="mr-auto text-sm text-fg-muted">+ {loaded && loaded.chosen.size > 0 ? "Shared." : "Not shared with anyone."}+ </p>+ )}+ <Button+ size="sm"+ variant="primary"+ className={saved ? "" : "ml-auto"}+ onClick={() => void save()}+ disabled={!loaded || saving || loaded.people.length === 0}+ >+ {saving ? "Saving…" : "Save"}+ </Button>+ <Button size="sm" variant="ghost" onClick={onClose} disabled={saving}>+ {saved ? "Close" : "Cancel"}+ </Button>+ </div></div>);}diff --git a/packages/ui/src/lib/api.ts b/packages/ui/src/lib/api.tsindex ed8f02f9..060fbacb 100644--- a/packages/ui/src/lib/api.ts+++ b/packages/ui/src/lib/api.ts@@ -962,6 +962,14 @@ export interface SessionSummary {match_count?: number;/** Search results only: the newest matching message around the match. */snippet?: string;+ /** Set only while the owner has it pinned; pinned chats list first. */+ pinned_at?: string;+ /** A chat someone else shared with the caller: readable, not writable. */+ read_only?: boolean;+ /** Shared chats only: the owner's name. */+ shared_by?: string;+ /** Shared-with-me list only: when it was shared. */+ shared_at?: string;}export async function listSessions(): Promise<SessionSummary[]> {@@ -990,6 +998,106 @@ export async function deleteSession(sessionId: string): Promise<void> {if (!res.ok) throw new Error("Failed to delete session");}+// The session routes' `detail` (a string for 409s, a list for 422s), or `fallback`.+async function sessionError(res: Response, fallback: string): Promise<Error> {+ const body = (await res.json().catch(() => ({}))) as { detail?: unknown };+ if (typeof body.detail === "string") return new Error(body.detail);+ const first = Array.isArray(body.detail) ? (body.detail[0] as { msg?: unknown }) : undefined;+ return new Error(typeof first?.msg === "string" ? first.msg : fallback);+}++/** One chat, as its owner or as someone it was shared with (`read_only`). */+export async function getSession(sessionId: string): Promise<SessionSummary> {+ const res = await fetch(`${API_BASE}/sessions/${encodeURIComponent(sessionId)}`);+ if (res.status === 404) throw new Error("not_found");+ if (!res.ok) throw new Error("Failed to load session");+ return res.json();+}++/** Chats other people shared with the caller, to read. */+export async function listSharedSessions(): Promise<SessionSummary[]> {+ const res = await fetch(`${API_BASE}/sessions/shared-with-me`);+ if (!res.ok) throw new Error("Failed to list shared chats");+ return res.json();+}++/** Rename and / or pin the caller's own chat. A renamed chat keeps its name. */+export async function updateSession(+ sessionId: string,+ patch: { title?: string; pinned?: boolean },+): Promise<SessionSummary> {+ const res = await fetch(`${API_BASE}/sessions/${encodeURIComponent(sessionId)}`, {+ method: "PATCH",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify(patch),+ });+ if (!res.ok) throw await sessionError(res, "Couldn't update this chat.");+ return res.json();+}++export interface SessionShare {+ person_id: number;+ full_name: string;+ shared_at: string;+}++/** Who the owner shared this chat with. */+export async function getSessionShares(sessionId: string): Promise<SessionShare[]> {+ const res = await fetch(`${API_BASE}/sessions/${encodeURIComponent(sessionId)}/shares`);+ if (!res.ok) throw await sessionError(res, "Couldn't load who this chat is shared with.");+ return res.json();+}++/** Shares the chat with exactly these team members (anyone left out is+ * unshared). Throws the server's reason, e.g. a chat that read the owner's+ * own mail stays private. */+export async function setSessionShares(sessionId: string, personIds: number[]): Promise<SessionShare[]> {+ const res = await fetch(`${API_BASE}/sessions/${encodeURIComponent(sessionId)}/shares`, {+ method: "PUT",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ person_ids: personIds }),+ });+ if (!res.ok) throw await sessionError(res, "Couldn't share this chat.");+ return res.json();+}++/** The filename in a Content-Disposition header, or null. */+export function dispositionFilename(header: string | null): string | null {+ if (!header) return null;+ const star = /filename\*=(?:UTF-8'')?([^;]+)/i.exec(header);+ if (star) {+ try {+ return decodeURIComponent(star[1].trim().replace(/^"|"$/g, ""));+ } catch {+ // Malformed encoding: fall through to the plain filename.+ }+ }+ const plain = /filename="?([^";]+)"?/i.exec(header);+ return plain ? plain[1].trim() : null;+}++/** The whole chat as Markdown, with the file name the server chose. */+export async function exportSession(sessionId: string): Promise<{ text: string; filename: string }> {+ const res = await fetch(`${API_BASE}/sessions/${encodeURIComponent(sessionId)}/export`);+ if (!res.ok) throw await sessionError(res, "Couldn't download this chat.");+ const text = await res.text();+ return { text, filename: dispositionFilename(res.headers.get("Content-Disposition")) ?? "chat.md" };+}++/** Takes back the chat's last turn (`lastMessageId` must still be its last+ * reply) and returns the words it answered, to send again. Throws the+ * server's reason on a 409 (still answering, moved on, not a web chat). */+export async function rewindSession(sessionId: string, lastMessageId: number): Promise<string> {+ const res = await fetch(`${API_BASE}/sessions/${encodeURIComponent(sessionId)}/rewind`, {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ last_message_id: lastMessageId }),+ });+ if (!res.ok) throw await sessionError(res, "Couldn't redo that answer.");+ const data = (await res.json()) as { message: string };+ return data.message;+}+export interface SuggestedPromptsResponse {prompts: string[];subtitle: string;diff --git a/packages/ui/src/lib/chatTurns.ts b/packages/ui/src/lib/chatTurns.tsnew file mode 100644index 00000000..8d2b8161--- /dev/null+++ b/packages/ui/src/lib/chatTurns.ts@@ -0,0 +1,68 @@+// What the chat's last turn allows: Try again on the last reply, Edit on the+// last message the user sent. Both take the turn back on the server+// (POST /sessions/{id}/rewind) and send the words again. Kept apart from the+// component so `npm test` can check it (see scripts/chatTurns.test.mjs).++import type { ChatMessage } from "@/lib/api";++export interface LastTurn {+ /** Index of the last message when it is a saved assistant reply. */+ replyIndex: number | null;+ /** Index of the last user message before that reply. */+ userIndex: number | null;+ /** The reply's row id, which the rewind names. */+ replyId: number | null;+ /** Whether Try again / Edit may be offered at all. */+ canRedo: boolean;+ /** The reply already acted (sent, booked, filed...), so redoing could repeat it. */+ didSomething: boolean;+}++/** Slack, Telegram, Discord and Google Chat chats have ids like+ * "slack:dm:..."; the reply also lives in that app and can't be taken back. */+function isChannelSession(sessionId: string): boolean {+ return sessionId.includes(":");+}++export function lastTurn(messages: ChatMessage[], sessionId: string | null | undefined): LastTurn {+ const last = messages.length - 1;+ const reply = last >= 0 ? messages[last] : undefined;+ const replyIndex = reply && reply.role === "assistant" && typeof reply.id === "number" ? last : null;+ let userIndex: number | null = null;+ if (replyIndex !== null) {+ for (let i = replyIndex - 1; i >= 0; i--) {+ if (messages[i].role === "user") {+ userIndex = i;+ break;+ }+ // Another reply first: this one answered nothing the user typed.+ if (messages[i].role === "assistant") break;+ }+ }+ const replyId = replyIndex !== null ? (reply?.id ?? null) : null;+ return {+ replyIndex,+ userIndex,+ replyId,+ canRedo: !!sessionId && !isChannelSession(sessionId) && replyId !== null,+ didSomething: replyIndex !== null && (reply?.actions?.length ?? 0) > 0,+ };+}++/** The messages without the last turn: the last reply and the user messages+ * it answered (everything after the reply before it). */+export function dropLastTurn(messages: ChatMessage[]): ChatMessage[] {+ let end = messages.length;+ // Skip the trailing reply (if the list ends on one), then the user+ // messages before it, stopping at the previous reply.+ if (end > 0 && messages[end - 1].role === "assistant") end -= 1;+ while (end > 0 && messages[end - 1].role === "user") end -= 1;+ return messages.slice(0, end);+}++/** The question asked before redoing a reply that already did something. */+export function confirmRedoText(actions: { summary: string }[] | undefined): string {+ const first = actions?.find((a) => a.summary.trim())?.summary.trim();+ const what = first ? `("${first}")` : "(sent a message, booked a meeting or filed a card)";+ return `That answer already did something ${what}. Doing it again could repeat it. Go ahead?`;+}diff --git a/packages/ui/src/lib/downloadChat.ts b/packages/ui/src/lib/downloadChat.tsnew file mode 100644index 00000000..73019a0d--- /dev/null+++ b/packages/ui/src/lib/downloadChat.ts@@ -0,0 +1,19 @@+// Saves a chat as a Markdown file (GET /sessions/{id}/export). Shared by the+// Chats list, the open chat's menu and the read-only view of a shared chat.++import { exportSession } from "@/lib/api";++/** Downloads the chat; throws when the export failed. */+export async function downloadChat(sessionId: string): Promise<void> {+ const { text, filename } = await exportSession(sessionId);+ const blob = new Blob([text], { type: "text/markdown" });+ const url = URL.createObjectURL(blob);+ const a = document.createElement("a");+ a.href = url;+ a.download = filename;+ document.body.appendChild(a);+ a.click();+ document.body.removeChild(a);+ // Revoked on the next tick: some browsers start the download after click returns.+ setTimeout(() => URL.revokeObjectURL(url), 0);+}diff --git a/packages/ui/src/lib/sessionGroups.ts b/packages/ui/src/lib/sessionGroups.tsindex d56f7aa2..4b33069b 100644--- a/packages/ui/src/lib/sessionGroups.ts+++ b/packages/ui/src/lib/sessionGroups.ts@@ -1,6 +1,6 @@import type { SessionSummary } from "@/lib/api";-export type GroupKey = "today" | "yesterday" | "prev7" | "prev30" | "older";+export type GroupKey = "pinned" | "today" | "yesterday" | "prev7" | "prev30" | "older";export interface SessionGroup {key: GroupKey;@@ -9,6 +9,7 @@ export interface SessionGroup {}const GROUP_ORDER: { key: GroupKey; label: string }[] = [+ { key: "pinned", label: "Pinned" },{ key: "today", label: "Today" },{ key: "yesterday", label: "Yesterday" },{ key: "prev7", label: "Previous 7 Days" },@@ -23,7 +24,8 @@ const DAY_MS = 86_400_000;* sorted newest-first (the API returns `updated_at DESC`), so item order within* each bucket is preserved. Empty buckets are dropped. `now` is injectable so* the bucketing is deterministically testable. Unparseable timestamps fall into- * "Older" rather than throwing.+ * "Older" rather than throwing. Pinned chats go first, in "Pinned", whatever+ * their date.*/export function groupSessionsByDate(sessions: SessionSummary[],@@ -39,6 +41,7 @@ export function groupSessionsByDate(const thirtyDaysAgo = startOfToday - 30 * DAY_MS;const buckets: Record<GroupKey, SessionSummary[]> = {+ pinned: [],today: [],yesterday: [],prev7: [],@@ -49,7 +52,9 @@ export function groupSessionsByDate(for (const s of sessions) {const t = new Date(s.updated_at).getTime();let key: GroupKey;- if (Number.isNaN(t)) {+ if (s.pinned_at) {+ key = "pinned";+ } else if (Number.isNaN(t)) {key = "older";} else if (t >= startOfToday) {key = "today";