AI-powered virtual executive team — a single coherent executive persona backed by 8 specialist agents (FastAPI + Next.js).
fix(delegation): show your whole writing profile and keep its line breaks (#252)
Rufus3f6ba5bf7cff
diff --git a/packages/core/openexecutive/api/routes/delegation.py b/packages/core/openexecutive/api/routes/delegation.pyindex d6050876..9d511e0d 100644--- a/packages/core/openexecutive/api/routes/delegation.py+++ b/packages/core/openexecutive/api/routes/delegation.py@@ -23,6 +23,9 @@ Routes:POST /delegation/voice/learn — learn it from the caller's sent mail (409in_progress / locked / too_soon /not_enough_mail / no_profile / changed)+ POST /delegation/voice/signature — take the signature from the caller's+ Gmail settings again (a locked profile+ stays locked; nothing else changes)PUT /delegation/voice — edit fields, lock / unlockDELETE /delegation/voice — forget it (history kept)@@ -31,6 +34,7 @@ Every change writes a private audit row.from __future__ import annotationsimport logging+from dataclasses import asdictfrom typing import Anyfrom fastapi import APIRouter, HTTPException, Request@@ -120,6 +124,15 @@ class VoiceUpdate(BaseModel):clear_signature: bool = False+# What a refused field must be, for the message an edit gets back.+_VOICE_RULES: dict[str, str] = {+ "greetings": "a greeting is one short line, and {first} is its only placeholder",+ "sign_off": "the sign-off is at most two short lines",+ "habits": "a habit or never-rule says how you write, without anyone's name",+ "avoid": "a habit or never-rule says how you write, without anyone's name",+}++def _refuse(status_code: int, code: str, message: str) -> HTTPException:return HTTPException(status_code=status_code, detail={"code": code, "message": message})@@ -251,6 +264,36 @@ async def learn_delegation_voice(request: Request) -> VoiceOut:return _voice_out(stored)[email protected]("/delegation/voice/signature", response_model=VoiceOut)+async def refresh_delegation_signature(request: Request) -> VoiceOut:+ """Read the signature from the caller's Gmail settings again and keep+ everything else, lock included: a relearn would replace their edits."""+ person = _caller(request)+ person_id = _person_id(person)+ status = await gmail_status(person.email)+ if status != "connected":+ raise _refuse(409, _BLOCKING_CODES.get(status, "gmail_error"), STATUS_MESSAGES[status])+ try:+ signature = await gmail_for(person.email or "").send_as_signature()+ except GmailAuthError as exc:+ raise _refuse(409, "gmail_needs_reconnect", STATUS_MESSAGES["needs_reconnect"]) from exc+ except GmailError as exc:+ logger.warning("delegation: reading the Gmail signature failed", exc_info=True)+ raise _refuse(502, "gmail_error", STATUS_MESSAGES["error"]) from exc+ # Read after the Gmail call, so an edit made meanwhile is kept.+ stored = get_voice(person_id)+ profile, _ = validate_profile(+ {**asdict(stored.profile), "signature": signature}, allow_exemplars=True, keep_signature=True+ )+ saved = save_voice(person_id, profile, locked=stored.locked, updated_by=f"person:{person_id}")+ _audit(+ "delegation_voice_changed",+ f"Signature taken from Gmail settings by person {person_id}",+ {"op": "signature", "person_id": person_id, "has_signature": bool(profile.signature)},+ )+ return _voice_out(saved)++@router.put("/delegation/voice", response_model=VoiceOut)def update_delegation_voice(request: Request, body: VoiceUpdate) -> VoiceOut:person = _caller(request)@@ -276,12 +319,15 @@ def update_delegation_voice(request: Request, body: VoiceUpdate) -> VoiceOut:if d["field"].split(".")[0] in sent]if rejected:+ fields = [d["field"].split(".")[0] for d in rejected]+ rules = dict.fromkeys(_VOICE_RULES[f] for f in fields if f in _VOICE_RULES)raise HTTPException(status_code=422,detail={"code": "invalid_voice",- "message": "Some of it can't be saved: write about how you write, "- "without links, handles, amounts or anyone's name.",+ "message": "Some of it can't be saved: "+ + "; ".join(rules or ["write about how you write"])+ + ". No links, handles or amounts.","rejected": rejected,},)diff --git a/packages/core/openexecutive/architecture/architecture-facts.yaml b/packages/core/openexecutive/architecture/architecture-facts.yamlindex 947fae68..2365695c 100644--- a/packages/core/openexecutive/architecture/architecture-facts.yaml+++ b/packages/core/openexecutive/architecture/architecture-facts.yaml@@ -3462,7 +3462,7 @@ audit:- workspace_settings_changed — solo/team mode, the user's time zone or the principal's role changed via PUT /workspace. actor is the caller's x-caller-email or "api"; details carry mode and timezone, each as from/to, plus role_fields_changed (the names of the role fields that changed, never their text — it is the principal's own and may name their manager) when the role changed. The summary names only what moved ("mode A → B, time zone X → Y" and/or "principal's role updated"). A PUT that changes nothing writes nothing.- delegation_settings_changed — a person turned Act as me on or off for themselves via PUT /delegation. actor "user"; details carry person_id and enabled. Always private. Setting the current value writes nothing.- delegation_gmail_verified — their own Gmail was checked (connected, and the mailbox on their People entry) just before Act as me was turned on. details carry person_id and status. Always private.- - delegation_voice_changed — "How I write" learned from their sent mail (actor "delegation"), or edited, locked or reset via /delegation/voice (actor "user"). details carry op (learn, edit or reset), person_id, and counts or the names of the fields changed — never their text. Always private.+ - delegation_voice_changed — "How I write" learned from their sent mail (actor "delegation"), or edited, locked or reset via /delegation/voice, or its signature read from Gmail again via /delegation/voice/signature (actor "user"). details carry op (learn, edit, reset or signature), person_id, and counts, the names of the fields changed or whether a signature was found — never their text. Always private.- delegation_drafted — one per draft ghostwrite_email saved in someone's own Gmail. details carry person_id, thread_id, draft_id, reply, the recipient count and flags — never the draft, the intent or the thread. Always private; the daily draft cap counts these rows.turn_id: Set per Executive turn (`f"t-{uuid12}"`) and propagated automatically to retriever / specialist / tool / cache / committee emits via `openexecutive.audit.context` ContextVars. Groups every row in one user-assistant exchange under the same `turn_id`; the session view derives causal edges from this.writer: openexecutive.audit.AuditLogger — synchronous SQLite writer; uses WAL + 5s busy_timeout so concurrent webhook/scheduler/poller threads don't see "database is locked".@@ -6712,14 +6712,26 @@ delegation:locked profile, and a lock or edit made while it runs wins (the learnedprofile is dropped: locked / changed). One forced-tool call(record_voice_profile), then validate_profile in code — greetings per- audience (team / contact / other) and a sign-off (short; no links,- handles, amounts or markup), length and formality from fixed lists, up+ audience (team / contact / other) and a sign-off (short, at most two+ lines; no links, handles, amounts or markup; a literal backslash-n is a+ line break, read after NFKC, and a value with more such lines than fit+ keeps its first ones — which also repairs a profile stored before that+ rule, since stored rows are re-validated as they are read; a typed value+ with too many lines is a 422 naming the rule), length and formality+ from fixed lists, upto 8 habits and 6 avoid rules through attunement.style's deny-list plusa writing-topic check and a roster-name check, and up to 3 exemplars(each verbatim from a sample, emails and phones masked, none while aclient slot is active). The signature comes from Gmail sendAs, never- the model. Tables delegation_voice and delegation_voice_history (every- change kept).+ the model, through gmail.html_to_text: a <br> always ends a line and a+ block tag (div, p, li, tr, table, lists, headings, blockquote…),+ opening or closing, ends one only when it has text — Gmail puts a+ signature's first line straight in the outer <div> and each later line+ in its own <div>, so closing tags alone glued the first two lines.+ POST /delegation/voice/signature reads it again without a relearn (a+ relearn would replace the person's edits, and a locked profile can't+ relearn): nothing else changes and the lock is kept. Tables+ delegation_voice and delegation_voice_history (every change kept).gmail_client: |delegation.gmail.DelegateGmail — direct Gmail REST (httpx), neverregistered with the MCP gateway. Methods profile_email, search_threads@@ -6731,6 +6743,13 @@ delegation:and any 429, is a GmailError to retry instead), mismatch, no_email, shared_mailbox(the person's address is the exec address; refused before askingGoogle) or error. Credentials per person, see integrations.own_gmail.+ html_to_text (HTML-only bodies and the sendAs signature) runs on mail+ anyone can send, on the event loop, so every step is one forward pass:+ the <br> and block patterns end at the next "<" as well as ">", tags and+ script / style elements are cut by scanning forward, and a decimal+ character reference past Unicode's range becomes U+FFFD before+ html.unescape (which raises past 4,300 digits). A unit test times+ crafted input.privacy: |From the moment ghostwrite_email sets touched_mail,people_tools.audit_row_private_to_principal answers True, so every row@@ -6753,7 +6772,9 @@ delegation:api: |/delegation — GET, PUT {enabled}; /delegation/voice — GET, PUT (edit,lock), DELETE (reset); POST /delegation/voice/learn (409 in_progress /- locked / too_soon / not_enough_mail / no_profile / changed). The+ locked / too_soon / not_enough_mail / no_profile / changed); POST+ /delegation/voice/signature (the Gmail sendAs signature again; 409 with+ the Gmail codes, 502 gmail_error). Thecaller's OWN delegation only. 403 not_available_yet for a caller can_delegaterefuses (the Settings card hides); 403 sign_in_required with nox-caller-email unless local login; turning it on needs gmail_status@@ -6762,8 +6783,12 @@ delegation:writes a private audit row.surfaces: |Settings → Act as me (ActAsMeCard): the Gmail status with the connect- command and Check again, the Write drafts as me switch, and How I write.- Setup status light your_gmail. The chat chip "Drafted an email as you+ command and Check again, the Write drafts as me switch, and How I write+ (length and tone, a greeting input per audience, the sign-off and the+ habit / never lists in textareas that grow to fit, the signature with+ Refresh from Gmail and Don't add my signature — or Add my Gmail+ signature — and each exemplar quoted, with Remove examples). Setup+ status light your_gmail. The chat chip "Drafted an email as youto … — in your Gmail Drafts" opens the draft (target=_blank,rel=noopener noreferrer). Evals: a scenario's delegation block runs theturn against evals.mailbox.ScenarioMailbox and hands the saved drafts todiff --git a/packages/core/openexecutive/architecture/prebuilt/api.json b/packages/core/openexecutive/architecture/prebuilt/api.jsonindex e53e66dd..92dd0b09 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 Google sign-in is not 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 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 configured UI origins. 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\nEndpoints grouped by router:\n\n| Router | Key endpoints | Purpose |\n|---|---|---|\n| `chat` | `POST /chat`, `POST /chat/stop` | SSE stream of a live Executive turn. 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. 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. 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/top-three`, `GET /today/weekly-review` | Morning-brief aggregation, recent-action rail, and Pulse heartbeat heatmap (per-day activity counts). `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/{id}/open-loops`, `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. 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`). `/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. |\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). 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`, `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. |\n| `personas` | `GET\\|PUT\\|POST\\|DELETE /personas` | Executive persona definitions. |\n| `alerts` | `POST /alerts/{id}/ack`, `POST /alerts/bulk-ack`, `POST /alerts/{id}/reopen`, `POST /alerts/review` | Groom the briefing queue. `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` and `supersedes_id` on every summary. `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. |\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). 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` | Act as me — the **caller's own** delegation only; nobody sets it for anyone else. `GET /delegation` returns `{enabled, gmail: {status, message, email, connect_command}}`, where `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), 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. 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 header itself is trusted from whoever holds the shared secret, the UI proxy, as on every principal-only route). Every change writes a private audit row. |\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). 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 list, its `total` and the usage totals leave them out, a private row's id is a 404, and a session shows only its other rows. |\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 (unauthenticated). |\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 Gmail (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. 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}` | Upload, list, view extracted text, and delete indexed company docs. 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. |\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}` — `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). 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`, `GET /workflows/tools/search?q=`, `GET /workflows/tools/describe?names=` | Workflow catalog, run management, and user-created (dynamic) workflow CRUD. 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: `GET /workflows/runs` and `GET /workflows/runs/{run_id}` read stored runs under their existing rules. `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` and `background` (true for the system-run built-ins the UI files under “System”). 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| `skill_drafts` | `/skill-drafts`, `/skill-drafts/{name}`, `/skill-drafts/{name}/approve` | Review queue for playbook changes the Executive proposed from chat. `GET` lists drafts (`action` create / update / delete, the proposed fields, an `id` version token, `current` — the playbook in effect now — and `followers`, the workflows that follow the name); `approve` (body `{id}`) applies exactly the reviewed version through the ordinary skills operations — 409 and the draft is kept if it was replaced since, on a conflict, or if its playbook vanished; `DELETE ?id=` discards that version only. |\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/people`, `GET /memories/people/{person_id}/conclusions` | Episodic-memory record management, 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). The principal's own peer memory — drawn from all their conversations, contacts included — is shown to the principal only: anyone else's overview omits that entry (and its conclusions from `conclusion_total`), and their `/conclusions` request for the principal 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/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/message`, `POST /workflows/designer/draft`, `GET /workflows/designer/{session_id}` | The conversational New workflow wizard. 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| `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. |\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. |\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` | Inbound integration callbacks (self-verified). |\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. |",+ "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 Google sign-in is not 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 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 configured UI origins. 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\nEndpoints grouped by router:\n\n| Router | Key endpoints | Purpose |\n|---|---|---|\n| `chat` | `POST /chat`, `POST /chat/stop` | SSE stream of a live Executive turn. 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. 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. 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/top-three`, `GET /today/weekly-review` | Morning-brief aggregation, recent-action rail, and Pulse heartbeat heatmap (per-day activity counts). `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/{id}/open-loops`, `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. 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`). `/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. |\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). 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`, `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. |\n| `personas` | `GET\\|PUT\\|POST\\|DELETE /personas` | Executive persona definitions. |\n| `alerts` | `POST /alerts/{id}/ack`, `POST /alerts/bulk-ack`, `POST /alerts/{id}/reopen`, `POST /alerts/review` | Groom the briefing queue. `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` and `supersedes_id` on every summary. `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. |\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). 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/signature` | Act as me — the **caller's own** delegation only; nobody sets it for anyone else. `GET /delegation` returns `{enabled, gmail: {status, message, email, connect_command}}`, where `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), 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 Gmail isn't connected, Google refuses it or the check itself fails (`gmail_error`), and a 502 `gmail_error` when reading the signature fails. 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 header itself is trusted from whoever holds the shared secret, the UI proxy, as on every principal-only route). Every change writes a private audit row. |\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). 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 list, its `total` and the usage totals leave them out, a private row's id is a 404, and a session shows only its other rows. |\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 (unauthenticated). |\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 Gmail (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. 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}` | Upload, list, view extracted text, and delete indexed company docs. 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. |\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}` — `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). 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`, `GET /workflows/tools/search?q=`, `GET /workflows/tools/describe?names=` | Workflow catalog, run management, and user-created (dynamic) workflow CRUD. 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: `GET /workflows/runs` and `GET /workflows/runs/{run_id}` read stored runs under their existing rules. `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` and `background` (true for the system-run built-ins the UI files under “System”). 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| `skill_drafts` | `/skill-drafts`, `/skill-drafts/{name}`, `/skill-drafts/{name}/approve` | Review queue for playbook changes the Executive proposed from chat. `GET` lists drafts (`action` create / update / delete, the proposed fields, an `id` version token, `current` — the playbook in effect now — and `followers`, the workflows that follow the name); `approve` (body `{id}`) applies exactly the reviewed version through the ordinary skills operations — 409 and the draft is kept if it was replaced since, on a conflict, or if its playbook vanished; `DELETE ?id=` discards that version only. |\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/people`, `GET /memories/people/{person_id}/conclusions` | Episodic-memory record management, 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). The principal's own peer memory — drawn from all their conversations, contacts included — is shown to the principal only: anyone else's overview omits that entry (and its conclusions from `conclusion_total`), and their `/conclusions` request for the principal 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/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/message`, `POST /workflows/designer/draft`, `GET /workflows/designer/{session_id}` | The conversational New workflow wizard. 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| `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. |\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. |\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` | Inbound integration callbacks (self-verified). |\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. |","mermaid": null,- "generated_at": "2026-09-26T11:18:25Z"+ "generated_at": "2026-09-26T16:58:25Z"}diff --git a/packages/core/openexecutive/architecture/prebuilt/audit.json b/packages/core/openexecutive/architecture/prebuilt/audit.jsonindex 63a34a9c..e6afac43 100644--- a/packages/core/openexecutive/architecture/prebuilt/audit.json+++ b/packages/core/openexecutive/architecture/prebuilt/audit.json@@ -1,7 +1,7 @@{"section_id": "audit","title": "Audit Log",- "markdown": "The audit log is a persistent, searchable, append-only record of what the system did — distinct from episodic memory (which biases future LLM behavior). Every event flows through `audit/logger.log_event`, a synchronous SQLite writer (WAL + 5s busy_timeout) that appends one row to the `audit_log` table in `episodic_memory.db`.\n\n### Event types\nRows are tagged by `event_type`, including `chat_turn`, `specialist_consult`, `tool_invocation`, `scheduled_action`, `alert`, `integration_inbound` (Slack / Discord / email / Telegram / Google Chat), plus `knowledge_retrieval`, `memory_extraction` (one row per episodic-extraction pass, written in a `finally` so a crashed pass is recorded too: how many items the model proposed, how many were stored, a `{kind, reason}` record per drop, a `malformed` count for payload shapes that were never usable items, and a `failure` naming the exception type when the pass raised — including `CancelledError`, which is a `BaseException` and so would otherwise be logged as a clean empty pass — a `proposed>0, stored=0` streak means the quote validator is rejecting everything, which is otherwise invisible), `cache_event` (one row per model call from every call site — Executive turns, specialist consults (chat turns and workflow steps), research specialists, the research routing and watchlist passes, triage, memory extraction — carrying tokens, cache hits, cost, server-side search count and, inside a research run, its `run_id`), `memory_snapshot`, `committee_review`, `peer_memory`, `attunement` (one row per open-loop extraction pass — opened / closed / dropped with a reason per drop and a `failure` type — plus a row per loop opened or closed and per 👍/👎 on a reply; see Attunement), `executive_paused` / `executive_resumed` (the operator pause switch; actor is the caller's email, details carry the reason, or on resume the held-action count), `scheduled_action_cancelled` (a pending scheduled action cancelled from the Pulse page or a script; actor is the signed-in email, `admin-token` or `local`), `workspace_settings_changed` (solo/team mode, the user's time zone or the principal's role changed through `PUT /workspace`; actor is the caller's email or `api`, details carry the mode's and zone's from/to, plus `role_fields_changed` — the names of the role fields that changed, never their text — when the role changed), `decision_class_mode_changed` (a decision class switched between `propose` and `auto_execute` through `PUT /decisions/classes/meeting_scheduling`; same actor rule, details carry the class and the mode's from/to), the four Act as me events — `delegation_settings_changed` (a person turned it on or off for themselves), `delegation_gmail_verified` (their own Gmail checked before turning it on), `delegation_voice_changed` (\"How I write\" learned, edited, locked or reset) and `delegation_drafted` (one per draft saved in their Gmail) — always private and metadata only: ids, counts and flags, never the draft or the thread; and the external-signal/monitor events.\n\n### Session & turn context\nEach row carries `session_id`, `turn_id`, `actor`, `summary`, `details_json`, `full_json`, `department`, and `private_to_principal`. A `turn_id` (`f\"t-{uuid12}\"`) is set per Executive turn and propagated automatically via ContextVars to retriever / specialist / tool / cache emits, grouping one user-assistant exchange. `summary` is the searchable column (LIKE, ~300 char cap); `details_json` is structured and not searched. `department` is filterable in SQL (`AuditLogger.query(department=…)`) — the department check-in's skip rule uses it to ask whether anything was logged for a department since its Goals were last reviewed.\n\n### Rows private to the principal\nEvery signed-in user can read `/audit`, so a row about something private to the principal is marked `private_to_principal` as it is written, and only the principal reads it. `AuditLogger.log` marks a row private when its caller passes `private=True` — the email poller's two inbound rows for mail from one of the principal's contacts or mail they forwarded, and `create_alert`'s row for a private alert — or when `people_tools.audit_row_private_to_principal` says so at write time:\n- every row a turn private to the principal writes (`Session.private_to_principal`): its reply, each tool call, the model-call rows, and the background passes that inherit the turn;\n- on the principal's own verified turn (or inside `grant_contact_egress`), any row whose summary, details or full payload names one of their contacts — their email address or full name anywhere in the text, or their person id or chat id in a person or recipient field (`person_id`, `attendee_person_ids`, `user_id`, `chat_id`, `channel_ref`), JSON tool results included.\n- every row an Act as me turn writes once `ghostwrite_email` has touched the speaker's mailbox (`TurnDelegation.touched_mail`, set before the tool's first read): the tool row, the reply's `chat_turn` row carrying the draft's preview, the model-call rows, and anything it starts in the background, under `private_rows` (it runs no learning passes). Only the principal can have Act as me for now, so private to the principal is the right visibility; the tool's input and result are also redacted (`ghostwrite` is a sensitive tool name).\n\nSome rows are written before their turn binds its session, so two scopes in `audit.context` count too. The email poller holds `private_rows` for the whole handling of a mail from a contact or a principal forward: every row is private, the knowledge retrieval (which quotes the mail) included. The chat adapters hold `principal_turn_rows` once they know the principal sent the message on a verified surface (`people_tools.audit_rows_on_senders_turn` on Slack, Discord and Telegram; the web chat route checks its caller), so the inbound row, the knowledge retrieval, alert triage and the start of the web stream follow the principal-turn rule above. Tasks started inside inherit the scope, except unattended work: a workflow run a chat reply resumes and each scheduled action start with neither (`unscoped_audit_rows`), so their rows follow the ordinary rule. A sender lookup that fails counts as not the principal, as the turn's own check does. Neither scope lets the turn reach anyone. A caller can add privacy but never remove it, and a check that cannot run keeps the row private. On anyone else's turn a contact is a stranger, so a row that names one keeps its visibility: hiding it would tell whoever wrote it that the address belongs to a contact. The poller handles each message with no session bound, so one message's private turn never marks the next message's rows.\n\nEvery read route resolves the caller as `/alerts` and `/decisions` do (`people.caller_is_principal`: the principal's signed-in email, or no `x-caller-email` — the CLI, direct curl, local login — once a principal is on the roster; before anyone is principal, nobody). For anyone else private rows are filtered in SQL (`include_private=False` on `query`, `count` and `usage_summary`), so `total` and pagination stay honest: `GET /audit/logs` leaves them out, `GET /audit/logs/{id}` answers 404 exactly as for a missing id, `GET /audit/sessions/{id}` shows only the other rows (404 when none are left), and `GET /audit/usage` leaves out their tokens and cost. Internal readers see every row unless they ask otherwise; the department check-in, whose report goes to the department, reads its recent activity without them, and its \"nothing new since the review\" skip rule ignores them too. Ids are one autoincrement sequence, so anyone else can still see a gap where a private row was written; that is accepted.\n\n### Views\n- `GET /audit` — filterable list with a \"Group by session\" toggle and session pills.\n- `GET /audit/session/{id}` — full ordered timeline plus a server-derived node/edge graph rendered as a three-pane React Flow chart.\n\n### Invariant\nAudit writes never break a chat turn: all writes swallow exceptions and log a warning, and instrumentation observes only — it never touches request building or the cached prompt blocks. Audit is append-only: no UPDATE or DELETE paths exist in product code.",+ "markdown": "The audit log is a persistent, searchable, append-only record of what the system did — distinct from episodic memory (which biases future LLM behavior). Every event flows through `audit/logger.log_event`, a synchronous SQLite writer (WAL + 5s busy_timeout) that appends one row to the `audit_log` table in `episodic_memory.db`.\n\n### Event types\nRows are tagged by `event_type`, including `chat_turn`, `specialist_consult`, `tool_invocation`, `scheduled_action`, `alert`, `integration_inbound` (Slack / Discord / email / Telegram / Google Chat), plus `knowledge_retrieval`, `memory_extraction` (one row per episodic-extraction pass, written in a `finally` so a crashed pass is recorded too: how many items the model proposed, how many were stored, a `{kind, reason}` record per drop, a `malformed` count for payload shapes that were never usable items, and a `failure` naming the exception type when the pass raised — including `CancelledError`, which is a `BaseException` and so would otherwise be logged as a clean empty pass — a `proposed>0, stored=0` streak means the quote validator is rejecting everything, which is otherwise invisible), `cache_event` (one row per model call from every call site — Executive turns, specialist consults (chat turns and workflow steps), research specialists, the research routing and watchlist passes, triage, memory extraction — carrying tokens, cache hits, cost, server-side search count and, inside a research run, its `run_id`), `memory_snapshot`, `committee_review`, `peer_memory`, `attunement` (one row per open-loop extraction pass — opened / closed / dropped with a reason per drop and a `failure` type — plus a row per loop opened or closed and per 👍/👎 on a reply; see Attunement), `executive_paused` / `executive_resumed` (the operator pause switch; actor is the caller's email, details carry the reason, or on resume the held-action count), `scheduled_action_cancelled` (a pending scheduled action cancelled from the Pulse page or a script; actor is the signed-in email, `admin-token` or `local`), `workspace_settings_changed` (solo/team mode, the user's time zone or the principal's role changed through `PUT /workspace`; actor is the caller's email or `api`, details carry the mode's and zone's from/to, plus `role_fields_changed` — the names of the role fields that changed, never their text — when the role changed), `decision_class_mode_changed` (a decision class switched between `propose` and `auto_execute` through `PUT /decisions/classes/meeting_scheduling`; same actor rule, details carry the class and the mode's from/to), the four Act as me events — `delegation_settings_changed` (a person turned it on or off for themselves), `delegation_gmail_verified` (their own Gmail checked before turning it on), `delegation_voice_changed` (\"How I write\" learned, edited, locked or reset, or its signature read from Gmail again) and `delegation_drafted` (one per draft saved in their Gmail) — always private and metadata only: ids, counts and flags, never the draft or the thread; and the external-signal/monitor events.\n\n### Session & turn context\nEach row carries `session_id`, `turn_id`, `actor`, `summary`, `details_json`, `full_json`, `department`, and `private_to_principal`. A `turn_id` (`f\"t-{uuid12}\"`) is set per Executive turn and propagated automatically via ContextVars to retriever / specialist / tool / cache emits, grouping one user-assistant exchange. `summary` is the searchable column (LIKE, ~300 char cap); `details_json` is structured and not searched. `department` is filterable in SQL (`AuditLogger.query(department=…)`) — the department check-in's skip rule uses it to ask whether anything was logged for a department since its Goals were last reviewed.\n\n### Rows private to the principal\nEvery signed-in user can read `/audit`, so a row about something private to the principal is marked `private_to_principal` as it is written, and only the principal reads it. `AuditLogger.log` marks a row private when its caller passes `private=True` — the email poller's two inbound rows for mail from one of the principal's contacts or mail they forwarded, and `create_alert`'s row for a private alert — or when `people_tools.audit_row_private_to_principal` says so at write time:\n- every row a turn private to the principal writes (`Session.private_to_principal`): its reply, each tool call, the model-call rows, and the background passes that inherit the turn;\n- on the principal's own verified turn (or inside `grant_contact_egress`), any row whose summary, details or full payload names one of their contacts — their email address or full name anywhere in the text, or their person id or chat id in a person or recipient field (`person_id`, `attendee_person_ids`, `user_id`, `chat_id`, `channel_ref`), JSON tool results included.\n- every row an Act as me turn writes once `ghostwrite_email` has touched the speaker's mailbox (`TurnDelegation.touched_mail`, set before the tool's first read): the tool row, the reply's `chat_turn` row carrying the draft's preview, the model-call rows, and anything it starts in the background, under `private_rows` (it runs no learning passes). Only the principal can have Act as me for now, so private to the principal is the right visibility; the tool's input and result are also redacted (`ghostwrite` is a sensitive tool name).\n\nSome rows are written before their turn binds its session, so two scopes in `audit.context` count too. The email poller holds `private_rows` for the whole handling of a mail from a contact or a principal forward: every row is private, the knowledge retrieval (which quotes the mail) included. The chat adapters hold `principal_turn_rows` once they know the principal sent the message on a verified surface (`people_tools.audit_rows_on_senders_turn` on Slack, Discord and Telegram; the web chat route checks its caller), so the inbound row, the knowledge retrieval, alert triage and the start of the web stream follow the principal-turn rule above. Tasks started inside inherit the scope, except unattended work: a workflow run a chat reply resumes and each scheduled action start with neither (`unscoped_audit_rows`), so their rows follow the ordinary rule. A sender lookup that fails counts as not the principal, as the turn's own check does. Neither scope lets the turn reach anyone. A caller can add privacy but never remove it, and a check that cannot run keeps the row private. On anyone else's turn a contact is a stranger, so a row that names one keeps its visibility: hiding it would tell whoever wrote it that the address belongs to a contact. The poller handles each message with no session bound, so one message's private turn never marks the next message's rows.\n\nEvery read route resolves the caller as `/alerts` and `/decisions` do (`people.caller_is_principal`: the principal's signed-in email, or no `x-caller-email` — the CLI, direct curl, local login — once a principal is on the roster; before anyone is principal, nobody). For anyone else private rows are filtered in SQL (`include_private=False` on `query`, `count` and `usage_summary`), so `total` and pagination stay honest: `GET /audit/logs` leaves them out, `GET /audit/logs/{id}` answers 404 exactly as for a missing id, `GET /audit/sessions/{id}` shows only the other rows (404 when none are left), and `GET /audit/usage` leaves out their tokens and cost. Internal readers see every row unless they ask otherwise; the department check-in, whose report goes to the department, reads its recent activity without them, and its \"nothing new since the review\" skip rule ignores them too. Ids are one autoincrement sequence, so anyone else can still see a gap where a private row was written; that is accepted.\n\n### Views\n- `GET /audit` — filterable list with a \"Group by session\" toggle and session pills.\n- `GET /audit/session/{id}` — full ordered timeline plus a server-derived node/edge graph rendered as a three-pane React Flow chart.\n\n### Invariant\nAudit writes never break a chat turn: all writes swallow exceptions and log a warning, and instrumentation observes only — it never touches request building or the cached prompt blocks. Audit is append-only: no UPDATE or DELETE paths exist in product code.","mermaid": "flowchart TD\n Chat[\"Chat turn / consult / tool call\"]\n Sched[\"Scheduled action\"]\n Inbound[\"Inbound integration\"]\n Log[\"audit/logger.log_event\"]\n Priv[\"private_to_principal? private turn, or names a contact on the principal's turn\"]\n DB[\"audit_log table (append-only)\"]\n Gate[\"read routes: private rows for the principal only\"]\n ListView[\"/audit list view\"]\n SessView[\"/audit/session/{id} flow chart\"]\n Chat -->|event + turn_id| Log\n Sched --> Log\n Inbound --> Log\n Log --> Priv\n Priv -->|swallow errors, never block| DB\n DB --> Gate\n Gate --> ListView\n Gate --> SessView\n class Chat entry\n class Sched entry\n class Inbound entry\n class Log compute\n class Priv compute\n class DB storage\n class Gate compute\n class ListView hot\n class SessView hot",- "generated_at": "2026-09-26T11:18:25Z"+ "generated_at": "2026-09-26T16:34:35Z"}diff --git a/packages/core/openexecutive/architecture/prebuilt/delegation.json b/packages/core/openexecutive/architecture/prebuilt/delegation.jsonindex 830204ce..0b04a8df 100644--- a/packages/core/openexecutive/architecture/prebuilt/delegation.json+++ b/packages/core/openexecutive/architecture/prebuilt/delegation.json@@ -1,7 +1,7 @@{"section_id": "delegation","title": "Act as Me (Delegation)",- "markdown": "The **delegation** module (`openexecutive.delegation`) is **Act as me**: the one place the Executive writes *as* a person instead of as itself. Everywhere else it has its own Google account and bots and signs as itself. Here, and only when the person asks, it writes an email in their voice and saves it as a **draft in their own Gmail** for them to review and send. This phase only drafts — nothing in the module can send — and only the principal can turn it on. It is off by default, and off changes nothing: the prompts, tool lists and prompt caches are byte-identical to an install without it.\n\n## Who can have it, and when it is offered\n\n`delegation.settings.can_delegate(person)` is the single rule for who may turn it on: for now, the principal (a non-archived team member flagged `is_principal`). The rails a teammate's mailbox would need don't exist yet — audit rows private to *that* person (a row is either visible to every signed-in user or private to the principal), principal-only guards on the persona and Council edit routes, and per-seat Gmail credentials. So everything is keyed by `person_id`, and widening that one function is what the teammate phase changes. A person turns it on for themselves (`PUT /delegation`); nobody turns it on for anyone else. The setting is one row per person in `delegation_settings`, and a missing, unreadable or zero row all mean off.\n\nAt the start of every chat turn (`Executive.stream_chat` and the committee path) `pin_turn_delegation(session, speaker_text)` runs next to the workspace-mode pin and records a `TurnDelegation` on the session. `ghostwrite_email` is **offered** only when all of these hold:\n\n- the speaker may have it and turned it on — read fresh every turn, so turning it off applies from the next message;\n- the speaker is the principal on a surface that verified it is them (`people_tools.is_principal_on_verified_surface`), and a web turn also carried a signed-in caller (`Session.web_caller_signed_in`, set from `x-caller-email`) or runs under local login — a request with no caller header is not a sign-in and never gets it (whoever holds the shared secret is trusted as the UI proxy that stamps that header, as on every principal-only route);\n- the conversation is private to the speaker: the web chat, a Slack or Discord DM, or a verified private Telegram chat — never a shared channel or thread, where the draft's preview or the matching threads would be posted for everyone and other people's messages sit in the model's context;\n- the turn is neither unattended (the scheduler's proactive run) nor private to the principal (the email poller's turns), so inbound text can never reach it. The MCP server, workflows, reflection and research never carry it at all.\n\nThe Gmail connection is deliberately **not** part of the offer: the handler checks it on every call and says how to fix it, so the cached tool prefix never flips when a token lapses. The pin lives in a context variable for the turn's task as well as on the session, so two turns running at once on one session (a second browser tab) each read their own. It also carries the speaker's own words for the turn (a new email may go to an address they just typed — the turn's message joins the history only once the turn ends), a per-turn draft count, and `touched_mail` (see Privacy).\n\n## The tool: `ghostwrite_email`\n\nIt lives in its own registry (`orchestrator.delegation_tools.DELEGATION_TOOLS` / `DELEGATION_TOOL_HANDLERS`), **never** `_ALL_SKILL_TOOLS`, so no other toolkit can carry it. On a turn it is offered to, the agent loop adds it to the pool *before* the sort and builds that turn's handler map from both registries; on any other turn a call to it is an unknown tool. The handler re-checks the pin and the surface anyway, then:\n\n1. **Caps** — at most 5 drafts per turn, and `DELEGATION_MAX_DRAFTS_PER_DAY` (default 50, at most 1000) per person per UTC day, counted from its own `delegation_drafted` audit rows, with a count kept in the process as a floor in case an audit row was lost. Each slot is taken before the first await — a round's tool calls run concurrently, so otherwise every call in it would pass the caps before any counted — and handed back if nothing was drafted. If the rows can't be read it refuses rather than guess.\n2. **Marks the turn** — sets `TurnDelegation.touched_mail` *before* its first read of the mailbox.\n3. **Checks the mailbox** — `gmail_status` asks Google whose mailbox the credential opens and compares it with the person's People email, on every call: a roster email can change, and a client slot swaps the roster.\n4. **Finds the thread** — by `thread_id`, or a Gmail search (`find`). Several matches return `{status: \"choose\", candidates}` (subject, sender and date — no message text) and draft nothing; none returns `not_found`.\n5. **Sets the recipients in code**, never from the model. A reply goes to the last inbound message's `From` — never its `Reply-To` (a different one is flagged `reply_to_ignored`) — with the thread's other recipients only on `reply_all`. A new email goes only to someone on the roster (contacts only when `contacts_reachable_now()`), or to an address the speaker typed this turn. Mailing-list mail, a thread they replied to last and a reply-all trimmed to 10 recipients are flagged. An address inside a block an adapter added to their message (the backstory hydrated into a DM) is not one they typed, and when the message carries an attachment — a document's inlined text, or a note naming the file — none of its addresses count: neither has an end mark, and a filename is chosen by whoever sent the file. They give the address in a message of its own.\n6. **Writes it** (the ghostwriter, below) and saves it with `DelegateGmail.create_draft`, threaded with `In-Reply-To`, `References` (whole message ids: when the chain is too long for one header the oldest after the thread's first go, never the parent) and `threadId`, and stamped `X-OE-Ghostwritten`.\n\nThe result is `{status: \"drafted\", draft_id, gmail_link, to, cc, subject, preview, flags, open_questions, note}`. The link is built server-side from a fixed Gmail prefix, and the note tells the model the preview is the person's draft, to be treated as data. The chat shows an action chip — \"Drafted an email as you to … — in your Gmail Drafts\" — that opens it in Gmail. A sincere \"are you an AI?\" in the thread comes back as an open question for the person to answer themselves.\n\n## The ghostwriter\n\n`delegation.ghostwriter.compose` writes the text. The Executive decides *what* to say (`intent`); this call decides *how* the person would say it, and it is deliberately small:\n\n- a constant `GHOSTWRITER_PROMPT` plus the person's voice block as the system prompt;\n- the thread (each message cut to its sender's own words, every line scrubbed), the intent and the recipients' names in the user turn — no company profile, memory or roster;\n- **no tools** but the forced `compose_reply` return, so text in the thread can ask for anything and there is nothing to do it with.\n\nIt is not a Council agent — the Council's edit routes have no principal check — and runs on `DELEGATION_COMPOSER_MODEL` (default: the default model), logged as `ghostwriter` usage. `lint` then runs in code on what comes back: a link or an email address survives only if it appears in the intent, the signature or the recipients, so a link planted in the thread is removed and flagged; the Executive's own name is flagged; and the body is capped, cut at a paragraph, line or word break in its last fifth. A draft with nothing left after that is refused. The signature from the person's Gmail settings is appended.\n\n## How I write\n\n`delegation.voice` learns how a person writes *their own* email (`attunement.style` learns how the Executive should write *to* someone). `POST /delegation/voice/learn` reads up to 40 recent sent messages, keeps only what they wrote (quoted replies stripped with the email poller's `sender_new_text`), skips automatic mail and every thread it drafted into, and makes one forced-tool call (`record_voice_profile`). Code validates every field before it is stored:\n\n- greetings per audience (their team, their contacts, anyone else), a sign-off, and a usual length and tone;\n- up to 8 habits and 6 things to avoid, through the same deny-list as working-style rules — no actions, links, handles, amounts, tool names or names of people;\n- up to 3 short exemplars, each checked to be verbatim from a sample, with addresses and phone numbers masked — and none while a client slot is active, so one client's mail never lands in another's state.\n\nThe signature comes from Gmail's `sendAs` settings, not the model. The person can edit it, lock it (a locked profile is never relearned) and reset it, and every change is kept in `delegation_voice_history`. One learn runs at a time per person, and a lock or an edit made while it runs wins: the learned profile is dropped (`changed`).\n\n## The mailbox client\n\n`delegation.gmail.DelegateGmail` talks to the Gmail REST API directly and is **never registered with the MCP gateway**, so the model reaches the mailbox only through the typed handler. The credential is one file per person in `DELEGATION_GOOGLE_CREDENTIALS_DIR`, named from a hash of the address (0600 in a 0700 directory), minted by `scripts/connect-own-gmail.py` on the Executive's own OAuth client with the scopes `gmail.readonly` and `gmail.compose`. It never lives in `WORKSPACE_MCP_CREDENTIALS_DIR`, where workspace-mcp picks a credential by address. There is **no send method** — a unit test fails if one appears.\n\n`gmail_status` answers `connected`, `not_configured`, `needs_reconnect` (Google refused the saved sign-in — an app in Testing mode has its tokens expire after 7 days; a rate limit, though Gmail may send it as a 403, is an `error` to retry, not a reconnect), `mismatch`, `no_email`, `shared_mailbox` or `error`. `shared_mailbox` means the person's address *is* the Executive's; it is refused before asking Google, because then everything the Executive writes would look like theirs. The gateway closes the other door: every `google_workspace__*` call must act as the Executive's own account, and a `user_google_email` naming anyone else is refused and audited (see Integrations).\n\n## Privacy\n\nOnce `touched_mail` is set, every audit row the turn writes is private to the principal (`people_tools.audit_row_private_to_principal`): the tool row (its input and result redacted, since `ghostwrite` is a sensitive tool name), the reply's `chat_turn` row that carries the preview, the model-call rows, and the background passes, which run under `private_rows`. The Honcho peer and department syncs are skipped, because peer memory is read on other people's turns. No memory is learned from the turn at all: the episodic, open-loop and working-style passes are skipped too, since its reply quotes a draft built from other people's mail. The four `delegation_*` audit events are always private and carry metadata only — ids, counts and flags, never the draft or the thread.\n\n## The system prompt\n\nA constant, name-free `DELEGATION_ADDENDUM` joins block 0 after the unchanged identity addendum while anyone on the install has it on (`block0_delegation_on`). It tells the model that `ghostwrite_email` is the single exception to *never impersonate*, and only for the person being spoken to; that everything else is written as itself; that when the tool isn't offered the asker can't have it; that a draft is never described as sent; and that it never denies being an AI. It is keyed on the install-level setting, never on the turn or the speaker, so switching it misses the 1h cache once (see Prompt Caching).\n\n## Surfaces\n\n- **Settings → Act as me** (`ActAsMeCard`, hidden unless `GET /delegation` answers): the Gmail connection with the connect command and **Check again**, the **Write drafts as me** switch, and **How I write**.\n- **Setup status**: a **Your own Gmail (Act as me)** light (`your_gmail`).\n- **API**: `GET`/`PUT /delegation`, `GET`/`PUT`/`DELETE /delegation/voice` and `POST /delegation/voice/learn` — the caller's own delegation only (see API Reference).\n- **Evals**: a scenario's `delegation:` block runs the turn against an in-memory mailbox (`evals.mailbox.ScenarioMailbox`) and hands the saved drafts to the judge (`delegation_001`–`003`).\n\nSending — after a tap, or within rules the person sets — and teammates having their own are later, separate changes, each behind its own switch, off by default.",+ "markdown": "The **delegation** module (`openexecutive.delegation`) is **Act as me**: the one place the Executive writes *as* a person instead of as itself. Everywhere else it has its own Google account and bots and signs as itself. Here, and only when the person asks, it writes an email in their voice and saves it as a **draft in their own Gmail** for them to review and send. This phase only drafts — nothing in the module can send — and only the principal can turn it on. It is off by default, and off changes nothing: the prompts, tool lists and prompt caches are byte-identical to an install without it.\n\n## Who can have it, and when it is offered\n\n`delegation.settings.can_delegate(person)` is the single rule for who may turn it on: for now, the principal (a non-archived team member flagged `is_principal`). The rails a teammate's mailbox would need don't exist yet — audit rows private to *that* person (a row is either visible to every signed-in user or private to the principal), principal-only guards on the persona and Council edit routes, and per-seat Gmail credentials. So everything is keyed by `person_id`, and widening that one function is what the teammate phase changes. A person turns it on for themselves (`PUT /delegation`); nobody turns it on for anyone else. The setting is one row per person in `delegation_settings`, and a missing, unreadable or zero row all mean off.\n\nAt the start of every chat turn (`Executive.stream_chat` and the committee path) `pin_turn_delegation(session, speaker_text)` runs next to the workspace-mode pin and records a `TurnDelegation` on the session. `ghostwrite_email` is **offered** only when all of these hold:\n\n- the speaker may have it and turned it on — read fresh every turn, so turning it off applies from the next message;\n- the speaker is the principal on a surface that verified it is them (`people_tools.is_principal_on_verified_surface`), and a web turn also carried a signed-in caller (`Session.web_caller_signed_in`, set from `x-caller-email`) or runs under local login — a request with no caller header is not a sign-in and never gets it (whoever holds the shared secret is trusted as the UI proxy that stamps that header, as on every principal-only route);\n- the conversation is private to the speaker: the web chat, a Slack or Discord DM, or a verified private Telegram chat — never a shared channel or thread, where the draft's preview or the matching threads would be posted for everyone and other people's messages sit in the model's context;\n- the turn is neither unattended (the scheduler's proactive run) nor private to the principal (the email poller's turns), so inbound text can never reach it. The MCP server, workflows, reflection and research never carry it at all.\n\nThe Gmail connection is deliberately **not** part of the offer: the handler checks it on every call and says how to fix it, so the cached tool prefix never flips when a token lapses. The pin lives in a context variable for the turn's task as well as on the session, so two turns running at once on one session (a second browser tab) each read their own. It also carries the speaker's own words for the turn (a new email may go to an address they just typed — the turn's message joins the history only once the turn ends), a per-turn draft count, and `touched_mail` (see Privacy).\n\n## The tool: `ghostwrite_email`\n\nIt lives in its own registry (`orchestrator.delegation_tools.DELEGATION_TOOLS` / `DELEGATION_TOOL_HANDLERS`), **never** `_ALL_SKILL_TOOLS`, so no other toolkit can carry it. On a turn it is offered to, the agent loop adds it to the pool *before* the sort and builds that turn's handler map from both registries; on any other turn a call to it is an unknown tool. The handler re-checks the pin and the surface anyway, then:\n\n1. **Caps** — at most 5 drafts per turn, and `DELEGATION_MAX_DRAFTS_PER_DAY` (default 50, at most 1000) per person per UTC day, counted from its own `delegation_drafted` audit rows, with a count kept in the process as a floor in case an audit row was lost. Each slot is taken before the first await — a round's tool calls run concurrently, so otherwise every call in it would pass the caps before any counted — and handed back if nothing was drafted. If the rows can't be read it refuses rather than guess.\n2. **Marks the turn** — sets `TurnDelegation.touched_mail` *before* its first read of the mailbox.\n3. **Checks the mailbox** — `gmail_status` asks Google whose mailbox the credential opens and compares it with the person's People email, on every call: a roster email can change, and a client slot swaps the roster.\n4. **Finds the thread** — by `thread_id`, or a Gmail search (`find`). Several matches return `{status: \"choose\", candidates}` (subject, sender and date — no message text) and draft nothing; none returns `not_found`.\n5. **Sets the recipients in code**, never from the model. A reply goes to the last inbound message's `From` — never its `Reply-To` (a different one is flagged `reply_to_ignored`) — with the thread's other recipients only on `reply_all`. A new email goes only to someone on the roster (contacts only when `contacts_reachable_now()`), or to an address the speaker typed this turn. Mailing-list mail, a thread they replied to last and a reply-all trimmed to 10 recipients are flagged. An address inside a block an adapter added to their message (the backstory hydrated into a DM) is not one they typed, and when the message carries an attachment — a document's inlined text, or a note naming the file — none of its addresses count: neither has an end mark, and a filename is chosen by whoever sent the file. They give the address in a message of its own.\n6. **Writes it** (the ghostwriter, below) and saves it with `DelegateGmail.create_draft`, threaded with `In-Reply-To`, `References` (whole message ids: when the chain is too long for one header the oldest after the thread's first go, never the parent) and `threadId`, and stamped `X-OE-Ghostwritten`.\n\nThe result is `{status: \"drafted\", draft_id, gmail_link, to, cc, subject, preview, flags, open_questions, note}`. The link is built server-side from a fixed Gmail prefix, and the note tells the model the preview is the person's draft, to be treated as data. The chat shows an action chip — \"Drafted an email as you to … — in your Gmail Drafts\" — that opens it in Gmail. A sincere \"are you an AI?\" in the thread comes back as an open question for the person to answer themselves.\n\n## The ghostwriter\n\n`delegation.ghostwriter.compose` writes the text. The Executive decides *what* to say (`intent`); this call decides *how* the person would say it, and it is deliberately small:\n\n- a constant `GHOSTWRITER_PROMPT` plus the person's voice block as the system prompt;\n- the thread (each message cut to its sender's own words, every line scrubbed), the intent and the recipients' names in the user turn — no company profile, memory or roster;\n- **no tools** but the forced `compose_reply` return, so text in the thread can ask for anything and there is nothing to do it with.\n\nIt is not a Council agent — the Council's edit routes have no principal check — and runs on `DELEGATION_COMPOSER_MODEL` (default: the default model), logged as `ghostwriter` usage. `lint` then runs in code on what comes back: a link or an email address survives only if it appears in the intent, the signature or the recipients, so a link planted in the thread is removed and flagged; the Executive's own name is flagged; and the body is capped, cut at a paragraph, line or word break in its last fifth. A draft with nothing left after that is refused. The signature from the person's Gmail settings is appended.\n\n## How I write\n\n`delegation.voice` learns how a person writes *their own* email (`attunement.style` learns how the Executive should write *to* someone). `POST /delegation/voice/learn` reads up to 40 recent sent messages, keeps only what they wrote (quoted replies stripped with the email poller's `sender_new_text`), skips automatic mail and every thread it drafted into, and makes one forced-tool call (`record_voice_profile`). Code validates every field before it is stored:\n\n- greetings per audience (their team, their contacts, anyone else), a sign-off of at most two lines, and a usual length and tone (a backslash-n the model wrote instead of a line break is read as one, keeping the first lines that fit, which also repairs a profile stored before that rule);\n- up to 8 habits and 6 things to avoid, through the same deny-list as working-style rules — no actions, links, handles, amounts, tool names or names of people;\n- up to 3 short exemplars, each checked to be verbatim from a sample, with addresses and phone numbers masked — and none while a client slot is active, so one client's mail never lands in another's state.\n\nThe signature comes from Gmail's `sendAs` settings, not the model, as plain text with its lines kept (`gmail.html_to_text`: a `<br>` always ends a line, and a block tag, opening or closing, ends one when it has text, so Gmail's layout of a first line followed by one `<div>` per line comes out line by line). `POST /delegation/voice/signature` reads it again without relearning: nothing else changes and a locked profile stays locked, so it picks up a changed Gmail signature and undoes **Don't add my signature**. The person can edit the profile, lock it (a locked profile is never relearned) and reset it, and every change is kept in `delegation_voice_history`. One learn runs at a time per person, and a lock or an edit made while it runs wins: the learned profile is dropped (`changed`).\n\n## The mailbox client\n\n`delegation.gmail.DelegateGmail` talks to the Gmail REST API directly and is **never registered with the MCP gateway**, so the model reaches the mailbox only through the typed handler. The credential is one file per person in `DELEGATION_GOOGLE_CREDENTIALS_DIR`, named from a hash of the address (0600 in a 0700 directory), minted by `scripts/connect-own-gmail.py` on the Executive's own OAuth client with the scopes `gmail.readonly` and `gmail.compose`. It never lives in `WORKSPACE_MCP_CREDENTIALS_DIR`, where workspace-mcp picks a credential by address. There is **no send method** — a unit test fails if one appears.\n\n`gmail_status` answers `connected`, `not_configured`, `needs_reconnect` (Google refused the saved sign-in — an app in Testing mode has its tokens expire after 7 days; a rate limit, though Gmail may send it as a 403, is an `error` to retry, not a reconnect), `mismatch`, `no_email`, `shared_mailbox` or `error`. `shared_mailbox` means the person's address *is* the Executive's; it is refused before asking Google, because then everything the Executive writes would look like theirs. The gateway closes the other door: every `google_workspace__*` call must act as the Executive's own account, and a `user_google_email` naming anyone else is refused and audited (see Integrations).\n\n## Privacy\n\nOnce `touched_mail` is set, every audit row the turn writes is private to the principal (`people_tools.audit_row_private_to_principal`): the tool row (its input and result redacted, since `ghostwrite` is a sensitive tool name), the reply's `chat_turn` row that carries the preview, the model-call rows, and the background passes, which run under `private_rows`. The Honcho peer and department syncs are skipped, because peer memory is read on other people's turns. No memory is learned from the turn at all: the episodic, open-loop and working-style passes are skipped too, since its reply quotes a draft built from other people's mail. The four `delegation_*` audit events are always private and carry metadata only — ids, counts and flags, never the draft or the thread.\n\n## The system prompt\n\nA constant, name-free `DELEGATION_ADDENDUM` joins block 0 after the unchanged identity addendum while anyone on the install has it on (`block0_delegation_on`). It tells the model that `ghostwrite_email` is the single exception to *never impersonate*, and only for the person being spoken to; that everything else is written as itself; that when the tool isn't offered the asker can't have it; that a draft is never described as sent; and that it never denies being an AI. It is keyed on the install-level setting, never on the turn or the speaker, so switching it misses the 1h cache once (see Prompt Caching).\n\n## Surfaces\n\n- **Settings → Act as me** (`ActAsMeCard`, hidden unless `GET /delegation` answers): the Gmail connection with the connect command and **Check again**, the **Write drafts as me** switch, and **How I write**: length and tone, a greeting per audience (`{first}` is their first name), the sign-off, habits and never-rules in fields that grow to show every line, the signature with **Refresh from Gmail** and **Don't add my signature** (or **Add my Gmail signature** when none is added), and each example quoted with **Remove examples**.\n- **Setup status**: a **Your own Gmail (Act as me)** light (`your_gmail`).\n- **API**: `GET`/`PUT /delegation`, `GET`/`PUT`/`DELETE /delegation/voice`, `POST /delegation/voice/learn` and `POST /delegation/voice/signature` — the caller's own delegation only (see API Reference).\n- **Evals**: a scenario's `delegation:` block runs the turn against an in-memory mailbox (`evals.mailbox.ScenarioMailbox`) and hands the saved drafts to the judge (`delegation_001`–`003`).\n\nSending — after a tap, or within rules the person sets — and teammates having their own are later, separate changes, each behind its own switch, off by default.","mermaid": "flowchart TD\n Ask[\"Principal on a verified surface<br/>'reply to Dana as me: yes'\"] --> Pin[\"pin_turn_delegation<br/>on? principal? verified? private? attended?\"]\n Pin -->|\"offered\"| Loop[\"Executive tool loop<br/>with ghostwrite_email\"]\n Pin -->|\"not offered\"| Self[\"writes as itself<br/>(unknown tool this turn)\"]\n Loop --> Tool[\"ghostwrite_email handler<br/>caps, mailbox check, recipients in code\"]\n Tool -->|\"touched_mail\"| Private[\"turn's audit rows private<br/>no memory learned\"]\n Tool --> Client[\"DelegateGmail<br/>REST, outside the MCP gateway\"]\n Client --> Box[(\"Principal's own Gmail\")]\n Voice[(\"delegation_voice<br/>How I write\")] --> Gw[\"ghostwriter<br/>no tools: voice + intent + thread\"]\n Tool --> Gw\n Gw --> Lint[\"lint: links and addresses<br/>only from the intent\"]\n Lint --> Draft[\"create_draft, threaded<br/>nothing is sent\"]\n Draft --> Box\n Draft --> Chip[\"chat chip: open in Gmail\"]\n class Ask entry\n class Pin compute\n class Loop compute\n class Self compute\n class Tool compute\n class Private compute\n class Client compute\n class Box external\n class Voice storage\n class Gw compute\n class Lint compute\n class Draft hot\n class Chip entry",- "generated_at": "2026-09-26T11:39:09Z"+ "generated_at": "2026-09-26T16:58:34Z"}diff --git a/packages/core/openexecutive/audit/logger.py b/packages/core/openexecutive/audit/logger.pyindex eb403e7e..64e0b703 100644--- a/packages/core/openexecutive/audit/logger.py+++ b/packages/core/openexecutive/audit/logger.py@@ -76,7 +76,7 @@ EVENT_TYPES: tuple[str, ...] = (# Act as me (delegation/) — every one written private to the principal."delegation_settings_changed", # a person turned Act as me on or off (PUT /delegation)"delegation_gmail_verified", # a person's own Gmail was checked and found usable when turning it on- "delegation_voice_changed", # "How I write" learned, edited, locked or reset+ "delegation_voice_changed", # "How I write" learned, edited, locked, reset or its signature re-read"delegation_drafted", # ghostwrite_email saved a draft in a person's own Gmail)diff --git a/packages/core/openexecutive/delegation/gmail.py b/packages/core/openexecutive/delegation/gmail.pyindex 0060b99d..bde88849 100644--- a/packages/core/openexecutive/delegation/gmail.py+++ b/packages/core/openexecutive/delegation/gmail.py@@ -252,17 +252,82 @@ def _headers(payload: dict[str, Any]) -> dict[str, str]:return out-_TAG_RE = re.compile(r"<[^>]+>")-_BLOCK_TAG_RE = re.compile(r"(?i)<\s*(br|/p|/div|/li|/tr|/h\d)\b[^>]*>")-_SCRIPT_RE = re.compile(r"(?is)<(script|style)\b.*?</\1\s*>")+# Everything here runs on mail anyone can send, on the event loop, so each step+# is one forward pass: these patterns end at the next "<" as well as at ">",+# and no two quantifiers compete for the same characters.+_BR_RE = re.compile(r"(?i)<\s*(?:/\s*)?br\b[^<>]*>")+# Opening and closing tags alike: Gmail puts a signature's first line straight+# in its outer <div> and each later line in a <div> of its own.+_BLOCK_EDGE_RE = re.compile(+ r"(?i)<\s*(?:/\s*)?(?:address|article|aside|blockquote|center|dd|div|dl|dt|figcaption|figure|"+ r"footer|h[1-6]|header|hr|li|main|nav|ol|p|pre|section|table|tr|ul)\b[^<>]*>"+)+_HIDDEN = {+ name: (re.compile(rf"(?i)<{name}\b"), re.compile(rf"(?i)</{name}\s*>")) for name in ("script", "style")+}+_DECIMAL_REF_RE = re.compile(r"&#(\d+)(;?)")+_EDGE = "\x00"+++def _strip_tags(text: str) -> str:+ """``text`` without its tags — each "<" through the next ">", with+ something between — in one forward pass."""+ out: list[str] = []+ at = 0+ while (lt := text.find("<", at)) != -1:+ gt = text.find(">", lt + 1)+ if gt == -1:+ break # nothing after this closes a tag+ out.append(text[at:gt + 1] if gt == lt + 1 else text[at:lt])+ at = gt + 1+ out.append(text[at:])+ return "".join(out)+++def _short_decimal_ref(match: re.Match[str]) -> str:+ # html.unescape turns the digits into an int, and Python refuses more than+ # 4,300 of them (ValueError). Beyond seven significant digits the value is+ # past Unicode's range, which unescape reads as U+FFFD anyway.+ digits = match.group(1).lstrip("0") or "0"+ return "�" if len(digits) > 7 else f"&#{digits}{match.group(2)}"+++def _drop_hidden(markup: str) -> str:+ """``markup`` without its ``<script>`` and ``<style>`` elements, in one+ pass each: an element nothing closes is left for the tag strip."""+ for opening, closing in _HIDDEN.values():+ out: list[str] = []+ at = 0+ while (start := opening.search(markup, at)) is not None:+ end = closing.search(markup, start.end())+ if end is None:+ break+ out.append(markup[at:start.start()])+ at = end.end()+ out.append(markup[at:])+ markup = "".join(out)+ return markupdef html_to_text(markup: str) -> str:- """Plain text from an HTML body or signature (line breaks kept)."""- text = _SCRIPT_RE.sub("", markup)- text = _BLOCK_TAG_RE.sub("\n", text)- text = html.unescape(_TAG_RE.sub("", text))- lines = [ln.rstrip() for ln in text.splitlines()]+ """Plain text from an HTML body or signature. A ``<br>`` (or a line break+ in the markup) always ends a line; a block's opening or closing tag ends+ one only when it has text, so ``</div><div>`` is a single break and+ ``<div><br></div>`` a blank line."""+ text = _drop_hidden(markup.replace(_EDGE, ""))+ text = _BLOCK_EDGE_RE.sub(_EDGE, _BR_RE.sub("\n", text))+ text = html.unescape(_DECIMAL_REF_RE.sub(_short_decimal_ref, _strip_tags(text)))+ out: list[str] = []+ has_text = False+ for piece in re.split(f"({_EDGE}|\n)", text):+ if piece == "\n" or (piece == _EDGE and has_text):+ out.append("\n")+ has_text = False+ elif piece != _EDGE:+ out.append(piece)+ # Only markup whitespace: a line of is a line the reader sees.+ has_text = has_text or bool(piece.strip(" \t\r\n\f\v"))+ lines = [ln.rstrip() for ln in "".join(out).splitlines()]return re.sub(r"\n{3,}", "\n\n", "\n".join(lines)).strip()diff --git a/packages/core/openexecutive/delegation/voice.py b/packages/core/openexecutive/delegation/voice.pyindex 440cff71..394e2222 100644--- a/packages/core/openexecutive/delegation/voice.py+++ b/packages/core/openexecutive/delegation/voice.py@@ -31,6 +31,7 @@ import jsonimport loggingimport reimport sqlite3+import unicodedatafrom dataclasses import asdict, dataclass, fieldfrom datetime import UTC, datetime, timedeltafrom pathlib import Path@@ -282,15 +283,29 @@ def rule_rejection(text: str, *, roster_names: list[str] | None = None) -> str |def _short_text(value: object, cap: int, *, lines: int) -> str | None:"""A greeting or sign-off: at most ``lines`` short lines with no link,handle, amount or markup (``{first}`` is the one allowed placeholder).- None when it does not pass; "" for empty."""+ None when it does not pass; "" for empty.++ A literal backslash-n is a line break: a model can write the escape+ rather than the break, and a stored profile is repaired as it is read.+ Such a value keeps its first ``lines`` lines rather than being lost; a+ typed one with too many lines is refused. The escape is read after+ normalizing (NFKC can make a backslash, and dropping a control character+ can join one to an "n"), so what is stored reads back the same."""if value is None:return ""if not isinstance(value, str):return None- parts = [_normalize(p) for p in value.replace("\r", "").split("\n")]+ text = "".join(+ ch for ch in unicodedata.normalize("NFKC", value)+ if ch == "\n" or unicodedata.category(ch) not in ("Cc", "Cf")+ )+ escaped = "\\n" in text+ parts = [_normalize(p) for p in text.replace("\\n", "\n").split("\n")]parts = [p for p in parts if p]if not parts:return ""+ if len(parts) > lines and escaped:+ parts = parts[:lines]if len(parts) > lines or any(len(p) > cap for p in parts):return Nonejoined = "\n".join(parts)@@ -394,8 +409,9 @@ one of their contacts, or someone else.Return, through record_voice_profile:- greetings: how they usually open, per audience ("Hi {first}," — use \{first} for the recipient's first name). Leave an audience out if unclear.-- sign_off: how they usually close (for example "Best,\\nJane"), without \-their signature block.+- sign_off: how they usually close, without their signature block. When it \+is two lines, such as "Best," with their name on the next line, put a line \+break between them.- length and formality: their usual.- habits: up to 8 short sentences about HOW they write (sentence length, \greetings, punctuation, directness, warmth, structure).diff --git a/packages/core/openexecutive/guide/prebuilt/settings.json b/packages/core/openexecutive/guide/prebuilt/settings.jsonindex 9d29b8e5..0d3dc8ac 100644--- a/packages/core/openexecutive/guide/prebuilt/settings.json+++ b/packages/core/openexecutive/guide/prebuilt/settings.json@@ -1,7 +1,7 @@{"section_id": "settings","title": "Settings & Advanced",- "markdown": "**What it is:** The hub for power-user and admin tools that were pulled out of the day-to-day nav to keep it focused.\n\n**What it does:**\n\n- Links to Setup status, the Agent Council, Audit Log, Token Usage, this User Guide, the Architecture reference, Company Simulator, and Client Companies.\n- Acts as a directory — each tile opens a dedicated screen.\n- Keeps advanced configuration one click away without cluttering the main workspace.\n- Shows whether the Executive is **running** or **paused**, with a switch to pause or resume it.\n- Holds the **Workspace** card: whether you use Open Executive just for yourself or with your team, your role when it's just you, your time zone, and whether the Executive books meetings without asking.\n- Holds the **Act as me** card, where the owner can let the Executive write email drafts as them, in their own voice, from their own Gmail.\n\n**How to use:**\n\n1. Click **Settings** at the bottom of the sidebar.\n2. Click the tile for what you want to do:\n - **Setup status** — check that every part of your setup is working, and see what to do about anything that isn't.\n - **Agent Council** — change a specialist's model or prompt, or the Executive's voice.\n - **Audit log** — find out what the Executive did, and why.\n - **Token usage** — see what you're spending and where.\n - **User Guide** — this guide.\n - **Architecture** — the technical reference for how the system is built.\n - **Company Simulator** — try the Executive on a test company.\n - **Client Companies** — switch between clients if you do fractional work.\n\n**Checking your setup:**\n\n- Open **Settings → Setup status**. Each part of your setup gets a light: green is working, amber needs attention, red isn't working, grey isn't set up (and is optional).\n- It tests things for real: the AI key, and each chat app's token, with a quick call that sends nothing. It also checks the Executive's email address, the company setup, the daily schedule, when and where your daily brief goes, and whether anyone on your team list can reach each chat app.\n- Anything that isn't green says what to do in plain words, with a button when the fix is on another page. After you change a setting and restart the app, click **Check again**.\n\n**Workspace:**\n\n- **Using Open Executive** — **Just me** or **With your team**. You pick this when you first set up; change it here. Switching asks you to confirm and says what changes:\n - **Just me** pauses department check-ins and shows **Goals** (grouped by area) in the sidebar instead of Departments. Nothing is deleted — your departments stay, as the areas your goals are grouped by.\n - **With your team** brings back Departments and their daily check-ins, and the People and department cards on the Briefing.\n- **Your role** (just you) — which describes you best (**Owner / founder**, **Executive inside an organisation**, **Independent or fractional**, or **Other**), your title, who you report to, what you're responsible for and what you're measured on. Every field is optional; click **Save role** after editing. The Executive uses it to fit its advice to your job — a VP gets help making the case to their boss, an owner gets help with a call that's theirs alone to make. It stays saved if you switch to your team.\n- **Time zone** — when your morning brief, end-of-day digest and reflection arrive, and how the Executive reads \"tomorrow at 9\". It suggests the zone your browser is in; **Follow server default** uses the server's setting.\n- **Book meetings without asking** — when on, the Executive books meetings on your calendar on its own; when off, each booking waits for your approval on the Briefing. (Shown only when your install supports it.)\n- Only the principal can change the mode, role and time zone. A persona you customised in Council stays in place in either mode.\n\n**Act as me:**\n\n- Normally the Executive writes only as itself, from its own email account. **Act as me** lets it write an email *as you*: ask in chat — \"reply to Dana as me: yes to the 5th\" — and it saves a draft in **your own Gmail Drafts** for you to read, change and send. It never sends anything itself, and everything else it writes stays in its own name.\n- For now only the owner (the principal) sees this card. It works when you ask in the web app, in a direct message to the Executive on Slack or Discord, or in a verified private Telegram chat — never in a shared channel or thread, from an email, a scheduled job or anyone else's conversation.\n- **Your Gmail** — connect your own Gmail first. The card shows the command to run on a computer with a browser; sign in as yourself, put the file it writes where your install reads it, then click **Check again**. It won't connect the Executive's own address as yours.\n- **Write drafts as me** — the switch. It stays off until your Gmail is connected, and turning it off applies from your next message.\n- **How I write** — click **Learn from my sent mail** and it reads your recent sent emails once and describes how you write: your usual **Length** and **Tone**, your greetings, your **Sign-off**, your **Habits** and what you **Never** do. Change the length, tone, sign-off, habits or nevers and click **Save changes**; **Lock** keeps it exactly as it is; **Reset** starts over. Your Gmail signature is added to every draft unless you click **Don't add my signature**.\n- In chat you get a card, \"Drafted an email as you to …\", that opens the draft in Gmail. If the Executive isn't sure about something, it asks you instead of guessing.\n\n**Setting up just for yourself:**\n\n- The first time you set up, Open Executive asks who it is for — **Just me** or **Me and my team** — before anything else, and saves your time zone from the browser. Re-running setup later skips this; change the mode here instead.\n- **Just me** is for anyone who uses Open Executive just for themselves, whatever their role: your own business, a team you lead inside an organisation, or clients you advise as an independent or fractional executive.\n- Choosing **Just me** then asks **What's your role?** — the same fields as **Your role** above. Fill in what you like, or click **Skip for now**.\n- Just for yourself, the setup conversation asks about your work rather than your team, following the role you gave: an owner about what you offer, your customers, pricing, cash and runway; an executive inside an organisation about that organisation (it becomes your company profile), what you're responsible for, who you report to and what you're measured on; an independent about your practice and clients. Everyone is asked about their goals. On **Here's what I understood** there is a single **You** card (your name and role) next to **Your sign-in email**, instead of the team and department lists.\n- The step-by-step form skips the team size, team members and fractional executives steps.\n- In the sidebar, **You** holds **Goals**, **People** and your profile: **Business profile** if you own the business, **Your work** for any other role (or none). The profile page follows the same choice: for any other role it is worded around the organisation you work in (**Where You Work** in place of Company Basics). Either way departments are listed there as **Areas**, and your title, who you report to and what you're responsible for stay under **Your role** above.\n\n**Pausing the Executive:**\n\n- Click **Executive running** at the bottom of the sidebar (or use the card at the top of Settings), add a reason if you like, and click **Pause Executive**.\n- While paused, the Executive starts nothing on its own: no briefs, nudges, monitoring, inbox processing or workflow timers. An amber banner appears on every page.\n- Chat and direct messages (Slack, Telegram, Discord, Google Chat) still get answers.\n- Nothing is lost. Work that falls due during the pause waits, and runs when you click **Resume**. The switch shows how many actions are waiting.\n- Anyone who can sign in can pause the Executive, but only the principal can resume it.\n\n*Tip: if you're looking for a feature that isn't in the sidebar, it's probably here. This guide is also pinned next to Settings at the bottom of the nav.*",+ "markdown": "**What it is:** The hub for power-user and admin tools that were pulled out of the day-to-day nav to keep it focused.\n\n**What it does:**\n\n- Links to Setup status, the Agent Council, Audit Log, Token Usage, this User Guide, the Architecture reference, Company Simulator, and Client Companies.\n- Acts as a directory — each tile opens a dedicated screen.\n- Keeps advanced configuration one click away without cluttering the main workspace.\n- Shows whether the Executive is **running** or **paused**, with a switch to pause or resume it.\n- Holds the **Workspace** card: whether you use Open Executive just for yourself or with your team, your role when it's just you, your time zone, and whether the Executive books meetings without asking.\n- Holds the **Act as me** card, where the owner can let the Executive write email drafts as them, in their own voice, from their own Gmail.\n\n**How to use:**\n\n1. Click **Settings** at the bottom of the sidebar.\n2. Click the tile for what you want to do:\n - **Setup status** — check that every part of your setup is working, and see what to do about anything that isn't.\n - **Agent Council** — change a specialist's model or prompt, or the Executive's voice.\n - **Audit log** — find out what the Executive did, and why.\n - **Token usage** — see what you're spending and where.\n - **User Guide** — this guide.\n - **Architecture** — the technical reference for how the system is built.\n - **Company Simulator** — try the Executive on a test company.\n - **Client Companies** — switch between clients if you do fractional work.\n\n**Checking your setup:**\n\n- Open **Settings → Setup status**. Each part of your setup gets a light: green is working, amber needs attention, red isn't working, grey isn't set up (and is optional).\n- It tests things for real: the AI key, and each chat app's token, with a quick call that sends nothing. It also checks the Executive's email address, the company setup, the daily schedule, when and where your daily brief goes, and whether anyone on your team list can reach each chat app.\n- Anything that isn't green says what to do in plain words, with a button when the fix is on another page. After you change a setting and restart the app, click **Check again**.\n\n**Workspace:**\n\n- **Using Open Executive** — **Just me** or **With your team**. You pick this when you first set up; change it here. Switching asks you to confirm and says what changes:\n - **Just me** pauses department check-ins and shows **Goals** (grouped by area) in the sidebar instead of Departments. Nothing is deleted — your departments stay, as the areas your goals are grouped by.\n - **With your team** brings back Departments and their daily check-ins, and the People and department cards on the Briefing.\n- **Your role** (just you) — which describes you best (**Owner / founder**, **Executive inside an organisation**, **Independent or fractional**, or **Other**), your title, who you report to, what you're responsible for and what you're measured on. Every field is optional; click **Save role** after editing. The Executive uses it to fit its advice to your job — a VP gets help making the case to their boss, an owner gets help with a call that's theirs alone to make. It stays saved if you switch to your team.\n- **Time zone** — when your morning brief, end-of-day digest and reflection arrive, and how the Executive reads \"tomorrow at 9\". It suggests the zone your browser is in; **Follow server default** uses the server's setting.\n- **Book meetings without asking** — when on, the Executive books meetings on your calendar on its own; when off, each booking waits for your approval on the Briefing. (Shown only when your install supports it.)\n- Only the principal can change the mode, role and time zone. A persona you customised in Council stays in place in either mode.\n\n**Act as me:**\n\n- Normally the Executive writes only as itself, from its own email account. **Act as me** lets it write an email *as you*: ask in chat — \"reply to Dana as me: yes to the 5th\" — and it saves a draft in **your own Gmail Drafts** for you to read, change and send. It never sends anything itself, and everything else it writes stays in its own name.\n- For now only the owner (the principal) sees this card. It works when you ask in the web app, in a direct message to the Executive on Slack or Discord, or in a verified private Telegram chat — never in a shared channel or thread, from an email, a scheduled job or anyone else's conversation.\n- **Your Gmail** — connect your own Gmail first. The card shows the command to run on a computer with a browser; sign in as yourself, put the file it writes where your install reads it, then click **Check again**. It won't connect the Executive's own address as yours.\n- **Write drafts as me** — the switch. It stays off until your Gmail is connected, and turning it off applies from your next message.\n- **How I write** — click **Learn from my sent mail** and it reads your recent sent emails once and describes how you write: your usual **Length** and **Tone**, a **Greeting** for your team, your contacts and anyone else ({first} stands for their first name), your **Sign-off**, your **Habits**, what you **Never** do, and a few **Examples of your writing** that set the tone. Change any of them and click **Save changes**; **Lock** stops it being relearned from your mail (you can still edit it); **Reset** starts over; **Remove examples** drops the examples. Your Gmail signature is added to every draft: **Refresh from Gmail** picks up a change you made to it in Gmail, **Don't add my signature** stops adding it, and **Add my Gmail signature** brings it back.\n- In chat you get a card, \"Drafted an email as you to …\", that opens the draft in Gmail. If the Executive isn't sure about something, it asks you instead of guessing.\n\n**Setting up just for yourself:**\n\n- The first time you set up, Open Executive asks who it is for — **Just me** or **Me and my team** — before anything else, and saves your time zone from the browser. Re-running setup later skips this; change the mode here instead.\n- **Just me** is for anyone who uses Open Executive just for themselves, whatever their role: your own business, a team you lead inside an organisation, or clients you advise as an independent or fractional executive.\n- Choosing **Just me** then asks **What's your role?** — the same fields as **Your role** above. Fill in what you like, or click **Skip for now**.\n- Just for yourself, the setup conversation asks about your work rather than your team, following the role you gave: an owner about what you offer, your customers, pricing, cash and runway; an executive inside an organisation about that organisation (it becomes your company profile), what you're responsible for, who you report to and what you're measured on; an independent about your practice and clients. Everyone is asked about their goals. On **Here's what I understood** there is a single **You** card (your name and role) next to **Your sign-in email**, instead of the team and department lists.\n- The step-by-step form skips the team size, team members and fractional executives steps.\n- In the sidebar, **You** holds **Goals**, **People** and your profile: **Business profile** if you own the business, **Your work** for any other role (or none). The profile page follows the same choice: for any other role it is worded around the organisation you work in (**Where You Work** in place of Company Basics). Either way departments are listed there as **Areas**, and your title, who you report to and what you're responsible for stay under **Your role** above.\n\n**Pausing the Executive:**\n\n- Click **Executive running** at the bottom of the sidebar (or use the card at the top of Settings), add a reason if you like, and click **Pause Executive**.\n- While paused, the Executive starts nothing on its own: no briefs, nudges, monitoring, inbox processing or workflow timers. An amber banner appears on every page.\n- Chat and direct messages (Slack, Telegram, Discord, Google Chat) still get answers.\n- Nothing is lost. Work that falls due during the pause waits, and runs when you click **Resume**. The switch shows how many actions are waiting.\n- Anyone who can sign in can pause the Executive, but only the principal can resume it.\n\n*Tip: if you're looking for a feature that isn't in the sidebar, it's probably here. This guide is also pinned next to Settings at the bottom of the nav.*","mermaid": null,- "generated_at": "2026-09-26T11:18:25Z"+ "generated_at": "2026-09-26T16:58:25Z"}diff --git a/packages/core/tests/unit/test_delegation_gmail.py b/packages/core/tests/unit/test_delegation_gmail.pyindex 8629820a..5a0e00c8 100644--- a/packages/core/tests/unit/test_delegation_gmail.py+++ b/packages/core/tests/unit/test_delegation_gmail.py@@ -10,6 +10,7 @@ import inspectimport jsonimport reimport stat+import timefrom email import policyfrom pathlib import Pathfrom types import ModuleType, SimpleNamespace@@ -165,6 +166,51 @@ def test_html_only_mail_becomes_text() -> None:assert parsed.auto_generated is True[email protected](("markup", "lines"), [+ # Gmail's signature editor: the first line sits in the outer <div>, each+ # later line in a <div> of its own.+ (+ '<div dir="ltr">Olivia Owner<div>Fernway Studio</div><div><span>[email protected]</span></div></div>',+ ["Olivia Owner", "Fernway Studio", "[email protected]"],+ ),+ ("<div>One</div><div>Two</div>", ["One", "Two"]), # no blank line between blocks+ ("<div>One</div><div><br></div><div>Three</div>", ["One", "", "Three"]), # Gmail's blank line+ ("<div>One<br></div><div>Two</div>", ["One", "Two"]), # a closing <br> adds no line+ ("<p>One</p><p>Two</p>", ["One", "Two"]),+ ("<p>Hi Dana,</p><p> </p><p>Thanks.</p>", ["Hi Dana,", "", "Thanks."]), # an editor's blank line+ ("Before<table><tr><td>Cell</td></tr></table>After", ["Before", "Cell", "After"]),+ ("Intro<ul><li>One</li><li>Two</li></ul>", ["Intro", "One", "Two"]),+ ("a<br/>b<BR >c", ["a", "b", "c"]),+ ("<picture>Not</picture> a <param>block", ["Not a block"]),+ ("Nul\x00 <div>kept out</div>", ["Nul", "kept out"]),+ ("a<style>p {}</style>b<script>x()</script>c<script>never closed", ["abcnever closed"]),+ # A tag runs to the next ">", whatever its attributes hold.+ ('<a href="https://x.example/" title="<">click</a> here', ["click here"]),+ ("if x<y then <b>bold</b>", ["if xbold"]),+ ("a <> b A &#" + "1" * 5000 + ";", ["a <> b A \ufffd"]), # Python refuses to int() 4,301+ digits+])+def test_html_becomes_the_lines_it_shows(markup: str, lines: list[str]) -> None:+ assert gm.html_to_text(markup).split("\n") == lines++[email protected]("markup", [+ "<" + " " * 100_000,+ "</" + " " * 100_000,+ "<" * 100_000,+ "<div" * 25_000,+ "<br" * 33_000,+ "<script" * 14_000,+ "<script>" + "</script" + " " * 100_000,+ "&#" + "0" * 100_000 + "65;",+])+def test_crafted_html_cannot_stall_the_parser(markup: str) -> None:+ # Anyone can send the mail this parses, and it runs on the event loop: a+ # backtracking pattern took minutes on inputs like these.+ started = time.perf_counter()+ gm.html_to_text(markup)+ assert time.perf_counter() - started < 2++def test_a_draft_is_threaded_and_cannot_smuggle_a_header() -> None:raw = build_raw(EMAIL, DraftSpec(to=["[email protected]"],diff --git a/packages/core/tests/unit/test_delegation_route.py b/packages/core/tests/unit/test_delegation_route.pyindex f46ddd51..be58604c 100644--- a/packages/core/tests/unit/test_delegation_route.py+++ b/packages/core/tests/unit/test_delegation_route.py@@ -11,6 +11,7 @@ from fastapi.testclient import TestClientfrom openexecutive.api.routes import delegation as routefrom openexecutive.delegation import voice as dvoice+from openexecutive.delegation.gmail import GmailAuthError, GmailErrorfrom openexecutive.delegation.settings import is_enabledfrom openexecutive.delegation.voice import VoiceProfile, get_voice, save_voicefrom openexecutive.memory import episodic@@ -154,6 +155,23 @@ def test_a_rejected_edit_says_so(client: TestClient, ids: dict[str, int], updateassert get_voice(ids["principal"]).profile.is_empty()+def test_greetings_are_edited_per_audience(client: TestClient, ids: dict[str, int]) -> None:+ saved = client.put(+ "/delegation/voice", json={"greetings": {"team": "Hi {first},", "contact": "Hello {first},"}}, headers=OWNER+ ).json()+ assert saved["greetings"] == {"team": "Hi {first},", "contact": "Hello {first},"}+ # The whole set is replaced: an audience left out has no greeting.+ assert client.put("/delegation/voice", json={"greetings": {"team": "Hey {first},"}}, headers=OWNER).json()[+ "greetings"+ ] == {"team": "Hey {first},"}+ resp = client.put("/delegation/voice", json={"greetings": {"team": "Hi {name},"}}, headers=OWNER)+ assert resp.status_code == 422 and resp.json()["detail"]["rejected"] == [+ {"field": "greetings.team", "reason": "invalid"}+ ]+ # The message names what went wrong, not only the habits' rule.+ assert "{first} is its only placeholder" in resp.json()["detail"]["message"]++def test_an_edit_keeps_the_signature_unless_cleared(client: TestClient, ids: dict[str, int]) -> None:save_voice(ids["principal"], VoiceProfile(signature="Olivia Owner\nFernway"), locked=False, updated_by="learn")kept = client.put("/delegation/voice", json={"habits": ["Keeps emails short"]}, headers=OWNER).json()@@ -184,3 +202,116 @@ def test_learning_needs_their_gmail(resp = client.post("/delegation/voice/learn", headers=OWNER)assert resp.status_code == 409 and resp.json()["detail"]["code"] == "locked"assert client.post("/delegation/voice/learn", headers=TEAMMATE).status_code == 403+++class _Mailbox:+ """The caller's Gmail as the signature route sees it: its sendAs signature."""++ def __init__(self, signature: str | Exception) -> None:+ self.signature = signature+ self.asked = 0++ async def send_as_signature(self) -> str:+ self.asked += 1+ if isinstance(self.signature, Exception):+ raise self.signature+ return self.signature+++def mailbox(monkeypatch: pytest.MonkeyPatch) -> _Mailbox:+ box = _Mailbox("Olivia Owner\nFernway Studio")+ monkeypatch.setattr(route, "gmail_for", lambda email: box)+ return box+++def test_the_signature_is_taken_from_gmail_again_and_nothing_else_changes(+ client: TestClient,+ ids: dict[str, int],+ gmail: dict[str, str],+ mailbox: _Mailbox,+ audit: list[tuple[str, dict[str, Any]]],+) -> None:+ # A locked profile with the signature an older parser glued together.+ save_voice(+ ids["principal"],+ VoiceProfile(habits=["Keeps emails short"], sign_off="Best,\nOlivia", signature="Olivia OwnerFernway Studio"),+ locked=True, updated_by="learn", learned=True, sample_count=12,+ )+ learned_at = get_voice(ids["principal"]).learned_at+ gmail["status"] = "connected"+ body = client.post("/delegation/voice/signature", headers=OWNER).json()+ assert body["signature"] == "Olivia Owner\nFernway Studio"+ assert (body["habits"], body["sign_off"], body["locked"]) == (["Keeps emails short"], "Best,\nOlivia", True)+ assert (body["learned_at"], body["sample_count"]) == (learned_at, 12)+ assert get_voice(ids["principal"]).profile.signature == "Olivia Owner\nFernway Studio"+ event, kw = audit[-1]+ assert event == "delegation_voice_changed" and kw["private"] is True+ assert kw["details"] == {"op": "signature", "person_id": ids["principal"], "has_signature": True}++ # Gmail has no signature any more: none is added from now on.+ mailbox.signature = ""+ assert client.post("/delegation/voice/signature", headers=OWNER).json()["signature"] == ""+ assert audit[-1][1]["details"]["has_signature"] is False+++def test_an_edit_made_while_gmail_is_read_is_kept(+ client: TestClient, ids: dict[str, int], gmail: dict[str, str], mailbox: _Mailbox, monkeypatch: pytest.MonkeyPatch+) -> None:+ save_voice(ids["principal"], VoiceProfile(habits=["Keeps emails short"]), locked=False, updated_by="learn")+ gmail["status"] = "connected"++ async def slow_signature() -> str:+ # The person locks it and changes a habit while Gmail answers.+ save_voice(ids["principal"], VoiceProfile(habits=["Writes in plain words"]), locked=True, updated_by="person")+ return "Olivia Owner"++ monkeypatch.setattr(mailbox, "send_as_signature", slow_signature)+ body = client.post("/delegation/voice/signature", headers=OWNER).json()+ assert (body["signature"], body["habits"], body["locked"]) == ("Olivia Owner", ["Writes in plain words"], True)++[email protected](("status", "code"), [+ ("not_configured", "gmail_not_connected"),+ ("needs_reconnect", "gmail_needs_reconnect"),+ ("mismatch", "gmail_mismatch"),+ ("error", "gmail_error"),+])+def test_the_signature_needs_their_gmail(+ client: TestClient, ids: dict[str, int], gmail: dict[str, str], mailbox: _Mailbox, status: str, code: str+) -> None:+ gmail["status"] = status+ resp = client.post("/delegation/voice/signature", headers=OWNER)+ assert resp.status_code == 409 and resp.json()["detail"]["code"] == code+ assert mailbox.asked == 0++[email protected](("error", "status_code", "code"), [+ (GmailAuthError("revoked"), 409, "gmail_needs_reconnect"),+ (GmailError("unavailable"), 502, "gmail_error"),+])+def test_a_gmail_failure_keeps_the_signature(+ client: TestClient,+ ids: dict[str, int],+ gmail: dict[str, str],+ mailbox: _Mailbox,+ error: Exception,+ status_code: int,+ code: str,+) -> None:+ save_voice(ids["principal"], VoiceProfile(signature="Olivia Owner"), locked=False, updated_by="learn")+ gmail["status"] = "connected"+ mailbox.signature = error+ resp = client.post("/delegation/voice/signature", headers=OWNER)+ assert resp.status_code == status_code and resp.json()["detail"]["code"] == code+ assert get_voice(ids["principal"]).profile.signature == "Olivia Owner"+++def test_only_the_owner_takes_their_signature(+ client: TestClient, ids: dict[str, int], gmail: dict[str, str], mailbox: _Mailbox+) -> None:+ gmail["status"] = "connected"+ assert client.post("/delegation/voice/signature", headers=TEAMMATE).status_code == 403+ resp = client.post("/delegation/voice/signature")+ assert resp.status_code == 403 and resp.json()["detail"]["code"] == "sign_in_required"+ assert mailbox.asked == 0diff --git a/packages/core/tests/unit/test_voice_profile.py b/packages/core/tests/unit/test_voice_profile.pyindex 76eaf78a..8d7ca729 100644--- a/packages/core/tests/unit/test_voice_profile.py+++ b/packages/core/tests/unit/test_voice_profile.py@@ -125,6 +125,53 @@ def test_a_long_sign_off_is_refused() -> None:assert profile.sign_off == "" and dropped == [{"field": "sign_off", "reason": "invalid"}]+def test_an_escaped_line_break_is_a_line_break() -> None:+ # A model can write the two characters backslash-n instead of a break.+ profile, dropped = validate_profile(+ {"sign_off": "Thanks,\\nOlivia", "greetings": {"team": "Hi {first},\\n"}},+ allow_exemplars=False, keep_signature=False, roster_names=[],+ )+ assert (profile.sign_off, profile.greetings, dropped) == ("Thanks,\nOlivia", {"team": "Hi {first},"}, [])+++def test_escaped_lines_past_the_limit_keep_the_first_ones() -> None:+ # Rather than losing a learned value; the escape is read after normalizing+ # (a full-width backslash, a backslash joined to its "n" by a dropped+ # zero-width space).+ profile, dropped = validate_profile(+ {+ "sign_off": "Best,\\nOlivia\\nFounder",+ "greetings": {+ "team": "Hi {first},\\nHope you're well",+ "contact": "Hi,\uff3cnthere",+ "other": "Hello,\\\u200bnthere",+ },+ },+ allow_exemplars=False, keep_signature=False, roster_names=[],+ )+ assert profile.sign_off == "Best,\nOlivia"+ assert profile.greetings == {"team": "Hi {first},", "contact": "Hi,", "other": "Hello,"}+ assert dropped == []++[email protected]("value", ["Best,\\nOlivia", "Best,\\\\nOlivia", "x\\ \n n", "Cheers \uff3c", "Ta,\r\n\u200bOlivia"])+def test_a_cleaned_sign_off_reads_back_the_same(value: str) -> None:+ once, _ = validate_profile({"sign_off": value}, allow_exemplars=False, keep_signature=False, roster_names=[])+ twice, _ = validate_profile({"sign_off": once.sign_off}, allow_exemplars=False, keep_signature=False, roster_names=[])+ assert twice.sign_off == once.sign_off+++def test_a_stored_escaped_sign_off_reads_back_on_two_lines(db: Path) -> None:+ person_id = people_store.upsert_person(full_name="Olivia Owner", is_principal=True, email="[email protected]")+ # Stored before the fix: save_voice keeps what it is given.+ save_voice(person_id, VoiceProfile(sign_off="Thanks,\\nOlivia"), locked=True, updated_by="learn")+ assert get_voice(person_id).profile.sign_off == "Thanks,\nOlivia"+++def test_the_learn_prompt_never_shows_an_escaped_line_break() -> None:+ assert "\\n" not in dvoice._SYSTEM++# --------------------------------------------------------------------------- ## Storage# --------------------------------------------------------------------------- #diff --git a/packages/ui/src/components/settings/ActAsMeCard.tsx b/packages/ui/src/components/settings/ActAsMeCard.tsxindex 6cf431c7..728bf060 100644--- a/packages/ui/src/components/settings/ActAsMeCard.tsx+++ b/packages/ui/src/components/settings/ActAsMeCard.tsx@@ -1,11 +1,12 @@"use client";-import { useCallback, useEffect, useState } from "react";+import { useCallback, useEffect, useLayoutEffect, useRef, useState } from "react";import {getDelegation,getVoiceProfile,learnVoiceProfile,+ refreshVoiceSignature,resetVoiceProfile,setDelegationEnabled,updateVoiceProfile,@@ -20,11 +21,15 @@ import {const LENGTHS = ["short", "medium", "long"] as const;const FORMALITIES = ["casual", "neutral", "formal"] as const;+// The audiences a greeting is learned for (delegation/voice.py AUDIENCES) and+// its per-line limit (GREETING_MAX_CHARS).+const AUDIENCES = ["team", "contact", "other"] as const;const AUDIENCE_LABEL: Record<string, string> = {team: "To your team",contact: "To your contacts",other: "To anyone else",};+const GREETING_MAX_CHARS = 60;function lines(text: string): string[] {return text@@ -33,6 +38,11 @@ function lines(text: string): string[] {.filter(Boolean);}+// The greetings as the form edits them: one per audience, "" for none.+function greetingFields(p: VoiceProfile): Record<string, string> {+ return Object.fromEntries(AUDIENCES.map((a) => [a, p.greetings[a] ?? ""]));+}+export default function ActAsMeCard() {const [settings, setSettings] = useState<DelegationSettings | null>(null);const [state, setState] = useState<"loading" | "hidden" | "ready" | "error">("loading");@@ -178,6 +188,7 @@ export default function ActAsMeCard() {// "How I write": learned from your sent mail, editable, lockable.function VoiceSection({ connected }: { connected: boolean }) {const [profile, setProfile] = useState<VoiceProfile | null>(null);+ const [greetings, setGreetings] = useState<Record<string, string>>({});const [habits, setHabits] = useState("");const [avoid, setAvoid] = useState("");const [signOff, setSignOff] = useState("");@@ -185,10 +196,12 @@ function VoiceSection({ connected }: { connected: boolean }) {const [formality, setFormality] = useState("");const [busy, setBusy] = useState(false);const [error, setError] = useState<string | null>(null);+ const [notice, setNotice] = useState<string | null>(null);const [loadFailed, setLoadFailed] = useState(false);const adopt = useCallback((p: VoiceProfile) => {setProfile(p);+ setGreetings(greetingFields(p));setHabits(p.habits.join("\n"));setAvoid(p.avoid.join("\n"));setSignOff(p.sign_off);@@ -212,11 +225,31 @@ function VoiceSection({ connected }: { connected: boolean }) {}if (!profile) return null;- const run = async (action: () => Promise<VoiceProfile>) => {+ // keepEdits (lock, signature, examples): a field you've changed and not+ // saved keeps your text; every other field takes the new value, which may+ // come from a change made elsewhere.+ const run = async (action: () => Promise<VoiceProfile>, keepEdits = false) => {+ const before = profile;setBusy(true);setError(null);+ setNotice(null);try {- adopt(await action());+ const next = await action();+ if (!keepEdits) {+ adopt(next);+ return;+ }+ const keep = (saved: string, fresh: string) => (typed: string) => (typed === saved ? fresh : typed);+ setProfile(next);+ setHabits(keep(before.habits.join("\n"), next.habits.join("\n")));+ setAvoid(keep(before.avoid.join("\n"), next.avoid.join("\n")));+ setSignOff(keep(before.sign_off, next.sign_off));+ setLength(keep(before.length, next.length));+ setFormality(keep(before.formality, next.formality));+ const [was, now] = [greetingFields(before), greetingFields(next)];+ setGreetings((typed) =>+ Object.fromEntries(AUDIENCES.map((a) => [a, keep(was[a], now[a])(typed[a] ?? "")])),+ );} catch (err) {setError(err instanceof Error ? err.message : "Could not save.");} finally {@@ -224,13 +257,29 @@ function VoiceSection({ connected }: { connected: boolean }) {}};+ const takeGmailSignature = () =>+ void run(async () => {+ const next = await refreshVoiceSignature();+ if (!next.signature) {+ setNotice(+ profile.signature+ ? "Your Gmail settings have no signature now, so none is added."+ : "Your Gmail settings have no signature to add.",+ );+ }+ return next;+ }, true);+const learned = profile.learned_at !== null;+ const savedGreetings = greetingFields(profile);const dirty =+ AUDIENCES.some((a) => greetings[a] !== savedGreetings[a]) ||habits !== profile.habits.join("\n") ||avoid !== profile.avoid.join("\n") ||signOff !== profile.sign_off ||length !== profile.length ||formality !== profile.formality;+ const linkButton = "text-xs text-indigo-400 hover:text-indigo-300 disabled:opacity-50";return (<div>@@ -253,7 +302,7 @@ function VoiceSection({ connected }: { connected: boolean }) {)}{learned && (- <div className="mt-3 space-y-3">+ <div className="mt-3 space-y-4"><div className="flex gap-3"><label className="text-xs text-fg-muted">Length@@ -287,71 +336,108 @@ function VoiceSection({ connected }: { connected: boolean }) {</label></div>- {Object.keys(profile.greetings).length > 0 && (- <div className="text-xs text-fg-muted">- {Object.entries(profile.greetings).map(([audience, greeting]) => (- <div key={audience}>- {AUDIENCE_LABEL[audience] ?? audience}: <span className="text-fg">{greeting}</span>- </div>+ <fieldset>+ <legend className="text-xs text-fg-muted">Greeting</legend>+ <p className="text-[11px] text-fg-subtle leading-relaxed">+ {"{first}"} becomes their first name. Leave one empty to let each draft choose.+ </p>+ <div className="mt-1.5 space-y-1.5">+ {AUDIENCES.map((audience) => (+ <label key={audience} className="flex items-center gap-2 text-xs text-fg-muted">+ <span className="w-28 flex-shrink-0">{AUDIENCE_LABEL[audience]}</span>+ <input+ type="text"+ value={greetings[audience] ?? ""}+ onChange={(e) => setGreetings((g) => ({ ...g, [audience]: e.target.value }))}+ placeholder="Not set"+ maxLength={GREETING_MAX_CHARS}+ className="min-w-0 flex-1 rounded border border-line bg-surface px-2 py-1 text-xs text-fg"+ />+ </label>))}</div>- )}+ </fieldset><label className="block text-xs text-fg-muted">Sign-off- <textarea- value={signOff}- onChange={(e) => setSignOff(e.target.value)}- rows={2}- className="mt-1 w-full rounded border border-line bg-surface px-2 py-1 text-xs text-fg"- />+ <GrowingTextarea value={signOff} onChange={setSignOff} minRows={2} /></label><label className="block text-xs text-fg-muted">Habits (one per line)- <textarea- value={habits}- onChange={(e) => setHabits(e.target.value)}- rows={4}- className="mt-1 w-full rounded border border-line bg-surface px-2 py-1 text-xs text-fg"- />+ <GrowingTextarea value={habits} onChange={setHabits} minRows={3} /></label><label className="block text-xs text-fg-muted">Never (one per line)- <textarea- value={avoid}- onChange={(e) => setAvoid(e.target.value)}- rows={3}- className="mt-1 w-full rounded border border-line bg-surface px-2 py-1 text-xs text-fg"- />+ <GrowingTextarea value={avoid} onChange={setAvoid} minRows={2} /></label>- {profile.signature && (- <div className="text-xs text-fg-muted">- Signature added to every draft (from your Gmail settings):- <pre className="mt-1 whitespace-pre-wrap rounded-md border border-line bg-surface px-2 py-1.5 text-[11px] text-fg">- {profile.signature}- </pre>- <button- type="button"- disabled={busy}- onClick={() => void run(() => updateVoiceProfile({ clear_signature: true }))}- className="mt-1 text-xs text-indigo-400 hover:text-indigo-300 disabled:opacity-50"- >- Don't add my signature- </button>- </div>- )}+ <div className="text-xs text-fg-muted">+ <div>Signature</div>+ {profile.signature ? (+ <>+ <p className="mt-0.5 leading-relaxed">+ Added to the end of every draft, from your Gmail settings.+ </p>+ <div className="mt-1 whitespace-pre-wrap break-words border-l-2 border-line pl-2 leading-relaxed text-fg">+ {profile.signature}+ </div>+ <div className="mt-1 flex flex-wrap gap-x-3">+ <button+ type="button"+ disabled={busy || !connected}+ onClick={takeGmailSignature}+ className={linkButton}+ >+ Refresh from Gmail+ </button>+ <button+ type="button"+ disabled={busy}+ onClick={() => void run(() => updateVoiceProfile({ clear_signature: true }), true)}+ className={linkButton}+ >+ Don't add my signature+ </button>+ </div>+ </>+ ) : (+ <>+ <p className="mt-0.5 leading-relaxed">No signature is added to drafts.</p>+ <button+ type="button"+ disabled={busy || !connected}+ onClick={takeGmailSignature}+ className={`mt-1 ${linkButton}`}+ >+ Add my Gmail signature+ </button>+ </>+ )}+ </div>+{profile.exemplars.length > 0 && (<div className="text-xs text-fg-muted">- {profile.exemplars.length} short example{profile.exemplars.length === 1 ? "" : "s"} of- your writing guide the tone.{" "}+ <div>Examples of your writing</div>+ <p className="mt-0.5 leading-relaxed">+ Short passages from your sent mail that set the tone. Drafts never reuse what they say.+ </p>+ <ul className="mt-1 space-y-1.5">+ {profile.exemplars.map((example, i) => (+ <li+ key={i}+ className="whitespace-pre-wrap break-words border-l-2 border-line pl-2 leading-relaxed text-fg"+ >+ {example}+ </li>+ ))}+ </ul><buttontype="button"disabled={busy}- onClick={() => void run(() => updateVoiceProfile({ clear_exemplars: true }))}- className="text-indigo-400 hover:text-indigo-300 disabled:opacity-50"+ onClick={() => void run(() => updateVoiceProfile({ clear_exemplars: true }), true)}+ className={`mt-1 ${linkButton}`}>- Remove them+ Remove examples</button></div>)}@@ -363,6 +449,9 @@ function VoiceSection({ connected }: { connected: boolean }) {onClick={() =>void run(() =>updateVoiceProfile({+ greetings: Object.fromEntries(+ AUDIENCES.map((a) => [a, (greetings[a] ?? "").trim()]).filter(([, g]) => g),+ ),habits: lines(habits),avoid: lines(avoid),sign_off: signOff,@@ -378,7 +467,7 @@ function VoiceSection({ connected }: { connected: boolean }) {<buttontype="button"disabled={busy}- onClick={() => void run(() => updateVoiceProfile({ locked: !profile.locked }))}+ onClick={() => void run(() => updateVoiceProfile({ locked: !profile.locked }), true)}className="rounded-md border border-line px-2.5 py-1 text-xs text-fg hover:bg-surface-overlay disabled:opacity-50">{profile.locked ? "Unlock" : "Lock"}@@ -394,7 +483,44 @@ function VoiceSection({ connected }: { connected: boolean }) {</div></div>)}+ {notice && <p className="mt-1 text-xs text-fg-muted">{notice}</p>}{error && <p className="mt-1 text-xs text-red-400">{error}</p>}</div>);}++// A textarea as tall as its text, so every line shows without an inner+// scrollbar; it refits when the text changes (typed or loaded) and when the+// window's width does.+function GrowingTextarea({+ value,+ onChange,+ minRows,+}: {+ value: string;+ onChange: (value: string) => void;+ minRows: number;+}) {+ const ref = useRef<HTMLTextAreaElement>(null);+ const fit = useCallback(() => {+ const el = ref.current;+ if (!el) return;+ el.style.height = "auto";+ // scrollHeight leaves out the border, which border-box sizing counts.+ el.style.height = `${el.scrollHeight + el.offsetHeight - el.clientHeight}px`;+ }, []);+ useLayoutEffect(fit, [fit, value]);+ useEffect(() => {+ window.addEventListener("resize", fit);+ return () => window.removeEventListener("resize", fit);+ }, [fit]);+ return (+ <textarea+ ref={ref}+ value={value}+ onChange={(e) => onChange(e.target.value)}+ rows={minRows}+ className="mt-1 block w-full resize-none overflow-hidden rounded border border-line bg-surface px-2 py-1 text-xs leading-relaxed text-fg"+ />+ );+}diff --git a/packages/ui/src/lib/api.ts b/packages/ui/src/lib/api.tsindex 28915174..ee353325 100644--- a/packages/ui/src/lib/api.ts+++ b/packages/ui/src/lib/api.ts@@ -1438,6 +1438,13 @@ export async function updateVoiceProfile(update: VoiceUpdate): Promise<VoiceProfreturn res.json();}+// Takes the signature from your Gmail settings again; nothing else changes.+export async function refreshVoiceSignature(): Promise<VoiceProfile> {+ const res = await fetch(`${API_BASE}/delegation/voice/signature`, { method: "POST" });+ if (!res.ok) throw await delegationError(res, "Couldn't read your Gmail signature.");+ return res.json();+}+export async function resetVoiceProfile(): Promise<VoiceProfile> {const res = await fetch(`${API_BASE}/delegation/voice`, { method: "DELETE" });if (!res.ok) throw await delegationError(res, "Couldn't reset how you write.");