AI-powered virtual executive team — a single coherent executive persona backed by 8 specialist agents (FastAPI + Next.js).
fix(people): stop teammates taking over the owner's entry (#227)
Rufus9325113ea395
diff --git a/docs/auth.md b/docs/auth.mdindex 3a444188..cbeb1eba 100644--- a/docs/auth.md+++ b/docs/auth.md@@ -27,6 +27,12 @@ Neither one overrides the other. Adding people to the roster cannot revoke an`ALLOWED_EMAILS` entry, and leaving `ALLOWED_EMAILS` blank is fine once the roster ispopulated.+While the owner's People entry has no email, someone let in by `ALLOWED_EMAILS` who is+on no entry can re-run the setup interview and add the address they signed in with to+the owner's entry. That is how an owner who set up with local login links theirs, and+it makes them the owner. So keep `ALLOWED_EMAILS` to people you would trust as the owner, or+make sure the owner's entry has an email. Only the owner can change the People list itself.+Membership is re-checked on every request the middleware gates, not just at sign-in, so aroster removal takes effect within the cache window rather than waiting out the 24h JWT.diff --git a/packages/core/openexecutive/api/routes/onboarding.py b/packages/core/openexecutive/api/routes/onboarding.pyindex c32785e6..3c03a72e 100644--- a/packages/core/openexecutive/api/routes/onboarding.py+++ b/packages/core/openexecutive/api/routes/onboarding.py@@ -97,7 +97,7 @@ async def start_onboarding() -> OnboardStatusResponse:@router.post("/onboard/answer", response_model=OnboardStatusResponse)-async def submit_answer(body: OnboardAnswerRequest) -> OnboardStatusResponse:+async def submit_answer(body: OnboardAnswerRequest, request: Request) -> OnboardStatusResponse:state = _wizard_sessions.get(body.session_id)if state is None:raise HTTPException(status_code=404, detail="Onboarding session not found")@@ -117,8 +117,19 @@ async def submit_answer(body: OnboardAnswerRequest) -> OnboardStatusResponse:state = process_answer(state, body.answer)if state.completed:+ from openexecutive.api.routes.chat import _caller_is_principal_or_unclaimedfrom openexecutive.onboarding.profile_builder import build_and_save_profile+ # Saving adds people with their emails (the web sign-in allow-list)+ # and a principal, so once there is an owner it is theirs to do — the+ # People routes' rule. Rolled back like a failed build, so the owner+ # can still finish this session.+ if not _caller_is_principal_or_unclaimed(request):+ _wizard_sessions[body.session_id] = snapshot+ raise HTTPException(+ status_code=403,+ detail="Only the owner can save this form, because it adds people and their emails.",+ )try:build_and_save_profile(state)except Exception as exc:@@ -529,6 +540,7 @@ async def commit_interview(body: OnboardCommitRequest, request: Request) -> Compderive_org_structure,link_owner_email,owner_change_blocked,+ owner_email_blocked,reconcile_onboarding_departments,save_onboarding_people,)@@ -590,8 +602,9 @@ async def commit_interview(body: OnboardCommitRequest, request: Request) -> Comp# owner may do that (owner_change_blocked explains the rule).from openexecutive.api.routes.chat import _resolve_caller_person_id+ caller_person_id = _resolve_caller_person_id(request)try:- blocked = owner_change_blocked(principal_name, _resolve_caller_person_id(request))+ blocked = owner_change_blocked(principal_name, caller_person_id)except (OSError, sqlite3.Error) as exc:logger.warning("onboarding commit: owner lookup failed (%s)", type(exc).__name__)raise HTTPException(@@ -609,6 +622,24 @@ async def commit_interview(body: OnboardCommitRequest, request: Request) -> Compowner_email = check_owner_email(body.owner_email, principal_name)except OwnerEmailError as exc:raise HTTPException(status_code=422, detail=str(exc)) from exc+ # Someone who isn't the owner may fill in the owner's missing email only+ # with the address they signed in with (owner_email_blocked explains why).+ caller_email = (request.headers.get("x-caller-email") or "").strip().lower()+ try:+ email_blocked = owner_email_blocked(owner_email, caller_person_id, caller_email)+ except (OSError, sqlite3.Error) as exc:+ logger.warning("onboarding commit: owner lookup failed (%s)", type(exc).__name__)+ raise HTTPException(+ status_code=503, detail="Could not check who owns this workspace. Try again."+ ) from exc+ if email_blocked:+ raise HTTPException(+ status_code=403,+ detail=(+ "Only the owner can put another address on the owner's entry. If you "+ "are the owner, use the email you signed in with; if not, leave it blank."+ ),+ )profile = derive_org_structure(profile, people, departments)diff --git a/packages/core/openexecutive/api/routes/people.py b/packages/core/openexecutive/api/routes/people.pyindex 8679d457..28ad208a 100644--- a/packages/core/openexecutive/api/routes/people.py+++ b/packages/core/openexecutive/api/routes/people.py@@ -2,7 +2,8 @@Phase 3 surface: CRUD + archive + approver lookup.All mutations invalidate the 60s registry cache so the next-Executive turn picks up the change.+Executive turn picks up the change. Adding, editing and archiving+people are the principal's alone (``_require_roster_owner``)."""from __future__ import annotations@@ -101,8 +102,33 @@ def get_person(person_id: int) -> Person:# Mutation routes# --------------------------------------------------------------------------- #+def _require_roster_owner(request: Request) -> None:+ """403 unless the caller may change the roster: the principal, or anyone+ while no one is principal yet, so a first setup can add its owner.++ A People row is also the web sign-in allow-list, the outbound-email+ allow-list and approval routing, so without this any signed-in teammate+ could put their own address on the principal's row and sign in as them.+ The same owner rule as the workspace settings; the Executive's roster+ tools (``orchestrator.people_tools``) are the principal's too.++ A person can't edit their own row either: its email and chat ids are how+ they sign in and how the Executive reaches them, and the rest decides+ their approvals and how they are chased. Their working style and open+ loops, further down, stay theirs.++ Called before the id lookup, so a refused caller can't probe which ids+ exist.+ """+ from openexecutive.api.routes.chat import _caller_is_principal_or_unclaimed++ if not _caller_is_principal_or_unclaimed(request):+ raise HTTPException(status_code=403, detail="Only the principal can change the People list")++@router.post("/people", response_model=Person, status_code=status.HTTP_201_CREATED)-def create_person(body: PersonCreate) -> Person:+def create_person(body: PersonCreate, request: Request) -> Person:+ _require_roster_owner(request)pid = people_store.upsert_person(full_name=body.full_name,role=body.role,@@ -129,7 +155,8 @@ def create_person(body: PersonCreate) -> Person:@router.patch("/people/{person_id}", response_model=Person)-def patch_person(person_id: int, body: PersonPatch) -> Person:+def patch_person(person_id: int, body: PersonPatch, request: Request) -> Person:+ _require_roster_owner(request)if people_store.get_person(person_id) is None:raise HTTPException(status_code=404, detail="Person not found")@@ -166,7 +193,8 @@ def patch_person(person_id: int, body: PersonPatch) -> Person:@router.post("/people/{person_id}/archive", status_code=status.HTTP_204_NO_CONTENT)-def archive_person(person_id: int) -> Response:+def archive_person(person_id: int, request: Request) -> Response:+ _require_roster_owner(request)if people_store.get_person(person_id) is None:raise HTTPException(status_code=404, detail="Person not found")people_store.archive_person(person_id)diff --git a/packages/core/openexecutive/api/setup_checks.py b/packages/core/openexecutive/api/setup_checks.pyindex aac9d032..57e4db27 100644--- a/packages/core/openexecutive/api/setup_checks.py+++ b/packages/core/openexecutive/api/setup_checks.py@@ -287,8 +287,9 @@ def check_owner(snap: Snapshot) -> SetupCheck:"warn",f"{owner.full_name} is the owner, but has no email on the team list, so the app won't recognise ""them when they sign in — owner-only actions will be refused.",- "Add the Google address they sign in with to their entry on the People page.",- link="/people",+ "Signed in as them, run the setup interview again: saving it adds the address they "+ "signed in with to their entry.",+ link="/onboard",)return _result("owner", "ok", f"{owner.full_name} ({owner.email}) is the owner.")diff --git a/packages/core/openexecutive/architecture/architecture-facts.yaml b/packages/core/openexecutive/architecture/architecture-facts.yamlindex 32e25b7d..bba04bce 100644--- a/packages/core/openexecutive/architecture/architecture-facts.yaml+++ b/packages/core/openexecutive/architecture/architecture-facts.yaml@@ -773,7 +773,9 @@ routing:decides, so an archived principal is refused too. Everything else gets`{"status": "refused", "detail": ...}` — a rostered teammate on anysurface, a signed-in web user whose email is on no People row (told to- link their email on the People page), and every unverified surface:+ sign in with the email on their own entry, or re-run the setup+ interview to fill in a missing one — the People page refuses them+ too), and every unverified surface:email (the poller resolves the From header, which proves nothing —even the principal's address), Google Chat (no sender identity), theCLI, the MCP server, and unattended runs (no `current_session`). Why:@@ -783,8 +785,8 @@ routing:address that can then sign in and receive mail, or grant themselvesWILDCARD. Refusals are audited (`tool_invocation`, ok=false,refused=true, with caller / origin_channel / from_web_chat) and render- no action chip. `list_people` stays open. The People page (behind the- web sign-in) is unaffected.+ no action chip. `list_people` stays open. The People page's own+ routes apply the same owner rule (see `people.api`).department_tools: |`list_department_goals` and `update_department_goal`(openexecutive.orchestrator.department_tools) let the Executive@@ -2496,7 +2498,26 @@ people:GET /people/by-scope/{token} — e.g. "ceo", "head-of-marketing","department:engineering". The Executive uses this through the`lookup_person` tool when a user asks "tell the head of X".- api: /people — CRUD plus by-scope lookup and archive.+ api: |+ /people — CRUD plus by-scope lookup and archive. Adding, editing and+ archiving (POST /people, PATCH /people/{id}, POST /people/{id}/archive)+ are the principal's only, via `_require_roster_owner` →+ `chat._caller_is_principal_or_unclaimed` (the check behind PUT+ /workspace and resuming the Executive): the caller resolves to the+ principal (a request with no x-caller-email — the CLI, local login —+ does), or no one is principal yet, so a first setup from the People+ page can add its owner. Fails closed when the roster can't be read.+ Anyone else gets 403 "Only the principal can change the People list",+ checked before the id lookup so it can't probe ids. Why: a People row+ is the web sign-in allow-list, the outbound-email allow-list and+ approval routing, so a teammate who could PATCH the principal's email+ to an address they sign in with would be resolved as the principal.+ Deliberately no self-service either: a person's email and chat ids are+ how they sign in and are reached, and name, role, departments,+ reporting line, authority, leave, hours, reply time and channel decide+ approvals and chasing — the owner's call, as for the Executive's+ roster tools. Their working style and open loops stay theirs+ (principal-or-self; see `attunement`).executive_write_access: |The Executive can mutate the roster directly without going through theUI via the `list_people` / `upsert_person` / `archive_person` /@@ -5572,6 +5593,29 @@ company_onboarding:renamed owner included), the caller — resolved from x-caller-email; noheader means the principal — must be the principal, else 403. Keepingthe owner, or a first setup, stays open.+ Owner email on such a re-run: commit.owner_email_blocked, after+ check_owner_email and before any write — a caller who is not the+ principal may fill in the owner's MISSING email only with their own+ x-caller-email (403 otherwise; the owner's current email is a no-op and+ passes). Why: the roster is the web sign-in allow-list, so an address+ of the caller's choosing on an email-less owner row would let them sign+ in with it and resolve to the principal — the takeover the People+ routes closed by going owner-only. Their own address stays allowed+ because that is the way in for an owner the app can't recognise yet+ (the review screen pre-fills it; Setup status's owner light and the+ roster tools' refusal send them here, since the People page refuses+ them); a rostered teammate's own address is on their own entry, which+ check_owner_email refuses. Decision: re-running setup stays open to+ anyone signed in who keeps the owner — PATCH /company-profile and the+ department routes already let them change the same profile and+ departments, so closing setup alone would protect nothing and would+ remove that way in. So anyone let in by ALLOWED_EMAILS who is on no+ entry can claim an owner entry that has no email (docs/auth.md says so).+ The form wizard (POST /onboard/answer) is different: its final answer+ adds people WITH emails and a principal (profile_builder+ ._save_wizard_people), so once there is an owner only they may send it+ (chat._caller_is_principal_or_unclaimed; 403, and the session is+ rolled back like a failed build so the owner can still finish it).org_structure_is_derived: |profile.org_structure.departments and .leadership_team are computed fromthe reviewed people and department tables at commit timediff --git a/packages/core/openexecutive/architecture/prebuilt/api.json b/packages/core/openexecutive/architecture/prebuilt/api.jsonindex 099cea3c..ecf520a2 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`. |\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` | 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. |\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. 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). |\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. 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| `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). |\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, 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`, and Discord `users/@me` only while the bot is still connecting. 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 and the user's time zone (`memory.workspace_settings`). Both return `{mode, timezone, effective_timezone}` — `timezone` is what the user set (null when unset), `effective_timezone` the zone in effect (`timezone`, else `USER_TIMEZONE`, else UTC). `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; an unknown zone, a bad mode or an unknown field is a 422. 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; each change writes a `workspace_settings_changed` audit row. `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/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. |\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). |\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) 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. `/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| `auth` | `GET /auth/allowed-emails` | Non-archived people with an email, offered to the UI's sign-in gate. 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`. |\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` | 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. |\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. 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. 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). |\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. 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| `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). |\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, 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`, and Discord `users/@me` only while the bot is still connecting. 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 and the user's time zone (`memory.workspace_settings`). Both return `{mode, timezone, effective_timezone}` — `timezone` is what the user set (null when unset), `effective_timezone` the zone in effect (`timezone`, else `USER_TIMEZONE`, else UTC). `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; an unknown zone, a bad mode or an unknown field is a 422. 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; each change writes a `workspace_settings_changed` audit row. `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/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. |\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). |\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| `auth` | `GET /auth/allowed-emails` | Non-archived people with an email, offered to the UI's sign-in gate. 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-25T15:23:57.766111+00:00"+ "generated_at": "2026-09-25T16:06:55.208339+00:00"}diff --git a/packages/core/openexecutive/architecture/prebuilt/org.json b/packages/core/openexecutive/architecture/prebuilt/org.jsonindex 8bb904e4..4145078d 100644--- a/packages/core/openexecutive/architecture/prebuilt/org.json+++ b/packages/core/openexecutive/architecture/prebuilt/org.json@@ -1,7 +1,7 @@{"section_id": "org","title": "Org Structure (Departments & People)",- "markdown": "The org model has two persistent registries backed by SQLite (both share `episodic_memory.db`): **departments** and **people**. Eight default departments are seeded exactly once per database on first boot, tracked by a `default_departments_seeded` sentinel in `departments_meta`; after that the user owns the list and deleted departments stay deleted across restarts.\n\n### Company setup (onboarding)\nBoth registries are first populated by **conversational onboarding** at\n`/onboard`. The user describes their business in their own words (optionally\nattaching a deck or one-pager); the `onboarding_interviewer` agent — Council-\nvisible but outside `SPECIALIST_REGISTRY`, so the Executive cannot reach it via\n`consult_specialist` — asks up to 8 clarifying questions, then emits a draft\ncompany profile, a leadership roster, and a department list. The user reviews\nand edits that draft inline (the same section editors `/company-profile` uses)\nbefore anything is written.\n\nTwo properties matter here. First, **the interview never writes**: the whole\nexchange lives in an in-memory, TTL'd session, and the single write happens at\n`POST /onboard/interview/commit`, so a rejected save leaves the draft editable\nand retryable. Second, **the department step is additive** — drafted\ndepartments are matched onto existing ones by slug or title and updated in\nplace, unmatched ones are created, and nothing is ever deleted. That is\ndeliberately unlike the fixture loader's `_seed_departments`, which DELETEs\nevery row first: doing that here would drop the eight defaults along with their\n`specialist_key` wiring, which onboarding's `create_department` calls (no\n`specialist_key`) cannot restore. Matching goes through\n`departments.store.match_department` (slug as given or as the store would slug\nit, else case-insensitive title), the same rule the `create_goal` chat tool uses. `profile.org_structure` is derived from the reviewed\npeople and department tables at commit time, so it cannot drift from them.\n\nExactly one person is marked `is_principal` and receives `WILDCARD` authority;\nno contact details are imported, even if the user volunteers them, because\nchannels and handles are a deliberate action on the People page. The one\nexception is the owner's own sign-in email: the review screen has a separate\nfield for it, pre-filled with the current owner's email on a re-run and with the\nsigned-in user's on a first setup. The commit checks it before writing anything\n(malformed, already another person's, or different from the owner's existing\nemail is a 422 — setup only fills in a missing one) and then saves it on the\nprincipal's row. Without it the signed-in owner matched no Person,\nso their chat history stayed empty until they found the People page. With\nlocal login (`make dev` without Google sign-in) the field is optional: that\nsession carries no email, which the backend already reads as the principal.\nBecause the save demotes the old principal, only the current owner may draft\nsomeone else as \"This is me\" when setup is re-run (403 otherwise); a re-run\nthat keeps the owner, or a first setup, is open to anyone who can sign in. The original\n12-step form wizard remains available at `/onboard?mode=form` and backs the\n`openexecutive onboard` CLI.\n\nA first setup opens on one question — **Just me** or **Me and my team** — and\nthe choice is written to `PUT /workspace` (with the browser's time zone) before\nthe conversation starts, because the two modes ask different things. A re-run\nover an existing profile skips it; the mode is changed in Settings. In solo the\ninterviewer's first user turn carries a short hint (the founder runs the\nbusiness alone: draft only them, as principal, and no departments; ask about\nthe offer, customers, pricing, cash and runway and their top goals instead of\na leadership team). It rides in the user turn, so the cached system prompt is\nthe same constant in both modes. The solo review screen shows only **You**\n(name and role) and the sign-in email, and commits that one principal with no\ndepartments — the existing departments stay, as the areas goals are grouped\nby. The form wizard (and the CLI) read the mode when a session starts and skip\nthe Team Size, Team Members and Fractional Executives steps in solo; each\nstatus response numbers the steps it actually asks and flags whether the\ncurrent one is `optional`.\n\n### Departments\nEach department carries a charter, `Goal` rows, `ChecklistItem`s, and named cadences. Cadence specs (`daily@HH:MM`, `weekly@DOW@HH:MM`, `quarterly@DD-HH:MM`, UTC) run a `department_check_in` workflow when due (never in solo mode, below), then chain the next occurrence; `PATCH /departments/{slug}` rejects a spec that does not parse with a 422. The check-in is skipped (and still chained) when the department has no specialist, no Goals, or nothing new since its Goals were last reviewed. An idle initiative is chased with the department's head, or with the principal when there is none. A department may map to a specialist agent via `specialist_key`, or stay informational. No department is seeded for the `sales` specialist (existing installs keep their departments unchanged), so its consults skip the department-memory prefetch and the Honcho department sync, as `triage`'s do. An assigned head gets a generated department-head voice persona.\n\n**Goals from chat.** Besides the goal routes and the UI, the Executive keeps goals current from a chat turn: `update_department_goal` records reported progress, and `create_goal` starts tracking a new goal the principal states (\"20 paying clients by the end of Q4\"). Only the principal, on a surface that verified it is them (`people_tools.is_principal_on_verified_surface`, the roster tools' rule: the web chat, their own Slack or Discord, a private Telegram chat with a valid webhook secret), may call it: a goal renders in every turn's org block as one of the principal's own, so a goal from an inbound email, Google Chat, a teammate or an unattended run would be text carrying their authority. Anyone else gets a refusal (audited with the caller and surface) and nothing is written. `create_goal` names the area as free text — a slug or a title, resolved by `match_department` — so its schema is static and adding an area never changes the cached tool prefix. When nothing matches it creates the area (`create_department`), giving it a specialist only when the title is obviously one's domain (`specialist_key_for_area`: the default departments' slugs and titles, plus Sales) and no department holds that specialist yet; anything else is informational. It refuses a goal the area already tracks (pointing at `update_department_goal`), caps a turn at 5 new goals (a sweep is not a stated goal) and an area at 8 (common practice keeps 3–5 key results per objective, and every goal renders in the 4000-character org block, so one area cannot crowd the others out), returns only the exception type on a store failure, is audited with its rationale, and is never offered to an unattended run (`schedule_tools.UNATTENDED_WITHHELD_TOOLS`: reflection, research and the scheduler's proactive trigger). The solo persona teaches it; team mode learns it from the tool description, so the team persona stays byte-identical.\n\nA department can also list **watched entities** (`watched_entities`, edited one per line on its page): vendors it is evaluating, competitors in its lane, tickers it tracks. The research watch policy treats them as strong grounding — a proposal about one can be added to the watch list on its own — and routes the resulting watch, its alerts and any suggestion cards to the department and its head rather than the principal (see External monitoring).\n\n### Solo and team mode\nAn install is either a **team** (the default) or **solo** — one person using Open Executive just for themselves. The mode lives with the user's time zone in its own one-row table, `workspace_settings` (`openexecutive.memory.workspace_settings`, `GET`/`PUT /workspace`), not on the company profile, because onboarding's commit and the form wizard rebuild the profile from scratch and would wipe it. Changing it is the principal's call (open while no principal exists, so first-run setup can choose).\n\nSolo also changes how the Executive speaks and what it can do. It works for one person — the principal — without assuming their role (an owner, an executive inside a larger organisation, or an independent); the people in their world are contacts it helps them work with, not a team it routes to. The cached org block becomes the principal's own line (\"Your Principal\") plus their goals grouped by **area** (a department row is an area; no authority levels, heads, cadences, channels or roster), and posting to a department room, broadcasting to the company and assigning a department head are not offered. A follow-up the Executive schedules to the principal goes straight to them — its department and scope are dropped, so the authority gate never files a card asking the principal to approve a message to themselves. Meeting bookings are gated on the `meeting_scheduling` class mode, not a department (see below).\n\nSolo turns the department rhythm off without touching the org: switching to solo cancels every pending `dept_cadence` row, `bootstrap_cadences` does nothing (the check sits inside it, so boot, the fixture reset and client-slot activation all honour it), and the scheduler cancels any stray check-in without running or chaining it, and a check-in already running across the switch schedules no successor. Department and people rows are kept, so switching back to team re-schedules the check-ins at once. The boot-time org-completeness warnings (departments with no head) are skipped in solo. A chat `Session` can carry an explicit `workspace_mode` override (read through `effective_workspace_mode`), so a caller that runs many conversations on one Executive — evals, for one — can pick the mode per session instead of flipping the install-wide setting.\n\nIn the UI, a `WorkspaceProvider` in the root layout reads the mode once (and again after Settings changes it) and reads **team** while loading or on error, so a team install never flashes the solo UI. Solo swaps the sidebar's Company group for **You** — Goals, People, Business profile — where `/goals` lists every goal grouped by area (a department row) and adds, edits and deletes them through the slug-scoped goal routes. `/departments` and `/people` stay reachable by URL.\n\nThe setting is per company: a blank client slot starts on the defaults, a saved slot keeps its own, a fixture load resets it and applies the fixture's optional `workspace.yaml` (read and validated before anything is swapped; a bad value is skipped, never a failed load), and the factory reset returns it to team with no zone. The user's own settings survive a demo: the backup a fixture load takes (or reuses) always gets the live settings written to its `workspace.yaml` while the live state is the user's, and an unload from an older backup without one leaves the settings as they are. A zone that cannot be loaded is never fatal — the API answers 422, and a stored one reads as unset.\n\n### Authority gate\nEach department declares an `AuthorityLevel`, which `departments.authority.gate_action` checks whenever a department-scoped scheduled action comes due. The check-in cadence is the exception: it sends nothing itself, and each action it proposes is run through the gate and shown with its verdict in the report — so a propose-only department's check-ins actually run instead of becoming a one-shot approval card. `auto_execute` (autonomous) fires directly. `propose_only` turns the action into an approval card for an approver (`propose_via_alert`) and sends nothing, deferring the card to the approver's next availability window when they are outside it. `escalate` also sends nothing until someone approves: it raises an urgent `[ESCALATION]` card (severity high) right away, never deferred — filed unrouted when nobody holds the scope and no principal is set, since the Briefing lists every unread card — what the Departments page promises (\"the specialist will not act — it forwards everything to a human\"). It used to raise the card *and* dispatch, so approving the card sent the action a second time. Calendar bookings follow the same rule in team mode. In solo mode there is no operations department to consult: the booking is decided by the `meeting_scheduling` class mode — `propose` puts it on the briefing for the principal, and `auto_execute` books right away only when the principal started the turn on a surface that verified it is them (the roster-write rule: the web chat, their own Slack or Discord, or a private Telegram chat with the webhook secret set). A booking asked for in an inbound email, by a contact, or by an unattended run is proposed to the principal instead, so text someone else wrote cannot put a meeting on their calendar. The principal sets it with `GET`/`PUT /decisions/classes/meeting_scheduling` (`{\"decision_class\": \"meeting_scheduling\", \"mode\": \"propose\" | \"auto_execute\"}`; the PUT is principal-only and audited). The approver is chosen by `AuthorityScope` — a scheduled action's `required_scope` (e.g. `vendor_onboarding`, `spend_lt_10k`) feeds `find_approvers(scope)`, which ranks non-principal scope-holders ahead of `WILDCARD` holders. A null/unknown scope falls back to `WILDCARD` (the principal).\n\n### People & channels\nThe people registry resolves each `Person` to a `(channel, channel_ref)` pair via `prefer_channel_for()`, honoring `preferred_channel` (falling back email → slack → discord → telegram) and availability windows. The principal briefs use their own order — the preferred channel, then Slack → Discord → Telegram, with email only for an `email` preference or an `any` principal with no chat channel (see Scheduler). Departments can also set `slack_channel_id` / `discord_channel_id` / `telegram_chat_id` to broadcast to a team room instead of DMing the head.\n\nEach person's page also lists their **open loops** (see Attunement) — what they committed to or were asked for in conversation — with a *Mark done* action; archiving a person closes their open loops, since an archived person can no longer be chased. The list is the principal's or that person's only; `people.store.is_principal_or_self` is the one check behind it, the close action and reply feedback.\n\nThe Executive can change the roster from a chat turn (`upsert_person`, `archive_person`, `set_department_head`) only when the principal asks, from the web chat, their own Slack or Discord, or a private Telegram chat when `TELEGRAM_WEBHOOK_SECRET` is set to a value Telegram can send. A teammate, an email (even one from the principal's address), Google Chat, the CLI, the MCP server and unattended runs are refused, because a People row is also the web sign-in allow-list, the outbound-email allow-list and approval routing. The People page itself is unaffected.",+ "markdown": "The org model has two persistent registries backed by SQLite (both share `episodic_memory.db`): **departments** and **people**. Eight default departments are seeded exactly once per database on first boot, tracked by a `default_departments_seeded` sentinel in `departments_meta`; after that the user owns the list and deleted departments stay deleted across restarts.\n\n### Company setup (onboarding)\nBoth registries are first populated by **conversational onboarding** at\n`/onboard`. The user describes their business in their own words (optionally\nattaching a deck or one-pager); the `onboarding_interviewer` agent — Council-\nvisible but outside `SPECIALIST_REGISTRY`, so the Executive cannot reach it via\n`consult_specialist` — asks up to 8 clarifying questions, then emits a draft\ncompany profile, a leadership roster, and a department list. The user reviews\nand edits that draft inline (the same section editors `/company-profile` uses)\nbefore anything is written.\n\nTwo properties matter here. First, **the interview never writes**: the whole\nexchange lives in an in-memory, TTL'd session, and the single write happens at\n`POST /onboard/interview/commit`, so a rejected save leaves the draft editable\nand retryable. Second, **the department step is additive** — drafted\ndepartments are matched onto existing ones by slug or title and updated in\nplace, unmatched ones are created, and nothing is ever deleted. That is\ndeliberately unlike the fixture loader's `_seed_departments`, which DELETEs\nevery row first: doing that here would drop the eight defaults along with their\n`specialist_key` wiring, which onboarding's `create_department` calls (no\n`specialist_key`) cannot restore. Matching goes through\n`departments.store.match_department` (slug as given or as the store would slug\nit, else case-insensitive title), the same rule the `create_goal` chat tool uses. `profile.org_structure` is derived from the reviewed\npeople and department tables at commit time, so it cannot drift from them.\n\nExactly one person is marked `is_principal` and receives `WILDCARD` authority;\nno contact details are imported, even if the user volunteers them, because\nchannels and handles are a deliberate action on the People page. The one\nexception is the owner's own sign-in email: the review screen has a separate\nfield for it, pre-filled with the current owner's email on a re-run and with the\nsigned-in user's on a first setup. The commit checks it before writing anything\n(malformed, already another person's, or different from the owner's existing\nemail is a 422 — setup only fills in a missing one) and then saves it on the\nprincipal's row. Without it the signed-in owner matched no Person,\nso their chat history stayed empty until they found the People page. With\nlocal login (`make dev` without Google sign-in) the field is optional: that\nsession carries no email, which the backend already reads as the principal.\nBecause the save demotes the old principal, only the current owner may draft\nsomeone else as \"This is me\" when setup is re-run (403 otherwise); a re-run\nthat keeps the owner, or a first setup, is open to anyone who can sign in. On such a re-run, someone who isn't the owner may fill in the owner's missing email only with the address they signed in with (403 otherwise): the roster is the sign-in allow-list, so any other address would let them sign in as the owner. That keeps the way in for an owner whose entry has no email, which is also where Setup status and the Executive send them, since the People page refuses anyone it can't recognise as the owner. Re-running setup stays open to everyone deliberately: the Company Profile and Departments pages already let anyone signed in change the same things. The original\n12-step form wizard remains available at `/onboard?mode=form` and backs the\n`openexecutive onboard` CLI. It adds people with their emails, so once there is an owner only they can save it.\n\nA first setup opens on one question — **Just me** or **Me and my team** — and\nthe choice is written to `PUT /workspace` (with the browser's time zone) before\nthe conversation starts, because the two modes ask different things. A re-run\nover an existing profile skips it; the mode is changed in Settings. In solo the\ninterviewer's first user turn carries a short hint (the founder runs the\nbusiness alone: draft only them, as principal, and no departments; ask about\nthe offer, customers, pricing, cash and runway and their top goals instead of\na leadership team). It rides in the user turn, so the cached system prompt is\nthe same constant in both modes. The solo review screen shows only **You**\n(name and role) and the sign-in email, and commits that one principal with no\ndepartments — the existing departments stay, as the areas goals are grouped\nby. The form wizard (and the CLI) read the mode when a session starts and skip\nthe Team Size, Team Members and Fractional Executives steps in solo; each\nstatus response numbers the steps it actually asks and flags whether the\ncurrent one is `optional`.\n\n### Departments\nEach department carries a charter, `Goal` rows, `ChecklistItem`s, and named cadences. Cadence specs (`daily@HH:MM`, `weekly@DOW@HH:MM`, `quarterly@DD-HH:MM`, UTC) run a `department_check_in` workflow when due (never in solo mode, below), then chain the next occurrence; `PATCH /departments/{slug}` rejects a spec that does not parse with a 422. The check-in is skipped (and still chained) when the department has no specialist, no Goals, or nothing new since its Goals were last reviewed. An idle initiative is chased with the department's head, or with the principal when there is none. A department may map to a specialist agent via `specialist_key`, or stay informational. No department is seeded for the `sales` specialist (existing installs keep their departments unchanged), so its consults skip the department-memory prefetch and the Honcho department sync, as `triage`'s do. An assigned head gets a generated department-head voice persona.\n\n**Goals from chat.** Besides the goal routes and the UI, the Executive keeps goals current from a chat turn: `update_department_goal` records reported progress, and `create_goal` starts tracking a new goal the principal states (\"20 paying clients by the end of Q4\"). Only the principal, on a surface that verified it is them (`people_tools.is_principal_on_verified_surface`, the roster tools' rule: the web chat, their own Slack or Discord, a private Telegram chat with a valid webhook secret), may call it: a goal renders in every turn's org block as one of the principal's own, so a goal from an inbound email, Google Chat, a teammate or an unattended run would be text carrying their authority. Anyone else gets a refusal (audited with the caller and surface) and nothing is written. `create_goal` names the area as free text — a slug or a title, resolved by `match_department` — so its schema is static and adding an area never changes the cached tool prefix. When nothing matches it creates the area (`create_department`), giving it a specialist only when the title is obviously one's domain (`specialist_key_for_area`: the default departments' slugs and titles, plus Sales) and no department holds that specialist yet; anything else is informational. It refuses a goal the area already tracks (pointing at `update_department_goal`), caps a turn at 5 new goals (a sweep is not a stated goal) and an area at 8 (common practice keeps 3–5 key results per objective, and every goal renders in the 4000-character org block, so one area cannot crowd the others out), returns only the exception type on a store failure, is audited with its rationale, and is never offered to an unattended run (`schedule_tools.UNATTENDED_WITHHELD_TOOLS`: reflection, research and the scheduler's proactive trigger). The solo persona teaches it; team mode learns it from the tool description, so the team persona stays byte-identical.\n\nA department can also list **watched entities** (`watched_entities`, edited one per line on its page): vendors it is evaluating, competitors in its lane, tickers it tracks. The research watch policy treats them as strong grounding — a proposal about one can be added to the watch list on its own — and routes the resulting watch, its alerts and any suggestion cards to the department and its head rather than the principal (see External monitoring).\n\n### Solo and team mode\nAn install is either a **team** (the default) or **solo** — one person using Open Executive just for themselves. The mode lives with the user's time zone in its own one-row table, `workspace_settings` (`openexecutive.memory.workspace_settings`, `GET`/`PUT /workspace`), not on the company profile, because onboarding's commit and the form wizard rebuild the profile from scratch and would wipe it. Changing it is the principal's call (open while no principal exists, so first-run setup can choose).\n\nSolo also changes how the Executive speaks and what it can do. It works for one person — the principal — without assuming their role (an owner, an executive inside a larger organisation, or an independent); the people in their world are contacts it helps them work with, not a team it routes to. The cached org block becomes the principal's own line (\"Your Principal\") plus their goals grouped by **area** (a department row is an area; no authority levels, heads, cadences, channels or roster), and posting to a department room, broadcasting to the company and assigning a department head are not offered. A follow-up the Executive schedules to the principal goes straight to them — its department and scope are dropped, so the authority gate never files a card asking the principal to approve a message to themselves. Meeting bookings are gated on the `meeting_scheduling` class mode, not a department (see below).\n\nSolo turns the department rhythm off without touching the org: switching to solo cancels every pending `dept_cadence` row, `bootstrap_cadences` does nothing (the check sits inside it, so boot, the fixture reset and client-slot activation all honour it), and the scheduler cancels any stray check-in without running or chaining it, and a check-in already running across the switch schedules no successor. Department and people rows are kept, so switching back to team re-schedules the check-ins at once. The boot-time org-completeness warnings (departments with no head) are skipped in solo. A chat `Session` can carry an explicit `workspace_mode` override (read through `effective_workspace_mode`), so a caller that runs many conversations on one Executive — evals, for one — can pick the mode per session instead of flipping the install-wide setting.\n\nIn the UI, a `WorkspaceProvider` in the root layout reads the mode once (and again after Settings changes it) and reads **team** while loading or on error, so a team install never flashes the solo UI. Solo swaps the sidebar's Company group for **You** — Goals, People, Business profile — where `/goals` lists every goal grouped by area (a department row) and adds, edits and deletes them through the slug-scoped goal routes. `/departments` and `/people` stay reachable by URL.\n\nThe setting is per company: a blank client slot starts on the defaults, a saved slot keeps its own, a fixture load resets it and applies the fixture's optional `workspace.yaml` (read and validated before anything is swapped; a bad value is skipped, never a failed load), and the factory reset returns it to team with no zone. The user's own settings survive a demo: the backup a fixture load takes (or reuses) always gets the live settings written to its `workspace.yaml` while the live state is the user's, and an unload from an older backup without one leaves the settings as they are. A zone that cannot be loaded is never fatal — the API answers 422, and a stored one reads as unset.\n\n### Authority gate\nEach department declares an `AuthorityLevel`, which `departments.authority.gate_action` checks whenever a department-scoped scheduled action comes due. The check-in cadence is the exception: it sends nothing itself, and each action it proposes is run through the gate and shown with its verdict in the report — so a propose-only department's check-ins actually run instead of becoming a one-shot approval card. `auto_execute` (autonomous) fires directly. `propose_only` turns the action into an approval card for an approver (`propose_via_alert`) and sends nothing, deferring the card to the approver's next availability window when they are outside it. `escalate` also sends nothing until someone approves: it raises an urgent `[ESCALATION]` card (severity high) right away, never deferred — filed unrouted when nobody holds the scope and no principal is set, since the Briefing lists every unread card — what the Departments page promises (\"the specialist will not act — it forwards everything to a human\"). It used to raise the card *and* dispatch, so approving the card sent the action a second time. Calendar bookings follow the same rule in team mode. In solo mode there is no operations department to consult: the booking is decided by the `meeting_scheduling` class mode — `propose` puts it on the briefing for the principal, and `auto_execute` books right away only when the principal started the turn on a surface that verified it is them (the roster-write rule: the web chat, their own Slack or Discord, or a private Telegram chat with the webhook secret set). A booking asked for in an inbound email, by a contact, or by an unattended run is proposed to the principal instead, so text someone else wrote cannot put a meeting on their calendar. The principal sets it with `GET`/`PUT /decisions/classes/meeting_scheduling` (`{\"decision_class\": \"meeting_scheduling\", \"mode\": \"propose\" | \"auto_execute\"}`; the PUT is principal-only and audited). The approver is chosen by `AuthorityScope` — a scheduled action's `required_scope` (e.g. `vendor_onboarding`, `spend_lt_10k`) feeds `find_approvers(scope)`, which ranks non-principal scope-holders ahead of `WILDCARD` holders. A null/unknown scope falls back to `WILDCARD` (the principal).\n\n### People & channels\nThe people registry resolves each `Person` to a `(channel, channel_ref)` pair via `prefer_channel_for()`, honoring `preferred_channel` (falling back email → slack → discord → telegram) and availability windows. The principal briefs use their own order — the preferred channel, then Slack → Discord → Telegram, then email as the backup for every preference (first for an `email` one); see Scheduler. Departments can also set `slack_channel_id` / `discord_channel_id` / `telegram_chat_id` to broadcast to a team room instead of DMing the head.\n\nEach person's page also lists their **open loops** (see Attunement) — what they committed to or were asked for in conversation — with a *Mark done* action; archiving a person closes their open loops, since an archived person can no longer be chased. The list is the principal's or that person's only; `people.store.is_principal_or_self` is the one check behind it, the close action and reply feedback.\n\nThe Executive can change the roster from a chat turn (`upsert_person`, `archive_person`, `set_department_head`) only when the principal asks, from the web chat, their own Slack or Discord, or a private Telegram chat when `TELEGRAM_WEBHOOK_SECRET` is set to a value Telegram can send. A teammate, an email (even one from the principal's address), Google Chat, the CLI, the MCP server and unattended runs are refused, because a People row is also the web sign-in allow-list, the outbound-email allow-list and approval routing. The People page follows the same rule: adding, editing and archiving people (`POST`/`PATCH /people`, `POST /people/{id}/archive`) are the principal's alone, or anyone's while no one is principal yet, so a first setup can add its owner (`chat._caller_is_principal_or_unclaimed`). Anyone else gets 403. That includes a teammate editing their own entry: its email and chat ids are how they sign in and how the Executive reaches them, and the rest decides their approvals and how they are chased. Their working style and open loops stay theirs. A signed-in owner whose email is on no People entry is refused too; they sign in with the email on their entry, or re-run the setup interview, which fills a missing one with the email they signed in with.","mermaid": "flowchart TD\n People[\"People registry (Person, is_principal)\"]\n Dept[\"Departments (8 seeded once)\"]\n GC[\"Goals / checklists / cadences\"]\n Head[\"Head + voice persona\"]\n Gate[\"Authority gate (propose_only vs autonomous)\"]\n Scope[\"AuthorityScope to find_approvers\"]\n Chan[\"Channel resolution (Discord / Telegram / email)\"]\n Dept --> GC\n Dept --> Head\n Dept -->|proposes action| Gate\n Gate -->|required_scope| Scope\n Scope -->|ranks approvers| People\n People --> Chan\n Dept -->|team room| Chan\n class People storage\n class Dept storage\n class GC storage\n class Gate compute\n class Scope compute\n class Chan compute\n class Head compute",- "generated_at": "2026-09-25T16:20:57Z"+ "generated_at": "2026-09-25T16:31:49.029263+00:00"}diff --git a/packages/core/openexecutive/guide/prebuilt/people.json b/packages/core/openexecutive/guide/prebuilt/people.jsonindex ccc0792f..1b7943a1 100644--- a/packages/core/openexecutive/guide/prebuilt/people.json+++ b/packages/core/openexecutive/guide/prebuilt/people.json@@ -1,7 +1,7 @@{"section_id": "people","title": "People",- "markdown": "**What it is:** Your org roster — the humans the Executive coordinates with, each with a response SLA, preferred channel, and the approval authority they hold.\n\n**What it does:**\n\n- Add people with their role, email, and chat IDs (Slack / Discord / Telegram).\n- Set a response SLA so the Executive knows when a proposal is overdue.\n- Assign **authority scopes** (e.g. approve spend under $10k, sign off on hiring) so proposals route to the right person.\n- Mark the principal (you / the founder) and set availability or on-leave dates.\n\n**How to use:**\n\n1. Open **People** and click **+ Add person**.\n2. Enter **Full name** (the only required field) and **Role**. If this is you, tick **This is me — Primary** — this can only be set when adding someone.\n3. Expand **Contact & routing**: the preferred channel, **Expected reply within *N* hours** (their SLA — default 24), email, and Slack / Discord / Telegram IDs. Those IDs are also what lets this person talk to the Executive on those channels.\n4. Expand **Approval authority** and click each scope they hold:\n\n | Button | They can approve |\n |---|---|\n | Spend <$2K / <$10K / >$10K | Spend up to that amount (>$10K covers large spend) |\n | Hiring | Hiring sign-off |\n | Vendors | New vendor onboarding |\n | Credit | Customer credits |\n | Legal | Legal signatures |\n | Board | Board communications |\n | All (wildcard) | Anything — the catch-all for approvals no one else is scoped for; usually the founder |\n\n5. Click **Add person**. Later, open the person and click **Edit** to set **On leave until**, add **Availability windows** (days, hours, timezone), or change their scopes; **Archive person** retires them from the roster.\n\n**Example from chat:** *\"Add Sarah Chen as our fractional CFO — [email protected] — she approves spend under $10k and usually replies within 48 hours.\"* Or open **+ Add person**, press **Ctrl/Cmd + .**, and describe the person — Ask OE fills in the dialog for you to check and save.\n\n**Just for yourself?** When you use Open Executive just for yourself, setup adds only you — marked as the principal, with authority over everything. **People** stays in the sidebar under **You**: add the clients, partners and contractors you work with whenever you want the Executive to reach them. The Briefing doesn't show a People card in this mode.\n\n*Note: authority scopes are how the Executive figures out who to ask for any given approval.*",+ "markdown": "**What it is:** Your org roster — the humans the Executive coordinates with, each with a response SLA, preferred channel, and the approval authority they hold.\n\n**What it does:**\n\n- Add people with their role, email, and chat IDs (Slack / Discord / Telegram).\n- Set a response SLA so the Executive knows when a proposal is overdue.\n- Assign **authority scopes** (e.g. approve spend under $10k, sign off on hiring) so proposals route to the right person.\n- Mark the principal (you / the founder) and set availability or on-leave dates.\n\n**How to use:**\n\n1. Open **People** and click **+ Add person**.\n2. Enter **Full name** (the only required field) and **Role**. If this is you, tick **This is me — Primary** — this can only be set when adding someone.\n3. Expand **Contact & routing**: the preferred channel, **Expected reply within *N* hours** (their SLA — default 24), email, and Slack / Discord / Telegram IDs. Those IDs are also what lets this person talk to the Executive on those channels.\n4. Expand **Approval authority** and click each scope they hold:\n\n | Button | They can approve |\n |---|---|\n | Spend <$2K / <$10K / >$10K | Spend up to that amount (>$10K covers large spend) |\n | Hiring | Hiring sign-off |\n | Vendors | New vendor onboarding |\n | Credit | Customer credits |\n | Legal | Legal signatures |\n | Board | Board communications |\n | All (wildcard) | Anything — the catch-all for approvals no one else is scoped for; usually the founder |\n\n5. Click **Add person**. Later, open the person and click **Edit** to set **On leave until**, add **Availability windows** (days, hours, timezone), or change their scopes; **Archive person** retires them from the roster.\n\n**Who can change it:** only the principal can add, edit or archive people — until someone is the principal, whoever sets up first can. Everyone signed in can see the list, and teammates can still edit their own working style and mark their open loops done on their page.\n\n**Example from chat:** *\"Add Sarah Chen as our fractional CFO — [email protected] — she approves spend under $10k and usually replies within 48 hours.\"* Or open **+ Add person**, press **Ctrl/Cmd + .**, and describe the person — Ask OE fills in the dialog for you to check and save.\n\n**Just for yourself?** When you use Open Executive just for yourself, setup adds only you — marked as the principal, with authority over everything. **People** stays in the sidebar under **You**: add the clients, partners and contractors you work with whenever you want the Executive to reach them. The Briefing doesn't show a People card in this mode.\n\n*Note: authority scopes are how the Executive figures out who to ask for any given approval.*","mermaid": null,"generated_at": "2026-09-25T13:35:51.913858+00:00"}diff --git a/packages/core/openexecutive/onboarding/commit.py b/packages/core/openexecutive/onboarding/commit.pyindex b1ae5145..11d8c390 100644--- a/packages/core/openexecutive/onboarding/commit.py+++ b/packages/core/openexecutive/onboarding/commit.py@@ -188,10 +188,11 @@ def check_owner_email(raw: str | None, principal_name: str) -> str | None:email would resolve sign-in to the older one); when the draftedprincipal's own row already has a different email (replacing it wouldsign the owner out — web sign-in and caller resolution both key on it —- so that change belongs on the People page); or when the roster can't be- read. "The drafted principal's row" is the one save_onboarding_people's- name-keyed upsert will update — compared by id, because two rows can- share a name and the upsert then takes the last one.+ so the owner changes it on the People page, signed in with the current+ one); or when the roster can't be read. "The drafted principal's row" is+ the one save_onboarding_people's name-keyed upsert will update — compared+ by id, because two rows can share a name and the upsert then takes the+ last one."""email = (raw or "").strip().lower()if not email:@@ -218,12 +219,13 @@ def check_owner_email(raw: str | None, principal_name: str) -> str | None:)raise OwnerEmailError("That email already belongs to someone else on the People page. "- "Use a different one, or change theirs there first."+ "Use the owner's own email, or leave it blank.")if own_row is not None and own_row.email and own_row.email.strip().lower() != email:raise OwnerEmailError(- "Your People entry already has a different sign-in email, and setup never "- "replaces it. Keep that one here, or change it on the People page."+ "The owner's People entry already has a different sign-in email, and setup "+ "never replaces it. Keep that one here, or sign in with it and change it on "+ "the People page.")return email@@ -255,6 +257,28 @@ def owner_change_blocked(principal_name: str, caller_person_id: int | None) -> breturn caller_person_id is None or not is_principal_or_self(caller_person_id, None)+def owner_email_blocked(email: str | None, caller_person_id: int | None, caller_email: str) -> bool:+ """Whether someone who isn't the owner is filling in the owner's missing+ email with an address other than the one they signed in with.++ The roster is the web sign-in allow-list, so an address of their choosing+ would let them sign in with it as the owner. Their own is allowed: it is+ how an owner the app can't recognise yet links theirs, and a rostered+ teammate's own is already on their entry, which check_owner_email+ refuses. Lookup errors propagate (the route answers 503).+ """+ from openexecutive.people.store import find_principal_person, is_principal_or_self++ if not email:+ return False+ current = find_principal_person()+ if current is None or is_principal_or_self(caller_person_id, None):+ return False+ if (current.email or "").strip().lower() == email:+ return False+ return email != caller_email++def link_owner_email(person_id: int, email: str) -> bool:"""Fill in the principal's sign-in email.@@ -262,8 +286,8 @@ def link_owner_email(person_id: int, email: str) -> bool:check_owner_email refuses both before anything is written, and thisre-checks the row it is about to change. Best-effort, like the rest ofthis module — the profile is already saved, and a failure here only leaves- the owner to add their email on the People page, as before this step- existed.+ the owner's email missing, as before this step existed: running setup+ again adds it."""try:from openexecutive.people.store import find_person_by_email, get_person, update_persondiff --git a/packages/core/openexecutive/orchestrator/people_tools.py b/packages/core/openexecutive/orchestrator/people_tools.pyindex fea66b0e..70cbc186 100644--- a/packages/core/openexecutive/orchestrator/people_tools.py+++ b/packages/core/openexecutive/orchestrator/people_tools.py@@ -288,8 +288,10 @@ def _roster_refusal_reason(session: Any) -> str | None:return ("Only the company's owner can change the People list, and this signed-in ""email is not on anyone's People entry, so I cannot confirm it is the "- "owner. If it is, they should add their sign-in email to their own "- "entry on the People page and ask again, or make the change there."+ "owner — the People page refuses them for the same reason. If it is the "+ "owner, they should sign in with the email on their own People entry, or, "+ "if that entry has none yet, run the setup interview again (it adds the "+ "email they signed in with) and then ask again.")return ("Only the company's owner can add, change or remove people or set "diff --git a/packages/core/tests/unit/test_onboarding_interview_route.py b/packages/core/tests/unit/test_onboarding_interview_route.pyindex 9ba0910f..e392d59f 100644--- a/packages/core/tests/unit/test_onboarding_interview_route.py+++ b/packages/core/tests/unit/test_onboarding_interview_route.py@@ -14,6 +14,7 @@ must not behave like the fixture loader."""from __future__ import annotations+import sqlite3from collections import OrderedDictfrom pathlib import Pathfrom typing import Any@@ -891,6 +892,133 @@ def test_local_login_and_the_cli_count_as_the_owner(assert owner is not None and owner.full_name == "Bob Lin"+# ── who may fill in the owner's missing email ────────────────────────────────+# The roster is the web sign-in allow-list, so an address put on an owner entry+# that has none becomes a way to sign in as the owner.+++OWNER_EMAIL_REFUSAL = "Only the owner can put another address on the owner's entry."+++def _seed_owner_without_email_and_teammate() -> None:+ from openexecutive.people import store as people_store++ people_store.upsert_person(full_name="Dana Reyes", is_principal=True)+ people_store.upsert_person(full_name="Bob Lin", email="[email protected]")+++def _commit_with_owner_email(+ client: TestClient, email: str, caller: str | None+) -> Any:+ sid = _start(client)+ body = _commit_body(sid)+ body["owner_email"] = email+ headers = {"x-caller-email": caller} if caller else {}+ return client.post("/onboard/interview/commit", json=body, headers=headers)+++def test_a_teammate_cannot_put_an_address_of_their_own_on_the_owners_entry(+ client: TestClient, seeded: list[Any], people_db: Path, profile_path: Path+) -> None:+ from openexecutive.people import store as people_store++ _seed_owner_without_email_and_teammate()+ seeded.append(_draft())+ # An address Bob controls that is on nobody's entry yet.+ resp = _commit_with_owner_email(client, "[email protected]", caller="[email protected]")+ assert resp.status_code == 403+ assert resp.json()["detail"].startswith(OWNER_EMAIL_REFUSAL)+ assert not profile_path.exists()+ dana = people_store.find_principal_person(db_path=people_db)+ assert dana is not None and dana.email is None+ assert people_store.find_person_by_email("[email protected]", db_path=people_db) is None+++def test_someone_signed_in_elsewhere_cannot_link_another_address(+ client: TestClient, seeded: list[Any], people_db: Path, profile_path: Path+) -> None:+ # Let in by ALLOWED_EMAILS, on no entry: only their own address may go on.+ from openexecutive.people import store as people_store++ _seed_owner_without_email_and_teammate()+ seeded.append(_draft())+ resp = _commit_with_owner_email(client, "[email protected]", caller="[email protected]")+ assert resp.status_code == 403+ assert resp.json()["detail"].startswith(OWNER_EMAIL_REFUSAL)+ assert not profile_path.exists()+ dana = people_store.find_principal_person(db_path=people_db)+ assert dana is not None and dana.email is None+++def test_a_teammates_own_address_is_refused_too(+ client: TestClient, seeded: list[Any], people_db: Path, profile_path: Path+) -> None:+ # What makes allowing the caller's own address safe: a rostered teammate's+ # is already on their own entry. What the review screen pre-fills for Bob+ # when the owner has none — and the message says what works.+ _seed_owner_without_email_and_teammate()+ seeded.append(_draft())+ resp = _commit_with_owner_email(client, "[email protected]", caller="[email protected]")+ assert resp.status_code == 422+ assert "leave it blank" in resp.json()["detail"]+ assert not profile_path.exists()+++def test_an_unreadable_roster_refuses_to_link_the_owner_email(+ client: TestClient,+ seeded: list[Any],+ people_db: Path,+ profile_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ def locked(*_args: Any, **_kwargs: Any) -> bool:+ raise sqlite3.OperationalError("database is locked")++ _seed_owner_without_email_and_teammate()+ seeded.append(_draft())+ monkeypatch.setattr("openexecutive.onboarding.commit.owner_email_blocked", locked)+ resp = _commit_with_owner_email(client, "[email protected]", caller="[email protected]")+ assert resp.status_code == 503+ assert not profile_path.exists()+++def test_the_owner_can_still_link_the_email_they_signed_in_with(+ client: TestClient, seeded: list[Any], people_db: Path+) -> None:+ # Dana's entry has no email, so the app can't tell her login is hers yet;+ # the review screen pre-fills the address she signed in with.+ from openexecutive.people import store as people_store++ _seed_owner_without_email_and_teammate()+ seeded.append(_draft())+ resp = _commit_with_owner_email(client, "[email protected]", caller="[email protected]")+ assert resp.status_code == 200, resp.text+ dana = people_store.find_person_by_email("[email protected]", db_path=people_db)+ assert dana is not None and dana.is_principal+++def test_local_login_and_the_cli_can_link_any_owner_email(+ client: TestClient, seeded: list[Any], people_db: Path+) -> None:+ from openexecutive.people import store as people_store++ _seed_owner_without_email_and_teammate()+ seeded.append(_draft())+ assert _commit_with_owner_email(client, "[email protected]", caller=None).status_code == 200+ dana = people_store.find_principal_person(db_path=people_db)+ assert dana is not None and dana.email == "[email protected]"+++def test_a_teammate_rerun_that_keeps_the_owners_email_still_saves(+ client: TestClient, seeded: list[Any], people_db: Path+) -> None:+ # What the review screen pre-fills on a re-run: the owner's current email.+ _seed_owner_and_teammate()+ seeded.append(_draft())+ resp = _commit_with_owner_email(client, "[email protected]", caller="[email protected]")+ assert resp.status_code == 200, resp.text++# ── solo: one person, no new departments, workspace settings untouched ───────diff --git a/packages/core/tests/unit/test_onboarding_wizard_route.py b/packages/core/tests/unit/test_onboarding_wizard_route.pyindex 2b8bd1d3..decce9fe 100644--- a/packages/core/tests/unit/test_onboarding_wizard_route.py+++ b/packages/core/tests/unit/test_onboarding_wizard_route.py@@ -222,3 +222,57 @@ def test_solo_wizard_saves_only_the_principal(people = people_store.list_people(db_path=db)assert [(p.full_name, p.is_principal) for p in people] == [("Dana Reyes", True)]+++# ── who may save the form ────────────────────────────────────────────────────+# Saving adds people with their emails (the web sign-in allow-list) and a+# principal, so once there is an owner only they may — as on the People page.+++def roster(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:+ from openexecutive.people import store as people_store++ db = tmp_path / "people.db"+ monkeypatch.setattr(people_store, "DB_PATH", db)+ people_store.initialize_db(db)+ people_store.upsert_person(full_name="Dana Reyes", email="[email protected]", is_principal=True)+ people_store.upsert_person(full_name="Bob Lin", email="[email protected]")+ return db+++def _finish(client: TestClient, session_id: str, caller: str) -> Any:+ return client.post(+ "/onboard/answer",+ json={"session_id": session_id, "answer": "final"},+ headers={"x-caller-email": caller},+ )+++def test_a_teammate_cannot_save_the_form(+ client: TestClient, monkeypatch: pytest.MonkeyPatch, roster: Path+) -> None:+ built: list[Any] = []+ monkeypatch.setattr(profile_builder, "build_and_save_profile", built.append)+ session_id = _answer_all_but_last(client)++ resp = _finish(client, session_id, "[email protected]")+ assert resp.status_code == 403+ assert built == []+ # Rolled back rather than stuck, so the owner can still finish it.+ assert client.get(f"/onboard/status/{session_id}").json()["completed"] is False+ assert _finish(client, session_id, "[email protected]").status_code == 200+ assert len(built) == 1+++def test_before_there_is_an_owner_anyone_can_save_the_form(+ client: TestClient, monkeypatch: pytest.MonkeyPatch, tmp_path: Path+) -> None:+ from openexecutive.people import store as people_store++ monkeypatch.setattr(people_store, "DB_PATH", tmp_path / "no-roster-yet.db")+ built: list[Any] = []+ monkeypatch.setattr(profile_builder, "build_and_save_profile", built.append)+ session_id = _answer_all_but_last(client)+ assert _finish(client, session_id, "[email protected]").status_code == 200+ assert len(built) == 1diff --git a/packages/core/tests/unit/test_people_route.py b/packages/core/tests/unit/test_people_route.pyindex ba7e66da..089a76f6 100644--- a/packages/core/tests/unit/test_people_route.py+++ b/packages/core/tests/unit/test_people_route.py@@ -1,7 +1,9 @@"""HTTP-level tests for /people routes."""from __future__ import annotations+import sqlite3from pathlib import Path+from typing import Anyimport pytestfrom fastapi import FastAPI@@ -205,3 +207,126 @@ def test_patch_clears_on_leave_with_flag(client: TestClient) -> None:resp = client.patch(f"/people/{pid}", json={"on_leave_until": None, "clear_on_leave": True})assert resp.status_code == 200, resp.textassert resp.json()["on_leave_until"] is None+++# --------------------------------------------------------------------------- #+# Who may change the roster+# --------------------------------------------------------------------------- #+# The UI proxy stamps the signed-in user's email as x-caller-email. A request+# without one (the CLI, local login) is read as the principal — which is why+# the tests above, which send none, act as the owner.++OWNER = {"x-caller-email": "[email protected]"}+TEAMMATE = {"x-caller-email": "[email protected]"}+STRANGER = {"x-caller-email": "[email protected]"} # signed in, but on no People row+++def team(client: TestClient) -> dict[str, int]:+ owner = client.post(+ "/people", json={"full_name": "Olive", "is_principal": True, "email": "[email protected]"}+ )+ teammate = client.post(+ "/people", json={"full_name": "Tom", "email": "[email protected]"}, headers=OWNER+ )+ assert (owner.status_code, teammate.status_code) == (201, 201)+ return {"owner": owner.json()["id"], "teammate": teammate.json()["id"]}+++def test_the_owner_can_add_edit_and_archive(client: TestClient, team: dict[str, int]) -> None:+ added = client.post("/people", json={"full_name": "Ann"}, headers=OWNER)+ assert added.status_code == 201+ edited = client.patch(f"/people/{team['teammate']}", json={"role": "CFO"}, headers=OWNER)+ assert (edited.status_code, edited.json()["role"]) == (200, "CFO")+ assert client.post(f"/people/{added.json()['id']}/archive", headers=OWNER).status_code == 204+++def test_no_signed_in_email_acts_as_the_owner(client: TestClient, team: dict[str, int]) -> None:+ # The CLI and local login, as for the workspace settings.+ assert client.patch(f"/people/{team['teammate']}", json={"role": "CFO"}).status_code == 200++[email protected]("caller", [TEAMMATE, STRANGER], ids=["teammate", "unrostered"])+def test_nobody_else_can_add_edit_or_archive(+ client: TestClient, team: dict[str, int], caller: dict[str, str]+) -> None:+ before = client.get("/people", params={"include_archived": True}).json()+ responses = [+ client.post("/people", json={"full_name": "Mallory"}, headers=caller),+ client.patch(f"/people/{team['owner']}", json={"role": "Intern"}, headers=caller),+ client.post(f"/people/{team['owner']}/archive", headers=caller),+ client.post(f"/people/{team['teammate']}/archive", headers=caller),+ ]+ assert [r.status_code for r in responses] == [403] * 4+ assert responses[0].json()["detail"] == "Only the principal can change the People list"+ assert client.get("/people", params={"include_archived": True}).json() == before+++def test_a_teammate_cannot_edit_their_own_entry_either(+ client: TestClient, team: dict[str, int]+) -> None:+ # Deliberate: every field is sign-in, messaging, approvals or chasing.+ resp = client.patch(+ f"/people/{team['teammate']}", json={"on_leave_until": "2026-12-01"}, headers=TEAMMATE+ )+ assert resp.status_code == 403+ tom = people_store.get_person(team["teammate"])+ assert tom is not None and tom.on_leave_until is None+++def test_a_teammate_cannot_take_over_the_owners_email(+ client: TestClient, team: dict[str, int]+) -> None:+ # The attack: put an address you sign in with on the principal's row, and+ # every later sign-in resolves to the principal.+ for email in ("[email protected]", "[email protected]"):+ resp = client.patch(f"/people/{team['owner']}", json={"email": email}, headers=TEAMMATE)+ assert resp.status_code == 403+ owner = people_store.find_person_by_email("[email protected]")+ assert owner is not None and owner.id == team["owner"]+ assert people_store.find_person_by_email("[email protected]") is None+++def test_a_teammate_cannot_add_a_principal(client: TestClient, team: dict[str, int]) -> None:+ resp = client.post(+ "/people",+ json={"full_name": "Mallory", "is_principal": True, "email": "[email protected]"},+ headers=TEAMMATE,+ )+ assert resp.status_code == 403+ assert people_store.find_person_by_email("[email protected]") is None+ assert [p.full_name for p in people_store.list_people() if p.is_principal] == ["Olive"]+++def test_a_refused_caller_cannot_probe_ids(client: TestClient, team: dict[str, int]) -> None:+ assert client.patch("/people/9999", json={"role": "X"}, headers=TEAMMATE).status_code == 403+ assert client.post("/people/9999/archive", headers=TEAMMATE).status_code == 403+ assert client.patch("/people/9999", json={"role": "X"}, headers=OWNER).status_code == 404+++def test_before_there_is_a_principal_anyone_signed_in_can_set_up(client: TestClient) -> None:+ # A first setup from the People page: no owner yet, so any signed-in user+ # may add people, including themselves as principal.+ tom = client.post("/people", json={"full_name": "Tom", "email": "[email protected]"}, headers=STRANGER)+ assert tom.status_code == 201+ tom_id = tom.json()["id"]+ assert client.patch(f"/people/{tom_id}", json={"role": "COO"}, headers=TEAMMATE).status_code == 200+ sam = client.post(+ "/people",+ json={"full_name": "Sam", "is_principal": True, "email": "[email protected]"},+ headers=STRANGER,+ )+ assert sam.status_code == 201+ # Now there is one, and only Sam may.+ assert client.patch(f"/people/{tom_id}", json={"role": "CFO"}, headers=TEAMMATE).status_code == 403+ assert client.patch(f"/people/{tom_id}", json={"role": "CFO"}, headers=STRANGER).status_code == 200+++def test_an_unreadable_roster_refuses(+ client: TestClient, team: dict[str, int], monkeypatch: pytest.MonkeyPatch+) -> None:+ def locked(*_args: Any, **_kwargs: Any) -> None:+ raise sqlite3.OperationalError("database is locked")++ monkeypatch.setattr(people_store, "find_principal_person", locked)+ assert client.post("/people", json={"full_name": "Ann"}, headers=OWNER).status_code == 403diff --git a/packages/core/tests/unit/test_people_tools.py b/packages/core/tests/unit/test_people_tools.pyindex 738f2049..855ee696 100644--- a/packages/core/tests/unit/test_people_tools.py+++ b/packages/core/tests/unit/test_people_tools.py@@ -423,7 +423,8 @@ def test_unlinked_web_user_is_told_how_to_prove_they_are_the_owner() -> None:with _turn(Session(from_web_chat=True, caller_person_id=None)):result = _call(handle_upsert_person, {"full_name": "Cindy Lee"})assert result["status"] == "refused"- assert "People page" in result["detail"]+ # Not "add it on the People page": that page refuses them too.+ assert "setup interview" in result["detail"]assert "Cindy Lee" not in _names()diff --git a/packages/core/tests/unit/test_setup_checks.py b/packages/core/tests/unit/test_setup_checks.pyindex a59030a2..0af4f92d 100644--- a/packages/core/tests/unit/test_setup_checks.py+++ b/packages/core/tests/unit/test_setup_checks.py@@ -277,7 +277,8 @@ def test_owner() -> None:unlinked = Person(id=1, full_name="Ada Park", is_principal=True)warn = check_owner(make_snap(principal=unlinked))- assert (warn.state, warn.link) == ("warn", "/people")+ # Not the People page: it refuses whoever the app can't recognise as the owner.+ assert (warn.state, warn.link) == ("warn", "/onboard")assert "owner-only actions will be refused" in warn.summary# Local login signs in as the owner, so no email is needed.diff --git a/packages/ui/src/lib/api.ts b/packages/ui/src/lib/api.tsindex 19615f20..4381e745 100644--- a/packages/ui/src/lib/api.ts+++ b/packages/ui/src/lib/api.ts@@ -2989,12 +2989,17 @@ export interface PersonCreate {availability?: AvailabilityWindow[];}+// Adding, editing and archiving people is the principal's alone (403 for anyone+// else): the People list is also who can sign in and who the Executive emails.+const PEOPLE_PRINCIPAL_ONLY = "Only the principal can change the People list.";+export async function createPerson(body: PersonCreate): Promise<Person> {const res = await fetch(`${API_BASE}/people`, {method: "POST",headers: { "Content-Type": "application/json" },body: JSON.stringify(body),});+ if (res.status === 403) throw new Error(PEOPLE_PRINCIPAL_ONLY);if (!res.ok) throw new Error(`Failed to create person: ${res.statusText}`);return res.json();}@@ -3021,12 +3026,14 @@ export async function updatePerson(id: number, patch: PersonPatch): Promise<Persheaders: { "Content-Type": "application/json" },body: JSON.stringify(patch),});+ if (res.status === 403) throw new Error(PEOPLE_PRINCIPAL_ONLY);if (!res.ok) throw new Error(`Failed to update person: ${res.statusText}`);return res.json();}export async function archivePerson(id: number): Promise<void> {const res = await fetch(`${API_BASE}/people/${id}/archive`, { method: "POST" });+ if (res.status === 403) throw new Error(PEOPLE_PRINCIPAL_ONLY);if (!res.ok) throw new Error(`Failed to archive person: ${res.statusText}`);}