Skip to content

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

925 KB
Raw Blame
# Curated, hand-written facts about the Open Executive architecture.
#
# This file is the highest-trust source of truth fed into the LLM when
# generating the /architecture page. It captures design intent and
# invariants that are not derivable from a quick code skim — the *why*
# behind the code. The page generator combines this with:
#   - live introspection (agents, workflows, openapi)
#   - repo code excerpts
#   - retrieved KB chunks
# A change to this file invalidates the cache and triggers regeneration
# of every section on next view.

system:
  name: Open Executive
  one_liner: A multi-agent AI system acting as a virtual corporate executive team.
  stack:
    backend: Python 3.11+ · FastAPI · Anthropic Claude SDK · ChromaDB · SQLite
    frontend: Next.js 15 · React 19 · TailwindCSS · Mermaid.js
  observability: |
    Opt-in request tracing via Pydantic Logfire (openexecutive.observability).
    Off unless LOGFIRE_TOKEN is set; then create_app() calls
    configure_tracing(app), which instruments FastAPI and get_provider()
    wraps every backend (anthropic / openrouter / local) in a tracing
    decorator. Spans: one per HTTP request, "specialist {name}" around
    router.route_to_specialist, "knowledge retrieve" around
    knowledge.retriever.retrieve, and "messages.create|stream {model}" per
    LLM call carrying gen_ai.usage.{input,output}_tokens and
    gen_ai.usage.cache_{read,creation}.input_tokens, so latency and
    prompt-cache hit rate are visible per turn. Invariant: no user content
    leaves the process — Logfire's own Anthropic / httpx instrumentation is
    deliberately NOT used (the former records message bodies on scrubber-safe
    keys; the latter records full URLs, and the Telegram bot token sits in the
    request path), the FastAPI argument mapper is replaced so endpoint bodies
    are dropped, a server_request_hook rewrites the request URL to its route
    template (path params such as /documents/{filename} never leave; query
    string, host, client IP and user agent are blanked), exceptions are
    recorded by type only via an exception_callback (SDK 4xx bodies echo the
    request), and incoming traceparent / baggage are ignored
    (distributed_tracing=False, add_baggage_to_attributes=False) so
    unauthenticated callers cannot write into the project. LLM spans are
    started without attaching context, because /chat pumps the streaming
    generator from fresh tasks and an attached context could not be detached
    across them. Tests are
    isolated by an autouse conftest fixture so a developer's .env token never
    turns tracing on in the suite.
  models:
    default: claude-sonnet-5-5
    deep_reasoning: claude-sonnet-5-5
    routing: claude-haiku-5-5
    provider_routing: |
      All LLM calls go through openexecutive.providers.get_provider(model).
      The registry returns the Anthropic SDK by default. When
      OPENROUTER_ENABLED=true (plus OPENROUTER_API_KEY), Claude calls are
      proxied through OpenRouter so usage is billed to the operator's
      OpenRouter account, and non-Anthropic slugs are added to the Council
      UI dropdown from OpenRouter's LIVE catalog:
        • openexecutive.providers.openrouter_catalog fetches the public
          GET {OPENROUTER_BASE_URL}/models at API startup (awaited, bounded
          by OPENROUTER_CATALOG_TIMEOUT_S) and again every
          OPENROUTER_CATALOG_REFRESH_S in a background task, then filters
          to: vendor prefix in OPENROUTER_CATALOG_PROVIDERS (default
          openai, google, anthropic, meta-llama, deepseek, x-ai), "tools"
          in supported_parameters, text-only output, no ":variant" suffix
          (:free / :batch / :thinking …), paid pricing, newest
          OPENROUTER_CATALOG_PER_PROVIDER (default 6) per vendor.
        • registry.openrouter_models() serves that cache; when nothing has
          loaded (fetch failed, OPENROUTER_CATALOG_ENABLED=false, CLI paths
          that skip the lifespan) it serves the hardcoded snapshot
          registry.OPENROUTER_MODELS instead — so a bad fetch degrades to
          the previous behaviour, never to an empty dropdown.
        • Catalog entries that are the same Claude model as an
          Anthropic-direct id (e.g. anthropic/claude-opus-5) are dropped to
          avoid duplicates; Claude generations that exist only on OpenRouter
          (e.g. anthropic/claude-opus-4.8) stay in and get the Claude feature
          spec.
      The rate-limited ``:free`` tier (and the utility_fast-only free-model
      matrix) was removed — its 429s surfaced as user-visible errors and the
      per-agent free-model surface was more than it earned; BYO-model routing
      through OpenRouter is otherwise unchanged.
      When LOCAL_MODELS_ENABLED=true (plus LOCAL_BASE_URL), the slugs listed
      in LOCAL_MODELS route to a self-hosted OpenAI-compatible server
      (Ollama / LM Studio / vLLM / llama.cpp) through the same provider seam,
      reusing the OpenRouter request/response/stream translator. Those slugs
      are added to the Council UI dropdown and get the tools-only local
      feature spec (no cache_control / thinking / web_search — a
      self-hosted server has no search plugin). This makes
      ANTHROPIC_API_KEY optional: a deployment with only local (or
      OpenRouter) models configured boots with no Anthropic key — the
      Settings validator just requires that at least one provider is
      reachable. Requesting a Claude model with no key and OpenRouter off
      returns an actionable 400.
      LOCAL_REASONING_EFFORT (optional, unset by default; one of none,
      minimal, low, medium, high, validated at startup) sends a top-level
      ``reasoning_effort`` on every local-backend request, streamed or not,
      unconditionally: local slugs get a no-thinking spec, so the Council
      deep-reasoning toggle never adds a per-call ``reasoning`` object on
      that path. It is added in the provider's ``_extend_body`` hook and
      logged once per model. Thinking-only
      hosted models (e.g. GLM on Fireworks, which rejects "none") otherwise
      spend the whole max_tokens budget reasoning and return no tool call —
      the onboarding interview then fails with "did not return a usable
      response".
      Slugs listed in LOCAL_MODELS route to the local backend before any
      other rule is consulted; remaining non-Claude slugs route through
      OpenRouter; selecting an
      OpenRouter-only slug with OPENROUTER_ENABLED=false is rejected at the
      API layer.
      Provider selection is per-call by model, not global — so the
      Executive can be on GPT-6 while the CFO specialist stays on
      claude-opus-5 within the same turn.
  invariants:
    - The internal sub-agent architecture is NEVER exposed to the end user — there is one voice (the Executive).
    - The Executive never signs messages under the name of company personnel or impersonates them. An identity addendum in system block 0 instructs the model to use its own exec name/email only. The single exception is Act as me (delegation) — with the person's own switch on and on their own verified turn in a conversation private to them, `ghostwrite_email` writes an email in their voice as a DRAFT in their own Gmail, never sent from chat (only that exact draft, when they tap Send on its reply card), never from the Executive's own account or bots, and never for anyone who has not turned it on (the principal, and team members once the owner lets them). The identity addendum itself is unchanged; the constant DELEGATION_ADDENDUM after it names the exception.
    - Voice follows the account. Text written as a person leaves only from that person's own Gmail (always as a draft first, sent only when they send it in Gmail or tap Send on its card); the Executive's own mailbox and bots always sign as the Executive.
    - The model cannot reach a delegated mailbox. delegation.gmail.DelegateGmail talks to the Gmail REST API directly and is never registered with the MCP gateway, so only typed handlers (ghostwrite_email, the voice learner) call it, and its credential never lives in WORKSPACE_MCP_CREDENTIALS_DIR. Every google_workspace__* call through the gateway acts as the Executive's own account (mcp_gateway._check_acting_account refuses any other user_google_email).
    - A teammate's own mail with the Executive is private to them. Every mailbox call the model makes through the MCP gateway (call_tool, a script's calls, a workflow step run from chat) passes through orchestrator.teammate_mail.guard_call_tool. Searches exclude every other teammate's address unless the reader is on the message too, except on a background run (Gmail query -from/-to/-cc OR'd with the reader's from/to/cc, headers forced on; Outlook lists always select the parties) and are filtered entry by entry; any other call naming a message or thread must use an id a filtered search returned to the same reader in this conversation (Session.mail_ids_seen, keyed by reader) or the inbound email the turn answers (email_poller seeds it); an Outlook call acting on a message (forward, reply, attachment) first reads its parties and is refused when it is another teammate's; a conversation where a non-principal teammate was shown their own mail is marked mail-private (session_store.mark_mail_private); Gmail thread/batch/search/attachment results are redacted in the audit log; reads are filtered message by message (a message naming another teammate is left out unless the reader is in its From / To / Cc); a Gmail reply with quote_original into a thread holding such a message is refused; Outlook search tools are refused. The reader is the principal or a teammate on a verified surface, or the teammate whose own email the turn answers when Gmail authenticated its From (Session.email_sender_authenticated); anyone else sees no teammate's mail. A background run the model drives (schedule_followup, reflection) reads as the principal; a workflow step outside any session reads as nobody (filters on, id gate off). Outlook mail rules / mailbox settings that forward or name another teammate are refused. The first turn that shows a non-principal teammate their own mail also marks that turn's remaining audit rows (its answer included) private to them. Internal callers (poller, brief) are unaffected. Fails closed when the roster can't be read.
    - An email from the team or the principal that got no reply becomes a Needs you card, with no model in the loop. The MCP gateway marks on the conversation who each accepted send reached (Session.mail_sent_to for Gmail send_gmail_message to/cc and Outlook send-mail recipients; Session.mail_replied_ids for the message an Outlook reply-mail-message / reply-all-mail-message answered). After the turn, email_poller._note_reply_outcome checks the sender's addresses and the message id; with no reply it files integrations.unanswered_mail's card (source unanswered_email, high, private:principal, routed to the principal), one per thread with repeats folded into its occurrence count, resolved by a later turn that replies. Only mail Gmail proved is the principal's (Session.email_authenticated) carries its subject and what the Executive wrote; a teammate's card names who is waiting, never their subject or text; mail only claiming a team address says it could not be proven. A plain-text Error tool result is not counted as a send. Contacts and senders off the team are skipped. Why — Needs you shows alerts only, alerts depended on the model calling create_alert, and turns that ended without a send (a refused tool, an answer only written) left the sender waiting while only the brief, which reads the inbound log, said so.
    - A teammate's own conversations with the Executive are private to them too. Every audit row of a turn a non-principal team member speaks on a verified surface, or by email Gmail authenticated as theirs, carries private_to_person (people_tools.teammate_turn_owner via audit_row_owner; the pre-bind rows via rows_for_person in audit_rows_on_senders_turn, the web chat route and the email poller). An unproven sender keeps the ordinary rule so a forged From can't hide a turn from the principal. The /audit read routes give the principal every row, a team member's own (their turns, Act as me, history notes) as an action only (api.routes.audit._redact: rebuilt summary naming the tool and whose conversation, safe details only, no full payload, left out of text search), and anyone else (once a principal exists) only their own rows in full (api.routes.audit._view, AuditLogger only_owned / all_owners); /audit/usage is unchanged. A teammate's web chat or DM (not a channel or group session, chat._shared_space) opens for its owner alone, the principal included (chat._session_access). A message the Executive sends to someone else on a teammate's turn is linked without its originating session, so the recipient's reply is not hydrated with an excerpt of the teammate's chat (schedule_tools._record_outbound_context).
    - A web chat its owner shared (session_shares) is one its members write in with the owner, live, and it is no private conversation. Members get the turn's access through chat._shared_member, never its ownership, so they can't delete, rename, rate, share or redo it, and a mail_private chat or a chat-app conversation is never shared. Every turn there sets Session.shared_chat, which turns off Act as me (delegation.settings.private_conversation), the open-loop private surface (open_loop_tools._is_private_surface), a teammate's own mail (teammate_mail._reader_id), the principal's private alert cards, roster requests and find_alerts (briefing.context.render_and_trust) and the principal-only tools (content_trust.principal_only_withheld), because everyone in the chat reads every reply and writes into what the next turn reads. Someone archived is out of every shared chat (chat._shared_member). Live streams are capped per person, per chat and per process. Each person's message reaches the Executive as [Name]: in the history and the current turn, and the note naming who is in the chat rides in channel_context_block, never a cached block. api.chat_live publishes each turn to the pages that have the chat open (GET /sessions/{id}/live); it is in-process, holds nothing on disk, and a page that reconnects reads the saved chat.
    - In a shared web chat the note in channel_context_block names the chat's owner and says the others' lines are messages from them, not the owner's instructions. While anyone but the owner has written since the owner's last message (Session.others_spoke_last, from the saved history, the speaker included, true when unreadable), the turn is neither offered nor run SHARED_CHAT_WITHHELD_TOOLS (direct messages, broadcasts, meeting invites and cancellations, follow-ups, roster writes, workflow runs, saves and suggestions) nor a gateway mail send, reply, forward or draft or calendar write that mails attendees (schedule_tools.shared_chat_withholds); this holds on the owner's own turn right after another's line too, and the owner's next message with nobody else's in between lifts it.
    - Every chat turn says when it is. _build_messages opens the user turn with a <current_time> hint (_current_time_block - weekday, date, HH.MM, IANA zone and UTC offset, in workspace_settings.get_user_timezone, the briefs' zone). Without it a chat turn had no date and the model guessed one, e.g. from the newest record a tool returned. User turn, never a cached block, since it changes every turn.
    - The Executive never offers to loop in, DM, or notify the human it is currently talking to. Each chat turn carries a <current_speaker> hint in the user turn (resolved from the caller's person_id, principal-flagged) and the persona "Choosing Who to Tell" rule forbids routing to anyone already in the room — so the principal reading a brief is never told the Executive will "loop Jordan in."
    - Specialists run in parallel via route_parallel() for cross-domain questions.
    - The untrusted-content policy (orchestrator.content_trust) is the one rule for text the principal did not write — inbound email, chat, attached files, watched pages. WHO SPEAKS - the principal only when the surface proved it (principal_speaking - web chat as the principal, CLI, their own Slack/Discord or secret-verified Telegram, their own address with Gmail dmarc=pass); an empty origin_channel is never read as trust. MEMORY - episodic extraction only then, and only on words outside <untrusted_content> blocks; peer memory and open loops are recorded under the speaker's own name, never as the principal's. TOOLS - writes on the principal's authority refuse others in their handlers; PRINCIPAL_ONLY_TOOLS (load_mcp_server - it connects the install to any URL; list_saved_tools and run_python_job - the principal's own automations and library files; run_script - it runs code the model just wrote, spending the turn's whole call budget) are not offered unless the principal is speaking on an interactive surface (email excluded, even authenticated), and a call emitted anyway is refused with a not_principal audit row. LABEL - outside text sits in the user turn inside <untrusted_content source author author_verified> with a fixed no-authority notice; NFKC folds compatibility forms, control characters are dropped and the tag's name is renamed wherever the text carries it (any case, spacing, entity-escaped), so the text cannot close its block. The principal's authenticated mail is theirs, but what it quotes or forwards still goes in a block (source email_quoted). A new inbound surface is an entry in this module, not a gate invented at its call site.
    - Outside content (orchestrator.outside_content). Once a turn has read text from outside the team - any gateway read (a call_tool other than a Google or Microsoft 365 tool whose name starts with a write verb), an attachment on the message, a web search result, a synced Drive / OneDrive / Confluence / Notion excerpt (the retrieved context's synced headings, or retriever.retrieve returning one), read_document, run_executive_research, or an extension tool registered reads_outside (a vendor app) - for the rest of that turn the chat loop refuses what the Act as me lockdown refuses (mail_touched_withholds), every upsert_person but a contact the speaker named this message at an address they typed or one that sent the mail read (lockdown.speaker_named_contact, never on a SENDER turn; the refusal points to an add_contact card), and every call_tool but the reads in MCP_CLIENT_MCP_TOOLS and a OneDrive file read, so no mail, Docs, Sheets, Drive or calendar write. The company's own Drive is not outside text: before a round (and before each run_script call) vet_reads looks up the one item a Google read names by id (company_read_item and _COMPANY_READS - Drive file content and downloads, folder listings, Docs, Sheets, Slides and their comments; never searches, forms, mail or calendar, and never with a drive_id, query or URL argument), once per id a turn, through MCPGateway.company_drive_items; a read of an item that is the company's own (mcp_gateway._company_item) marks the turn COMPANY instead of GATEWAY. COMPANY holds the same calls (anyone who can edit a company file wrote its words), except that while every read so far is COMPANY a rename or move passes (_company_rename - update_drive_file with only file_id, name, add_parents, remove_parents; _company_only checks the round's pending reads too). The Executive's own files go through the same check, so one it shared outside is not the company's. A refusal tells the model a rename or move the person asked for can go on a drive_files approval card. A round that calls a read also holds that round's other such calls (they run together); the read itself runs and marks the turn once the round is done; a web search marks it as soon as the response arrives. Inside run_script each call is checked, and a read marks the turn for the calls after it. Handlers that reach outside re-check (lockdown.outside_reach_refusal), including the gateway's call_tool. The offered list never changes (the cached prefix stays the same) and the state lives in a context variable and on the session (session.turn_outside, found through current_session, because the web chat route resumes the generator in a fresh task per step), set by begin_turn and closed by end_turn, so nothing after the turn (the poller sending the reply) is held. Like the Act as me lockdown it lasts for the turn only; the next turn's history carries the reply, not what the tools returned. Mail to the Executive from someone not in People (a contact or a stranger) is outside text from its first word, so the email poller sets Session.sender_off_team, begin_turn marks the turn SENDER, and the whole turn is held; it may still raise an alert (create_alert), which is how that mail reaches the principal (private to them, routed to no one else, with the mail's real sender as its from), it may not send direct messages or remove watchlist entries (SENDER_WITHHELD_TOOLS), and a refusal on it tells the model to put the request in an alert rather than ask again. The poller's own audit rows still feed the brief. Separately, someone added to People this turn by upsert_person (or given a new address or chat account) is held until the next turn. _roster_allow_set leaves them out of the gateway's mail, calendar and Drive allow-list (the refusal says why, _block), and _guard_outbound, message_person and calendar attendees refuse them. What a turn held (outside_withheld_error and mail_touched_withheld_error call note_held) is kept in process, per conversation and speaker (never in a shared chat or a SENDER turn), for the next turn for HELD_TTL_SECONDS (an hour). When that message is a go (GO_RE - a short yes, or one opening with go, go ahead, do it or proceed as its own clause), begin_turn sets go_first, and the first round with a read has its reads (source_of, or a mailbox read tool) refused once with go_first_error, which names no tool and asks for nothing new (defers_read), so the approved writes run before a re-read holds them again; reads run from the next round. Nothing is replayed; the model makes the calls under every usual check. In the web chat the go is a tap - pending_held gives the held steps in plain words (step_words - only names it knows, else the app's generic label, as a tool name the model chose can carry planted words) to the chat stream's held_steps event and to the last reply in GET /sessions/{id}/messages, the UI shows Approve and Not now under the reply, and Approve sends Go ahead as the person's own message; a web turn's refusal (approve_hint, TurnOutside.web from Session.from_web_chat) points at Approve instead of asking for a typed go. Why - the owner asked for a tap instead of say go. A SENDER turn remembers nothing.
    - Safety level, When should I check with you? (orchestrator.outside_mode, orchestrator.content_scan). The owner's level, one row in outside_content_mode with the company's level and the channels set apart from it (channels JSON - web, slack, google_chat, telegram, discord, email; a turn on any other surface follows the company's level), changed only by the principal (GET/PUT /executive/outside-content, Settings -> Your Executive), fixed per turn by begin_turn as TurnOutside.mode from the turn's channel (channel_of). Every outside read is checked at every level by content_scan - one small-model call (classifier_model) with no tools that reads the content as data and reports steers_assistant plus categories from a fixed list (CATEGORIES) - so no words of the content reach the person through the verdict; a failed call, an unreadable answer, content over MAX_CHARS or a turn past MAX_PER_TURN checks is unchecked; verdicts are cached by content hash. The check flags only text written to an assistant or a system, never one person asking another to forward or share (a false flag on a deal email's search made the reply claim a forward request no email held). A search of the owner's own mail is checked entry by entry (content_scan.scan_list, items naming the flagged entries) - a flagged thread's subject and sender name are left out behind LEFT_OUT_NOTICE and the rest passes once a second check finds it clean, holding nothing below Careful; a flag naming no entry flags the whole list as before. A thread whose newest message the Executive itself sent is not checked - its own address, which the mail service authenticated on the search (ThreadSummary.sender_authenticated - Gmail's Authentication-Results, or Exchange's stamp on an Outlook search, the same proof as a message read; kept per turn in TurnDelegation.mail_verified), under a subject that is not a reply's or forward's, since those carry someone else's words (the Executive's own deal summary for a teammate was flagged as a forward request). A read whose text is in hand is checked in mark_read; an attachment or a synced excerpt is queued (mark_pending - the retriever runs in a thread) and checked by settle before each round's tools are dispatched and before each run_script call. ask (Careful) is the hold above - every read marks the turn. outsiders (Balanced, the default) marks it only when the check flags the read (Verdict.holds); a read it couldn't check reaches the model behind UNCHECKED_NOTICE and marks nothing (except content too big to read whole or read past the turn's MAX_PER_TURN checks, TOO_BIG, which marks like a flag, since padding or a pile of harmless reads is how content would dodge the check), and nor does a web search (its results arrive encrypted, so nothing checks them). Reads from the team are not even checked - a Gmail search showing only ids, a Gmail message read whose every sender is a teammate (not a contact) that Gmail authenticated (fact_confirmation.sender_authenticated on a raw read of each id, at most 10) with no other address in it, or a calendar read naming only the team where the Executive itself organized every event (a teammate's invite is outside, since an invite's organizer is what the mail that brought it says; Google get_events only when detailed or for one event; Microsoft 365 calendar reads) (from_the_team). trust (Hands-off) applies only on the principal's own turn on an interactive surface that is not email or a shared chat (content_trust.principal_only_withheld empty), where no read marks the turn but an attachment or synced excerpt the check flagged (the model read it before its check), a round that reads holds none of its other calls, a result the check couldn't read reaches the model behind UNCHECKED_NOTICE, and reading their own mail locks nothing but posts to everyone and roster changes (delegation.lockdown.mail_lock_holds); anyone else gets Balanced. The owner's own mail is checked the same way (outside_content.check_mail_read after each round that reads the mailbox or notes, setting TurnDelegation.mail_held and mail_vetted) and the Act as me lockdown follows the level - Careful holds it after any mail read, Balanced only once a mail read was flagged or too big to check or while one is unchecked (the reading round holds its other calls), Hands-off not at all - while MAIL_PRIVATE_WITHHELD_TOOLS (broadcasts, department messages, alerts, roster and authority changes) and an upsert_person the speaker didn't name stay shut after any mail read at every level (lockdown.mail_turn_withholds, used at dispatch, in outside_reach_refusal and by app_control). Why - the owner asked for the mail hold to follow the same level after the per-channel level freed almost every other read-then-act request. At every level a flagged read's result reaches the model behind FLAG_NOTICE (data, not to be followed; never brought up in the reply, since the person sees the flag apart from it), each flag is logged as content_flagged with which item it was (a mail's subject and sender, private to the person), and the flag is kept in plain words (flag_words - the module's own words around that item) for the web chat's flags event and the last reply in GET /sessions/{id}/messages (pending_flags, an hour, in process, per conversation and speaker, each turn replacing the last's). Shared chats, another AI app's turn and mail from someone not in People are always Careful; sends still go only to People; someone added this turn waits for the next. An unreadable setting is Careful. Why - the hold stopped almost every read-then-act request, and the owner asked for one lever the person sets anywhere from careful to hands-off, per channel, that cuts that friction (so Balanced stops only on a real flag, and the check flags only clear instructions to an assistant), with the content always checked and flagged. The test suite pins get_mode to ask (tests/conftest.py) and every check to unchecked (content_scan.scan).
    - The workspace mode (memory.workspace_settings, `workspace_settings` table) is per install and defaults to team. Solo (one person using Open Executive just for themselves) runs no department check-ins anywhere — bootstrap_cadences and enqueue_next are no-ops and the runner cancels a stray dept_cadence row without running or chaining it — but department rows are kept, so switching back is instant. A Session may carry an explicit `workspace_mode` override (read via effective_workspace_mode) so a caller running several conversations on one Executive, such as evals, can pick the mode per session; otherwise the install-wide mode is read fresh at the start of each turn and pinned on the session for that turn only (Session.turn_workspace_mode, via pin_turn_workspace_mode), so every tool handler in the turn uses the mode its persona and tools were built in. The same row holds the principal's role (role_kind owner | in_house | independent | other, role_title, reports_to, remit, measured_on; all nullable) — solo is about who uses Open Executive, not the principal's level. Only solo mode reads it (the solo org block's role lines and the specialists' <principal_role> tag), and team output is byte-identical whether a role is stored or not. A Session may carry a `principal_role` override (effective_principal_role) for the same reason as the mode override.
    - A global operator pause (scheduler.pause, `executive_control` table) gates every autonomous loop — the scheduler, the Gmail poller and the workflow resumer. Inbound conversations (web chat, Slack, Discord, Telegram, Google Chat) are never gated. Pausing holds work, never cancels it.
    - Each specialist gets its own RAG fetch filtered by its declared domain alias.
    - System-prompt blocks marked with cache_control must remain byte-identical across turns — any dynamic content in them breaks Anthropic prompt caching and roughly 10× the cost.
    - Total cache_control blocks must stay ≤ 4 (the Anthropic API hard limit), with longer TTLs before shorter ones. The layout is tools 1h, persona 1h, then company 5m on a first message or the history marker 1h once there is history, then the agent loop's 5m marker (see `caching.breakpoint_budget`).
    - Tool definitions are sorted by name before being sent to the API so cache hits survive across processes.
    - Company-specific data lives under packages/core/company/ and is gitignored. Never commit it.
    - Audit writes never break a chat turn or tool call — exceptions are swallowed with a warning.
    - Provider selection is per-call by model (openexecutive.providers.get_provider(model)). A single chat turn can mix Anthropic-routed Claude calls, OpenRouter-routed non-Claude calls, and locally-routed self-hosted models — no global "current provider" state.
    - When a non-Claude or local model is selected, Anthropic-only fields (cache_control on system/tool/user blocks, adaptive thinking + output_config) are stripped by the feature gate before the request leaves the process. The web_search server tool is kept for every OpenRouter model (the translator swaps it for OpenRouter's `web` plugin, which serves any model) and stripped only for a self-hosted OpenAI-compatible backend, which has no search plugin. Callers do NOT need to know which model they're routing to.
    - ANTHROPIC_API_KEY is optional: a Settings validator requires at least one provider (Anthropic key, OpenRouter, or local models) to be configured, so an Anthropic-free deployment is supported but a zero-provider one fails fast at startup.
    - External-monitor adapters are read-only — they never write to upstream systems. The whole `monitoring/` subsystem is observation-only; surfacing happens through the alert pipeline, never via a direct upstream side-effect.
    - External signals never auto-execute on the principal's behalf. Every signal that surfaces is proposed via the alert pipeline (and thus subject to triage / mute / severity gates); the scheduler never dispatches an outbound message directly off a signal.
    - An external signal whose `dedup_key` already exists is dropped at ingest via the UNIQUE(dedup_key) constraint on `external_signals`. Adapter retries / re-polls cannot multiply alerts for the same upstream event.
    - Alerts have a lifetime. Every user-facing surface (`/today`, the chat `<briefing>` block, the briefs, the reflection) reads `alerts.lifecycle.list_live_alerts` — unread, inside its category TTL, not snoozed — and the scheduler sweep persists the same predicate as status `expired`. `artifact` and `decision_scheduling` rows are exempt (own lifecycle). Every autonomous close is reversible via `POST /alerts/{id}/reopen`.
    - A repeat of an open alert with the same `(source, dedup_key)` coalesces into the existing row (`alerts.store.coalesce_alert`) rather than inserting a second card, and does not re-dispatch unless severity rose into high/urgent. Monitoring alerts carry a producer-supplied `watch:<slug>` key so one watch = one open card.
    - Unattended prose is grounded deterministically (`briefing.grounding`, no model in the check). The morning brief, the EOD digest, the executive reflection's "Flagged for the brief" bullets and its outward tool calls (message_person, send_department_message, send_company_broadcast, schedule_followup, create_alert), triage's rewrite of an alert and the alert review's rewrites may name only people and figures found in their own inputs — the rendered context, the tool results so far, the event, the evidence — or the company profile. Standing facts (memory.facts) count as input wherever the prompt carried them: they sit in the brief, digest and reflection context, and the alert review grounds its rewrites against the batch's STANDING FACTS block too, so correcting a card to the principal's correction is not refused. A name must appear whole in ONE source line (or belong to a roster person some source mentions; being on the roster alone is not enough); a figure (money, %, k/M/B, bare numbers ≥ 11) must match a source number within the precision the prose shows. What fails is held back (briefs — one repair call, then the line is dropped and a "held back N lines" note added), refused with a reason the model can act on (tools), or replaced by the event's own text / the old text (alerts, made inert first — links masked, markup and @-mentions stripped). Fail-open; `GROUNDING_CHECKS=enforce|report|off`; every finding writes a `grounding` audit row.
    - Every brief knows its reader in code (briefing.reader). The /today header, morning brief and EOD digest mask the reader's full name and addresses in their context to "the reader", head it with THE READER line, and share READER_NAME_RULE ("you" for the reader, never their name or "the principal", anyone else by name, "I/me/my" for the Executive). A draft that still slips is rewritten once, then fixed in code. Before this the header had no reader at all and called its own reader by name or "the principal".
    - The alert review model (`agents.alert_review`) never mutates state. `alerts.review.apply_verdict` is the only writer: it closes only on a high-confidence `resolved`/`stale` verdict with named evidence, routes only to a person on the roster slice it showed the model (scope-holders or the principal for board/comp/legal matters), runs department moves through `departments.authority.gate_action` (propose-only → `propose_via_alert`, never a third-party DM), caps outbound moves per pass, and audits every move with its evidence and prior state. Status `resolved` (Executive closed) is distinct from `ack` (user approved).

  update_check: |
    GET /version (api/routes/version.py) returns the running version
    (the FastAPI app's release-please-stamped version), the latest
    published release and `update_available`. The latest release comes
    from GitHub's public releases API for SenteLabsAI/OpenExecutive,
    cached in-process for 6h (1h after a failure, keeping the last good
    answer). Only `tag_name` is read, and only an `X.Y.Z`/`vX.Y.Z` tag is
    accepted; the release link is built from that tag, never taken from
    GitHub's response. Behind the shared-secret gate like any route.
    `UPDATE_CHECK_ENABLED=false` skips the GitHub call entirely and still
    returns the running version. Settings → About renders it. There is
    deliberately no in-app update action: replacing containers would need
    the Docker socket (host root) in the API container, so upgrading is
    documented host-side in docs/deployment.md#upgrading.

caching:
  block_layout: |
    Two cache_control blocks (down from four, consolidated in commit c27dcec
    to stay within the Anthropic 4-block API limit alongside any other
    ephemeral markers the request uses).
  breakpoint_budget: |
    The full 4-block budget, and why none of it is spare:
      1. last client tool (1h)         — executive tool list
      2. persona + knowledge (1h)      — system block 0
      3. company + org (5m, optional)  — system block 1, on a turn with no
         history; with history the slot goes to the history marker (1h) on
         the newest non-empty history turn (normally the previous reply)
      4. newest tool_result (5m)       — the agent loop's intra-turn marker
         (on the loop's first call, before any tool result, the slot marks
         the message being answered instead: executive._mark_turn_message,
         so the turn's context is written once and read back by later
         calls rather than sent uncached and then written; it comes off
         when the loop marker lands)
    The history marker (executive._apply_history_cache_marker, applied by
    the agent loop, never by _build_messages) is what lets the next message
    read the conversation back. History turns are rebuilt from plain text,
    so the previous turn's loop entries (which ended inside that turn's
    retrieved context and tool calls) never match; without the marker every
    message re-wrote the whole history into the cache. The
    company block keeps its place in the prefix, covered by the history
    marker, and losing its own 5m marker keeps the TTLs in the order the API
    requires (1h before 5m). 1h because people reply in minutes; a 5m entry
    would mostly be gone. Session.get_recent_history moves its window's
    start in steps of 10 turns (20 to 30 turns kept) so the first history
    message, and with it the cached prefix, stays put between steps.
    On OpenRouter the translator keeps every assistant turn as typed text
    parts when a request carries the history marker
    (translator._request_caches_assistant_text), so the marker is forwarded
    and a reply has one shape whether marked or not.
    The committee revision call reuses the turn's messages without the
    history marker, so its request keeps the plain two-system-marker layout.
    A rolling marker on every history turn used to claim a latent fifth
    breakpoint, which Anthropic rejects outright on the direct path.
  block_order:
    - id: persona_and_knowledge
      ttl: 1h
      what: |
        Executive persona constant — EXECUTIVE_PERSONA_PROMPT (team) or
        EXECUTIVE_PERSONA_SOLO_PROMPT (solo), picked by
        build_system_blocks(workspace_mode=…) — or an admin-set persona
        override, which wins as-is in either mode +
        {VOICE_PERSONA} substitution + conditional WEB_SEARCH_ADDENDUM and
        MCP_ADDENDUM + identity addendum (exec name/email, impersonation
        guard) + Connected Systems section (prompts/connected_systems.py:
        Google Workspace on/off from the running gateway's server_names, and
        when on the own-account guidance plus the pinned GOOGLE_TOOL_MANIFEST
        names to call directly — or "needs reconnecting", with no tool
        names, while google_workspace is in MCPGateway.needs_reconnect (set
        by _note_grant_health when a tool answers with an authorization
        failure, mcp_gateway.grant_failure; cleared by the next answer that
        is not one, or mark_reconnected), passed as needs_reconnect=
        gateway_reconnect_needed(gateway) so the set changing re-renders
        block 0 once; other MCP servers by name; Slack / Discord /
        Telegram / Google Chat on/off; Notion sync; a constant Act as me line
        pointing at DELEGATION_ADDENDUM — all process-stable and sorted) +
        DELEGATION_ADDENDUM (Act as me — a constant, only while
        anyone on the install has it on) + timezone addendum +
        KNOWLEDGE_INDEX_SUMMARY.
        The timezone addendum names the user's zone from
        memory.workspace_settings.get_user_timezone() (the workspace's zone,
        else USER_TIMEZONE, else UTC), read fresh on every build.
      why_cached: |
        All components are either constants, file-loaded once at startup,
        or admin-mutable but otherwise stable. Long TTL because these
        blocks change rarely. Setting a new time zone (PUT /workspace)
        changes the addendum, so the 1h block misses once on that change
        and is warm again from the next turn — accepted, since the zone
        changes about never and a stale zone would mis-schedule follow-ups.
        Act as me works the same way: build_system_blocks(delegation=...)
        is passed delegation.settings.block0_delegation_on(session) — the
        install-level setting (or an eval session's override), never a
        per-turn or per-speaker value — so switching it misses the 1h block
        once. Off, block 0 is byte-identical to an install without it.
    - id: company_and_org
      ttl: 5m
      what: |
        company_profile.to_prompt_block() rendering of profile.yaml +
        render_org_block(mode=workspace_mode) from
        departments/prompt_block.py — team: departments, heads, principals,
        charters, the People roster; solo: a "## Your Principal" line
        (name, person_id, reachable channels), the principal's role lines
        when set (Role / Reports to / Responsible for / Measured on, from
        the workspace settings or a Session.principal_role override), and
        "## Your Principal's Goals" grouped by
        area (a department row), with no authority levels, heads, cadences,
        channels or roster. Same 4000-char cap and sanitizing either way.
      why_cached: |
        Changes when the profile YAML or department/people state changes,
        or the principal edits their role (set once per install, so it is
        as stable as the rest). Shorter TTL so org edits propagate quickly.
        Only emitted when non-empty. Per mode, two stable variants: with the
        principal's private `## Contacts` section (only on the principal's
        own verified turn — `build_system_blocks(include_contacts=...)`,
        decided by `executive._contacts_in_prompt`; after the team block, or
        after the solo "## Your Principal" line, role and goals) and without
        it (every other turn, byte-identical to an install with no contacts).
        Nothing per-request.
  per_mode_prefix: |
    Solo mode (one person using Open Executive for themselves) changes three
    cached parts, all resolved ONCE per turn by
    memory.workspace_settings.pin_turn_workspace_mode(session) (the
    Session.workspace_mode override, else the workspace read fresh), which
    also pins the result on Session.turn_workspace_mode so every tool
    handler in the turn (schedule_followup, create_calendar_event, the
    dispatch guard) reads the same mode through effective_workspace_mode —
    a switch made mid-turn applies from the next turn. They agree on:
    the block-0 persona (the solo constant), the block-1 org block (the solo
    render), and the tool prefix (orchestrator.schedule_tools.
    filter_tools_for_workspace_mode drops send_company_broadcast,
    send_department_message and set_department_head BEFORE the sort, so the
    solo list is still sorted and still carries its 1h marker on the last
    tool). Every piece is a constant or stable per install, so each mode has
    its own warm cache and a mode switch misses once. Team is byte-for-byte
    unchanged: prompts/executive_persona.py is plain literals concatenated
    at import (shared head / body / tail + _TEAM_* or _SOLO_* sections, never
    formatted) and a test pins the team prompt's sha256.
  private_turn_prefix: |
    A turn private to the principal (Session.private_to_principal — the email
    poller sets it for mail from one of their contacts and for mail they
    forwarded) is sent the tool list without
    schedule_tools.PRIVATE_TURN_WITHHELD_TOOLS, dropped BEFORE the sort like
    the solo and unattended sets, so it stays sorted, keeps its 1h marker on
    the last tool, and private turns in a mode share that one stable prefix. The
    system blocks are unchanged: such a turn comes from email, which is never
    the principal's verified surface, so block 1 is the no-contacts variant.
  delegation_tool_prefix: |
    Act as me adds a tool instead of withholding one. ghostwrite_email lives
    in its own registry (orchestrator.delegation_tools.DELEGATION_TOOLS),
    never _ALL_SKILL_TOOLS. On a turn delegation.settings.pin_turn_delegation
    offered it to (the principal's own verified, attended turn in a private
    conversation, with it on) it joins the pool BEFORE the sort, so those turns share one
    more sorted prefix with the 1h marker on the last tool, and every other
    turn's list is byte-identical to before. The offer deliberately ignores
    the Gmail connection (the handler checks it per call), so a lapsed token
    never flips the prefix. The ghostwriter's own call carries no cache
    markers: a short constant GHOSTWRITER_PROMPT plus the person's voice
    block, sent only when a draft is written. The mail-touched lockdown
    (delegation.lockdown) refuses at dispatch and never removes a tool from
    the offered list, so a turn that reads the principal's mail keeps the
    same prefix from its first round to its last. recall_history (Always in
    the loop, orchestrator.history_tools) joins the same way when
    history_tools.recall_person allows it, before the same sort.
  turn_reading_budget: |
    TOOL_RESULTS_TURN_MAX_CHARS (default 40,000; 0 = off) bounds what all of
    one turn's tool results add together, since every result is re-sent on
    each later call of the turn. executive._turn_result_limit gives each
    result min(TOOL_RESULT_MAX_CHARS, what is left), never below 3,000
    (_TURN_BUDGET_FLOOR), and _cap_tool_result(budget_spent=True) replaces the
    marker's "call the tool again more narrowly" advice (that re-read would be
    cut too) with: the question has read as much as it can: answer from what you
    have and say what you could not read, and never edit, rewrite or replace
    anything from that cut result, so a partial read never becomes a lossy
    write. The read the question needs to edit may be the cut one, so
    executive._TurnReadingBudget gives each turn one full re-read: repeating a
    cut call with the same tool and input (compared as sorted JSON) is answered
    with the stored full result (replay, before dispatch) under the per-result
    cap, never by running the tool again (the cut may have been a write), and
    the marker offers that while it is left;
    after it, the marker says to offer the edit as its own request (a fresh
    budget). A turn so reads at most the budget plus one result. A result short
    enough not to be cut never spends the re-read. consult_specialist results neither
    count nor are cut (they are the analysis, not a read); run_script results
    count but are never cut below the per-result cap, since step_script puts
    the list of writes that already ran at their head and a 3,000-character
    cut would hide some, so the model would repeat them. open_tools and
    search_tools results are treated the same way (_NEVER_CUT_BY_TURN_BUDGET):
    they are the schema the next call needs. Pairs with
    TOOL_BUILDING_ADDENDUM's multi-read rule: an answer that needs three or
    more reads builds a run_script tool that returns only what answers the
    question, so the budget is rarely reached.
  extensions: |
    orchestrator.extensions lets an install add chat tools and kinds of
    document without changing this code. OPENEXECUTIVE_EXTENSIONS names
    Python modules, imported once (first turn or first Documents read); each
    register() calls register_tool / register_collection, and a module that
    fails is logged and skipped so the install still starts. A tool's name
    may not be one the loop knows (executive.builtin_tool_names). Extension
    tools are never in _ALL_SKILL_TOOLS, so reflection, research and the
    synthesis never get them; the chat loop adds them per turn like the Act
    as me tools, never on an unattended run, a turn private to the
    principal or to a speaker not on the People list, and only where the
    tool's offered(session) says. known_caller=False lifts the People-list
    rule for that tool alone (an extension surface that names its user
    without proving who is speaking, so the turn has no caller_person_id);
    register_tool then requires an offered(), which decides alone. Never on
    an unattended, private, AI-app (mcp_client) or replay turn either way.
    That
    predicate must depend only on the kind of turn, so each kind keeps one
    cached tool list. Act as me's lockdown refuses them after a mail read
    (unclassified, fails closed), except one registered with
    after_mail_read=True: it only reads the install's own data and carries
    nothing the model wrote anywhere outside. A tool may sit in a tool group, new or
    existing (tool_groups.add_to_group, done at load, so the groups are
    fixed per process). Its chip goes through summarize_action's usual
    no-chip rules, and a chip link must be a path inside the app. A
    waiting_for_approval result is the extension chip's to describe
    (summarize_action skips its generic held-action chip for an extension
    tool: the department gate never holds one). activity_label names the
    chat's activity line while it runs (activity_labels._extension_label,
    after the built-in labels), and private_row makes its dispatch audit row
    private (executive._private_tool_row). A
    collection is a drafted artifact tagged collection:<name>: the record
    carries it, GET /artifacts returns collection / collection_label, the
    Documents page shows one filter per collection, and archive, restore and
    delete call the collection's on_change first (502 and no change if it
    raises). draft_artifact(supersedes=) refuses a collection's document.
    The alert pipeline strips collection: tags, so only an extension's own
    code files into its collection. A module failing partway through
    register() is rolled back. ExtraTool(workflow=True) also offers the tool
    to workflow action steps as oe__<name> (tool_catalog._extension_specs,
    merged under the fixed built-ins, which win a clash; name at most 60
    chars so the prefixed name fits 64). offered() is not asked there: the
    step's approved tool list is the approval, and the call runs inside
    extensions.workflow_step(name) so in_workflow_step(name) is True for
    that tool only, and the handler decides what an unattended call may do
    (it must not call other extension handlers or leave tasks running). read_only=True is the
    only way to be labelled reads-only on the review card.
  deferred_tool_groups: |
    The less common skill tools are not in the tool list. orchestrator.
    tool_groups.GROUPS puts them in named groups (calendar, people, memory,
    corrections, goals, watch_and_alerts, workflows, documents, app,
    messaging), and
    tool_groups.split takes them out of the turn's offered tools after every
    filter (workspace mode, unattended, private turn) and BEFORE the sort,
    adding two small tools in their place: open_tools(group), whose
    description names every offered group and its tools, and use_tool(name, input).
    open_tools is answered in the loop with the group's tools (name,
    description, input_schema) as a tool RESULT, never by changing the tool
    list, because the list is the start of the cached prefix: a list that
    grew mid-turn would miss the cache for the tools, the system blocks and
    the whole history. So the list is the same on every call of every turn,
    and a group's descriptions are paid for only on a turn that opens it.
    open_tools' description (tool_groups.open_tools_tool) and its results
    name only the tools the turn offers, so a private turn never sees a
    withheld tool's name; the description depends only on that set, fixed
    per kind of turn, so each kind keeps one stable list. A use_tool call is rewritten into the
    tool's own call (same tool_use id, the model's assistant block left as
    sent) before dispatch, so it meets the same guards (workspace mode,
    private turn, unattended, Take the lead), handler, progress events and
    audit rows as a direct call. use_tool accepts only names in
    tool_groups.DEFERRED; anything else, or input that is not an object,
    gets an error tool result. The everyday tools (consult_specialist,
    propose_form_values, read_user_guide, message_person, lookup_person,
    list_people, remember_fact, follow-ups, the MCP meta-tools) stay direct.
    This cut the direct list from about 19.5k to about 6-7k tokens, which
    every model call of a turn re-sends. ask_about_person (people group),
    forget_fact and update_company_profile (memory group) moved behind
    open_tools later: on a busy test install they ran about 2 times in 674
    answers, and their ~5k characters of descriptions were re-sent on every call.
  rag_context_placement: User turn (NOT the system prompt) — RAG hits vary per query, would poison the cache if cached.
  intra_turn_cache: |
    executive._apply_loop_cache_marker moves a single ephemeral marker onto
    the newest non-empty tool_result after each iteration of the tool-use
    loop. Without it the loop caches only the static tools+system prefix and
    re-sends its whole accumulated transcript at full input price on every
    iteration; the runtime signature of that bug is cache_read_input_tokens
    pinned flat while the prompt grows iteration over iteration.
    The marker MOVES rather than accumulates — each pass sweeps every
    tool_result clean before re-marking the newest. Left in place per
    iteration it would reach max_iterations breakpoints and blow the 4-block
    limit. Sweeping first also makes the helper idempotent and self-healing:
    there is no bookkeeping index to drift out of sync.
    The marker must stay at the tool_result block's own top level —
    providers.feature_gate._strip_cache_control walks one level deep only, so
    a marker nested inside tool_result["content"] would survive the gate and
    reach a backend that rejects the field.
  tool_result_bound: |
    TOOL_RESULT_MAX_CHARS (default 20,000, about 5k tokens) caps one tool result before it
    enters the prompt. Applied at the single point every result reaches the
    model (the tool_results comprehension in _stream_agent_loop), not at each
    producer: that also covers specialist output, tool errors and the
    unknown-tool fallback, and leaves non-model consumers — the
    propose_form_values json.loads, the audit trail — reading the full text.
    Capping upstream of that parse would feed it truncated JSON and silently
    drop the form_patch SSE event.
    A circuit breaker, not a routine clipper: the default is set so ordinary
    tool output (a status, an email thread, a specialist's analysis) never
    reaches it; a long document read does, and the marker asks for a
    narrower request (a page range, a section). A cut result carries an explicit marker
    naming the tool and stating the result is incomplete — silent truncation
    is worse than none, because the model reads the cut text as the whole
    answer and confabulates the rest.
  openrouter_passthrough: |
    When OPENROUTER_ENABLED=true and the selected model is in the Claude
    family, cache_control markers pass through the OpenRouter translator
    unchanged — on system content, user-turn content, tool entries, and
    tool-result content. The tool-result case is the agent loop's intra-turn
    marker and needs the translator to carry it onto the emitted `tool`
    message as a typed array: a marker text block appended to the user
    message would be re-ordered ahead of the tool messages (they are
    appended last) and land before the very bytes it must cover.
    OpenRouter forwards these markers to Anthropic, so prompt-cache hit
    rates stay roughly equivalent to direct routing. For non-Claude
    models the feature gate strips cache_control before translation —
    those backends have no equivalent feature and would reject the
    field. The two-block layout above is unchanged either way.
    Web search via OpenRouter — for Claude and non-Claude models alike —
    is preserved by replacing the Anthropic web_search server tool with
    OpenRouter's own ``openrouter:web_search`` server tool (see
    providers.translator_shapes), so a research specialist or the
    Executive pinned to e.g. Gemini still searches, with the same
    per-request contract as Anthropic-direct: the model decides when to
    search, ``max_uses`` caps searches server-side per request (so
    RESEARCH_WEB_SEARCH_MAX_USES and WEB_SEARCH_MAX_USES mean the same
    thing on both deployment types; on either path a multi-step chat turn
    gets the cap afresh on each step),
    WEB_SEARCH_ALLOWED_DOMAINS / BLOCKED_DOMAINS map to allowed_domains /
    excluded_domains, and the response's search count
    (``usage.server_tool_use_details.web_search_requests`` on the wire; the
    flat ``usage.web_search_requests`` the docs show is accepted too) is
    surfaced as ``server_tool_use`` so the usage rows record searches on
    this path too. The searches themselves never appear as ``tool_calls``;
    their results come back as ``annotations`` (url_citation) on the
    message. The engine is left on OpenRouter's ``auto`` (native
    provider search for Claude / GPT / Gemini / Grok, Exa otherwise).
    OpenRouter search's ``<cite>`` markup is stripped from tool-call
    arguments before they are parsed, so a citation inside an
    `emit_research_findings` string cannot empty the payload. Only the
    self-hosted OpenAI-compatible backend strips the tool (no server tool
    there). The older ``plugins:[{"id":"web"}]`` plugin is deprecated by
    OpenRouter and no longer used.

providers:
  module: openexecutive.providers
  protocol: openexecutive.providers.provider.LLMProvider — two-method surface (messages_create / messages_stream) that mirrors anthropic.AsyncAnthropic().messages.create/stream so call sites stay Anthropic-shaped.
  resolver: |
    openexecutive.providers.registry.get_provider(model) picks the
    backend per call. Module-level singletons cache one provider per
    backend — the Anthropic SDK and the httpx-backed OpenRouter client
    each pool their own connections.
  backends:
    - id: AnthropicProvider
      what: Thin delegate over anthropic.AsyncAnthropic; default for the Claude trio when OPENROUTER_ENABLED is off.
    - id: OpenRouterProvider
      what: httpx-backed client targeting OpenRouter's OpenAI-format /chat/completions endpoint. Translates request/response/stream shape via openexecutive.providers.translator.
  feature_gate: |
    openexecutive.providers.feature_gate.apply_feature_gates(spec, kwargs)
    runs inside the OpenRouter provider before translation. Spec-driven
    stripping covers cache_control on system/tool/user blocks, adaptive
    thinking + output_config, and — for the local backend only — the
    Anthropic server-side web_search tool; every OpenRouter model keeps
    web_search (supports_web_search=True on both non-Claude specs) so the
    translator can turn it into OpenRouter's ``openrouter:web_search``
    server tool. A misrouted call cannot ship an unsupported field.
    supports_thinking is TRUE for the Claude family and for any non-Claude
    catalog slug whose OpenRouter entry lists "reasoning" in
    supported_parameters (registry._openrouter_model_resolver consults
    openrouter_catalog.supports_reasoning); unknown slugs (hardcoded
    fallback list, or outside the catalog) keep thinking OFF.
  deep_reasoning: |
    The Council "Deep reasoning" toggle (BaseAgent.use_deep_reasoning /
    agent_overrides.use_deep_reasoning) adds Anthropic-native
    ``thinking={"type":"adaptive"}`` + ``output_config.effort``
    (SPECIALIST_EFFORT) to the call. It is honoured on: Claude Opus/Sonnet
    via Anthropic direct; Claude via OpenRouter; and every non-Claude
    OpenRouter model the live catalog marks reasoning-capable (today: all
    OpenAI, Gemini, DeepSeek and Grok entries — not Llama). It is a silent
    no-op on models that can't reason (feature gate strips the fields).
    Haiku guard: Haiku rejects adaptive thinking (HTTP 400), so
    providers.registry.model_supports_deep_reasoning() returns False for any
    Claude id / OpenRouter Claude slug naming the Haiku family (current
    ``claude-haiku-4-5`` and legacy ``claude-3-5-haiku-…`` orderings; scoped
    to Claude names so an unrelated slug containing "haiku" is unaffected)
    and the agent call paths (BaseAgent.analyze,
    analyze_with_tools) skip the thinking fields
    for it; the Council UI disables the checkbox for the same models, clears
    it when the model is switched to Haiku, masks a stale stored
    deep_reasoning=true on load (so the next Save corrects the row), and
    never sends deep reasoning for a Haiku model from the Test button.
  translator_shapes: |
    Anthropic ``system`` list → OpenAI single ``system`` message;
    Anthropic ``tools[].input_schema`` → OpenAI ``tools[].function.parameters``;
    Anthropic ``tool_choice={"type":"tool","name":X}`` → OpenAI
    ``{"type":"function","function":{"name":X}}``;
    Anthropic ``thinking={"type":"adaptive"}`` + ``output_config.effort`` →
    OpenRouter unified ``reasoning={"effort": <level>}`` where level is passed
    through when it is one of OpenRouter's accepted strings
    (none/minimal/low/medium/high/xhigh/max) and otherwise FAILS CLOSED to
    "low" — never up to an expensive tier (legacy
    ``{"type":"enabled","budget_tokens":N}`` → ``reasoning={"max_tokens":N}``;
    ``enabled`` with no usable budget → no field),
    which OpenRouter maps to each vendor's native form. The
    ``reasoning_details`` array OpenRouter returns (non-streaming
    ``message.reasoning_details``, streaming ``delta.reasoning_details``) is
    carried as a synthetic ``openrouter_reasoning`` content block (always
    LAST in ``content`` so ``content[0].text`` readers are unaffected) and
    replayed verbatim as ``reasoning_details`` on the assistant message by
    the request translator. The Executive / executive_research /
    executive_reflection loops never enable thinking and drop the block
    harmlessly (each consults `reasoning_replay_block`, so the echo is
    already wired should deep reasoning ever be added to them).
    Anthropic base64 PDF ``document`` block → OpenAI ``{"type":"file",
    "file":{"filename","file_data":"data:application/pdf;base64,…"}}`` part
    (the user message then goes out as a typed array, text and files in
    order; a URL/text-source document has no faithful shape and is left
    out). ``FeatureSpec.supports_pdf_input`` gates it per model: false for a
    local server unless LOCAL_PDF_INPUT, and a gated-off block becomes the
    text note "[PDF omitted: …]" rather than vanishing. OpenRouterProvider's
    ``_extend_body`` hook adds ``plugins=[{"id":"file-parser","pdf":
    {"engine": …}}]`` when a file part is present: ``native`` for
    anthropic/claude-* or a catalog entry whose input_modalities has
    "file" (openrouter_catalog.accepts_files), else PDF_OPENROUTER_ENGINE
    (default mistral-ocr). No file part → the body is byte-identical.
    The Anthropic
    server-side web_search tool (no input_schema) cannot be executed by
    OpenRouter, so it is replaced in ``tools[]`` by OpenRouter's
    ``{"type": "openrouter:web_search", "parameters": {max_uses,
    allowed_domains, excluded_domains}}`` server tool for ANY model routed
    via OpenRouter, Claude or not — without this a call routed
    via OpenRouter would silently lose web search (the executive_research
    council emitted zero findings). Server-side tool calls in the response
    (``tool_calls[].type`` starting with ``openrouter:``, including the
    untyped continuation chunks of a streamed call) are skipped, never
    surfaced as tool_use blocks for the caller to run; a response whose
    only tool calls were server-side ends the turn (``end_turn``) rather
    than waiting on tool results. Unlike the Anthropic path, which echoes
    ``server_tool_use`` / ``web_search_tool_result`` blocks back into the
    next step's history, the OpenRouter path carries only the model's own
    text forward, so across a multi-step chat turn it may search again for
    what it already found. OpenRouter search makes the model cite sources
    with inline ``<cite index="...">…</cite>`` markup; the response path
    strips those wrapper tags from both text and tool-call arguments so they
    don't leak into findings / chat replies. Streaming SSE chunks
    pass through a ``StreamAccumulator`` that fabricates Anthropic-shape
    content_block_start/delta/stop events for text and assembles
    fragmented tool_call argument deltas into a single tool_use block
    at stream close.
  routing_rules:
    - Slug listed in LOCAL_MODELS (with LOCAL_MODELS_ENABLED=true) → local OpenAI-compatible backend. Checked FIRST, before the Claude-id regex, so an operator's explicit local slug (even one shaped like ``claude-proxy-1``) is never re-routed to a hosted vendor.
    - Claude model + OPENROUTER_ENABLED=false → AnthropicProvider.
    - Claude model + OPENROUTER_ENABLED=true → OpenRouterProvider. The slug is DERIVED, not looked up — registry.openrouter_slug_for_claude maps ``claude-<family>-<major>[-<minor>][-<yyyymmdd>]`` to ``anthropic/claude-<family>-<major>[.<minor>]`` (claude-sonnet-5 → anthropic/claude-sonnet-5, claude-haiku-4-5-20251001 → anthropic/claude-haiku-4.5). The same regex defines "is a Claude model" for routing, so a previous-generation id persisted in agent_overrides (claude-opus-4-7) still routes to Anthropic instead of falling through to the non-Claude path.
    - Non-Claude model + OPENROUTER_ENABLED=true → OpenRouterProvider with the slug passed through verbatim (live catalog or the hardcoded fallback). A ``model_resolver`` callback (registry._openrouter_model_resolver) hands Claude ids and ``anthropic/claude-*`` catalog slugs the Claude feature spec; everything else gets the non-Claude default — so a catalog refresh after the provider singleton is built needs no rebuild.
    - Non-Claude model + OPENROUTER_ENABLED=false → HTTP 400 at the API boundary. No silent fallback.
  generation_fit: |
    Both provider paths pass every request through
    feature_gate.fit_claude_generation(model, kwargs) after
    relax_forced_tool_choice. A Claude model from the 5 generation on
    never receives temperature / top_p / top_k (non-default values 400 and
    the default is what it runs on). Haiku 5.5 thinks unless told not to,
    where Haiku 4.5 thought only when asked; the helpers on ROUTING_MODEL
    are sized for a reply without thinking, so a Haiku 5.5 request that sets
    no thinking gets {"type": "disabled"} (kept off efforts xhigh / max,
    where Anthropic rejects it). On the OpenAI-compatible path the
    translator turns disabled thinking into reasoning {"enabled": false}.
    Non-Claude and local slugs are left untouched.
  council_ui_dropdown_source: |
    openexecutive.providers.allowed_models_for(agent_id) — returns
    ANTHROPIC_DIRECT_MODELS (claude-fable-5-1, claude-opus-5-5, claude-opus-5,
    claude-sonnet-5-5, claude-sonnet-5, claude-haiku-5-5, claude-haiku-4-5) plus registry.openrouter_models() (live
    catalog, else the OPENROUTER_MODELS fallback snapshot) when the toggle is
    on; catalog slugs that duplicate a direct id are dropped.
    Every agent (including utility_fast) gets the same list; the
    utility_fast-only free/cheap OpenRouter matrix was removed. The PATCH
    /agents/{id} validator and GET /agents/models share this function.
    The Council UI reads GET /agents/models/options?agent_id= instead —
    registry.model_options_for(), the same ids in the same order, each
    annotated with provider (anthropic for claude-* ids and anthropic/*
    slugs, the vendor prefix otherwise, local for LOCAL_MODELS — local
    checked first), provider_label, route (mirrors get_provider: local /
    direct / openrouter — Claude ids route via OpenRouter whenever
    OPENROUTER_ENABLED is on) and a display label ("Claude Opus 5.5"). The
    UI renders it as a Provider dropdown plus a Model dropdown filtered to
    that provider; a stored model missing from the list (a stale override)
    is kept selectable and marked "not in the current allowlist".
  scope_caveat: |
    Non-specialist fast classifiers (workflows.wait_for_human.parse_decision,
    workflows.inbound_resolver._llm_disambiguate, the Discord response
    gate and thread-title generator) share a single Council-configurable
    knob — the ``utility_fast`` virtual agent. Their model resolves via
    ``openexecutive.agents.utility_fast.get_fast_model()`` which checks
    the agent_overrides DB row first and falls back to
    ``settings.routing_model``. The chat surface (Executive, all
    specialists, committee, _test_executive, episodic memory extraction)
    routes through providers per-call. wait_for_human.parse_decision is
    still on the synchronous anthropic SDK construction path — provider
    abstraction migration tracked as follow-up.
  non_specialist_council_agents: |
    Four agents live in the Council but NOT in SPECIALIST_REGISTRY, so they
    are model/prompt-overridable in the UI yet not callable via
    consult_specialist: ``quality_judge`` (committee reviewer),
    ``utility_fast`` (fast-classifier knob, model-only),
    ``research`` (research-model knob — model + deep-reasoning, controls the
    executive_research specialist fan-out; resolves via
    openexecutive.agents.research_council.get_research_model() /
    get_research_use_deep_reasoning(), Council override → settings.research_model
    / off), and ``fixture_generator`` (authors company simulator fixtures —
    openexecutive.agents.fixture_generator, default model settings.default_model).
    They are registered in api/routes/agents.py::_agent_registry() and resolve
    their model via BaseAgent.effective_model() at call time.
  additional_instructions: |
    Every Council agent (the Executive included) has an optional
    ``instructions`` override stored in the additive
    ``agent_overrides.instructions`` column (idempotent _add_column_if_missing
    migration, versioned in agent_override_history, restored by rollback).
    agents.overrides.append_instructions appends it after the agent's prompt
    in an <additional_instructions> block; blank or None returns the prompt
    unchanged so an agent without instructions keeps its cache prefix.
    BaseAgent.base_system_prompt() is the built-in prompt or its full
    replacement (the ``prompt`` override) and is what AgentDetail.prompt
    shows; effective_system_prompt() is base + instructions and is what every
    call sends. The Executive gets the same text via
    build_system_blocks(persona_instructions=...), after the voice persona and
    before the identity addendum, inside block 0. It is admin-set static
    config, so block 0 re-warms once on save. Unlike a replaced prompt,
    instructions keep the agent on the built-in prompt, so prompt upgrades
    still reach it. PATCH /agents/{id} and /test accept ``instructions``
    (max 4,000 chars; blank clears it).
  quality_presets: |
    The Council's Quality choice (agents/presets.py) sets every agent's model
    and deep-reasoning flag at once. Fast: a small model (claude-haiku-5-5, else claude-haiku-4-5)
    for every agent, deep reasoning off. Balanced: each agent's built-in
    defaults. Thorough: the largest allowed model (claude-opus-5-5, then
    claude-opus-5) for the Executive and the domain specialists, deep
    reasoning on where model_supports_deep_reasoning allows; triage and the
    Council-only helpers keep their defaults. Presets change quality only and
    never cap spend. Models resolve at request time against
    providers.allowed_models_for; a preset none of whose models the install
    allows is reported unavailable (POST returns 409) instead of picking
    something else. There is no preset table: POST /agents/presets/{id}
    writes ordinary agent_overrides rows (model and use_deep_reasoning only,
    leaving prompt, role, voice and instructions alone), one history row per
    agent that changes, clearing a field whose target equals the default and
    deleting a row left empty. GET /agents/presets works out the active
    preset from the overrides: ``active`` when every agent matches,
    otherwise null ("Custom") with ``base`` (the preset most agents match,
    Balanced on a tie) and ``custom_agents`` (the agents that differ).
  council_simple_view: |
    BaseAgent.visibility is "core" (the Executive proxy and every domain
    specialist declares it) or "internal" (the default: triage and the
    Council-only helpers). AgentMeta carries it, and agents.presets uses it
    to decide which agents Thorough moves up. The Council opens in a simple
    view for everyone:
    the Quality presets, the shared VoicePicker, and only core agents with
    their additional instructions and a model badge. "Show all agents" lists
    internal agents too; "Advanced" opens the full editor, and the browser
    remembers that choice. There is no setting for it. A test fails if a
    registered specialist other than triage is not core.
  executive_voices: |
    The Executive's voice persona (personas/builtin/*.md, shadowed by
    voice_personas rows) is substituted into block 0 at {VOICE_PERSONA}.
    Three general voices are offered by the VoicePicker in Settings ->
    Executive (setup no longer asks; it ends on Home), saving voice_persona_slug through PATCH /agents/executive:
    Direct (slug ``default``, stored as no override), Supportive and
    Analytical. Frontmatter ``description`` / ``sample`` feed the picker;
    ``legacy: true`` marks the named-executive voices, hidden from the picker
    but still loadable (PersonaMeta.is_legacy), so existing picks keep
    working. Voice files hold disposition only; length rules live in
    prompts/executive_persona.py, enforced by test_voice_picker. Eval
    scenarios may set ``voice_persona`` (validated by
    evals.scenarios.scenario_voice_persona), carried on
    Session.voice_persona_slug, which wins over the install override for
    that session only, like workspace_mode and principal_role.
  per_specialist_research_focus: |
    Each consult-routable specialist (cso, cfo, cmo, coo, chro, cpo, gc) has a
    Council-editable ``research_focus`` override — the per-domain scope tail
    appended to that specialist's research-mode turn (what external signals it
    watches). Stored in the additive ``agent_overrides.research_focus`` column
    (mirrors voice_persona_slug; idempotent _add_column_if_missing migration,
    versioned in agent_override_history). A non-null override REPLACES the code
    default in monitoring.research.prompts._RESEARCH_FOCUS; the SHARED research
    contract (shared_research_addendum — output schema + grounding/recency/
    actionability bars) is NEVER overridable and stays code-only so a bad edit
    can't break the output contract. The override is static config, so it does
    not break the cached system block (just re-warms on edit). Surfaced on
    AgentDetail as research_focus + research_focus_default (null for agents with
    no research scope, e.g. executive / utility knobs).

routing:
  pattern: Anthropic tool use with a single `consult_specialist` tool. Multiple parallel tool_use blocks per assistant turn fan out to specialists concurrently.
  parallel_function: openexecutive.orchestrator.router.route_parallel
  when_to_consult: |
    The persona's Domain Expertise section ("Going deeper") and the
    consult_specialist tool description say when: a question asking for
    judgment in a specialist's area (decision, plan, analysis, negotiation,
    hire, contract term, pricing/fundraising move, board message, or a
    department's own targets and stance) is consulted before answering;
    lookups, scheduling, status, routine drafting and questions about the
    Executive itself are not. Without this the Executive answered nearly
    everything itself. Chat evals score it: required_routing / no_routing,
    checked by evals.scenarios.routing_check.
  fanout_cap: |
    The number of parallel `consult_specialist` calls dispatched in a single
    turn is bounded by `MAX_PARALLEL_SPECIALISTS` (config). Default 0 is inert
    — `router.resolve_fanout_cap` falls back to the specialist roster size,
    which no real cross-domain turn exceeds. Calls past the cap are not fanned
    out; each receives a skip tool_result (`router.FANOUT_SKIP_MESSAGE`) so the
    Executive can re-ask on a later turn. The `routing_decision` debug event
    carries requested_count / cap / dispatched_count / skipped_count so the
    fan-out width is observable per turn.
  retrieval_per_call: Each parallel tool call runs its own domain-filtered ChromaDB query before the specialist sees the question.
  failure_isolation: |
    route_parallel isolates every call. A specialist whose analyze() raises
    (timeout, 529 overloaded, any provider error after the SDK's own
    retries) or returns no text does NOT fail the batch any more — before,
    the bare asyncio.gather propagated the first exception out of the agent
    loop and the web chat answered "An internal error occurred". Now:
      - its tool_result is router.specialist_unavailable_result: "UNAVAILABLE:
        the <name> specialist could not answer this time (<reason>)… Do not
        invent it and do not consult it again this turn; answer from what the
        other specialists said." Reason is the exception CLASS only.
      - tell_user_when_unavailable (the Executive passes
        `not session.from_web_chat`) appends "say in one short sentence that
        this part of the analysis is missing… Do not mention specialists" on
        channels; on the web chat it says the app shows it instead, so the
        user sees the gap once.
      - its index in `calls` goes to failed_calls_out (call order). The loop
        calls TurnSources.mark_unavailable for it and mark_answered for each
        call that answered; payload() lists the AREA ("finance", "legal",
        "people and hiring"…, answer_sources._AREAS; unknown → "one area")
        of a specialist that failed and never answered this turn (a retry or
        a second call to it that answered covers it) — never the specialist,
        per the one-voice invariant.
      - it does not count as consulted: consulted_out (committee critic
        seats, per-department Honcho sync) and specialist_outputs_out take
        only the calls that answered. The loop's own specialists_consulted,
        which only marks the next round as synthesis_start for the debug
        panel, keeps every dispatched call.
      - its retrieved documents are dropped: route_parallel holds each call's
        record_source calls and replays only the answered calls', in call
        order, after the gather.
      - a `specialist_unavailable` debug event carries name + reason.
    asyncio.CancelledError (Stop, turn timeout) is BaseException and still
    propagates. _retrieve_for_call / _retrieve_failures_for_call degrade to
    "" on any exception (warning logged) for the same reason: their gather
    had no return_exceptions either. No prompt changed: the instruction
    lives in the tool_result (user turn), so caching is untouched.
  answer_sources: |
    orchestrator/answer_sources.py — what a turn LOOKED AT (not per-sentence
    citations; that was the product choice). The web chat route
    (api/routes/chat.py _run_chat_turn) owns one TurnSources per turn and
    passes it to its own retrieve(record_source=…) and to
    stream_chat / stream_chat_with_committee(turn_sources=…) →
    _stream_agent_loop. Other callers (.chat() wrapper, CLI) pass nothing,
    so they collect nothing. Producers:
      - knowledge: the route's turn-level search (what the Executive's
        <retrieved_context> holds) and route_parallel(record_source=…) →
        _retrieve_for_call → retrieve(record_source=…) → _record_sources:
        company (filename), knowledge (title_from_filename), notion
        (filename), research ("Research notes from <date>"), document
        (published artifact title, url /artifacts/<quoted id>). A failed
        specialist's documents are not recorded (see failure_isolation).
        Never raises.
      - web: record_web_sources(final_msg.content) per model response — pages
        cited by text-block citations (add(cited=True)) and the first 3
        results of each web_search_tool_result. Never raises.
    Caps, applied in payload(): cited pages first, then documents, then
    other search results, until 12 in all and 6 web — so a page the reply
    cites is listed whatever was recorded before it. Dedupe on (kind, url or
    title); titles whitespace-folded and clipped to 120; a web url is kept
    only if http(s); a document url only if http(s) or /artifacts/<one
    segment of [A-Za-z0-9_%~-]> (_IN_APP_PATH_RE; the UI's IN_APP_PATH is
    the same, a test checks). Thread-safe (retrieval records from
    asyncio.to_thread workers; the collector is passed explicitly, no
    ContextVars).
    Delivery: the route, once the reply is over on EVERY ending (complete,
    Stop, whole-turn timeout), before the stopped / error / done frames and
    only when non-empty and the reply has text: {"type": "sources",
    session_id, sources: [{kind, title, url}], unavailable: [area]}. The
    same payload is saved in chat_messages.sources by _persist_turn, also on
    a client disconnect; load_messages re-attaches it (assistant rows only,
    dict only, malformed JSON ignored). UI: lib/answerSources.ts
    (answerSourcesFrom reads an event or a saved reply without trusting its
    shape; groups, safe links, the "Some of the analysis is missing
    (finance, legal)…" line) and components/AnswerSourcesFooter.tsx under
    each reply in the chat and the Ask OE panel;
    scripts/answerSources.test.mjs keeps the UI's kinds equal to SourceKind
    and IN_APP_PATH equal to _IN_APP_PATH_RE.
  specialist_user_turn: |
    BaseAgent.analyze assembles each specialist's USER turn from per-call
    blocks, outermost first: <company_stage>, <principal_role> (solo only),
    <department_memory>, <past_decisions>, <failure_cases>,
    <relevant_knowledge>, <conversation_context>, then the query. The specialist's system prompt is
    its static domain constant under one cache_control block and never carries
    per-call or per-company content.

    <company_stage> is the profile's `stage` field, collapsed to one line and
    skipped when empty. Specialists never see the company profile (it lives in
    the Executive's cached system block), yet stage decides which benchmarks
    apply. CFO_PROMPT, CSO_PROMPT and SALES_PROMPT key on the tag: a
    bootstrapped, self-funded, "default alive" or solo company gets cash-first
    advice (cash net of tax owed, runway at current burn, receivables, pricing,
    owner pay, tax set-aside) instead of venture fundraising benchmarks, and
    raising is presented as an option only if the founder wants it.

    Where the stage comes from: route_parallel takes `company_stage` per turn,
    like episodic_context. Executive._stream_agent_loop passes the stage of
    the session's company_profile — the profile the Executive's own system
    block renders, and the one the eval runner injects per scenario — or None
    when the session has no profile, in which case the router reads it once
    per batch from disk (router.load_company_stage). Session-less callers of
    route_to_specialist (workflow steps, the MCP server's consult_specialist)
    read it fresh from disk on every call, so a profile edit reaches them
    without a restart. load_company_stage never raises: a missing or
    unreadable profile means no tag, not a failed consult.

    <principal_role> (solo mode only) says what kind of principal the advice
    is for — router.principal_role_context: the role kind in plain words
    (workspace_settings.ROLE_KIND_PHRASE), the title and the remit, each
    collapsed to one line and capped (120 / 300 chars); reports_to and
    measured_on stay in the Executive's org block. Specialists never see
    that block, and the kind changes which advice fits: an executive inside
    a large company makes the case to their CFO or VP rather than raising a
    round. The turn pins the role ONCE, next to pin_turn_workspace_mode
    (Executive.stream_chat and the committee path):
    pin_turn_principal_role(session, mode) — the role in solo, an empty
    role in team; the same value goes to
    build_system_blocks and, as principal_role_context(...), to
    _stream_agent_loop(principal_role_tag=…) and so route_parallel — so the
    org block and every specialist tag in a turn describe the same role ("" in
    team, so the router reads nothing). A direct _stream_agent_loop caller
    that passes no tag gets it resolved from the current session. Angle
    brackets in the text are defanged (‹ ›) so it cannot close the tag.
    None (session-less callers: workflow steps, the MCP server's
    consult_specialist) reads it once per call or batch via
    router.load_principal_role, which checks effective_workspace_mode of the
    current session (else the workspace) and never raises. No domain prompt
    changed: the tag body is self-describing.
  committee_review: |
    Optional 3-phase response synthesis exposed via
    Executive.stream_chat_with_committee():
      Phase 1 — silent draft.
      Phase 2 — Committee.select_reviewers() picks 1 QualityJudge + 2
        domain critics from the consulted specialists (fallback cso/cfo);
        all three review in parallel.
      Phase 3 — streamed revision pass that addresses the critiques.
    The UI subscribes to phase events for a stepper visual; the rest of
    the system sees only the final stream.
  web_search: |
    `web_search` server tool (Anthropic native `web_search_20250305`) is
    exposed by default — ENABLE_WEB_SEARCH defaults to true so briefing
    proposals that ask for research (e.g. "skim Ford IR", "check Lucid
    news") can actually execute instead of degrading to reasoning from
    priors. Set ENABLE_WEB_SEARCH=false to opt out. It is executed inside
    the Anthropic API itself — no client handler runs — and
    `server_tool_use` + `web_search_tool_result` blocks come back inside
    the same generation. The Executive echoes those blocks in the
    assistant turn on the next iteration so continuity is preserved. The
    tool is appended after the sorted client-tool list so it never
    receives the cache_control marker. Each turn is capped at
    `WEB_SEARCH_MAX_USES` searches (default 2) — every search is billed, so
    this bounds per-turn search spend and, multiplied across the
    7-specialist research fan-out, is a primary cost control.

    When the selected model is non-Claude (routed via OpenRouter), the
    feature gate strips this server tool from the request before it
    leaves the process — OpenRouter has no equivalent server-tool
    primitive. The Council UI does not surface this to the user; the
    capability simply does not fire on non-Anthropic turns.
  channel_tools: |
    `lookup_person`, `send_discord_dm`, `send_telegram_message`,
    `send_slack_dm`, and `schedule_followup` are exposed as tools so the
    Executive can resolve a person → preferred channel → message in a
    single turn.
  alert_tools: |
    `ack_alert(alert_id, status)` lets the Executive clear a briefing
    proposal from the user's "Needs you" list directly from a chat turn —
    used in the Discuss flow when the user explicitly approves or
    dismisses a proposal mid-conversation. Wraps `alerts.store.set_status`
    (the same backing call as `POST /alerts/{id}/ack`); registered as a
    side-effecting tool so a chip surfaces in the live stream
    ("Approved proposal #N" / "Dismissed proposal #N"). The button-driven
    Approve / Dismiss path on the briefing page still acks via the HTTP
    TRUST: the server-side check runs on EVERY session, not only those with an origin_channel. It previously skipped web sessions, so the browser — the surface the principal actually uses — had no check and the model could ack any id, including one an inbound email wrote into an alert body that the Discuss handoff quoted into the turn. `briefing.context.render_and_trust` is the single place that renders the digest AND records the live board onto session.trusted_alert_ids (the whole live set, not only the printed rows, so a card past the 30-row render cap stays ackable). The control bounds the model to server-derived live ids — it refuses invented, closed, snoozed and expired ones — but does NOT prevent the model being argued into acking the wrong live card; do not document it as immunity to cross-alert injection; the web chat route and the channel adapters both go through it, so the block shown and the set accepted cannot drift. An empty trusted set refuses everything, which is the safe default for a turn that was shown no board (non-DM / non-principal channel turns, or a digest that failed to build). The tool reads that set off `current_session`, so the BINDING is load-bearing: the chat route binds the session for the whole SSE body via `schedule_tools.set_session`, beside `set_turn`. `Executive.stream_chat` also binds it with a bare `set()` at its top, and that suffices only for callers driving the generator with a plain `async for` (the adapters' .chat() wrapper, CLI, tests). The SSE route drives it under `asyncio.wait_for(stream.__anext__())`, which copies the context per step, so a binding made inside the generator dies with step one and every later step — including the entire tool-call loop — reads None. That shipped in the same change that extended the check to web, and the two combined refused every ack the principal made on live cards. Both managers save/restore rather than Token.reset, because __exit__ runs in a different Context than __enter__ on this path. Anything else reading current_session mid-turn inherits the same requirement, and two needed more than the binding. schedule_followup's seen-channel_ref anti-spam gate is a no-op without a session (so web could schedule to ANY address) and refuses everything with an empty one (so it refused the principal's own), until the route seeds the caller's own addresses onto the session — replaced every turn, so in a shared chat each speaker may schedule only to their own addresses (a teammate speaking after the principal can't queue a message to the principal) and an address dropped from the roster stops being one. Reply linkage (_record_outbound_context, read back by inbound_hydration) is deliberately NOT switched on for web by that binding; it is keyed on the explicit Session.from_web_chat flag, never on an empty origin_channel, because alert review, the CLI, the MCP server, the scheduler and the unattended workflows all leave origin_channel empty while legitimately recording linkage (the email poller, which records it too, tags its turns origin_channel="email"). scheduled_actions rows also lose their session_id without the binding. The digest additionally names recently closed alerts in an 'Already handled' tail so the Executive can say an item is already cleared instead of sending the principal to dismiss it again; those ids are NOT added to the trusted set. FIND_ALERTS widens the set in one place only: `find_alerts(query, limit)` (schedule_tools) searches headline and body of alerts of any status in SQL (`alerts.store.search_alerts`: every word must match, LIKE-escaped, newest first) so the principal can clear an item that has left the live board — observed: asked to retire three duplicates they had already opened, the Executive named the right ids and was refused because the rows were `read`. It answers at all only when `render_and_trust` set Session.principal_board_shown this turn (the verified principal, and on a channel only in their DM — attach_briefing_context's gate) and the session is neither unattended nor email-started. Two gates that looked sufficient were not: "widen if trusted_alert_ids is not None" (every Session starts with an EMPTY set, which is how Google Chat, other people's DMs, email and unattended turns refuse every ack, so any of them could find-then-ack anything), and `is_principal_on_verified_surface` alone (it also passes the principal's turn in a shared Slack/Discord thread, where others read the reply — the board is company-wide — and can write into the thread the model reasons over). It trusts only ids its own query returned, only open rows (`unread`, `read`; closed rows come back can_ack false), never `roster_request` cards, at most 25 rows per call and 25 ids per TURN across calls (Session.found_alert_ids, reset by render_and_trust and by the chat route with the trusted set), and refuses a query with no word of 3+ characters — a per-call cap alone bounds nothing when a steered model can call once per letter. What it widens is the attack surface already admitted above: the query is the model's choice and the model reads attacker-controlled alert bodies, so an argued-into search can put up to 25 open, off-board alerts in reach per turn; the tool description forbids searching for text taken from an alert or inbound message, which is a prompt rule, not a control.
    route — the tool exists for the chat-driven path that the model
    self-detects from natural-language approval. The same feedback loop as
    the HTTP ack applies: a `dismissed` on a watch-sourced alert lowers
    that watch's `trust_score` (`monitoring.store.record_dismissal`); an
    `ack` recovers it a little.
    TEAM MEMBERS: on a team member's turn (`department_gate.speaker`, via
    `alert_tools.team_member_speaker`) `ack_alert` refuses any alert not
    routed to them (`routed_to_person_id`); the principal clears anything.
    `create_alert` there ignores the given `source`, `external_id` and
    `from_address`: source `team_member` (`alerts.models.TEAM_RAISED_SOURCE`),
    a fresh uuid id, from = their email, `AlertEvent.raised_by` = their name.
    Otherwise a teammate could raise "urgent from ceo@..." or pre-claim a
    real (source, external_id) so the real alert is dropped as a duplicate.
    The pipeline leads the body with "Raised by <name>." and drops
    `company_broadcast` after `resolve_channels` (person / department only),
    and prefixes the dedup key with who raised it so teammates' cards never
    coalesce. A teammate's saved workflow raises as its creator
    (`alert_tools.raised_for_workflow_owner`, bound in `action_step._dispatch`).
    HTTP matches: `/alerts/{id}/ack` (ack/dismissed) and `/alerts/bulk-ack`
    let a team member clear only alerts routed to them (403 otherwise, no age
    sweep), and only the principal's dismiss applies `mute_topic`.
  alert_lifecycle: |
    `openexecutive.alerts.lifecycle` gives every alert a lifetime and one
    shared read view. TTL per category — `ALERT_TTL_DAYS_ACTION` (14) for
    anything a human should look at, `ALERT_TTL_DAYS_MONITORING` (3) for
    unrouted low/medium watchlist signals (`briefing.ranking.categorize`
    decides), computed from `created_at` at read/sweep time (no stored
    expiry, so a setting change applies to existing rows; 0 = never).
    The age anchor is the latest of `created_at`, `last_seen_at` and
    `snoozed_until`, so a situation that keeps re-firing (coalescing) stays
    live and a card snoozed past its TTL comes back instead of expiring.
    `list_live_alerts` = unread ∧ inside TTL ∧ `snoozed_until` null/past.
    Snooze is written by `POST /alerts/{id}/snooze` (`until` up to 30 days
    ahead, or null to clear; `unread` rows only, never a roster request;
    audited `alert_snoozed` / `alert_unsnoozed`) via
    `store.set_snoozed_until`, from a card's ⋯ on Home (later today,
    tomorrow 9:00, Monday 9:00 in the viewer's clock, with an Undo).
    `is_live(alert, now)` is the same predicate for one row;
    `/today`, `briefing.context`, the briefs and the reflection all read it.
    `expire_stale_alerts` (called by the scheduler loop every 15 min and once
    at boot, `runner._maybe_sweep_alerts`) flips past-TTL rows to `expired`
    and audits `alert_sweep`. `artifact` and `decision_scheduling` rows are
    exempt. Additive `alerts` columns: `last_seen_at`, `occurrence_count`
    (coalescing), `last_reviewed_at`, `review_verdict`, `review_note`,
    `recommended_move`, `why_now`, `due_at`, `superseded_by_alert_id`,
    `snoozed_until`, `suggested_workflow` (review). Store helpers:
    `coalesce_alert`, `bulk_set_status`, `update_alert_content`,
    `set_review`, `update_alert_routing`, `mark_superseded`,
    `count_superseded_by`, `reopen_alert`. Routes (`api/routes/alerts.py`):
    `POST /alerts/{id}/ack` (now accepts `mute_topic`: a pattern or `true`
    to derive `external:<slug>` / `department:<slug>` / first tag), `POST
    /alerts/bulk-ack` (`status`, `alert_ids` and/or `older_than_days`,
    `category`; exempt sources skipped), `POST /alerts/{id}/reopen` (Undo: only `resolved` /
    `expired` / `dismissed` rows, never `ack` or exempt sources; clears every
    review stamp incl. `last_reviewed_at`, stamps `last_seen_at = now` so a
    past-TTL row is live again, and hands a merged row's occurrence count
    back to its survivor),
    `POST /alerts/review` (on-demand review, ignores the interval but not the
    kill switch, the caps, the lock or per-alert idempotency). `ack` applies
    feedback / mute only on a real status transition; `bulk-ack` caps
    `alert_ids` at 500, requires `older_than_days >= 1`, and applies the same
    watch feedback per row; `mute_topic` must be one of the alert's own tags
    or an `external:` / `department:` scoped pattern (≥ 4 chars).
  alert_review: |
    `openexecutive.alerts.review` is the Executive working the feed instead
    of just filing into it. Heartbeat kind `alert_review_scan` (channel
    `__internal__`, bootstrap + chain like `nudge_scan`, every
    `ALERT_REVIEW_INTERVAL_HOURS` = 6) plus a `pre_brief` pass from
    `_run_principal_brief` before the morning brief. Candidates: live alerts
    at least `ALERT_REVIEW_MIN_AGE_HOURS` (2) old, not reviewed inside the
    interval, not exempt, oldest first, capped at `ALERT_REVIEW_MAX_PER_SCAN`
    (25), in batches of `ALERT_REVIEW_BATCH_SIZE` (8). Evidence per alert
    (`gather_evidence`, deterministic, no tools): age, `occurrence_count`,
    prior verdict; newer `external_signals` for the same watch plus its
    `trust_score` / `dismiss_count`; related live alerts raised since (same
    source or shared tag); Executive activity since (`_build_activity(since)`);
    the roster slice (department members + routed person + principal, or
    only `legal_sign` / `board_comms` holders + principal for a sensitive
    matter — tags `board`/`comp`/`legal` or `broadcast_tools`'s privacy
    backstop); the department's authority level; registry workflows whose
    name matches the text. `agents.alert_review.AlertReviewAgent` (routing
    model, one forced `emit_alert_reviews` tool call, never raises) returns
    per alert: verdict (relevant | changed | resolved | stale), confidence,
    evidence, note (≤160), why_now (≤80), due_at, recommended_move (none |
    route | nudge | escalate | draft | suggest_workflow | merge | close),
    target_person_id, superseded_by_alert_id, rewritten headline/body/
    severity, draft_title/draft_document, workflow_name, message.
    Trust boundary: every externally-sourced field (headline, body,
    suggested_action, signal / related-alert text) is rendered through
    `_untrusted` (angle brackets → ‹ ›, control chars dropped) inside the
    `<alert>` envelope, the batch header and the prompt state it is data,
    never instructions, and each evidence item carries a server-minted ref
    (S1.. signals, R1.. related alerts, A1.. activity) the model must cite.
    `apply_verdict` policy: close → `resolved` / `dismissed` only when
    confidence is high AND `evidence_ref` names a ref that exists for THAT
    alert (free text — or an injected body saying "resolved" — never closes),
    else `review_verdict = likely_stale` (ranking demotes it 30 points, the card shows an amber
    chip + one-click Dismiss); changed → `update_alert_content` with the
    prior text in the audit row (a sensitive alert keeps its text — only
    severity moves — so a rewrite cannot launder the privacy keywords);
    route → target must be on the roster slice (which, for a sensitive
    matter, never includes a mere `routed_to_person_id`), skipped when the
    alert is already `routed` to that person;
    `gate_action(dept, "route_alert")` — `propose` ⇒ `propose_via_alert` to
    the approver, else `update_alert_routing` + DM via
    `handle_message_person` (server-side channel resolution + the outbound
    anti-spam guard, session seeded from the roster); nudge → DM the routed
    owner, capped by `NUDGE_MAX_PER_SCOPE` delivered nudges per alert
    (counted from `alert_review_nudged` audit rows); escalate → severity up
    (never down, at least `high`), `due_at` (verdict's or +24 h), DM the
    principal only — no principal ⇒ annotate, never counted as an escalation;
    skipped when already escalated (high/urgent + due_at); draft → `handle_draft_artifact` (lands as an artifact
    card), source marked `drafted`; suggest_workflow → `suggested_workflow`
    stored only when the name was offered, never runs anything; merge →
    only at high confidence, `mark_superseded` into a survivor that was SHOWN
    as a related alert and is live (`lifecycle.is_live`), absorbing the merged
    row's occurrence_count (handed back on reopen); draft → skipped when the
    source is already `drafted`; escalate → the DM goes first and only a
    delivered DM bumps severity / sets `due_at` / counts; a `_dm` that fell
    back to creating an alert ("alerted") counts as not delivered. Activity
    refs (A1..) are only minted for items that mention the alert's subject
    (`_subject_terms`), and untrusted text is collapsed to one line so a body
    cannot forge a section header;
    a standalone `close` move is ignored (closing is only ever a verdict).
    Every DM goes out as "[Alert review] Re: <headline>\n\n<text>"
    (`_dm_text`) so provenance is visible. `run_alert_review` honours
    `ALERT_REVIEW_ENABLED` for every caller (the manual endpoint does not
    bypass it) and is single-flight (`asyncio.Lock`: an overlapping
    heartbeat / pre-brief / manual pass is skipped). Outbound moves
    (route/nudge/escalate/draft) count against
    `ALERT_REVIEW_MAX_MOVES_PER_SCAN` (10; 0 = annotate-only). Audit event
    types: `alert_review` (annotation), `alert_review_closed`, `_routed`,
    `_nudged`, `_escalated`, `_drafted`, `_merged`, `_suggested_workflow`,
    `_changed` — `briefing.brief_state.handled_since` reads all but
    `_changed` for the brief's "Handled overnight" block and
    `/today.handled_overnight` (a rewrite leaves the alert open, so it is
    reported under "what changed" via `brief_state.rewritten_since`, never as
    done). Routed / nudged summaries name the roster person
    (`_MoveContext.person_label`, `target_person_name` in details); merged
    details carry `superseded_by_headline`.
  artifact_tools: |
    Three tools (openexecutive.orchestrator.artifact_tools), registered via
    `DRAFT_ARTIFACT_TOOLS` / `DRAFT_ARTIFACT_TOOL_HANDLERS` in
    `_ALL_SKILL_TOOLS` / `_ALL_SKILL_HANDLERS`, so they are available in
    BOTH the chat tool loop and the executive_research synthesis loop.
    - `draft_artifact(title, why_interesting, format?, document?, sheets?,
      url?, link_label?, source_urls?, supersedes?, severity?)` publishes a
      deliverable. `format` is one of `ARTIFACT_FORMAT_NAMES`
      (`artifact_formats.py`, a hard-coded SORTED tuple so the cached tool
      schema is byte-stable): markdown (default), html, docx, xlsx, link.
      Distinct from `create_alert`: the content is written DIRECTLY to the
      alerts table via `alerts.store.insert_alert` (source=`artifact`,
      topic_tags=`["artifact"]`, `artifact_format`, `owner_person_id` and
      routed to its owner), BYPASSING the triage
      pipeline so the authored content is never suppressed or rewritten.
      Ownership (`orchestrator/artifact_records.py`): a draft is the
      person's whose turn published it (`current_viewer`: the speaker; with
      nobody speaking — scheduler, CLI — the principal; an unrostered web or
      channel speaker is nobody and the tool refuses). A NULL owner is the
      principal's (rows from before the column were backfilled from
      `routed_to_person_id`). Workflow runs carry `owner_person_id` too: the
      starter of a hand-started run (`turn_owner`: HTTP run, `run_workflow`,
      research in chat); scheduled/system runs keep NULL and are the team's
      (`persistence.run_visible_to`, which also admits the person a gate
      waits on). Every read and change — the HTTP routes, the tools, the
      `/workflows/runs` history, `/today` cards (`lifecycle.list_live_alerts`
      keeps an artifact only for its owner `viewer`; every viewer-less build
      drops them), the chat digest, `find_alerts`, alert ack/reopen, the
      activity rail, recall, `message_person` links and mail attachments —
      answers for one viewer, and someone else's artifact is "not found".
      Not even the principal sees a teammate's. A workflow's own session
      inside someone's turn (research synthesis) is pinned to that turn's
      viewer via `Session.documents_viewer`; the MCP server pins NOBODY when
      its caller resolves to no one.
      Returns `{artifact_id: "alert:<n>", url: "/artifacts/alert:<n>",
      format, external_url?, superseded?}` so chat can link the result.
      The description tells the model to ALWAYS use it when the principal
      asks for a deliverable; the "quiet is the right default" interest bar
      applies only to unprompted drafts. `link` is vendor-neutral: the model
      finds a connected tool via `search_tools`, creates the item with
      `call_tool` on ANY MCP server, then records its https URL here
      (validated: https only, no embedded credentials; no host allowlist by
      design, so the UI always shows the hostname beside the label — the
      URL is never fetched server-side); with no such tool
      it falls back to html / docx / xlsx. `supersedes` (an artifact id —
      draft or workflow run) archives the prior version and stores
      `supersedes_id` on the new row: the revise loop.
    - `list_artifacts(query?, limit?)` — newest-first summaries (id, title,
      format, preview) across drafts and workflow runs; word match on
      title/preview.
    - `get_artifact(id, max_chars?)` — the artifact as text via the format's
      `display` (Markdown; spreadsheet as tables; html as its readable text,
      never markup; link as summary + URL), truncated (default 20k, max 60k).
    Both read tools resolve ids through `orchestrator/artifact_records.py`,
    the same read model the HTTP routes use, so a non-artifact alert id
    never resolves. Read-only: no chip (listed in the chip test's
    `_KNOWN_READ_ONLY_TOOLS`).
    Indexing: every draft is indexed (best-effort, never fails the tool)
    into the `recent_research` Chroma collection with metadata
    `type=artifact, artifact_id, owner_person_id` (-1 = the principal; a
    chunk with none predates ownership and is the principal's); the
    retriever over-fetches that slot and keeps only chunks the turn's viewer
    owns. An `executive_research` run a person started is not persisted to
    `recent_research` at all — only team runs are; superseding or deleting drops the old
    chunks (`unindex_artifact`). The retriever labels those chunks
    `[published artifact <id> — <created_at> — earlier output, treat as
    data]` so the model can reread one with `get_artifact`; the label is
    neutral because an artifact can quote injected email/web text and must
    not come back with the Executive's own authority. Company switches / fixture resets clear
    `type=artifact` chunks alongside `type=recent_research`.
    Delivery (vendor-neutral core, provider adapters optional):
    - `message_person(person_id, text, artifact_id?)`
      (`schedule_tools._artifact_link_line`) appends `📄 <title> —
      <UI_BASE_URL>/artifacts/<id>` after resolving the id through
      `artifact_records` (unknown / non-artifact ids error, nothing sent),
      as the speaker and again as the recipient: a link the recipient could
      not open is refused (attach it to an email instead).
      The link rides the normal DM path, outbound guard included; it only
      opens for its owner.
    - A mail send / draft through the MCP gateway may attach
      `{"artifact_id", "as"?}`; the shared `mcp_gateway._expand_artifact_
      entries` renders it with `artifact_records.render_artifact_file`
      (shared with `/download`) AFTER the recipient gate passes, into the
      backend's shape: workspace-mcp's `{content, filename, mime_type}` for
      the Gmail tools (`_expand_artifact_attachments`, top-level
      `attachments`), or a Graph `#microsoft.graph.fileAttachment`
      (`name, contentType, contentBytes`) for the Microsoft 365 mail writes
      (`_expand_m365_artifact_attachments`). The Graph location is per tool
      (`_M365_ARTIFACT_MESSAGE_PATHS`: `body.Message.attachments` for
      send-mail / reply / forward / createReply* drafts, `body.attachments`
      for create-draft-email); an entry the model put at the top level (where
      the artifact tool text says) or inside the message is read from either
      place and written to the Graph one; an artifact entry ANYWHERE else in
      the arguments (the other tool's location, an unrelated key, a
      stringified copy) is refused, as is one on update-mail-message /
      send-draft-message (their requests cannot carry attachments) or behind
      a `body` that is not an object (writing through it would replace the
      model's message with an empty one) — nothing is ever forwarded
      unexpanded. Normalises a stringified or
      single-object `attachments` first (an unexpanded artifact entry would be
      silently skipped by workspace-mcp, rejected by Graph). Refuses unknown /
      non-artifact ids, links, extra keys, more than 5 distinct artifacts
      (repeats dropped) and over 15 MB rendered in total; renders via
      `asyncio.to_thread`. Audits `artifact_attachment_refused` on refusal and
      `artifact_attached` only after a non-error send, both with recipients
      (`_audit_recipients`: Gmail's to/cc/bcc or the Graph message's
      recipient lists). Other attachment entries are untouched; the gate
      skips OData annotation KEYS (`@odata.type`) whose `@` is not an address.
    Side-effecting (`draft_artifact` only): a `tool_invocation` audit row
    (actor="executive", details carry `format`, `supersedes`) and an
    `action_taken` chip ("Drafted artifact for review: {title}") linking to
    `/artifacts/<id>`. It does not page/DM anyone — it lands in the
    `/today` "Needs you" queue (document card with a format badge, an
    "Open artifact" link, and for links an "Open in app (host)" link) and
    stays browsable under `/artifacts` after it is acked/dismissed.
  people_tools: |
    `list_people`, `upsert_person`, `archive_person`, and
    `set_department_head` (openexecutive.orchestrator.people_tools) let
    the Executive manage the People roster directly from a chat turn —
    create or update a person, soft-delete them, or assign a department
    head. Writes call `people_registry.invalidate()` /
    `departments.registry.invalidate()` so subsequent reads see the new
    state, and `set_department_head` also calls
    `ensure_head_persona_override` so the head-voice plumbing fires.
    Every invocation emits a `tool_invocation` audit event with
    actor="executive".

    The three WRITE tools are the principal's alone, and only on a surface
    that verified the speaker (`_refuse_unless_owner`): the web chat
    (`Session.from_web_chat`, the signed-in Google account) or the
    principal's own Slack / Discord (`origin_channel`, the platform's user
    id over an authenticated connection), or a PRIVATE Telegram chat only
    when TELEGRAM_WEBHOOK_SECRET is set to a value Telegram can send
    (Settings.telegram_webhook_secret_valid) — Telegram identifies the chat, not
    the sender (a group is all its members), and /webhook/telegram is
    exempt from the shared secret, so without the webhook secret anyone
    can post an update naming the principal's chat id
    (`_is_verified_speaker_surface`). `is_principal_or_self(caller, None)`
    decides, so an archived principal is refused too. Everything else gets
    `{"status": "refused", "detail": ...}` — a rostered teammate on any
    surface, a signed-in web user whose email is on no People row (told to
    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), the
    CLI, the MCP server, and unattended runs (no `current_session`). Why:
    these tools are offered on every turn, and a People row is the web
    sign-in allow-list, the outbound-email allow-list and approval routing
    at once — a crafted inbound email or a teammate could otherwise add an
    address that can then sign in and receive mail, or grant themselves
    WILDCARD. 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's own
    routes apply the same owner rule (see `people.api`).

    `upsert_person` also takes `email_aliases` (the full list, replacing;
    omitted keeps it; `people.store.clean_aliases` + `set_person_emails`,
    an address already on someone else is an error) and, after every
    write, calls `roster_intake.after_roster_write` so a pending roster
    request whose sender now matches someone closes and replays. A fourth
    write tool, `resolve_roster_request` (request_id, decision approve /
    link / decline, full_name, kind, role, person_id,
    replace_channel_id), answers a roster request (see
    `people.roster_requests`) under the same `_refuse_unless_owner` gate,
    and only for an id in `Session.trusted_roster_request_ids` — filled by
    `briefing.context.render_and_trust` from the `<roster_requests>` block
    it appends to the user-turn digest on the principal's verified turn
    (server-derived lines only: id, channel, address / account id, the
    sanitised unverified name, a company-domain hint, the message count;
    never the sender's words). `approve` without `kind` uses
    `roster_intake.default_kind` (team on a company domain, else
    contact). The id is removed from the trusted set once answered; the
    tool is in `UNATTENDED_WITHHELD_TOOLS`. `_names_a_contact` (audit
    privacy) matches contacts' aliases too.

    Contacts (see `people.kind`): `upsert_person` takes `kind` — explicit
    wins; an update that omits it keeps the row's kind; a new person
    defaults to "team", or to "contact" when
    `memory.workspace_settings.effective_workspace_mode` is solo.
    Making the principal a contact is refused. `list_people` returns both
    kinds, each with `kind`; `lookup_person` searches the team only.
    `set_department_head` refuses a contact. The same verified-principal
    rule, exposed as `people_tools.is_principal_on_verified_surface(session)`
    and `contacts_reachable_now()`, decides whether a turn may reach a
    contact at all (egress, calendar attendees, `message_person` and the
    raw DM tools) — see `integrations.channel_access`.
  standalone_goals: |
    A goal has an owner and, optionally, a department
    (departments.models.Goal: `department_slug` and `owner_person_id` are
    both nullable). Why: departments are heavyweight (a lead, authority,
    a channel, a check-in) and most small teams and solo users never want
    them, but every goal still needs someone it is on and a weekly check.
    The owner is resolved at read time (`departments.goals.
    effective_owner_id`): own owner, else the department's head, else the
    principal; storing NULL keeps a goal following its department when the
    head changes. Coverage: a department with a specialist grades its own
    goals in its check-in; every other goal (no department, or a department
    with no specialist) is graded weekly by the `goal_review` scheduled kind
    (`departments.goal_review`, `GOAL_REVIEW_TIME`, default
    weekly@mon@09:00, both modes) with `cso` (`goals.FALLBACK_REVIEWER`),
    reusing the check-in's verdict contract and `persist_goal_verdicts`.
    It skips goals graded within six days and unedited since, so a quiet
    week costs no model call. Deleting a department detaches its goals
    (an unowned goal takes the head as owner first) instead of deleting
    them. Migration `_migrate_goals_stand_alone` rebuilds the table once to
    drop NOT NULL, then adds `owner_person_id` (no backfill). Routes:
    `GET /goals` (with owner name and department title), `POST /goals`
    (blank area = no department), `PATCH`/`DELETE /goals/{id}`. The org
    block renders goals with no department with their goal_id (team:
    `## Goals With No Department`; solo: `### No area`); the brief adds an
    "Other goals" row (slug "") shaped like a department so every reader of
    `departments` counts them, and attention goals carry the owner. The UI
    shows the Departments tab only when `GET /workspace` reports
    `has_departments`, and adding a teammate while solo switches the
    workspace to team mode without asking.
  department_tools: |
    `list_department_goals` and `update_department_goal`
    (openexecutive.orchestrator.department_tools) let the Executive
    mutate department Goal `status` and `current` progress text from
    a chat turn — used when the user reports progress ("we shipped
    the migration") or a setback ("we lost the deal"). Phase B —
    closes the loop opened by `department_check_in` workflow in Phase
    A (see `departments.goal_review_persistence`). Neither needs a
    department: `list_department_goals` without `department_slug` lists
    every goal with its owner and department, and `update_department_goal`
    names a goal by `goal_id` alone (a `department_slug` it is given must
    match the goal's department). `update_department_goal` requires `goal_id` +
    `rationale` and at least one of `status`/`current`. `rationale` is
    stored in the audit log (never on the goal row) so future readers
    see the provenance of every chat-driven change. The handler enforces
    a cross-department id guard (a goal_id from `engineering` cannot
    be mutated as `finance`), rejects boolean ids (Python `isinstance(
    True, int)` quirk), and calls `dept_registry.invalidate()` after
    the write. Status mutation routes through `store.update_goal(...,
    last_reviewed_at=now)` so `updated_at` AND `last_reviewed_at`
    advance in one transaction (single Honcho mirror, single audit row,
    same wall-clock for both columns). No authority gate — the goal
    surface is principal-editable at any time through the UI, so a
    chat-turn change is no riskier than a manual edit. That open
    surface is paired with a BEHAVIORAL guardrail (not a code gate):
    the persona + tool descriptions instruct the Executive to update
    goals one-at-a-time, each backed by goal-specific evidence, and to
    REFUSE a blanket detail-free sweep ("mark all my goals off track")
    by asking which goals changed and what happened instead — closing
    a QA-audit gap where the Executive could be talked into mass-
    flipping every status with a reused, non-specific rationale. The
    handler itself stays stateless per-goal (it cannot see a sweep), so
    the guard is enforced via prompt + negative eval
    `department_goal_update_004`, mirroring the speculation guard in
    `department_goal_update_003`. Every invocation
    emits a `tool_invocation` audit event tagged `actor="executive"`,
    `details.tool="update_department_goal"`, `details.from_status`/
    `to_status`, and `details.rationale`. Surfaced in the live stream
    via `action_chips.summarize_action` as
    "Updated {slug} goal → {status}".
    `create_goal` (same module, both modes) starts tracking a NEW goal the
    principal states ("20 paying clients by the end of Q4"). Inputs: `area`
    (free text — a department slug or title), `key_result`, `target`,
    `rationale` (required), optional `period_type` (default quarter),
    `period_value` (default the current period in the user's zone, shaped
    like the UI's suggestPeriodValue), `current`, `status` (default
    on_track). The schema is STATIC — no enum of existing areas, which would
    change the cached tool prefix whenever one is added.
    WHO: the whole tool runs only when the turn is the principal on a
    verified surface (`people_tools.is_principal_on_verified_surface`, the
    roster tools' rule: web chat, their own Slack or Discord, a private
    Telegram chat with a valid webhook secret). A goal renders in every
    turn's org block as one of the principal's own, so a goal from an inbound
    email (the sender is the From header), Google Chat, the CLI, the MCP
    server, a teammate or an unattended run would be text with their
    authority: refused before any write, audited refused=true with
    caller_person_id / origin_channel / from_web_chat / unattended.
    The area resolves through `departments.store.match_department` (slug as
    given or as the store would slug it, else case-insensitive title — the
    rule onboarding's reconcile also uses); when nothing matches,
    `create_department` makes it (a bare slug from the model is
    title-cased), with a `specialist_key` only when `specialist_key_for_area`
    maps the title (the default departments' slugs and titles, plus sales)
    AND no department already holds that specialist — otherwise the area is
    informational. Guards in code: field caps matching the goal routes;
    refuses a goal whose normalized key_result the area already tracks
    (error names the goal_id and points at update_department_goal); at most
    5 goals per chat turn (keyed on the audit turn id — a sweep is not a
    stated goal; no cap without a turn); at most 8 goals per area
    (`_MAX_GOALS_PER_AREA` — common practice keeps 3-5 key results per
    objective, and every goal renders in the 4000-char org block, so one
    area cannot crowd the others out; the goal routes / UI are not capped).
    A store failure reaches the model as the exception TYPE only (as
    `executive._tool_error_result`; the log keeps the rest) — the same now
    holds for list_department_goals and update_department_goal.
    Audited as `tool_invocation` with `details.tool="create_goal"`,
    department_slug, goal_id, area_created, specialist_key and the
    rationale; invalidates the department registry. Chip: "Added a {area}
    goal: {key_result}", linking to /goals in solo (the turn's mode reaches
    `summarize_action(workspace_mode=...)`) and /departments/{slug} in team.
    Never offered to an unattended run: it is in
    `schedule_tools.UNATTENDED_WITHHELD_TOOLS`, which `unattended_toolkit`
    drops for reflection and research (both modes) and the chat loop drops
    (list AND dispatch, `unattended_withheld_error`) when the Session has
    `unattended=True` — set by the scheduler's PROACTIVE TRIGGER dispatch
    (`scheduler.runner._execute_action`). That run therefore has its own
    stable tool prefix. The solo persona teaches it (`_SOLO_CREATE_GOAL`);
    team mode learns it from the tool description, so the team persona
    stays byte-identical.
    Goals stand on their own: `create_goal` leaves `area` out unless the
    principal names one (a goal with no area creates no department) and
    takes an optional `owner_person_id` (a non-archived team member, else
    refused). The duplicate check and the 8-goal cap apply to the goals
    with no department as one group.
    Evals: `department_goal_update_005`, `department_goal_update_006`.
    `record_decision_outcome` (orchestrator/decision_tools.py, both modes)
    records how a past decision turned out. The weekly review lists up to
    three decisions older than 30 days with an empty outcome as
    `[decision N]`; when the principal answers, the tool writes
    `decisions.outcome` (`episodic.update_decision`, the column the
    Memories page edits). Inputs: `decision_id`, `outcome` (the principal's
    words, max 1000 chars), `rationale` (required, audited). Same gate as
    `create_goal`: the principal on a verified surface only (refused and
    audited refused=true with the caller context otherwise), and in
    `UNATTENDED_WITHHELD_TOOLS`, so no unattended run is offered it. A
    missing or unknown id returns an error carrying `awaiting_outcome` (up
    to five decisions with no outcome yet, newest first) so the model can
    retry with the right id. Audited as `tool_invocation` with
    `details.tool="record_decision_outcome"`, decision_id, the previous
    and new outcome and the rationale; a store failure reaches the model as
    the exception TYPE only. Chip: "Recorded how it turned out: {decision}"
    linking to /memories. Static schema; the solo persona has one line on
    it (`_SOLO_DECISION_OUTCOME`), team learns it from the description, so
    the team persona stays byte-identical. Evals: `decision_outcome_001`.
  outbound_target_selection: |
    For any proactive outbound message, the Executive picks the audience
    by choosing which outbound tool to invoke. The persona's
    `## Choosing Who to Tell` section codifies the rule (smallest
    audience that owns the matter; DM the single owner if known; dept
    channel if dept-scoped; company broadcast if no clear owner;
    DM the scope-holder for board/comp/legal regardless). Three tiers
    of outbound tools sit alongside each other:

      1. Per-Person DMs — `send_slack_dm`, `send_discord_dm`,
         `send_telegram_message`. People-roster gated
         (`schedule_tools._dm_recipient_on_roster`, unconditional on all
         three), and additionally passed through the outbound anti-spam
         guard before the network send (see
         `outbound_antispam_invariant`). The gate is what keeps untrusted
         turn content — inbound mail, a chat message, a knowledge document
         — from aiming a DM at an arbitrary workspace member, so it is the
         model-exposed `user_id`/`chat_id` argument it exists to constrain.
         Until the gate was added to the Slack handler, that claim was
         true of Discord and Telegram only: `send_slack_dm` looked the
         recipient up solely when `turn_is_private_to_principal()`, a
         per-turn flag the inbound mail poller sets, so an ordinary turn
         reached `chat_postMessage` with no roster check at all.
      2. Department channels — `send_department_message(slug,
         integration, text)` posts to a configured room on the
         department row. No roster gate — channels are team-visible.
      3. Company broadcasts — `send_company_broadcast(integration,
         text)` posts to the env-configured default channel.

    Each tool returns a structured error on missing configuration so
    the model can read it and route around (e.g. dept has no slack
    channel → DM the head instead). Every successful call surfaces
    an `action_taken` SSE chip in the live chat (see `chat:` section).

    Solo mode has no audience to choose: only one person — the principal —
    uses Open Executive. The principal's role is not assumed (an owner, an
    executive inside a larger organisation, or an independent); the people
    in their world (manager, direct reports, peers, clients, investors,
    board) are contacts the Executive helps them work with, not a team it
    coordinates. The solo persona replaces "Choosing Who to Tell" with
    "The People in Their World" and "Who Hears From You": everything goes
    to the principal, and contacts are messaged only when the principal
    asks and only if they are a contact. Tiers 2 and 3
    are not offered at all: filter_tools_for_workspace_mode withholds
    send_department_message, send_company_broadcast and
    set_department_head from the chat loop, the reflection and the
    research synthesis (message_person, list_people and upsert_person
    stay). The model can still emit a withheld name, so every dispatch
    site refuses it — the chat loop answers with a JSON error tool_result
    (schedule_tools.withheld_tool_error), reflection and research drop
    the names from the handler map ("unknown tool — skipped"). The alert
    triage backstop matches: alerts.preferences.resolve_channels strips
    department_channel and company_broadcast in solo.
  ai_disclosure_invariant: |
    What the Executive sends to people says it is an AI assistant, added by
    plain code, never the prompt (orchestrator.disclosure). Mail from its
    own mailbox: the MCP gateway appends the mail line to every Gmail send
    or draft and every Outlook send, reply, forward or draft
    (mcp_gateway._with_disclosure) after every outbound gate passed and only
    on the arguments sent to the server, so gates, outbound-context records
    and audit rows see the model's words. Skipped when every recipient is
    the principal, when the body already has it, and for send_draft_message
    (the draft got it when made). Only a last shown line counts as already
    there. HTML that could hide what follows (disclosure.hides_what_follows)
    is refused; the roster acknowledgement to a new sender gets
    BARE_MAIL_LINE, which names nobody. Chat: the shorter line on the Executive's
    Slack / Telegram / Discord / Google Chat replies and on send_slack_dm,
    send_discord_dm, send_telegram_message and broadcast_tools._dispatch,
    once per conversation per 24 hours (in memory; a restart shows it
    again), applied at the send call only so the anti-spam guard and session
    history see the text without it. AI_DISCLOSURE (default on) turns it
    off; AI_DISCLOSURE_MAIL_TEXT / AI_DISCLOSURE_CHAT_TEXT reword it and are
    ignored unless they say "AI". Fails open. Sends as a person (Act as me)
    carry delegation.disclosure.LINE by that person's own switches
    (delegation_disclosure: handle_it default AI_DISCLOSURE_HANDLE_IT=true,
    approved_sends default AI_DISCLOSURE_APPROVED_SENDS=false), written into
    the reply when it is drafted (inbox._consider, follow_ups) so card,
    draft and sent mail match. PUT /delegation/disclosure changes them;
    turning one off needs a signed caller. tests/conftest.py sets
    AI_DISCLOSURE=false for the suite; test_ai_disclosure.py turns it on.
  outbound_antispam_invariant: |
    Every Per-Person DM (`send_slack_dm` / `send_discord_dm` /
    `send_telegram_message`) passes through a deterministic anti-spam guard
    (`orchestrator.outbound_guard.check_outbound_allowed`) AFTER the roster
    gate and recipient-id recovery but BEFORE the network send. This is the
    single chokepoint every proactive DM path reaches — ad-hoc chat sends,
    the scheduler's followup/nudge dispatch, principal-brief delivery, the
    reflection turn, and research-finding routing all bottom out in these
    three handlers. The guard enforces three controls and, on a violation,
    returns a human-readable reason; the handler then SUPPRESSES the send
    (returns `{"status":"suppressed","reason":…}`), writes a
    `tool_invocation` audit row with `suppressed=true`, and does NOT write a
    `done` activity row — so a suppressed attempt never counts toward the
    rate cap. The Executive reads the reason and can hold the message or
    `schedule_followup` for the recipient's next window. The controls:

      1. Content dedup — refuse a near-identical message (whitespace- and
         case-normalized, first 160 chars) already sent to the same
         (channel, channel_ref) within OUTBOUND_DEDUP_WINDOW_MINUTES
         (default 360).
      2. Per-recipient rate cap — refuse once
         OUTBOUND_MAX_PER_RECIPIENT_PER_WINDOW (default 5) sends have gone
         to that recipient within OUTBOUND_RATE_WINDOW_MINUTES (default 60).
      3. Quiet hours / availability — when OUTBOUND_RESPECT_QUIET_HOURS is
         true (default), refuse while the recipient is on leave or outside
         their `people.channel` availability windows. The reason carries the
         next open window so the model can reschedule.

    The delivery history is read from the existing `status='done'`
    `scheduled_actions` rows (`episodic.recent_sends_for_channel_ref`) — no
    new table. The guard is FAIL-OPEN: any internal lookup error (or a
    settings object missing the knobs) returns "allow", so it can never turn
    a working send into a crash or a silently-dropped message. This is
    distinct from, and additive to, the `seen_channel_refs` scheduling guard
    and the `max_pending_*` caps on `schedule_followup`. Principal briefs and
    the internal heartbeat kinds (`__internal__` channel) never reach these
    handlers, so they are unaffected (see the `scheduler:` kinds note).
    After the guard allows a send, the handlers apply the recipient's own
    notification settings to the Executive's own (tagged) outreach:
    `_hold_outbound` → `outbound_guard.check_hold` stores the DM in
    `held_messages` and returns {"status":"held"} when they are in quiet
    hours or chose "In my briefs" (people.notification_settings).
  reflection_then_decide: |
    Shift 5 introduces a new routing pattern: ``executive_reflection``
    is the first workflow that lets OE consume structured signal data
    (the /today + /today/activity + open-alerts triple) and decide what
    to ACT on, not just what to summarise. The reflection workflow
    invokes a single LLM call against the routing_model with the
    Executive's full outbound toolkit (the same `_ALL_SKILL_TOOLS` /
    `_ALL_SKILL_HANDLERS` registries used by chat), plus its own
    `search_knowledge`. Up to 5 iterations
    of tool-use loop; each tool call hits the real handler — DMs go
    out, follow-ups get scheduled, alerts are flagged, broadcasts post
    to channels. DMs to a person go through `message_person(person_id,
    text)` (the server resolves the recipient's real channel id) — the
    raw per-channel send_*_dm tools are withheld from the reflection
    toolkit, same as the research synthesis, so the model never supplies
    or fabricates a channel id. The audience rule ("single human owns
    it", system prompt built per-run by `_build_reflection_system`) names
    message_person whenever any DM channel is configured
    (`configured_integrations`) and, with no DM channel at all, steers to
    a department message / morning brief instead. The reflection turn also
    carries the active roster (`_render_team_roster`, shared with research)
    so the model DMs by person_id directly and is told NOT to call
    lookup_person — same fix as research for the "looks up, never routes"
    failure. The model emits a final Markdown summary of what
    was done and what was deferred to the morning brief.

    Solo: the system prompt is `_build_reflection_system_solo` (the
    principal — whatever their role — is the only person who uses Open
    Executive and the only one it takes direction from; prefer create_alert
    and schedule_followup to the principal; never message anyone else from
    an unattended pass — flag it for the principal to raise), the roster
    block is replaced by a single YOUR PRINCIPAL line (person_id +
    follow-up channel refs), the seen-refs guard is seeded from the
    principal only, at-risk departments render as AREAS WITH GOALS AT RISK
    and the people-waiting block is dropped. The research synthesis follows
    the same rule (`_build_synthesis_system(mode="solo")` routes only to the
    principal; its roster lists only the principal). In both,
    message_person is wrapped by schedule_tools.principal_only_handlers,
    which refuses any person_id but the principal's (fails closed on a
    roster read error) — the "contacts only when the principal asks" rule is code,
    not just prompt, on the passes that run unattended with inbound text in
    context. Solo's unattended passes also never get create_calendar_event,
    create_instant_meeting or run_workflow
    (schedule_tools.SOLO_UNATTENDED_WITHHELD_TOOLS): a booking reaches its
    attendees and a workflow can do anything its steps do, so injected text
    ("book a sync with X") must not reach a contact — the principal books
    and starts workflows from chat. Both read the mode through
    effective_workspace_mode(current_session) before binding their own
    session, and pin that mode on their own session (turn_workspace_mode)
    so their tool handlers use it too.

    Offered means runnable, in BOTH modes: schedule_tools.unattended_toolkit
    builds each pass's handler map from exactly the tool list it offers
    (handlers_for_offered_tools), so a name the model emits without being
    offered it is skipped as "unknown tool". Before this, both passes
    dispatched against the whole _ALL_SKILL_HANDLERS registry, so tools
    they deliberately withhold still ran when emitted — the raw
    send_*_dm tools (send_slack_dm has no roster check), ack_alert and
    close_open_loop in reflection; the watchlist writes, run_workflow,
    send_company_broadcast and ack_alert in research.

    Knowledge: chat looks the knowledge base up before each turn and each
    consulted specialist looks up its own domain; the reflection has
    neither, so it gets `search_knowledge` (orchestrator/knowledge_tools.py),
    the same `knowledge.retriever.retrieve` as chat, read-only and never
    gated. The prompt (`_KNOWLEDGE_RULE`, both modes) asks for a search
    before acting on or flagging something that turns on a customer's or
    supplier's terms, a price, a policy, a plan or a past decision. Its
    passages return up to 4,000 characters (execute_tool_calls
    wide_results) while other tools keep the short preview; the run's tool
    log trims every line to 160. The pass runs with no viewer, so no
    published artifact that is someone's own comes back.

    Audit trail: every tool the reflection model invokes flows through
    the existing handler audit rows (`tool_invocation` with actor=
    "executive"); the workflow run_id ties them together so a human
    inspecting the audit log can see "OE's 07:30 reflection on this
    date fired N DMs and queued M follow-ups." Tool failures don't
    abort the loop — the model sees the failure summary and can
    choose to retry, route differently, or surface the failure in the
    morning brief.

  outbound_privacy_invariant: |
    For decisions touching `authority_scope` of `board`, `comp`, or
    `legal`, OE must DM the scope-holder rather than posting to a
    department channel or company broadcast — even when the matter
    would otherwise qualify as department-scoped or company-wide.
    The blast radius of a broadcast is the whole team; the privacy
    expectation for these scopes is the named decision-maker.
    Enforced PRIMARILY by persona instruction ("Choosing Who to Tell"),
    with a deterministic code backstop on the broadcast tools:
    `broadcast_tools._privacy_backstop_violation` refuses
    `send_department_message` / `send_company_broadcast` whose body matches a
    curated, word-boundary set of sensitive terms (layoffs, severance,
    valuation, compensation, litigation, lawsuit, term sheet, cap table,
    equity grant, board deck/meeting/vote), returning an error that tells the
    model to DM the scope-holder instead. This mirrors the alert dispatcher's
    `_violates_privacy_invariant` (which gates on topic_tags); the broadcast
    backstop works on free text and is curated for precision (few false
    positives) over recall — the persona is the primary control, the code is
    defence-in-depth. Every refusal emits a `tool_invocation` audit row
    carrying the matched term.

knowledge:
  embedding_function: |
    Every ChromaDBStore collection is opened with one shared embedding
    function (knowledge.store._embedding_function): all-MiniLM-L6-v2 ONNX,
    the same model and vectors as Chroma's DefaultEmbeddingFunction.

    Why not Chroma's default: it builds a new ONNXMiniLM_L6_V2 per call, so
    every query reloads the model (~240 ms), and its session keeps ONNX
    Runtime's CPU memory arena, which retains the peak of a 32-text batch
    padded to 256 tokens. A 300-chunk upload peaked near 760 MB. The shared
    session is built once, runs with enable_cpu_mem_arena=False and embeds 4
    texts per run: ~300 MB peak, ~30 ms per query, ~90 MB more at idle
    because the model stays loaded.

    Compatibility invariants: collections persist the function they were
    created with ({"name": "default", "config": {}} on every existing
    install), and Chroma raises on a differently named function, so the
    shared one answers name() == "default" with an empty config. It must NOT
    be a DefaultEmbeddingFunction instance: Collection._embed ignores those
    and embeds with a fresh default rebuilt from the collection config.
  chat_excerpt_budget: |
    The chat surfaces (web chat, Telegram, Discord, Google Chat) pass
    max_chars=KNOWLEDGE_CHAT_MAX_CHARS (default 6000, 0 = no cap) to
    retrieve(). retriever._fit_to_budget keeps the closest chunks across every
    collection until the cap, skipping one that would overflow so a shorter
    weaker one can still fit, and always keeps the closest. Each excerpt is
    re-sent on every model call of the turn, so the tail of weak matches cost
    on every call. Workflows and specialists keep their own counts, uncapped.
  distance_gates: |
    Two gates. KNOWLEDGE_DISTANCE_THRESHOLD (default 0.55) is the shared one,
    applied to COMPANY, NOTION_WIKI and RECENT_RESEARCH.
    KNOWLEDGE_BUILTIN_DISTANCE_THRESHOLD optionally tightens BUILTIN and the
    FAILURES collection queried by retrieve_failures() — both ship with the
    repo and are generic by construction, so they move together. Unset (the
    default) every collection keeps the shared value, which is the historical
    behaviour.

    The builtin gate can only ever TIGHTEN: _resolve_builtin_threshold takes
    min() against the shared value. Without that clamp an operator who
    transposed the two variables would invert the whole point — BUILTIN looser
    than COMPANY, admitting handbook prose at a distance where a company doc is
    still dropped. The field is also range-checked to [0, 2]; a negative value
    would disable builtin retrieval and present as "the knowledge base stopped
    helping" rather than as a config error.

    Why the split exists: BUILTIN is generic material and an order of magnitude
    larger than a typical company corpus, so a threshold loose enough to admit
    the right company doc admits a lot of unrelated handbook prose with it.
    Raising the shared gate to fix company-doc recall therefore costs precision
    everywhere; the per-collection gate buys the recall without the noise.

    Precedence inside retrieve(): an explicit `builtin_distance_threshold`
    argument, then KNOWLEDGE_BUILTIN_DISTANCE_THRESHOLD, then the shared
    threshold — each clamped by min() against the shared value.

    A caller-pinned `distance_threshold` deliberately does NOT suppress the
    builtin setting. No caller in the repo pins one, so such a tier would be
    dead code today; and a future caller loosening the shared gate for an
    unrelated reason must not silently revoke an operator's deployment-level
    guardrail. A caller that genuinely wants one gate for both collections
    says so with `builtin_distance_threshold`.
  skills: |
    Skills are Markdown procedures with YAML frontmatter (name, description,
    when_to_use, category). The UI shows each one as "How it's done" on the
    page of the workflow that follows it (components/jobs/HowItsDone.tsx:
    Edit = PUT /skills/{name}, a customized copy on a built-in; Reset to
    original = DELETE on that copy); there is no separate Playbooks tab
    any more, and `/skills` redirects to `/jobs`. The
    mental model the UI and persona teach: a playbook is HOW the Executive
    does a piece of work (method, template, checklist; no inputs, schedule or
    side effects); a workflow is the runnable job that produces an artifact.
    Every playbook belongs to a workflow: a built-in or custom one that
    follows it, or else its own Quick workflow (below). Backend names
    (`/skills`, the `search_skills` / `load_skill` tools, the `skills`
    collection) are unchanged.

    Quick workflows (workflows/quick.py): one per playbook in effect that no
    built-in or custom workflow follows (switched-off custom ones count),
    derived whenever the catalog is read, never stored. Name
    `quick_<playbook, dashes as underscores>` (custom workflows may not take
    the `quick_` prefix, validate_definition); WorkflowMeta.quick is true.
    One required field, `request`; steps context (profile + RAG for the
    category's specialist) -> draft (that specialist follows the playbook
    via playbook_clause, one Markdown document). Category -> specialist /
    section: strategy cso (Growth), finance cfo (Capital), hr chro (People),
    legal gc (Risk), operations coo (Operating), marketing cmo (Growth),
    product cpo, board board_comms, sales (Growth), general cso
    (Operating). list_workflows() = built-ins + Quick + active custom;
    get_workflow resolves a Quick name after the registry. The 8 built-in
    playbooks no built-in workflow follows are Quick: board-update-memo,
    exec-1on1-template ("1:1 agenda"), layoff-comms-plan,
    positioning-statement, post-mortem-template ("Post-mortem"),
    customer-interview-plan, feature-prioritization, market-sizing. A
    company's own playbook shows up as one; hiding a built-in drops it; a
    custom workflow that starts following one replaces it. If the custom
    store can't be read, no Quick workflows are offered (unknown followers).
    Playbooks whose names map to one Quick name (market-sizing,
    market_sizing) get none, so sort order never picks the method. A
    custom workflow stored under a `quick_` name before the prefix was
    reserved keeps it: no Quick workflow takes a name a built-in or stored
    custom one already has. A run whose playbook can't be read (hidden or
    broken since listing) ends with an error rather than a generic draft.

    Storage: built-ins ship in git under knowledge/builtin/skills/<category>/;
    company skills in company/skills/<category>/ (gitignored, copied with
    client slots, wiped by fixture reset). One Chroma doc per skill in the
    `skills` collection, id `skill::{source}::{name}`, text = name +
    description + when_to_use; the body is only returned by load_skill.

    Customize / hide / restore (knowledge/skills_repo.py):
      - A company skill with a built-in's name CUSTOMIZES it — the company
        file wins in get/list/load and in workflows that read a skill body
        (board_prep, quarterly_plan via get_skill). `update_skill` on a
        built-in writes that company copy with frontmatter
        `customizes_builtin: true`; the built-in file is never touched. The
        built-in's index row is dropped while shadowed. Only a flagged copy
        of a built-in that is not hidden counts as `customized` — a company
        skill that merely shares a name with a built-in shipped later is the
        user's own, so deleting it reports "deleted", not "reverted".
      - A malformed company file shadows nothing: lookups, listing and
        index reconciliation all skip it, and the next write for that name
        replaces it (one company file per name).
      - `delete_skill` never raises for built-ins any more. It returns an
        outcome: "deleted" (plain company skill), "reverted" (company
        customization removed, built-in re-indexed) or "hidden" (built-in
        added to company/skills/.hidden.yaml and dropped from the index).
        `restore_skill` validates the built-in before editing the hidden
        list, so a failed restore changes nothing.
      - Hidden built-ins are invisible to search_skills/load_skill and to
        list_skills unless include_hidden; `GET /skills/{name}` still reads
        them so the UI can show one before `POST /skills/{name}/restore`.
      - skills_repo.create_skill conflicts with every existing name, hidden
        built-ins included (customizing goes through update).

    Index reconciliation: `sync_builtin_skill_index` makes the built-in rows
    match "built-ins in effect" (on disk, not hidden, not customized) —
    dropping extra rows and (re)indexing missing or changed ones. It runs at
    startup (seed_builtin_skills), after a client-slot restore, and after a
    fixture reset. Before this, seeding skipped whenever the collection was
    non-empty, so a built-in added in a release never reached an existing
    install's index.

    Chat does not change playbooks: it has only search_skills and
    load_skill. Repeatable work is saved as a workflow (draft_workflow ->
    the user confirms -> save_workflow), with the method in its steps; a
    playbook's body is changed by a person (How it's done on the workflow
    page; the HTTP API also keeps hide / restore). Workflows read playbooks at run
    time, including approved scheduled custom ones whose later action steps
    write to already-approved targets unattended, and the tool loop also
    runs on inbound email/Slack/etc., so no model a crafted message could
    steer may rewrite one. (The old create/update/delete_skill chat tools
    and their draft review queue, /skill-drafts, are removed; a leftover
    company/skills/.drafts/ folder is ignored.)

    Workflows follow playbooks (workflows/playbooks.py): `load_playbook`
    returns the body in effect ("" when hidden, missing or malformed — never
    raises) and `playbook_clause` appends it to a step prompt. Built-ins
    declare `Workflow.playbooks`; test_workflow_playbooks.py asserts the
    declaration equals the module's load_playbook("…") calls, so the "used
    by" reporting can't drift. Pairs: board_prep→board-prep-deck,
    quarterly_plan→quarterly-okr-set + quarterly-forecast,
    mbr→monthly-business-review, competitive_teardown→competitive-teardown,
    fundraising_prep→fundraise-narrative, exec_search_brief→role-scorecard.
    (board_prep used to also load board-update-memo and never use it; that
    dead load is gone.) Custom workflows: SpecialistStepSpec.playbook,
    validated at save, appended AFTER {field} rendering. playbook_users()
    feeds SkillMeta.used_by, search_skills hits' `workflows` (Quick ones
    included), and the UI's hide/revert/delete warnings; it counts
    switched-off custom workflows (list_definitions(active_only=False)), and
    followed_by_workflows() is the same set without the Quick ones.
    load_playbook catches every exception; a
    custom step whose playbook is unavailable emits a `progress` event.
    Persona routing: a hit with `workflows` +
    a request for the finished deliverable -> run/offer the workflow;
    otherwise follow the playbook inline.
  collections:
    - name: BUILTIN
      what: |
        Curated MBA-style domain knowledge shipped with the repo, one directory
        per DOMAIN_MAP domain (sales included: founder-led sales,
        qualification and pipeline, proposals and pricing conversations,
        follow-up and forecasting), plus solo-founder guides in finance,
        marketing, legal and hr.

        SEEDING. loader.seed_builtin_knowledge (BUILTIN) and
        loader.seed_failures (FAILURES) run on every boot. On an empty
        collection, or with force=True, they index the whole tree. Otherwise
        they top up: every SHIPPED_BUILTIN_FILES entry with no chunks in the
        collection is indexed, once. Both used to return early on any
        non-empty collection, so a doc added in a later release shipped,
        registered as an approved trusted default, and was never retrievable
        on an install seeded by an earlier release.

        Presence is judged from each row's `source` relative to
        knowledge/builtin/ (loader._builtin_relative_source), NOT the absolute
        path: `source` and the chunk id both embed the absolute install path,
        so an upgrade that moves the install would otherwise re-index every
        doc under fresh ids and duplicate the collection. The check is one
        metadata-only scan narrowed by `where={"type": "builtin"}` (or
        `failure_case`), so the external OER rows sharing BUILTIN
        (`type=external`) are never pulled; a complete store indexes nothing.
        If no row carries the tag (rows from a build that did not write
        `type`), it falls back to a full scan rather than reading untagged
        rows as absent.
        The top-up is manifest-driven, never a tree scan: a user's own upload
        in the same tree is indexed by the endpoint that wrote it, and a
        manifest entry missing on disk is skipped rather than resurrected.
        Changed content of an already-indexed shipped doc is NOT re-indexed by
        this path. The top-up is best-effort: a doc that fails to embed is
        logged and stays missing, so the next boot retries it, and startup
        never fails on it. First-boot seeding and force=True still raise.
        Blank shipped files never count as missing.
    - name: COMPANY
      what: |
        Customer-supplied documents ingested via the /documents endpoint. The
        original file is also persisted under <company_profile_dir>/docs/, so
        the Knowledge UI can list (GET /documents), retrieve the extracted text
        for read-only viewing (GET /documents/{filename}), and delete
        (DELETE /documents/{filename}) individual docs. Synced Notion pages
        do NOT land here — see NOTION_WIKI.

        The knowledge page shows ONE Company documents list: these uploads
        plus synced Drive and OneDrive files and Notion pages (GET
        /documents/drive, GET /documents/onedrive, GET /documents/notion,
        each read from that sync's state file, with a text view at
        /documents/{drive|onedrive|notion}/{id} whose path comes from the
        state record, never the caller). Synced rows are read-only — removing
        the file from the folder / integration is what drops it. Each
        connected source shows last_run, last_error and a Sync now button
        (POST /documents/sources/{id}/sync: 202, or 409 not connected /
        already running, 429 within 60 s of the last run). The route keeps
        its started task per source (`_SYNC_TASKS`) and re-checks it right
        before create_task, so two simultaneous clicks start one tick.
        last_error is also set by a tick that succeeded but had files/pages
        fail (stats["failed"] > 0, "N files could not be synced"); the next
        clean tick clears it. Both syncs hold a
        per-process run lock (`_RUN_LOCK`), so a manual tick and the heartbeat
        never overlap; the loser returns {"busy": 1}. Uploads from the page
        no longer pick a domain and go in as `general`.

        IDENTITY IS THE FILENAME. ingest_file takes an explicit `source_name`
        that becomes the filename/source metadata AND the chunk-id namespace
        (_make_chunk_id is an MD5 of it). The upload endpoint stages the body
        in a tempfile so the PDF/DOCX extractors have a real path to open, and
        MUST pass the real name — passing the staging path was issue #113:
        every re-upload got fresh ids so the id-keyed upsert never collided
        and company_docs grew without bound, and the stored filename was
        `tmpXXXXXXXX.md`, which the DELETE `where={"filename": …}` could never
        match (it unlinked the file, returned 200, and stranded every chunk).
        Because the id namespace is the bare filename and not the absolute
        path, an uploaded plan.md and a fixture-loaded plan.md are the same
        document rather than two.

        Chat/integration attachments are NOT in this collection — see
        ATTACHMENTS below. They used to be, isolated only by a domain outside
        the specialist set, which isolated nothing. Rows left by that path are
        migrated out on boot by
        loader.migrate_attachments_out_of_company_docs, not purged.

        RECONCILE ON BOOT. The lifespan calls
        loader.reconcile_company_docs(store, docs_dir), which drops rows whose
        filename still matches the temp pattern and is absent from docs_dir,
        then indexes any docs_dir file with no rows at all. It deliberately
        does NOT re-ingest documents that are already indexed: the on-disk
        copy carries no record of the domain the uploader chose, so
        re-ingesting would retag a `finance` document as `general`. Idempotent
        (filename-derived ids), so it is a no-op on a clean store.
    - name: NOTION_WIKI
      what: |
        Synced Notion wiki pages (ChromaDB collection `notion_wiki`). Kept
        SEPARATE from COMPANY because a Notion share is inherited and
        multi-writer: every teammate, contractor, or guest who can edit any
        page under the share can change the text, and that text becomes
        agent context on the next sync tick with no review step. Agents
        cannot tell information from instructions, so unvetted wiki text
        must never blend into curated company uploads. Optional
        (`NOTION_SYNC_ENABLED`, off by default): a scheduler heartbeat
        (`notion_sync_scan`) incrementally re-indexes pages the internal
        integration can see (metadata `notion_page_id` / `type=notion`),
        writing Markdown under <company_profile_dir>/docs/notion/. State
        (`pages` dict + last_edited watermark) lives in
        <company_profile_dir>/notion_sync_state.json. Each tick reconciles:
        pages the integration no longer sees have their files and chunks
        purged. The watermark advances only past pages that actually
        ingested; overflow beyond NOTION_MAX_PAGES_PER_SCAN is retried next
        tick. At retrieval the retriever queries this collection with a
        small n and appends it under a clearly-labelled "Synced Notion wiki
        (unreviewed, multi-writer …)" section ranked BELOW curated company
        documents and above recent research. Manual: `openexecutive
        sync-notion` / `openexecutive purge-notion`.
    - name: DRIVE
      what: |
        Files synced from shared Google Drive folders (ChromaDB collection
        `drive_docs`, metadata `drive_file_id` / `type=drive` / `name` /
        `url` / `synced_at`), by knowledge.drive_sync. SEPARATE from COMPANY
        for NOTION_WIKI's reason: a shared folder is multi-writer and
        unreviewed. Optional (`DRIVE_SYNC_ENABLED`, off by default; setup in
        docs/drive_sync_setup.md): a scheduler heartbeat (`drive_sync_scan`)
        lists `DRIVE_SYNC_FOLDER_IDS` and their subfolders (depth 4, 2000
        items per tick) through knowledge.drive_client. That client calls the
        Drive v3 API directly with httpx, as a SERVICE ACCOUNT with
        drive.readonly (`DRIVE_SYNC_SERVICE_ACCOUNT_FILE`; token via
        google-auth, refreshed off the loop). It is deliberately NOT the
        workspace-mcp gateway: that acts as the Executive's own account at
        the complete tier and returns display text. Here Google enforces the
        folder scope (only what is shared with the service account), the sync
        can change nothing, and results are JSON; ids are checked against
        [A-Za-z0-9_-]{1,128} before use.

        Change detection: a file is dirty when its (modifiedTime,
        md5Checksum) differs from its record in
        <company_profile_dir>/drive_sync_state.json. Dirty files are handled
        newest first, capped at DRIVE_MAX_FILES_PER_SCAN; the overflow waits
        for the next tick.
        - Text: Docs / Slides are exported as text/plain and Sheets as .xlsx
          (Drive's CSV export holds only the first sheet). .docx / .xlsx /
          txt / md / csv are downloaded and read with
          loader.extract_text_from_file. A PDF goes through
          pdf_reader.read_pdf_text, the path uploads take (not inbound, so
          PDF_VISION_MAX_PAGES, not the inbound budget): the text layer, else
          the opt-in model step (PDF_PROVIDER_READING), else local OCR in a
          child process under the two-slot OCR gate, with PDF_OCR_ENABLED
          switching it off for Drive as for uploads. Why: a scanned contract
          in a shared folder used to be skipped silently. Anything else, and
          anything over 20 MB, is skipped. Downloads stream and stop at the
          cap. A .docx / .xlsx whose zip declares more than 100 MB
          uncompressed is not parsed. Non-PDF extraction has a 120 s deadline
          (the worker thread cannot be killed, but the tick moves on); a PDF
          read keeps pdf_reader's own child limits, under a backstop
          (_PDF_READ_TIMEOUT_S, 1200 s: text layer + a model allowance + OCR
          slot wait, budget and slack). Busy parsers / OCR slots are a retry
          next tick, not a verdict. An unreadable file is recorded with no
          chunks and its reason (`unreadable` in the state record, e.g. the
          reader's "it looks scanned and local OCR is turned off"), logged,
          and shown on the knowledge page through `unreadable_reason` in
          `GET /documents/drive`; it is not refetched until it changes.
        - A file with no text is recorded with no chunks, so it is not
          refetched until it changes.
        - Text is written under <company_profile_dir>/docs/drive/
          (drive-<id8>-<slug>.md, with a drive_file_id comment); subdirectory,
          so never in company_docs.

        Reconcile purges files no longer listed. It is skipped when a folder
        failed to list, the 2000-item cap was hit, or every folder listed
        nothing while files are on record; the reconcile_skips streak is
        logged. Locking matches Notion: skip while _FIXTURE_OP_LOCK is held,
        fetch unlocked, apply under the lock, discard if the active client
        changed. Fixture load/reset and client-slot switches wipe the
        collection and the state file.

        At retrieval: n=3, below NOTION_WIKI, under "Synced Google Drive
        (unreviewed, multi-writer …)". Each chunk is labelled
        `[drive · file id … · synced … · "<name>"]`. The trusted fields come
        first. The name comes last, NFKC-normalised, quoted and stripped of [ ] " · • ∙ ⋅ # |, so a
        folder editor cannot plant a second `file id` for the Executive to
        open with its own, broader account. The block tells the Executive to
        open the live file with get_drive_file_content, using only the id
        after "file id" at the start of a label. Recorded as `drive` answer sources with the Drive link.
        Manual: `openexecutive sync-drive` / `purge-drive`.
    - name: ONEDRIVE
      what: |
        Files synced from OneDrive / SharePoint folders (ChromaDB collection
        `onedrive_docs`, metadata `onedrive_key` (`<drive id>:<item id>`) /
        `type=onedrive` / `name` / `url` / `synced_at`), by
        knowledge.onedrive_sync — DRIVE's twin, isolated for the same reason.
        Optional (`ONEDRIVE_SYNC_ENABLED`, off by default; setup in
        docs/onedrive_sync_setup.md): heartbeat `onedrive_sync_scan` lists
        `ONEDRIVE_SYNC_FOLDERS` (`<drive id>/<item id>` pairs; the
        `openexecutive onedrive-folder <link>` command resolves a sharing link
        via Graph /shares) through knowledge.onedrive_client, which calls
        Graph directly with httpx, GETs only. CREDENTIAL: unlike Drive there
        is no per-folder service account (app-only Graph access is the whole
        tenant), so it reads as the Executive's own Microsoft 365 sign-in,
        via the launcher's --access-token helper (see the Microsoft 365
        hosting note); the folder list is the scope. Ids are checked against
        [A-Za-z0-9!_-]{1,256}; a paging nextLink is followed only to
        https://graph.microsoft.com; a `remoteItem` shortcut inside a
        listed folder is NOT followed (Files.Read.All reaches far more than
        the list, and a multi-writer folder's editor could otherwise pull an
        unlisted folder into the knowledge base); OneNote packages are
        skipped. `/content`
        answers 302 to a pre-authenticated URL on another host, which is
        fetched WITHOUT the bearer token, streamed and cut at 20 MB; its
        errors never carry that URL (a personal drive puts the credential in
        its path), so the sync logs exception types only.

        Change detection: (lastModifiedDateTime, cTag) against
        <company_profile_dir>/onedrive_sync_state.json; newest first, capped
        at ONEDRIVE_MAX_FILES_PER_SCAN. PDF / .docx / .xlsx / .xlsm / txt /
        md / csv are read as stored; .pptx / .ppt / .pps / .ppsx / .doc /
        .xls / .rtf / .odt / .odp / .ods are fetched as Graph's PDF rendering
        (`?format=pdf`) and read as PDF. The extractor, size caps, depth 4,
        2000-item cap, 120 s deadline and request pause are imported from
        drive_sync, so the two stay in step. Unlike Drive, a PDF here is read
        by that extractor (text layer only), so a scanned PDF yields nothing. Text is written under
        <company_profile_dir>/docs/onedrive/ (onedrive-<id>-<slug>.md, with
        an onedrive_key comment). Reconcile, skip rules, locking and resets
        (fixture load/reset, client-slot switch) are Drive's. A refused
        sign-in stops the tick before any listing and records a user-facing
        last_error.

        At retrieval: n=3, right after DRIVE, under "Synced OneDrive
        (unreviewed, multi-writer …)", labelled
        `[onedrive · item <drive id>:<item id> · synced … · "<name>"]` with
        the name defanged exactly as Drive's (shared helpers in retriever).
        The block tells the Executive to open the live file with the
        microsoft_365 OneDrive tools using only the ids after "item".
        Recorded as `onedrive` answer sources. Knowledge page: source
        `onedrive` (GET /documents/onedrive, /documents/onedrive/{key}, Sync
        now via /documents/sources/onedrive/sync). Manual: `openexecutive
        sync-onedrive` / `purge-onedrive`.
    - name: CONFLUENCE
      what: |
        Pages synced from Confluence spaces (ChromaDB collection
        `confluence_wiki`, metadata `confluence_page_id` / `type=confluence` /
        `title` / `space` / `url` / `synced_at`), by knowledge.confluence_sync.
        SEPARATE from COMPANY for NOTION_WIKI's reason: a wiki is multi-writer
        and unreviewed. Optional (`CONFLUENCE_SYNC_ENABLED`, off by default;
        setup in docs/confluence_sync_setup.md). Cloud and Server/Data Center
        alike: knowledge.confluence_client calls the v1 REST API
        (`<CONFLUENCE_URL>/rest/api`, served by both) directly with httpx,
        Bearer for a personal access token (Server/DC) or Basic with
        username + API token (Cloud). It is deliberately NOT a Confluence MCP
        server behind the gateway (e.g. mcp-atlassian, which stays the live,
        in-chat path): the sync runs from the scheduler with no turn and needs
        version and restriction JSON. The URL, credential and SSL env names
        match mcp-atlassian's so one set serves both. Redirects are never
        followed (the token stays on the configured site), responses stream
        and stop at 20 MB, 429 / 5xx retry with backoff honouring a
        Retry-After of up to 60 s, and paging takes only the `cursor` (Cloud)
        or `start` (DC) parameter out of `_links.next`, re-issued against the
        client's own endpoint. Page ids are checked against [0-9]{1,20} and space
        keys against [A-Za-z0-9_]{1,255} or ~[A-Za-z0-9._@-]{1,255} before use.
        CONFLUENCE_SYNC_PUBLIC_HOSTS_ONLY (default false) is for an install
        where whoever sets CONFLUENCE_URL must not reach the backend's own
        network: each request resolves the host, refuses it when any address
        is not global (loopback, RFC 1918, link-local, CGNAT, ULA, and the
        IPv4 inside IPv4-mapped, NAT64, 6to4 and Teredo forms), with a 10 s
        resolver timeout, and connects to the checked address with the Host
        header and TLS server name kept as the site's name, so a re-pointed
        name cannot slip between check and connect. Those requests skip any
        HTTP(S)_PROXY (a tunnel would verify the certificate against the bare
        address). confluence_client.config_problem is the Settings check as a
        pure function, for a caller that writes these settings for someone
        else and must not write a set the app would refuse to start with.

        ACL: a Confluence token is a user's, so the sync sees what that user
        sees, and anything it syncs is retrievable by everyone who talks to
        the Executive. Two controls narrow it: `CONFLUENCE_SYNC_SPACE_KEYS`
        is required (no "everything the token sees" mode), and
        `CONFLUENCE_SYNC_SKIP_RESTRICTED` (default true) leaves out every page
        with a read restriction of its own or on any ancestor page. The
        listing expands `restrictions.read.restrictions.{user,group}` and
        `ancestors` for every page, so restrictions are re-checked each tick
        at no extra request cost; a page whose restrictions are missing from
        the response, or whose ancestor its fully listed space did not
        return, counts as restricted (fail closed). When the space listed
        only in part (the 5,000-page cap, a lost next link, a failure), a
        missing ancestor may just be past the cut, so the page is held back:
        not synced that tick, and not purged, or it would flap in and out
        of the index every tick. A page that becomes restricted drops out of
        the visible set and is purged by reconcile.

        Each tick (`confluence_sync_scan`) lists every page in the spaces
        (CQL `space = "KEY" and type = page`, expand version + ancestors +
        restrictions; 5000 pages per tick across spaces). A page is dirty when
        its `version.number` differs from its record in
        <company_profile_dir>/confluence_sync_state.json, so there is no
        timestamp watermark and no CQL timezone handling. Dirty pages are
        fetched newest first (`/content/{id}?expand=body.storage,version`),
        capped at CONFLUENCE_MAX_PAGES_PER_SCAN. knowledge.confluence_storage
        turns storage-format XHTML into Markdown with stdlib html.parser:
        headings, lists, tables, links, task lists, code / noformat macros as
        fenced blocks, callout macros (info / note / warning / tip) with a
        bold label, other macros' rich-text bodies kept, parameters and
        non-code plain-text bodies dropped (so toc / children / Jira / include
        leave nothing). Markdown is written under
        <company_profile_dir>/docs/confluence/ (confluence-<id>-<slug>.md,
        with a confluence_page_id comment) and ingested with ingest_text_sync.

        Pages the listing returned as restricted (positively, or fail-closed)
        are purged on every tick, complete listing or not. Reconcile purges
        pages on record but no longer visible: in full when every space
        listed completely, else per space for the spaces that did (a space
        listing 0 pages while it has pages on record is left alone), so one
        broken space never freezes purges elsewhere. Orphan files and pages
        of spaces dropped from the config wait for a full reconcile. A full
        reconcile is also skipped when the spaces listed 0 pages while pages
        are on record; pages listed but all restricted ARE purged. Page
        bodies are fetched with a 5 MB cap (listings 20 MB), JSON is parsed
        and storage converted off the event loop (conversion capped at 1M
        characters and 60 s; a timeout records the page unreadable until its
        version changes), since the scheduler shares the API process. A listing
        failure stores a user-facing `last_error` (401/403: credentials;
        404: space not found). Same two-phase locking as drive_sync (network
        unlocked, writes under _FIXTURE_OP_LOCK, tick discarded if the active
        client changed) and the same per-process _RUN_LOCK.

        At retrieval the retriever queries this collection with n=3 and
        appends it after the Drive and OneDrive blocks, under "Synced Confluence wiki
        (unreviewed, multi-writer …)", each chunk labelled `[confluence ·
        page id … · space … · synced … · "<title>"]` (title defused like
        Drive names) and every line prefixed by _format_untrusted_wiki. The
        header says to open a page live only by the id after "page id", and
        only when a Confluence tool is connected. Recorded as `confluence`
        answer sources with the page link. connected_systems adds a constant
        line when the sync is on. Client-slot rebuild and fixture load/reset
        clear the collection and state. Manual: `openexecutive
        sync-confluence` / `purge-confluence`.
    - name: FAILURES
      what: Recorded failure cases used to teach specialists what to avoid.
    - name: RECENT_RESEARCH
      what: |
        Web-research artifacts persisted from executive_research runs
        (ChromaDB collection `recent_research`). Kept SEPARATE from COMPANY
        so unvetted, machine-generated research never blends into curated
        company knowledge. Keep-latest — each research run clears the prior
        artifact (delete by metadata `type=recent_research`) and ingests the
        new one. Wiped per-company on fixture load / reset. At retrieval the
        retriever queries it with a small n and appends it under a clearly-
        labelled "Recent research (unverified, web-sourced …)" section ranked
        BELOW the curated company-documents section.
    - name: ATTACHMENTS
      what: |
        Files attached in an integration channel (ChromaDB collection
        `inbound_attachments`), written only by
        integrations.attachments._schedule_ingest. Rows carry
        `type=attachment`, domain `attachment`, filename
        `attachment:<bare name>`.

        The one collection retriever.retrieve NEVER queries. An attachment's
        content is chosen by whoever sent the message, passes through no
        upload endpoint, gets no review, and leaves no copy in docs/. It is
        already inlined into the turn that carried it, which is where it is
        useful; what it must not become is company knowledge resurfacing in
        later, unrelated turns. NOTION_WIKI and RECENT_RESEARCH are
        queried-but-labelled; this one is not queried at all.

        Wiped per company by store.delete_attachment_docs() on client-slot
        restore and fixture reset — drop-and-recreate, not a where-delete,
        because a surviving row there is one company's attachment visible to
        the next.

        Caveat for anyone auditing an existing install: before this
        collection existed, the ingest built its store with the bare
        ChromaDBStore() default rather than settings.vector_store_path, so
        wherever that differs from VECTOR_STORE_PATH the rows went to a
        different database than the API reads. In a container that directory
        is outside the data volume and goes with the container; on a
        non-container install with a stable CWD it persists as a stray
        <cwd>/chroma_db holding the plaintext of every attachment ever sent,
        which no wipe path reaches and an operator should delete by hand. The
        boot migration cannot see it either way and correctly reports zero.
  domain_aliases_source: openexecutive.knowledge.retriever.DOMAIN_ALIASES
  dedupe_note: Multi-domain chunks can fan out to multiple rows; the retriever dedupes by text before returning.
  upload_domains: |
    POST /documents accepts the nine DOMAIN_MAP domains (sales included) plus `general`
    (loader.UPLOAD_DOMAINS) and returns 400 for anything else. Unvalidated, a
    typo like `domain=finanace` returned 200 and indexed the document under a
    value no specialist filters on — issue #114, silent and only observable by
    asking a specialist a question it should be able to answer and getting
    nothing back.
  general_catch_all: |
    `general` is the domain an upload gets when nobody classified it: the
    default on POST /documents (the knowledge page no longer offers a picker), and
    what reconcile_company_docs assigns to a recovered document. It maps to no
    specialist in DOMAIN_ALIASES, so retriever._with_general widens each
    specialist's COMPANY filter to include it — otherwise an unclassified
    document is retrievable by NO specialist rather than by all of them.

    Scoped to the COMPANY collection on purpose. BUILTIN shares its rows with
    external OER sources, and external_sources falls back to ["general"] for a
    source that declares no domains; widening BUILTIN too would fan unvetted
    third-party material into every specialist's context. NOTION_WIKI and
    RECENT_RESEARCH keep their existing filters, and ATTACHMENTS is not
    queried at all.

    The property that makes all of this easy to get wrong: _with_general
    returns a falsy filter UNCHANGED, and ChromaDBStore.query builds a `where`
    clause only when the filter is truthy. So a retrieve with no domain filter
    and no specialist — every Executive-level turn, as opposed to the
    specialist fan-out — queries COMPANY with no `where` at all and matches
    EVERY domain, including values chosen precisely because no specialist maps
    to them. An unrecognised domain excludes nothing. That is what put inbound
    attachments in front of the Executive under "From your company documents",
    and it is why isolation belongs in the collection, never in a domain
    value.
  parse_isolation: |
    Document parsing runs in a short-lived child process
    (knowledge.isolated.run_isolated -> `python -m
    openexecutive.knowledge.isolated`), not in the API process: pdf_reader's
    text-layer pass (_text_layer) and local OCR (_ocr_pdf), and the PDF /
    .docx / .doc / .xlsx / .xlsm branches of loader.extract_text_from_file.
    An .xlsx / .xlsm is read for at most _XLSX_MAX_ROWS (200,000) rows,
    blank ones included, and _XLSX_MAX_COLS (1,024) columns: openpyxl's
    read-only reader yields a filler row for every row a sheet's <dimension>
    claims, so a ~5 KB workbook claiming A1:XFD1048576 otherwise pins a
    parser slot for the whole timeout (#316).
    Why: pypdf's object graph, pdfium bitmaps and the OCR model are hundreds
    of MB of small allocations, and CPython keeps the arenas, so an
    in-process parse left its peak in uvicorn for good. Measured on a 34 MB,
    131-page text-layer PDF through POST /documents: 272 -> 440 MB peak, 378
    MB after (before); 274 -> 324 MB peak, 318 MB after, all of the rest
    from embedding (after). A 30-page scan through OCR: 787 MB peak, 446
    after (before); 297 / 290 (after) — the OCR child itself peaks ~600 MB
    for the length of the OCR, then exits.
    Protocol: (module, qualname, args) pickled to the child's stdin (the
    child trusts its parent); the answer is JSON on stdout, so the API never
    unpickles anything a parser of a hostile file could have shaped. The
    child's environment is reduced to PATH, HOME, PYTHONPATH/PYTHONHOME,
    VIRTUAL_ENV, LD_LIBRARY_PATH, locale and temp-dir variables: no API
    keys. That is hygiene, not a sandbox: the child runs as the same user
    and could read /proc/<ppid>/environ, .env or credential files.
    Bounded output (security review): the child's stdout and stderr go to
    temp files, never into the API's memory. pypdf logs text taken from the
    file (e.g. a font's /Encoding name, once per font per page), so a 9 KB
    crafted PDF logged ~6 MB and a 2000-page one grew a captured stderr by
    ~85 MB/s until OOM. The child therefore logs nothing
    (logging.disable, warnings ignored), fd 1 carries only the answer
    (library output is dup2'd to stderr), only the last 2000 chars of stderr
    are read back on a failure, and the answer (UTF-8 JSON,
    ensure_ascii=False, so non-ASCII text is not inflated 6x) is capped at
    _MAX_ANSWER_BYTES (32 MB): the child swaps a larger one for an
    AnswerTooLarge error and the parent refuses a larger file unread, both
    as WorkerStopped. read_pdf_text's note for WorkerStopped: "the PDF could
    not be read: it was too large or took too long". The answer is encoded
    with surrogatepass both ways: pypdf decodes some ToUnicode maps with
    surrogatepass, and strict UTF-8 would lose a whole file over one lone
    surrogate. RLIMIT_FSIZE (2x the answer cap) bounds what native code can
    write to the stderr file.
    A Path source is read more than once (hash, parse, maybe model), so a
    result is cached only if the file's sha256 is unchanged after the read:
    an upload rewriting the same name mid-read must not store its text
    under the old file's hash.
    Contract kept: read_pdf_text never raises (an exception the caller names
    in `reraise` — PdfTooLarge, OcrUnavailable — is rebuilt as itself; a
    child that dies or passes its timeout raises WorkerStopped, which
    read_pdf_text turns into method "none" with a note); a Word/Excel parse
    error still raises, as IsolatedError naming the original type.
    Timeouts: 300 s for the text layer and file extractors, OCR's 240 s
    budget + 120 s. extract_text_from_file takes a `timeout`: drive_sync
    passes its own _EXTRACT_TIMEOUT_S (120 s), so the child is killed when
    the sync's wait_for gives up rather than running on. The page ceiling
    travels as an argument because the child never sees this process's
    module state.
    Concurrency (review): at most _MAX_CHILDREN (2) parser children run at
    once. A caller waits at most _MAX_SLOT_WAIT_S (30 s) for a slot, and the
    wait counts against its own timeout, so the call never outlasts the
    limit its caller set (Drive sync's 120 s still kills the child when its
    wait_for gives up). No slot in time -> ParserBusy (a WorkerStopped):
    "never tried", not "unreadable". Without the short wait, two slow files
    held every other parse, and its executor thread, for 300 s. OCR passes
    its own two-slot gate (`slots=_ocr_slots`), so a long OCR never holds a
    slot a quick text-layer parse needs, and waits longer for it
    (`max_wait=_OCR_MAX_SLOT_WAIT_S`, one OCR budget, 240 s; its timeout
    covers wait + run).
    ParserBusy handling: read_pdf_text returns PdfReadResult(busy=True),
    method "none" (or the thin text layer) with a "server was busy" note,
    never cached. A busy OCR attempt refunds its own inbound page
    reservation (by identity, not any of the same size), but only when no
    request could reach the model: a failed transcription can still have
    billed its other slices, and refunding those would let a sender run up
    model spend past the hourly budget.
    extract_text_from_file_async / ingest_file take `busy_raises`: POST
    /documents, the preview and intake uploads set it, so a busy PDF raises
    ParserBusy like a busy Word/Excel parse and they answer 503 with
    Retry-After, storing and indexing nothing (a re-upload keeps the old
    chunks and file). Other callers (fixture loader, client slots, boot
    reconcile) keep the empty result. drive_sync counts ParserBusy as failed
    for this tick and fetches the file again on the next, instead of
    recording it unreadable (which would drop its chunks until it changed).
    Spawn failure (review): only FileNotFoundError / PermissionError (no
    usable interpreter) falls back to parsing in-process, logged once, and
    that parse runs outside the slot gate (it cannot be timed out, so a hung
    one must not hold a slot). Any other OSError (ENOMEM, EAGAIN) is
    WorkerStopped: memory pressure is exactly when an in-process parse would
    hurt most.
    POST /documents, GET /documents/{filename} and intake uploads turn any
    other IsolatedError from a Word/Excel parse into a 422 ("Could not read
    <name>: ..."), not a 500. Only IsolatedError.kind (the exception's type)
    and the repr of the filename are logged: the parser's message can quote
    the file, and a name could carry CR/LF. Tests that monkeypatch parser internals set isolated.enabled =
    False; tests/unit/test_isolated.py runs the real child.
    read_document_text passes read_pdf_text the Path, so the API process
    hashes the file in 1 MB pieces and only loads it whole when pages go to
    the model (step 2 of pdf_reading).
    POST /documents streams the upload to its staging file 1 MB at a time
    and returns 413 once it passes MAX_UPLOAD_BYTES (50 MB), instead of
    reading the whole body into memory; the stored copy is copied from the
    staging file.
  pdf_reading: |
    Scanned / image-only PDFs (no text layer) are read, not returned empty.
    knowledge.pdf_reader.read_pdf_text tries, in order, and never raises:
    1. pypdf's text layer — kept when it has >= ~20 visible chars per page.
    2. The deployment's own model, through its provider's PDF support:
       base64 `document` blocks, PDF_VISION_PAGES_PER_CALL pages (default
       20) per request, 3 concurrent, transcribed to Markdown by
       PDF_VISION_MODEL (unset = DEFAULT_MODEL). Sent only when
       providers.registry.pdf_input_supported(model): Anthropic direct and
       every OpenRouter model (translator -> `file` part; OpenRouter's
       file-parser: native for file-input models, else
       PDF_OPENROUTER_ENGINE, default mistral-ocr), a local server only with
       LOCAL_PDF_INPUT (e.g. LOCAL_BASE_URL = OpenAI's API). OpenAI models
       are reached through OpenRouter (openai/...) — there is no direct
       OpenAI provider.
       OPT-IN: PDF_PROVIDER_READING (default false). It is data egress (to
       the provider, and on OpenRouter possibly to Mistral OCR), so an
       upgrade must not start it: off, this step is skipped and scanned
       PDFs never leave the server. That default also moves Anthropic-
       direct deployments off #254's default (Claude read scans there);
       they OCR locally until they opt in. When on, the destination is
       logged once per process. PDF_OCR_ENABLED only governs step 3.
    3. Local OCR: pypdfium2 renders each page (scale 2), RapidOCR
       (rapidocr-onnxruntime, models bundled in the wheel; opencv-python is
       overridden to opencv-python-headless in pyproject so python:3.11-slim
       needs no libGL) reads it. Offline, no key: what a local model without
       PDF input gets, and the fallback on every provider when step 2
       errors, refuses or returns nothing.
       PDF_OCR_ENABLED=false turns it off. Not installed on Python >= 3.13
       (the wheel's cap) — the note then says OCR is not installed.
    PDF_VISION_MAX_PAGES (default 100) caps pages read (note says so).
    inbound=True (a file a channel delivered: chat/Slack/Google Chat/email
    attachments; NOT POST /chat/upload, the signed-in user's own) caps at
    PDF_INBOUND_MAX_PAGES (30) and draws on a rolling hourly budget,
    PDF_INBOUND_PAGES_PER_HOUR (300), shared by all senders — a spent budget
    returns a note, not a conversion. Text layers are never metered.
    OCR bounds (security review): each page renders within a 25 MP pixel
    budget (scale lowered for a huge MediaBox — a 20000pt page would be a
    multi-GB bitmap), at most 2 documents OCR at once (BoundedSemaphore),
    and each stops after 240 s with the pages it has.
    _MAX_PDF_PAGES (2000) is checked before the text-layer pass extracts any
    page (PdfTooLarge -> "none" with a note): the page caps bound conversion
    only, and a crafted many-thousand-page tree would otherwise be walked.
    A vision slice answering stop_reason=max_tokens is split in half and
    re-requested until each part fits (depth <= log2 pages-per-call); a
    single page still cut off keeps its text + "[transcription cut off
    here]" and the note says so — never returned as complete.
    Results are cached in process by sha256 (32 entries); failures are not.
    loader.read_document_text / extract_text_from_file_async are the async
    entry points; ingest_file (uploads, reconcile_company_docs), the
    /documents/{filename} preview, intake uploads, integrations.attachments,
    the email poller and read_document (a workflow step's oe__read_document) use them. The sync
    extract_text_from_file serves its other callers (see parse_isolation).

    Where files reach the Executive:
    - web chat / Discord / Telegram / Slack / Google Chat —
      integrations.attachments (inlined under `[Attached: <name>]`, label
      adds "(converted from scanned pages)"). Slack lets `file_share`
      through, downloads after the roster + response gates, sends the bot
      token only to https://files.slack.com/ (needs `files:read`). Google
      Chat downloads uploaded content via media.download with the chat.bot
      credentials (5/message, 20 MB checked per chunk), only when the
      event's user.email is on the People roster — the webhook
      authenticates Google, not the sender, so anyone else's files are
      named, never downloaded; a driveDataRef attachment is left to the
      Drive tools with its id.
    - email — integrations.email_attachments: for a known sender (team,
      contact, principal) the poller calls get_gmail_attachment_content for
      up to 5 readable attachments of THIS message (20 MB each); workspace-
      mcp in stdio mode answers "Saved to: <path>" — taken only from a line
      it starts, the LAST one, and only if its name equals the "Saved
      filename:" line (the answer echoes the sender-chosen filename first,
      which could carry a fake "Saved to:") — which must then pass
      tool_catalog.resolve_readable_file; text appended to the turn under
      "--- ATTACHMENT TEXT ---" (15k chars each). Outside the model loop, so
      it works on private turns without widening PRIVATE_TURN_MCP_TOOLS.
      An unknown sender's attachments stay a list (no downloads).
      Image attachments (png/jpg/gif/webp) are downloaded the same way
      (resolve_readable_file with suffixes=IMAGE_MEDIA_TYPES) and passed as
      attachment_blocks: MAX_IMAGES 3, none under MIN_IMAGE_BYTES 10 KB
      (logos, tracking pixels), none over MAX_IMAGE_BYTES 3 MB (the model
      API's 5 MB base64 cap would fail the turn). A mail source's
      read_attachments may return EmailAttachments(text, image_blocks).
      Audio attachments (ogg/m4a/mp3/wav/webm/…) are transcribed when
      providers.transcription is available: MAX_AUDIO 2, the words appended
      as attachment text (untrusted-wrapped, note "transcribed").
    - voice notes — providers.transcription turns audio into words before
      the turn (Claude takes no audio). Any OpenAI-compatible
      POST {base}/audio/transcriptions server: TRANSCRIPTION_BASE_URL (+
      _API_KEY, _MODEL, default whisper-1) wins; else OpenRouter when
      OPENROUTER_API_KEY is set (elevenlabs/scribe-v2); else none, and a
      voice note becomes a line asking the sender to type it. 25 MB and
      TRANSCRIPTION_MAX_SECONDS (300) caps, the length read on the server
      from the Ogg / WebM / MP4 / WAV container (recording_seconds; the
      browser's own stop is not trusted); a file whose length can't be read
      (mp3, flac, aac) is held to 16 KB per allowed second. A container's length is the
      sender's word, so the bound that holds is bytes: at most
      TRANSCRIPTION_MAX_MB_PER_DAY (200) sent per UTC day, counted in
      process, failed calls included. Each call writes one usage row
      (actor "transcription", the server's reported cost) and tells any
      add_usage_listener listener. In the chat apps (integrations.
      attachments) only a voice note the sender recorded there (Telegram
      voice / video_note, a Discord voice message, a Slack clip with
      subtype slack_audio; AttachmentItem.voice_note) becomes their own
      words ("[Voice note, transcribed]"; senders are roster-gated). The
      reply is the answer alone, with no echo of what was heard. Any other audio (a Telegram audio file, an uploaded recording,
      anything on Google Chat) may hold someone else's voice, so its words
      are attachment text, untrusted-wrapped like a document's.
      The web chat mic records in the browser and posts to
      POST /chat/transcribe; the words land in the message box to edit and
      send, nothing is kept. GET /chat/voice says whether the mic shows.
    - anything else — the chat tool `read_document`
      (orchestrator.document_tools): `path` (a file another tool saved,
      e.g. get_drive_file_download_url for a scanned Drive PDF) or company
      doc `filename`, optional PDF `pages`. Confined to the tool download
      dirs + company docs dir; withheld on private turns.

memory:
  episodic_db: ./episodic_memory.db
  tables:
    - decisions
    - initiatives
    - advice_given
    - scheduled_actions
    - "facts — standing facts and corrections the principal asked to keep, with provenance (memory/facts.py; see `standing_facts` below)."
    - "app_migrations — one-shot data migrations (name PK, applied_at). Schema DDL stays idempotent and is NOT recorded here; only sweeps that must run exactly once per DB insert a row. First user is `cancel_orphaned_talent_reminders` (2026-09), deletable in the release after next."
  formatter: openexecutive.memory.episodic.format_for_prompt — produces a compact prompt block of recent decisions/initiatives.
  drive_reads: |
    memory.drive_reads keeps what a conversation has seen of Google Drive,
    which is otherwise reached only as live Google Workspace calls inside a
    turn and lost once history keeps only prose. MCPGateway.call_tool hands
    every search_drive_files / get_drive_file_content result (workspace-mcp
    1.29.0 text shapes; errors and refusals record nothing) to
    record_drive_result when drive_reads.may_remember(session) holds: a bound
    current_session with a rostered caller_person_id, not private_to_principal,
    and not a turn that touched the speaker's own mailbox (Act as me).
    Workflow steps and other session-less callers keep nothing. Rows are keyed
    (session_id, person_id) and rendered only to that speaker, because one
    session id spans several people on email / Slack / Discord threads.
    Tables session_drive_files ((session_id, person_id, file_id) PK; name,
    mime_type, link, summary = first 600 chars of an opened file, opened,
    found_by query) and session_drive_searches (person_id, query,
    result_count) are created on first write, not in initialize_db; readers
    treat a missing table as empty. Pruned on write to 100 files and 100
    searches per speaker per session. workspace-mcp interpolates names
    unescaped, so a name with a newline can forge a search-result line: only
    a Drive-shaped id ([A-Za-z0-9_-]), a type/subtype mime and a
    docs|drive.google.com https link are kept (else the line is dropped or
    the link blanked); the name is always rendered quoted.
    format_drive_memory renders the 20 most recent files and the queries that
    matched nothing (dropped once the same query later matches) into a
    <drive_memory> block in the user turn (Executive._build_messages, so the
    committee path too), never a cached system block. Names and text are
    Drive content an outsider can write: quoted, "<" neutralised so they
    cannot close the tag, and labelled data, not instructions. A search that
    matched nothing also gets empty_search_note appended to its tool result
    (report the exact query; never say the file does not exist).
    session_store.delete_session drops the rows. Complements, not replaces,
    the folder sync (knowledge collections: DRIVE): a synced folder is known
    without a search; this remembers whatever else a conversation read.
  chat_controls: |
    The owner's controls on a saved chat (api/routes/sessions.py). Pin
    (sessions.pinned_at; pinned chats list first) and rename
    (sessions.title_locked: session_store.update_session_title, the automatic
    title, never overwrites a name the owner gave). Share, read-only, with
    named team members (session_shares; PUT /sessions/{id}/shares sets the
    exact list; contacts, the archived and the owner refused). A reader may
    open, list (GET /sessions/shared-with-me) and export the chat and nothing
    else; every write route keeps the usual owner check. A mail_private chat
    (Act as me read the owner's mail) is never shared and stops being
    readable by earlier readers. Export (memory/chat_export.py) is Markdown
    with each message under its writer's People name or Executive and the
    reply's sources. Try again and Edit both call POST
    /sessions/{id}/rewind, which, under the conversation's turn lock and
    only while the given reply is still the chat's last row, deletes the
    last turn and returns the person's words; the page resends them (or the
    edit) as an ordinary /chat turn through the same gates. Web chats only:
    a chat-app conversation's reply also lives in that app. The page asks
    first when the reply being redone already did something (action chips),
    since the new turn could do it again.
  chat_topics: |
    The Chats page groups a person's own chats by date or by topic
    (memory/chat_topics.py, utils/chat_topics.py). Topics are per owner
    (chat_topics rows; sessions.topic_id, sessions.topic_source). Why it
    costs almost nothing: the one utility-fast call that already titled a
    new chat now returns its topic too, choosing from the owner's recent
    topic names, so filing adds a few tokens, not a call. A second short
    call runs only when that turn made a new topic: it checks the new name
    against the others (names only) and merges a duplicate at once, rather
    than a scheduled tidy. Older chats are filed from their titles in
    batches, started by the first Topic view, not at boot, so an idle tenant
    spends no CPU or usage on it. What the owner does sticks: a chat they
    filed (topic_source 'owner') is never refiled, and a topic they renamed,
    pinned, merged into or filed a chat under (kept) is never merged away.
    A chat shared with someone keeps its owner's topic, which the reader
    never sees. Areas keep a long list short: related topics share
    chat_topics.area (one property, deal or client) and show under one
    heading. No extra call: the same short call that checks a new topic
    also names its area, and the backfill ends with one call over the names
    for topics not yet looked at. An area needs two topics; one the owner
    renamed or ungrouped (area_kept) is left alone. The page bands topics by
    their last chat (this week, quiet a week, two weeks, a month or more),
    computed in the browser from updated_at, so it costs nothing server side.
  session_scoping: |
    Decisions and advice rows carry a session_id so per-thread continuity
    (Discord, Telegram) can pull just-this-thread history without leaking
    cross-conversation context. Falls back to a global view when
    session_id is null.
  peer_memory_link: |
    External peer-keyed memory layer running alongside the builtin
    episodic store (does not replace it). The full architecture lives
    under the top-level `peer_memory:` section — including the wrapper
    surfaces (prefetch / sync_turn / directional_chat /
    prefetch_department / sync_department_turn / append_department_note),
    the caller-resolution pipeline, audit shape, per-fixture workspace
    isolation, and reset semantics. This section just notes that
    peer_memory is one input to the user turn alongside
    `<past_decisions>`, `<retrieved_context>`, and `<briefing>` (see
    `briefing_context` below) and is keyed by Person.id; department-keyed
    memory is injected as `<department_memory>` into dept-bound
    specialist turns only.
  briefing_context: |
    `<briefing>` user-turn block — a compact digest of the current open
    (unread) alerts, built by
    `openexecutive.briefing.context.format_open_alerts_for_prompt`
    (company-wide, `status="unread"`, the same rows `/today` surfaces as
    proposals; one line per alert: `[id] (action|monitoring) headline —
    body snippet | suggested: ... | tags: ...`, body capped, top ~30).
    The chat route (`api/routes/chat.py`) resolves it via
    `asyncio.to_thread` in the same `asyncio.gather` as RAG / episodic /
    peer-memory, then threads it through `Executive.stream_chat` /
    `stream_chat_with_committee` / `chat` into `_build_messages`, which
    appends it to the USER turn right after `<past_decisions>`. It is
    omitted when there are no open alerts and is NEVER placed in a cached
    system block (per-request content). Purpose: so the Executive can
    discuss a briefing item the principal clicked or named on `/today`
    (e.g. "Gulf Coast Port Cyberattack"); the `/today` narrative bullets
    are click-to-discuss handoffs that rely on this block. The formatter
    swallows its own errors and returns "" so a chat turn is never blocked
    by an alerts-store hiccup.
  standing_facts: |
    Corrections that persist everywhere (`openexecutive.memory.facts`,
    table `facts`, created on first write). Before it, a chat correction's
    one durable home was Honcho peer memory: optional, best-effort (its
    prefetch times out or errors under load), re-injected only
    into that person's later chat turns, never read by briefs, scheduled
    runs or the six-hourly alert review. The episodic extractor cannot hold
    one: it stores only decisions backed by a commitment quote.
    IN BRIEFS — every brief prompt (the /today header, a teammate's header,
    the morning brief, the end-of-day digest) carries
    `briefing.narrative.STANDING_FACTS_RULE`: use the facts quietly, never
    mention one or that it was saved, leave an item a fact settles out
    without saying it was dropped, and never stretch a fact to an item it
    does not name. Why: the header had no rule for the block and turned a
    fact saved in chat into its top point ("a standing fact says X, so drop
    it"), applied to an item the fact never named.
    OWN MESSAGES — the reader's own mail and chat-app messages to the
    Executive leave INBOUND for a background OWN block (principal scope
    only), and every brief prompt carries
    `briefing.narrative.OWN_MESSAGES_RULE`: never report the reader's own
    messages, chats, complaints or ratings back, state only the figures
    and decisions in them, and show an open ask as what the Executive is
    doing. Why: the header opened with "you've been messaging me heavily
    tonight" and made the reader's own complaint its headline.
    RIGHT NOW — the whole-company header is written from
    `briefing.header_context`: MOVED TODAY lines tagged [M1]…, COMING UP
    TODAY (calendar), STILL OPEN and BACKGROUND (chat titles, own messages)
    as context only. Each bullet must end with a tag; `keep_cited_points`
    drops the rest and keeps three at most. No MOVED TODAY line means no
    model call (the quiet line, or "Nothing new today — what's open is
    below."). The history rail is read only for work finished today. Why:
    chat titles and a 20-row history rail were most of its input, the prompt
    banned the Needs you items and demanded 2–4 bullets, so it padded with
    "I'm combining the PDFs now" and yesterday's DMs (2026-10-20). Every
    brief uses `narrative.brief_model()`, the Executive's model, not
    ROUTING_MODEL.
    WRITE PATH — chat tools in `orchestrator/fact_tools.py`:
      - `remember_fact(subject, statement, previous_value?, replaces_fact_id?,
        source_quote)` and `forget_fact(fact_id, rationale, source_quote)` —
        a retire needs the same quote proof as a write.
      - `update_company_profile(field, operation set|add|remove, value,
        metric?, source_quote)` over a whitelist of `CompanyProfile` fields
        (text / int / number set; list add/remove; financials.key_metrics by
        name). Writes `company/profile.yaml` via `save_to_yaml`, updates
        `session.company_profile` so the NEXT turn's cached company block
        carries it (one cache miss per change), and records a
        `kind='profile'` row for the Pulse page.
      - Gate: the principal on a verified surface
        (`is_principal_on_verified_surface`), never an unattended session;
        all three in `UNATTENDED_WITHHELD_TOOLS` and in
        `PRIVATE_TURN_WITHHELD_TOOLS` (what they write or retire is read on
        everyone's turns).
      - TEAMMATES (remember_fact only): a rostered `team` member, not
        archived, not the principal, on a verified surface (web signed in,
        own Slack / Discord — `people_tools._is_verified_speaker_surface`),
        not unattended, not a private or email turn
        (`fact_tools._teammate_speaker`; fails closed). Same own-words gates
        on the TEAMMATE's words. The row is attributed:
        `recorded_by_role='teammate'`, `recorded_by_name` (People-list name
        at write time), rendered "(per <name>)"; the header says such a line
        is the teammate's word and the principal's unmarked line wins a
        conflict. PRINCIPAL OUTRANKS: a teammate write whose subject /
        replaces_fact_id hits an active principal fact raises
        `PrincipalFactConflict` → stored `proposed` (never renders) with
        `replaces_fact_id` naming it; teammates supersede each other freely;
        the principal supersedes anyone. "NEEDS MY APPROVAL":
        `fact_approval_rules(person_id, needs_approval)`, DEFAULT ON (no row
        = needs approval; the owner chose opt-in trust over opt-in review),
        principal-only `GET/PUT /memories/facts/approval[/{person_id}]` →
        every write from that teammate is `proposed` unless the principal
        marked them trusted (off). Read inside record_fact's BEGIN
        IMMEDIATE, so a switch flipped mid-request cannot leak one fact; a
        teammate write with no person id is never trusted. At most
        MAX_PENDING_PROPOSALS_PER_PERSON (20) proposals per teammate
        (TooManyProposals). A teammate retire guards ownership in the UPDATE
        (`retire_fact(teammate_id=)`: role teammate, their id, not approved). The tool answers
        `awaiting_approval` (no chip). `approve_fact` → active, supersedes
        what it names (the principal's own included — approval is their
        word) and stamps `approved_at`: from then on the row is
        `principal_owned` (outranks teammates, principal-only to retire), so
        approval is not a one-shot gate. `decline_fact` → `declined`.
        forget_fact and update_company_profile stay principal-only; a
        teammate retires only their own unapproved facts, from the Pulse
        page. No field of a TEAMMATE's fact may contain `(per <anyone>` (any case; units such as
        month/unit/square foot excepted, `_PER_UNITS`), `[fact N]` or a dash + `YYYY-MM-DD`
        stamp (`_marker_error`): the render adds those, so a stored one
        would be a forged second attribution. Columns added by `_migrate` on
        first write (old rows read as the principal's; the read-only render
        tolerates an unmigrated DB).
      - BRIEF FYI: `facts.render_teammate_changes(since)` → the morning
        brief's TEAMMATE CORRECTIONS SINCE LAST BRIEF block (active teammate
        facts created in the window; proposed ones too only when
        `_private_ok()` — any teammate may run the brief and its run history
        is shared — and then `private_used`), rendered before the
        quiet check and carried in `build_brief_fingerprint(teammate_changes=)`
        so a correction alone un-suppresses the brief.
      - `source_quote` (at least 2 words / 8 chars) must appear, normalized
        like the episodic quote gate, in the principal's own words this turn:
        `delegation.settings.own_words(TurnDelegation.speaker_text)` — the
        adapter-hydrated `<outbound_reply_context>` backstory stripped (first
        by its exact anchored shape, `strip_outbound_reply_context`, so a
        look-alike closing tag like `</outbound_reply_context >` quoted inside
        it cannot end the block early — security review of F082), and
        None (refused) when the message carries an attachment. Otherwise a
        Discord/Slack reply to the Executive's DM about an attacker's alert
        could have the alert's text stored as the principal's fact.
      - remember_fact (statement, subject and previous_value alike — each is
        rendered; `_claim_error`; an omitted previous_value falls back to
        the replaced row's statement): every number must be one the principal
        wrote this turn (`_numbers_in` / `_number_in_own_words`, compared at
        magnitude: "$180k" ↔ "180,000" either way, never "180m" → "$180k"),
        and every name (a capitalised or non-ASCII-letter word other than
        the statement's very first word — exempting each sentence's first
        word let "Landlord. Acme." split names past it) and date word
        (month, weekday, quarter) must appear in their own words
        (`_unsaid_claim_words`). A name written in lower case is not caught:
        a heuristic that narrows, not a proof of paraphrase.
        A real quote ("remember what the lease doc says") therefore cannot
        carry a document's figure, name or date into every prompt; a
        paraphrase of what they said still passes.
      - Every write / refusal is a `tool_invocation` audit row; a Pulse-page
        retire is a private `fact_retired` row (it names the retired fact,
        which teammates can no longer read). The tools' own rows carry no quote or
        rationale and are written `private=True`, and the chat loop's
        `skill:` dispatch row for them (its `full.input` quotes the principal
        verbatim) is private too (`executive._private_tool_row`): each ties a
        fact to the principal's session_id / turn_id, and /audit/logs serves
        any non-private row to every signed-in teammate, and GET /memories/facts blanks `source_quote` and
        `retired_reason` for anyone but the principal.
      - Profile edits run load → change → save under
        `company_profile.PROFILE_EDIT_LOCK`, which PATCH /company-profile
        also takes (no lost update between the two).
      - All three handlers are sync bodies run via `asyncio.to_thread`
        (context copied, so current_session / the speaker pin / audit ids
        resolve), and PATCH /company-profile does its locked edit in a
        thread too: neither blocks the event loop on SQLite, the YAML file
        or PROFILE_EDIT_LOCK. stream_chat / committee, the alert review,
        `synthesize_briefing_narrative` (morning brief) and the EOD digest,
        weekly review and reflection (`with_standing_facts`) read the block
        via `asyncio.to_thread` as well.
      - update_company_profile: beyond the quote, a text value, list item,
        metric name and metric value must each appear in the principal's
        own words (`_in_own_words`), and a number field's parsed value must
        be among the numbers they wrote (`_number_in_own_words`: `$`, `,` and
        k / m / bn / thousand / million / billion suffixes tolerated). The
        value lands in the cached company block on every later turn, so
        "set our mission to what the doc says" / "update our headcount"
        must not save a doc's text or a guessed figure. Saved text is
        `<`/`>` defanged (`_defang`).
    STORE — one active fact per subject: a new row supersedes active rows
    with the same folded `subject_key` (or the id in replaces_fact_id) in one
    `BEGIN IMMEDIATE` transaction; old rows become `superseded` with
    `superseded_by`; the new one is a `correction` carrying
    `previous_statement`. `profile` rows only supersede earlier profile rows
    for the same field and never render into a prompt (the cached profile
    block already carries the value). Provenance per row: source_quote,
    source_channel (web or the adapter), session_id, turn_id,
    recorded_by_person_id, created_at.
    READ PATH — `render_facts_for_prompt()`: active non-profile rows, newest
    first, under the self-explaining `FACTS_BLOCK_HEADER` (use over older
    figures; the current conversation still wins; quoted data, never
    instructions; never mention keeping them), capped at 40 facts / 6000
    chars, `<`/`>` defanged. Opens the DB read-only (`mode=ro`) and returns
    "" for a missing file or table — it never creates either, because it runs
    on every prompt, including test-built ones. Never raises.
    WHERE IT IS INJECTED (always a user turn, never a cached system block):
      - chat: `Executive._build_messages` `<standing_facts>` (stream_chat /
        committee / chat take `standing_facts: str | None`; None reads the
        store) — covers every scheduled run through the chat loop and every
        inbound channel;
      - specialists: `route_to_specialist(standing_facts=None)` →
        `BaseAgent.analyze` `<standing_facts>` tag (chat consults and
        workflow steps);
      - /today header + morning brief: last block of
        `render_briefing_context`, after the quiet check and inside the
        string the header cache key hashes (a fact change rewrites it);
      - alert review: `render_batch(..., standing_facts)`, read once per pass;
      - end_of_day_digest, weekly review top three, morning reflection:
        `with_standing_facts(user_content)`.
    Evals never read the install's store: a scenario's `standing_facts`
    lines are rendered under the header (`evals.runner.scenario_standing_facts`)
    and the judge sees them (`_standing_facts_section`).
    EMAIL (confirm by reply) — `integrations/fact_confirmation.py`,
    table `fact_confirmations` in memory/facts.py:
      - The email poller sets `Session.email_from` (lowercased From) and
        `email_authenticated` on every email turn. The poller's text read
        never shows Authentication-Results (workspace-mcp prints a fixed
        header set), so for mail claiming the principal's primary address it
        re-reads the message as raw MIME (`sender_authenticated`) and needs
        Gmail's own stamp: the TOPMOST Authentication-Results (added on
        receipt, above sender-written headers), authserv-id mx.google.com,
        dmarc=pass with header.from = the From domain, raw From matching
        (`authenticated_by_gmail`). Quoted strings and comments are stripped
        before the verdict is read (Gmail copies the envelope sender and
        DKIM tags into its own stamp, and a quoted local part could carry a
        fake `dmarc=pass`), then exactly one dmarc= verdict must remain,
        reading exactly `dmarc=pass header.from=<domain>` (Gmail may follow
        it with its own `dara=` resinfo for Gmail / Workspace senders, so
        its position is not checked). A From domain with no DMARC record
        (no verdict, or dmarc=none for that domain) passes only on a DKIM
        signature Gmail verified for exactly that domain (`_dkim_aligned`,
        strict alignment), or Google Workspace's default key for it
        (`<domain-with-hyphens>.<date>.gappssmtp.com`, read back only for a
        two-label domain without hyphens, since `a-b-com` is ambiguous).
        SPF alone never counts (a domain listing Google's servers passes
        anyone sending through Google). On every branch, mail a list or
        group resent (List-Id, X-Google-Group-Id, Mailing-List, or a Groups
        `+bnc` envelope) is never proven: an open group in the domain's own
        Workspace resends an outsider's forged From under the Workspace's
        signature. A stamp echoing `smtp.helo=` (sender text) proves nothing
        either. Fails closed (absent header, temperror,
        dmarc=fail, no aligned DKIM, unbalanced quotes or comments, two
        verdicts, extra text in the verdict, read failure). On an Outlook
        mailbox the same check reads Exchange's stamp instead: Graph's
        internetMessageHeaders for the message (get-mail-message), then
        delegation.outlook.exchange_authenticated (topmost header with EOP's
        compauth=, dmarc=pass for the From domain, or for dmarc=none /
        bestguesspass a DKIM pass with header.d = that domain; Microsoft
        365's default onmicrosoft.com key never counts, as it names the
        tenant, not the domain; list-resent mail never passes; a smtp.helo=
        echo or a second dkim= verdict never passes). It assumes Exchange
        Online stamps every message into the mailbox: a tenant whose mail
        arrives through an on-premises server or another gateway without
        EOP's stamp gets no real proof (compauth= only checks the shape). Outlook
        still sends no roster acknowledgement (the grant is Gmail's).
        Anyone else: no second read, never authenticated.
        `fact_tools._gate` admits one only from the principal's PRIMARY
        address (exact; no alias / domain rule), authenticated, and not
        private_to_principal (forwarded mail and contacts stay refused).
        Such a call is checked like chat, then HELD: the tool returns
        `awaiting_confirmation` (no chip; the model is told nothing changed).
      - `request_confirmation`: store action JSON + sha256(token)
        ("FC-" + 20 base32, 100 bits), 7-day TTL, max 10 pending; email the
        token to the principal's roster address outside any turn context;
        a failed send holds nothing. Profile edits are dry-run first.
      - The token never reaches a model: absent from the tool result, and
        `mcp_gateway.hide_roster_tokens` scrubs `FC-` as well as `RR-` from
        every Google Workspace result except the poller's inbound fetch;
        Act as me's reads of the principal's own Gmail
        (`delegation.gmail.parse_message`, thread search) hide them too.
      - `try_email_fact_confirmation` runs in `_handle_one_email` right after
        the roster-answer check, before any model turn: principal primary
        address + the token of a PENDING confirmation (made-up, spent,
        cancelled or expired tokens match nothing and fall through to the
        ordinary path, token hidden — no reply, so no token can make the
        Executive email the principal) → re-read as raw MIME; not
        authenticated by Gmail (same check as the request, or the read
        failed) is refused, still waiting, principal told → an automatic
        reply (printed Precedence: bulk, or raw Auto-Submitted /
        X-Auto-Response-Suppress / Precedence: auto_reply / out-of-office
        subject — an Exchange OOF echoes the token and may say "confirm")
        is consumed quietly, no reply, no model turn, still waiting →
        CONFIRM /
        yes applies via `fact_tools.apply_confirmed` (the same apply step as
        chat), CANCEL / no drops, unclear keeps waiting. A compare-and-set
        makes a token single-use.
      - Audit: private `fact_confirmation` rows (held / applied / cancelled
        / refused_unauthenticated / auto_reply_ignored / no_live_token); the applied change writes the
        tools' usual private rows with source_channel "email".
    SURFACE — Pulse page Memory → Corrections tab (`GET /memories/facts`
    with `retirable_ids` / `can_review`; `POST /memories/facts/{id}/retire`
    — principal any, a teammate their own; `/approve`, `/decline` —
    principal only). Other viewers get the active rows plus their own
    proposals, with the retire reason, session_id, turn_id and
    recorded_by_person_id blanked, and the quote blanked except on their own
    facts. Proposals show first with Approve / Decline; the principal sets
    "needs my approval" per teammate at the bottom of the tab. A subject that
    folds to an empty key ("???") is refused, so such subjects never
    supersede one another. `/memories?tab=corrections` opens it; the chat
    chips for the three tools link there / to /company-profile.
  peer_memory_mirror: |
    SQL is the system of record; the peer-memory service is the recall
    layer. When `store_decision` / `store_initiative` / `store_advice`
    insert a row whose `department` field is non-empty and not the
    literal "general", the row is mirrored as a kind-tagged note into
    that dept's peer via `append_department_note`. The mirror fires
    only after a successful INSERT (dedup hits and idempotent
    initiative upserts don't double-mirror), is fire-and-forget, and
    never rolls back the SQL row on peer-memory failure. Each store
    function accepts an optional `person_id` so the originator is
    attached as a co-present peer in the dept's notes session.
    Scheduled_actions is NOT mirrored — it's a dispatch queue, not
    memory. The extraction layer (`extract_and_store`) currently
    populates `domain` but not `department`, so today the mirror only
    fires for explicit dept-scoped writers; falling back to `domain`
    is a deliberate follow-up decision, not silent drift.
    Extraction is gated by `should_extract(speaker_text, session=...)`, which has NO
    length floor — it admits any non-blank user message. There used to be a
    combined user+assistant floor of 1500 chars, which on a live tenant
    blocked 9 of 16 turns — every instruction the principal gave — while
    admitting the 7 long analytical exchanges that contained no commitment;
    the extractor ran 13 times and stored nothing. Moving that floor to the
    user's side relocates the bug rather than fixing it: the canonical
    executive decision is a long analysis answered with "Approve option B."
    (17 chars) or "Do B." (5), and any floor high enough to skip "Done" (4)
    also skips those. "Do B." and "Done" differ by one character and mean
    opposite things, so length cannot separate a decision from an
    acknowledgement. `_is_valid_user_commitment` — the verbatim-quote check
    against the user's own words — is the gate that can, and it is the one
    that runs. The cost of admitting acknowledgements is one utility-fast
    call per turn that proposes nothing.
    The "user's own words" are the turn's speaker text
    (`executive._speaker_text`: `memory_text` when the entry point passes
    one, else the prompt). An inbound email's prompt carries the quoted
    chain and a briefing handoff's carries the Executive's card body, either
    of which let the Executive's own recommendation pass the quote check as
    the principal's decision.
    That quote check presumes `user_message` holds the PRINCIPAL's words, and
    on a chat channel it does not: `Executive.chat()` is reached from Slack,
    Discord, Telegram, Google Chat and the email poller, so a teammate's line
    would be stored in `decisions` with no speaker attached, and an inbound
    email body is text the sender chose (a self-quote is free). Removing the
    length floor is what makes this bite — short channel traffic used to fall
    under it incidentally — so `should_extract` asks the untrusted-content
    policy, `orchestrator.content_trust.principal_speaking(session)`: the web
    chat as the principal (or, with no principal on the roster yet, a request
    carrying no sign-in — a signed-in email on nobody's entry, e.g. an
    archived teammate still allowed to sign in, is NOT the principal), the CLI (`Session.from_cli`), the principal's own Slack/Discord
    or a secret-verified private Telegram chat
    (`is_principal_on_verified_surface`), or the principal's primary address
    with Gmail's own `dmarc=pass` (`Session.email_authenticated`). Anything
    else fails closed — teammates (web included), strangers, unauthenticated
    mail claiming the principal's address, Google Chat, the MCP server,
    unattended runs, an unreadable roster.
    WHY IT CHANGED (the email gate bug): the old rule read an EMPTY
    `origin_channel` as "web / CLI / API", and the email poller left it
    empty, so every stranger's email ran through the extractor with the
    whole prompt (headers, quoted chain) as the principal's words, and what
    it stored rendered to every specialist on every later turn. The poller
    now sets `origin_channel="email"`, and no gate may treat an empty
    channel as trust — name the principal's surfaces instead.
    `schedule_extraction` strips every `<untrusted_content>` block
    (`content_trust.strip_untrusted`) before the model or the quote check
    sees the text, so an attached document's sentence can never be stored
    as the principal's commitment.
    `format_for_prompt` tags a decision recorded on a channel with its
    source from the session_id prefix — `(via email)`, `(via Slack)`, … —
    so rows extracted from mail before the policy read as mail.
    Every pass writes a `memory_extraction` audit row (proposed / stored /
    dropped-with-reason / malformed, plus a `failure` reason when the pass
    raises — the handler catches BaseException too, so a CancelledError at
    shutdown is not logged as a clean empty pass). Before it, an extractor
    storing nothing looked identical to one with nothing to store. A
    `proposed>0, stored=0` streak is the signal to watch; `malformed` keeps a
    pass that got only garbage from reading as one that found nothing.
    `stored` is incremented AFTER the write, so a locked database reports
    `stored=0` rather than a healthy-looking pass that wrote no rows.
    A `bad_quote` drop earns exactly one corrective call: the model is shown
    the rejected items and the quotes it gave, told to copy the span
    character-for-character (typos included) or return empty arrays, with the
    tool forced where the provider supports tool choice. Every retry item is
    validated first (a still-invalid one adds no second drop; counted
    `still_invalid`), then classified: label matches a pending bad-quote drop
    record → recovery, stored and record released; else its quote (terminal
    punctuation ignored) already supports a stored item of that kind →
    re-send, ignored and counted `repeated`; else a new proposal, stored and
    counted — a reworded label cannot be told from a different item, so its
    original drop stands. Recovery is checked before re-send because two
    items can rest on one sentence. Malformed shapes at any level (a kind
    that is not a list, an item or payload that is not a dict, a response
    with no tool call) are counted `malformed`. The row's `retry` block
    (`rejected`, `recovered`, `repeated`, `still_invalid`, `malformed`,
    `failure`) is always present; `rejected` is set from the complete drop
    list when the row is written, so neither a store failure before the
    retry nor a cancellation during it can zero it. `proposed == stored +
    item drops` still holds after the retry. A retry exception is the
    retry's own `failure`; the first pass's results stand. `memory_extraction`
    is a declared `EVENT_TYPES` member so the audit UI filter can select it.

  always_in_the_loop: |
    Always in the loop (memory.history, memory.history_notes,
    memory.history_chat, memory.history_brief, memory.history_reminders,
    memory.history_drafts,
    orchestrator.history_tools, api/routes/history.py):
    private, dated notes of what a person said. Two sources: a reply the
    person approved and sent through Act as me (delegation.reply_send starts
    history_notes.note_sent_reply in the background after the send), and what
    they type to the Executive in a chat where it knows it is them (the
    post-turn block of stream_chat and stream_chat_with_committee calls
    history_chat.schedule_chat_notes). Why it is shaped this way:
    - One switch (history_person_settings.reply_notes, the name kept from
      phase 1) covers every channel. Any team member on the People list may
      turn it on (history.can_keep_notes); email notes still only come
      through Act as me.
    - Chat notes read only own_words(speaker_text) of a verified speaker:
      caller_person_id is them, not unattended, private_to_principal, an
      email turn or an eval override, on the web chat signed in (or local
      login), their own Slack or Discord, a private Telegram chat with a
      valid webhook secret, or a channel whose adapter set
      Session.speaker_verified. An adapter's Session.speaker_verified (with
      the caller_person_id it resolved from the sender identity it verified
      itself) makes its channel a verified surface everywhere
      (people_tools._is_verified_speaker_surface), as Slack and Discord are;
      Session.private_chat makes the conversation private
      (delegation.settings.private_conversation), so Act as me and
      recall_history may be offered there. Never another person's words, never the reply,
      never a turn that touched the speaker's mailbox.
    - Paced: messages under MIN_CHARS (40) are skipped and each person gets at
      most MAX_PASSES_PER_DAY (40) passes a day, counted in the company DB
      (history_chat_passes, history.take_pass) so the cap holds across
      workers and restarts. CHAT_PROMPT says requests to the assistant, questions and
      small talk are not notes; check_note runs with the message as body and
      allowed words. Shared threads are noted too, but read back only in a
      private chat.
    - Notes record events, never instructions. Code sets trust, visibility
      and the checks; the model writes only the summary sentence.
    - The note-taker reads only the person's own sent words
      (email_poller.sender_new_text) and the recipients' names cut to four
      words (short_name), never the mail being answered nor the subject, so
      another person's text can't become a note. One forced record_notes call, a constant NOTES_PROMPT, at most
      three notes, model DELEGATION_CLASSIFIER_MODEL or the routing model.
    - check_note drops a note whose quote isn't word for word in what they
      sent, whose summary has a figure not in the quote, a name or date word
      not in their words or recipients, mostly words they didn't write, or a
      link or address. A
      due_date is kept only for promised or agreed.
    - Every note is private to its person, the principal included. Company
      retention defaults to 90 days (30, 90, 365 or until forgotten, the
      principal's choice); a person may only shorten it. Pinned notes never
      expire. The scheduler's alert sweep deletes expired ones.
    - "Don't remember this" forgets a conversation's notes and records it in
      history_excluded so it is never noted again. Conversations are keyed by
      a hash of channel and thread id.
    - recall_history is offered only when history_tools.recall_person finds
      the speaker verified (history_chat.verified_speaker), able to keep
      notes, in a private chat (history_chat.private_chat, or
      Session.private_chat), with their switch on. Act as me isn't needed. Recall
      sets touched_mail first, for the principal too (private rows, no
      memory, the lockdown from that round: touched_mail and read_mail), and
      marks the conversation mail_private so later turns are private the same
      way (not locked down) and, for a team member, the principal can't open
      it.
    - recall_history takes due=true to list only dated notes, a week overdue
      to two weeks ahead, soonest first ("what's due today?").
    - The owner's briefs read the owner's own notes (memory.history_brief):
      the morning brief a FROM YOUR NOTES - DUE SOON block, the end-of-day
      digest a FROM YOUR NOTES - TODAY block. Only on the scheduler's
      delivery (PRINCIPAL_DELIVERY), never a chat run (its tool result
      reaches the shared audit row and Honcho), only with the switch on,
      never a teammate's notes. A run that used any is private_to_principal
      (the run history keeps PRIVATE_RUN_ARTIFACT) and the note ids with
      their state enter the fingerprint.
    - The first week (briefing.first_week, seven days from the principal's
      People row) gives the briefs a GETTING STARTED block so a new install
      is never "quiet": goal rows or, while there are none (setup saves
      no goal rows), the profile's strategic_priorities and north star,
      departments with no
      head_person_id and, only on PRINCIPAL_DELIVERY with Act as me and Draft replies to my inbox on (the watcher's consent) and gmail_status connected, up
      to five people who wrote to the owner's own mailbox in 48 hours as
      sender and subject (no message text, bulk mail skipped). Counts
      against the quiet check, its keys enter the fingerprint, the inbox
      part marks the run private. With Read my calendar on (and the same
      Act as me and gmail_status gates) it also lists up to eight of
      today's events on their own calendar as time and title, declined
      ones skipped, keys meeting:<event id>, also private. The /today header
      does not get the block. Home shows a first-week card instead
      (first_week.first_week_card, no model call): a fixed goal ask while
      no goal row exists, up to two findings from the latest team
      executive_research run (parse_artifact_findings reads the stored
      artifact's Findings reviewed lines), a Watch list link, and "first
      morning brief comes tomorrow" on setup day until one is delivered.
      GET /today sets first_week_card and first_week for the principal
      only; the UI drops the "Quiet day" banner while there is a card.
    - Due-today reminders (memory.history_reminders, from the scheduler
      tick, 09:00 to 18:00 local) cover only promises made by email
      (approved_reply): chat promises are already open loops the nudge
      engine chases. The message says how many, never what or to whom; the
      senders' audit rows are private to the person (rows_for_person) and
      stay off the activity rail. The person asks for the detail in a
      private chat. Sent to their own DM, private Telegram chat (delivery_order
      skips group ids, for the briefs too) or email (runner.deliver_to_person),
      one try a day per person (history_reminders, claimed, never released).
    - Act as me drafts (chat ghostwrite and the inbox watcher) get a
      <writer_noted> block (memory.history_drafts.notes_for_draft): the
      writer's own approved_reply notes whose recipients include every
      recipient of the new draft, at most 8, switch on. Ghostwriter rule 6:
      a consistency check only; a contradiction becomes an open question,
      never new content.
    - Notes never feed Honcho, episodic extraction or standing facts. The six
      history_* tables swap with client slots and the factory reset clears them.

peer_memory:
  what: |
    External peer-keyed memory layer that gives the Executive durable,
    cross-channel recall at two scopes:

      - **Per-person**, keyed by ``Person.id``. A user who chats from
        Discord, Telegram, email, and the web UI is one peer card —
        facts they share in any channel surface in the others.
      - **Per-department**, keyed by ``department_<slug>``. Each
        department is its own peer that accumulates an institutional
        voice from dept-scoped decisions, advice, committee outcomes,
        goal updates, cadence check-ins, and dept-bound specialist
        turns. When a person turn touches a department, the dept peer
        joins the person's session as a co-present peer — that's the
        hybrid peer-graph cross-pollination that lets later
        ``peer.chat()`` queries on either peer synthesize across both
        timelines.

    The peer-keyed surfaces sit on top of Honcho (https://honcho.dev)
    as the underlying provider. Production runs against hosted Honcho;
    the repo also carries a self-hosted image (``docker/honcho/``)
    as a fallback. The
    integration is provider-agnostic at the wrapper boundary
    (``openexecutive.memory.honcho_client``) — swapping providers
    would touch that one module without rippling through the
    Executive, router, or specialists.
  wrapper:
    module: openexecutive.memory.honcho_client
    gate: |
      ``HONCHO_ENABLED`` env var. When false, every entry point
      short-circuits with ``outcome=disabled`` and the rest of OE
      behaves identically to its pre-Honcho posture. Per-loop client
      cache keyed by ``asyncio.AbstractEventLoop`` so a caller that
      spins up its own loop doesn't bind a stale client. (Slack was the
      original motivation; it now awaits on the app loop like every
      other adapter, but the cache still guards tests and the
      standalone entrypoints.)
  surfaces:
    prefetch: |
      ``prefetch(query, *, person_id, session_id=None, reasoning_level="low")``
      — once per turn at the start of ``Executive.stream_chat`` /
      ``stream_chat_with_committee`` (the chat route runs it in parallel
      with RAG and episodic retrieval and hands the result in). Returns a
      short ``<peer_memory>`` block injected into the USER turn (never a
      cached system block, so it doesn't poison prompt caching); on
      timeout or error the turn proceeds with an empty block.
      ``HONCHO_PREFETCH_MODE`` picks how the block is produced:

      ``representation`` (default) reads the peer's card and the derived
      conclusions most relevant to the inbound message —
      ``peer.aio.context(search_query=message, search_top_k=K,
      max_conclusions=K)``, ``K = HONCHO_PREFETCH_MAX_CONCLUSIONS``
      (default 20) — a GET with no LLM behind it, ~100 ms on a
      self-hosted instance. The block is the card lines (``IDENTITY:
      Name: ...``, which binds the bare peer id the conclusions name the
      person by) then Honcho's representation text, whole lines only up
      to ``_REPRESENTATION_MAX_CHARS`` (4000): a line that does not fit is
      dropped, never cut, control characters are stripped and a literal
      ``</peer_memory>`` is defanged, since conclusions derive from text
      anyone who can email the Executive wrote. A person Honcho has
      nothing on yet yields no block and ``outcome=empty``.
      It runs on ``HONCHO_PREFETCH_TIMEOUT_S`` unscaled and ignores
      ``reasoning_level``. Honcho's own guidance is the same split:
      ``context()`` for per-turn grounding, ``chat()`` when a reasoned
      answer is worth the latency.

      ``dialectic`` asks Honcho's chat endpoint (``peer.aio.chat(query)``)
      with the inbound message as the question, so the answer is
      synthesized prose from an LLM call (seconds). There
      ``reasoning_level`` trades latency for synthesis depth:
      ``"minimal"`` on ``stream_chat``, which awaits the prefetch inline
      before the first streamed byte (``"low"`` was measured hitting the
      ~5s tail for peers with large representations); ``"low"`` from the
      chat route, which runs the prefetch inside the same gather as RAG
      and episodic retrieval so the extra depth adds no dead air of its
      own; ``"medium"`` for committee-reviewed turns that already pay
      deep-review latency. The mode applies to every per-person
      ``prefetch`` call, committee turns included; only
      ``prefetch_department`` and ``directional_chat`` (the
      ``ask_about_person`` tool) always use the chat endpoint, because
      they are deliberate questions off the inline path. Set ``dialectic``
      for a Honcho server without the
      peer-context route; an error there is one audit row with
      ``error_type`` and a memory-less turn, never a fallback that spends
      the budget twice.

      In dialectic mode, ``HONCHO_PREFETCH_TIMEOUT_S`` is the knob for the FAST per-turn
      path and is used unscaled there (``minimal``/``low`` sit at 1.0).
      Only the deliberate levels scale off it — ``medium`` 4x, ``high``
      5x, ``max`` 6x — capped at ``_PREFETCH_CEILING_S`` and never below
      the configured base, via ``prefetch_timeout_s()``. At the default 3s
      base that is 12s for ``medium`` with ``high``/``max`` at the 15s
      ceiling; at a 10s base every deliberate level IS the ceiling — the
      multipliers only differentiate below it, by design. Honcho's
      dialectic latency scales steeply with the level (measured on
      hosted Honcho: ``low`` ~2s, ``medium`` ~8s), so a single flat
      budget made the deeper levels unreachable — every ``medium`` call
      timed out and the turn silently ran with no peer memory, strictly
      worse than having asked for ``low``. ``medium`` carries more
      headroom than its measurement alone implies because the budget
      spans ``peer()`` + ``chat()`` and a budget at the mean still times
      out half the time.

      The fast levels stay unscaled deliberately: ``prefetch`` is awaited
      inline before the first streamed byte, so multiplying the base
      there adds dead air to every ordinary turn; and any multiplier
      above 1.0 flattens every level onto the ceiling once the base
      approaches it, which would stop the operator's knob distinguishing
      the two paths at all. A non-positive base falls back to
      ``_DEFAULT_PREFETCH_TIMEOUT_S`` — ``wait_for`` with timeout <= 0
      fires before the request is made. Each prefetch audit row carries
      the ``timeout_s`` it ran under.

      ``_client_timeout_s`` is an OUTER bound over every PER-CALL budget
      in the module, kept strictly greater than all of them; the aggregate
      ceilings on whole passes are deliberately excluded, since it applies
      per request. Because it is no longer tight, the
      fire-and-forget bodies (person sync, department sync, department
      note) — none of whose individual calls is separately budgeted —
      carry their own ``_SYNC_TOTAL_TIMEOUT_S`` ceiling and emit
      ``outcome=timeout`` when it fires; the workspace purge's session
      listing is bounded by ``_SESSION_PURGE_BUDGET_S`` for the same reason.
    sync_turn: |
      ``sync_turn(user, assistant, *, person_id, session_id, co_present_person_ids)``
      — fire-and-forget background task scheduled on the current event
      loop; never blocks the user-facing response. Persists the
      completed exchange to a Honcho session: the person's message under
      their peer and the Executive's reply under the ``executive`` peer,
      which is resolved through ``_executive_peer`` with
      ``PeerConfig(observe_me=False)``. Recording the reply lets the
      person's representation see both sides of the exchange; without
      the flag Honcho's deriver also built a representation OF the
      Executive from those replies — pure cost, nothing reads it, and the
      place where a person's words were misattributed to the Executive.
      The async ``peer()`` is a get-or-create POST that applies a changed
      configuration to an existing peer, so the flag is re-asserted on
      every sync for free.

      The "person's message" is ``memory_text`` when the entry point
      passes one (``Executive.chat`` / ``stream_chat`` /
      ``stream_chat_with_committee``), else the LLM-facing
      ``user_message``. Honcho derives facts about a person from every
      message posted under their peer, and several prompts carry text the
      person did not write. Observed in production: an inbound email's
      framing, headers (the Executive's own address in ``To:``) and quoted
      chain produced "<person> is associated with <exec address>" and
      "<person> received an email from <person>"; a briefing Discuss seed
      quoting the Executive's artifact produced "<person> assigned a
      colleague to …". So the email poller passes ``_email_memory_text`` (subject, the
      sender's new text, attachment filenames), ``/chat/upload`` passes
      the typed text plus filenames, and the briefing handoffs send a short
      ``memory_text`` line through ``POST /chat``, phrased as the user
      speaking and ended with "." before the headline on its own line
      ("I approve this proposal." / "<headline>"): an "Asked to …" line
      was derived as "<person> was asked to …", and a "?" in a headline
      inside the sentence voided the extraction quote gate. An email's
      subject is dropped when it is a reply's or forward's (Re:/Fwd:) —
      the earlier message's subject, often the Executive's own. ``co_present_person_ids``
      enumerates other humans in the conversation context (Discord
      thread members, Slack thread participants, email To+Cc) so
      Honcho can store them as session peers — the data shape that
      makes peer-of-peer reasoning possible. Also seeds each person
      peer's Honcho card with the roster's name (``_seed_identities`` /
      ``_seed_peer_identity``, applied on the department sync path too):
      peers are keyed by ``Person.id``, so without this the only identity
      signal Honcho receives is a bare integer, and its dreaming agent
      concludes the number IS the person's name — observed in production
      as a card reading ``IDENTITY: Name: 1``. Cards are injected into
      the dialectic system prompt on every ``peer.aio.chat()``, so that
      error then propagates into every later answer about that person.

      The card carries the NAME ONLY: email and role would export roster
      PII to a third-party memory service, for cc'd people included, and
      neither is needed to fix the defect. ``set_card`` replaces the
      whole card, so only ``IDENTITY:`` lines are swapped (matched case-
      and whitespace-insensitively) and the deriver's ``ATTRIBUTE:`` /
      ``RELATIONSHIP:`` lines are preserved; the existing card is split
      on PHYSICAL lines first, because one list element may itself span
      lines and hide an identity claim on its second, and the carried-over
      lines are capped.

      Roster values are attacker-reachable (``upsert_person`` is a chat
      tool an inbound email sender can reach), so ``_card_value``
      NFKC-normalises, flattens whitespace, strips Cc/Cf characters,
      length-caps, and then holds the value to an ALLOW-LIST of letters,
      combining marks, digits and a small punctuation set, with the
      colon lookalikes the category allow-list would otherwise admit
      STRIPPED out — taken from Unicode's confusables data (everything
      mapped to U+003A) rather than from character names; U+A4FD is a
      Lisu tone LETTER whose name never says colon. Stripped rather than
      refused, because the visarga is the nominative ending in formal
      Devanagari/Gujarati names: refusing would leave those people never
      seeded, stripping keeps the stem form and still lets no colon shape
      reach the card. Modifier letters as a class stay allowed (々, ー, ʻ). A deny-list of structure
      tokens is not sufficient: the consumer is an LLM system prompt
      rather than a parser, so ``ATTRIBUTE :``, a fullwidth colon, a
      zero-width space and a Cyrillic homoglyph all read the same to the
      model while defeating a literal match. The allow-list refuses every
      colon variant, checked by an exhaustive test over every Unicode
      codepoint whose name contains COLON plus an explicit test of the
      confusables that names miss. It does NOT stop merely persuasive prose
      — OE already embeds ``full_name`` in its own system prompt, so that
      exposure is pre-existing, not introduced here.

      Seeding runs AFTER the message write (that write is the point of
      the sync and must not queue behind two card round trips per peer),
      is bounded per peer by ``_IDENTITY_SEED_TIMEOUT_S`` AND per pass by
      ``_SEED_TOTAL_TIMEOUT_S`` (the pass is serial, so the per-peer bound
      alone costs peers x budget on a wide thread), and is best-effort. It runs OUTSIDE the
      sync ceiling and is audited as its own ``seed_identity`` row (``ok`` only when no
      peer failed; ``error`` when any did, with the ``failed`` count on
      the row; ``timeout``; ``empty``), so the
      sync row is a pure record of the persist, emitted the instant the
      write lands — a slow card round trip can neither delay nor replace
      it. Memoized per ``(workspace, person)`` on the facts
      sent with an ``_IDENTITY_RECHECK_S`` interval: a rename re-seeds at
      once, and because the deriver keeps re-deriving identity from the
      peer id a one-shot memo would let ``IDENTITY: Name: 1`` return
      unnoticed. A failure is memoized separately for
      ``_IDENTITY_RETRY_AFTER_S`` — including every peer a pass-ceiling
      cut-off left in flight or unreached — so a degraded card endpoint is
      probed once per interval, not once per peer per turn.

      Known limitation: the card replace is read-modify-write with no
      ETag in the SDK, so a deriver write landing in between is lost
      (self-correcting, since the deriver re-derives). Sanitizes session
      ids through ``_safe_honcho_id`` (Honcho rejects
      ``[^a-zA-Z0-9_-]``) so channel-shaped ids like
      ``discord:thread:N`` get rewritten to
      ``discord_thread_N``.
    directional_chat: |
      ``directional_chat(*, person_id, question, target_person_id=None)``
      — backs the ``ask_about_person`` Anthropic tool registered
      alongside ``consult_specialist``. With ``target_person_id`` set,
      queries peer A's representation OF peer B
      ("what does Alice know about Bob"). Without it, queries peer A's
      own representation.
    delete_workspace_and_reset_client: |
      ``delete_workspace_and_reset_client(workspace_id=None)`` — wipes
      a Honcho workspace via the SDK (defaults to the active one), then
      drops the per-loop client cache. Called by the fixture loader's
      unload + reset paths. Cascades sessions first: Honcho's
      ``delete_workspace`` rejects with ``ConflictError`` while any
      session in the workspace remains, and the Python SDK exposes no
      ``--cascade`` flag, so the wrapper enumerates ``client.aio.sessions()``
      and deletes each one (bounded concurrency, per-session timeout)
      before issuing the workspace delete. Uses a one-shot teardown
      client constructed explicitly against ``target`` so the session
      listing hits the right workspace even when the active-workspace
      override file is mid-flip. The fixture loader clears the override
      BEFORE issuing teardown deletes so a delete failure can't leave
      the override pointing at a half-deleted workspace.
    prefetch_department: |
      ``prefetch_department(query, *, department_slug, session_id=None, reasoning_level="low")``
      — fired inside ``orchestrator.router._prefetch_department_for_call``
      for every specialist consultation whose specialist key resolves
      to a department via
      ``openexecutive.departments.registry.slug_for_specialist``.
      Queries the dept peer's representation via Honcho's dialectic
      endpoint and returns a ``<department_memory>`` block that
      ``BaseAgent.analyze`` injects into the specialist's USER turn
      alongside ``<relevant_knowledge>`` / ``<past_decisions>`` (never
      a cached system block). Specialists with no owning department
      (e.g. ``triage``) skip the prefetch and receive an empty block.
      Cardinality note: roughly one prefetch per specialist call, so a
      cross-domain turn pulling Finance + Marketing + HR fires 3
      parallel prefetches alongside RAG + failure-case retrievals.
    sync_department_turn: |
      ``sync_department_turn(user, assistant, *, department_slug,
      session_id, originating_person_id, co_present_person_ids,
      co_present_department_slugs)`` — fired by the Executive once per
      unique consulted department after the per-person ``sync_turn``.
      Writes into a department-scoped Honcho session
      (``dept-<slug>-<sanitized-session>``) so the dept peer
      accumulates a coherent timeline distinct from the person-scoped
      session populated by ``sync_turn``. The originating person
      authors ``user_message`` (NOT the dept peer — attributing user
      words to the dept would pollute its representation extraction).
      Other people and departments that touched the turn join as
      co-present peers in the dept session. Cardinality note:
      N_threads × N_consulted_depts sessions over the lifetime of the
      org; Honcho is designed for this — sessions are cheap.
    append_department_note: |
      ``append_department_note(*, department_slug, kind, body,
      person_id=None)`` — fire-and-forget structured note used by the
      episodic-store mirror and by future non-turn event sources
      (goal updates, committee outcomes, cadence check-ins). ``kind``
      is one of ``decision``, ``initiative_update``, ``advice``,
      ``goal_update``, ``committee_decision``, ``cadence_checkin`` and
      is inlined into the body as a ``[kind]`` prefix so the dept
      peer's representation extraction can distinguish categories
      without a side channel. Notes accumulate in a single per-dept
      ``dept-<slug>-notes`` session — the dept peer is explicitly
      added to the session (it authors no message here) so its
      representation derives from session participation.
  caller_resolution: |
    Each entry point into the Executive resolves the inbound user to a
    ``Person.id`` differently:

      - Channel adapters (Discord, Slack, Telegram) use
        ``find_person_by_{discord,slack,telegram}_id`` against the
        channel ID extracted from the inbound message; the email poller
        uses ``people.identity.resolve_email_sender`` (primary or alias,
        then the company-domain rule). No match → the message does not
        reach the Executive as that sender: a chat DM / mention / private
        verified Telegram chat is held as a roster request and replayed,
        attributed, once the principal adds them; non-roster email is
        triaged unattributed (see `integrations.channel_access`,
        `people.roster_requests`).
        A matched chat-app sender reaches alert triage under that
        Person's ``full_name``, never the chat app's self-chosen display
        name, and the principal's own chat messages are not triaged
        (``alerts.pipeline.schedule_chat_message_evaluation``).
      - Web ``/chat`` uses ``x-caller-email`` stamped by the Next.js
        proxy from the verified NextAuth session →
        ``find_person_by_email`` (primary address only — an alias never
        signs in). Header present + no match → person_id
        stays ``None`` so the turn doesn't get fused into the principal's
        peer card. Header absent → falls back to
        ``find_principal_person``. The proxy strips inbound
        ``x-caller-*`` from clients before re-stamping so the header
        can't be spoofed.
  audit_shape: |
    Every wrapper call emits one ``peer_memory`` audit row through the
    ``audit/logger.log_event`` funnel. ``op`` is one of ``prefetch``,
    ``sync_turn``, ``directional_chat``, ``workspace_reset``,
    ``prefetch_department``, ``sync_department_turn``, or
    ``append_department_note``. ``outcome`` is one of
    ``ok | timeout | error | disabled | no_person | no_department |
    no_loop | empty`` (``empty`` on a prefetch means no block was
    produced: nothing to ask — ``reason: no_query`` — or nothing known
    about the person yet). Prefetch rows carry
    ``mode``, ``timeout_s`` and, per mode, ``reasoning_level`` or
    ``max_conclusions`` / ``card_lines`` / ``representation_chars``;
    error rows add ``error_type``. Rows carry ``person_id``, optional
    ``department_slug`` (the new field joins person_id at the top of
    the audit details for dept-keyed ops; person-only ops leave it
    None), ``duration_ms``, and op-specific ``details`` (query
    preview, reasoning_level, peer count, co_present_person_ids,
    co_present_department_slugs, originating_person_id,
    target_person_id, session_id, workspace_id, kind, error_type,
    error_msg). Rows inherit ``session_id`` + ``turn_id`` from the
    orchestrator's audit ContextVars so the per-turn flow chart at
    ``/audit/session/{session_id}`` renders the peer_memory path
    alongside ``knowledge_retrieved``, ``specialist_consult``, etc. No
    existing consumer filters on ``person_id``, so dept-keyed rows
    with ``person_id=NULL`` are safe; dashboards that want to scope to
    a dept should filter on ``details.department_slug``.

    Department peers are not bound to inbound channels (departments
    are not message endpoints), so ``caller_resolution`` doesn't apply
    to the dept-keyed ops — the dept slug is the only identity key.

    Fire-and-forget background tasks (``sync_turn``,
    ``sync_department_turn``, ``append_department_note``) snapshot
    ``(session_id, turn_id)`` via ``audit.context.get_active_ids()``
    at scheduling time and re-bind via ``with set_turn(...)`` inside
    the background coroutine before emitting the audit row. Without
    this, the row lands with ``session_id=NULL`` (the parent's
    ``set_turn`` block in ``stream_chat`` has already exited by the
    time the task runs) and is invisible in the per-session view.
  workspace_isolation: |
    Production uses one Honcho workspace (``HONCHO_WORKSPACE_ID``,
    default ``openexec``). Loading a demo fixture switches to a
    sacrificial ``openexec-fixture-<name>-<uuid8>`` via
    ``set_active_workspace_id`` (state persisted in
    ``_user_backup/.honcho_active_workspace.json``); demo turns sync
    to that workspace instead of polluting real peer cards.
    ``unload_fixture`` deletes the demo workspace and clears the
    override. ``reset_all_state`` deletes both the active and
    env-default workspaces when they differ. On startup,
    ``reconcile_honcho_workspace_on_startup`` clears a stale
    override left by a crashed previous process (state file present,
    ``.fixture_active`` sentinel absent). The wrapper's
    ``_get_client`` consults ``get_active_workspace_id`` at
    construction time so a workspace switch takes effect on the next
    Honcho call.
  observability:
    health_endpoint: |
      ``GET /health/honcho`` — config check + 2s base-URL ping. Returns
      ``disabled | ok | error`` with ``latency_ms``. Intentionally does
      NOT exercise the dialectic endpoint (that would cost an LLM call
      per probe).
    people_overview: |
      ``GET /memories/people?recent=N`` (``honcho_client.people_overview``)
      — what peer memory knows about the caller, for the Your profile
      card on Settings → About you (/settings/memory): only the caller's own entry, the principal included (a
      caller off the roster sees none; /conclusions 404s for anyone else). Read-only, no LLM call: one ``peers()`` listing
      (every page, under one 15 s clock — the SDK walk is otherwise bounded
      only per request), then per matched person (at most 8 in flight, each
      under the unscaled prefetch budget, because the reads share the
      per-loop client with the live chat prefetch) one self-conclusions
      page (``peer.conclusions``,
      newest first, ``recent`` of them, plus the page total) and one
      ``get_card()`` with OE's own ``IDENTITY:`` lines removed. Peers are
      matched to the roster by id and never created — ``peer(id)`` is a
      get-or-create POST and a read must not mint peers for people who
      have never talked; the ``executive`` and ``department_*`` peers and
      archived people are skipped. Every line, timestamps included, passes
      ``_block_safe_line``. Reads close together in the UI share one
      in-flight request.
      Response ``{status: ok|disabled|error, people: [{person_id,
      full_name, is_principal, card, conclusion_count, last_observed_at,
      recent: [{content, created_at}], error}], conclusion_total}``; one
      person's failure or timeout sets that entry's ``error`` and leaves
      the rest intact. One ``peer_memory`` row per call, ``op=overview``,
      ``person_id`` null, ``details.people / conclusions / errors``. Pulse
      neither shows nor counts peer notes (each person sees only their
      own, so it is a page about them, not a list of people); the UI hides
      the card when ``status`` is ``disabled``. The card drops the
      memory service's category tags (``ATTRIBUTE:`` …) from card lines and
      shows the person's first name in place of their bare peer id in
      notes, display-only (ui ``lib/aboutYou.ts``). Peers match only an id spelled exactly
      as OE writes it, once per person; within the newest page the
      conclusions are ordered by instant (never by the rendered string,
      which is not chronological across offsets); card elements and
      conclusions are split on physical lines and scrubbed before the
      identity-line filter, so a claim on an element's second line is
      caught too. The UI is
      read-only here: peer memory is Honcho's derived view, not the
      Executive's own record the way decisions and advice are.
    person_conclusions: |
      ``GET /memories/people/{person_id}/conclusions?page=&size=``
      (``honcho_client.person_conclusions``) — every self-conclusion about
      one person, newest first, one page at a time (``size`` 1–100, default
      50). The About you card's notes pane is
      seeded from the overview's ``recent`` and, on "Show all", reads this
      page by page as the pane scrolls. The peer is found through the same
      ``peers()`` listing as the overview (shared ``_matched_peers``), never
      ``peer(id)``: an unknown, archived or never-talked person is a 404,
      not a new peer. Items are ordered by instant and scrubbed by the same
      ``_to_conclusion`` as the overview. Response ``{status, person_id,
      items, page, size, total, has_more}``; ``has_more`` falls back to "the
      page was full" when the server sends no total. Listing under the 15 s
      clock, the page read under the unscaled prefetch budget; one
      ``peer_memory`` row per page, ``op=conclusions``.
    audit_filter: |
      ``/audit?event_type=peer_memory`` for the flat list;
      ``/audit/session/{id}`` for per-turn context with peer_memory
      nodes rendered alongside the rest of the turn. Filter dept-keyed
      rows by ``details.department_slug``; filter person-keyed rows by
      ``details.person_id``.
  dreaming: |
    The provider's server-side deriver + dream passes asynchronously
    enrich peer representations from accumulated messages. OE does not
    call ``schedule_dream``, ``refresh``, ``queue_status``, or
    ``search`` — dreaming policy is whatever the hosted service does
    on its own. Implication: a fact written via ``sync_turn`` /
    ``sync_department_turn`` / ``append_department_note`` may not be
    visible to the very next ``prefetch`` until the deriver has
    processed it. Usually seconds; can be longer under load.
  example_trace: |
    End-to-end behavior, captured from the automated dept-Honcho test
    harness run on dev (2026-05-25, Round 2 fixture loaded). Three
    acts on the same dept (`strategy`), proving write → same-person
    recall → cross-person recall.

    | Act | Caller | Session | dept_memory chars | Audit op fired             | Outcome   |
    |-----|--------|---------|-------------------|----------------------------|-----------|
    | 1   | Jordan  | new     | 1,480 (seeded)    | prefetch_department + sync_department_turn | WRITE ✓   |
    | 2   | Jordan  | new     | 1,678 (own write) | prefetch_department          | STRONG ✓  |
    | 3   | Alex   | new     | 609 (cross-peer)  | prefetch_department          | WEAK ✓    |

    Act 1: Jordan (person_id=66) asks the CSO whether to push Morgan's
    web positioning live before or after Karel's walkthrough.
    Specialist routes, returns a decision ("split-phase: team page
    before, positioning copy after"). The post-turn
    sync_department_turn writes the exchange to the strategy dept peer.

    Act 2: Jordan opens a brand new session and asks the recall
    question. The dept peer's prefetch returns a 1,678-char synthesis
    that cites the specific operational tightenings (Thursday-noon
    gate, minimal-spec requirement, Karel-referral half-life). Same
    person, different session — proves cross-session continuity.

    Act 3: Alex (person_id=69) — a different person who was NEVER in
    Act 1's session — asks the same dept the same question. The dept
    peer's prefetch returns a 609-char synthesis (~36% of Act 2's
    depth) that cites the same direction Act 1 chose but omits the
    operational nuance. Proves the peer graph genuinely cross-
    pollinates across person boundaries, with the documented gradient
    that synthesis depth degrades with peer-graph distance.

    Optional Act 4 (not shown): Alex asks about reaching out to a
    contact at Vertex Exchange. Response cites the seeded 2026-05-21
    decision walling Alex off from Vertex and suggests Morgan handle
    instead — proves the fixture loader correctly populates the dept
    field on seeded memory.json decisions so the mirror fires at
    fixture-load time.
  invariants:
    - "Provider calls must never break a chat turn — every wrapper entry point swallows exceptions and logs an audit row with the failure shape."
    - "The <peer_memory> and <department_memory> blocks live in the USER turn only; never in a cached system block. Putting them in a cached block would either poison the cache or stale-serve the wrong peer's memory."
    - "person_id is the only key for person peers; department_<slug> is the only key for dept peers. Two different humans MUST never share a Person.id (enforced by the channel adapters' roster check + the demo workspace isolation)."
    - "Session ids passed to the provider must match ^[a-zA-Z0-9_-]+$; the wrapper sanitizes channel-shaped ids before send."
    - "Fire-and-forget background tasks (sync_turn, sync_department_turn, append_department_note) snapshot the audit ContextVars (session_id, turn_id) at scheduling time and re-bind inside the coroutine — without this, the audit rows land with session_id=NULL and are invisible in the per-session view."

attunement:
  what: |
    The Executive adapting to each person it works with
    (`openexecutive.attunement`). First piece: open loops — commitments and
    asks from ANYONE on the roster, tracked until done and chased when they
    slip. Complements Honcho (facts / stated preferences) rather than
    duplicating it; works with HONCHO_ENABLED=false (the default).
  why: |
    Commitments used to be captured only from the principal's words
    (`episodic.should_extract` requires is_principal) because stored messages
    didn't record who said them, and nothing in production set
    `scheduled_actions.awaiting_response_since`, so the nudge engine's
    commitment source never fired on a real install.
  attribution: |
    `chat_messages.sender_person_id` = the RESOLVED rostered sender of a user
    message, never the session owner (Discord/Telegram sessions from
    unrostered senders are owned by the principal for sidebar visibility;
    attribution keeps outsiders' words from being read as the principal's).
    Web passes `_resolve_caller_person_id` (header-less = principal's CLI/API
    surface; unrostered email header = None); Slack/Discord/Telegram pass the
    sender they resolved. `Executive.stream_chat` / committee set
    `Session.caller_person_id = person_id` every turn for tool handlers.
    Email / Google Chat don't persist chat_messages (known gap) but the
    open-loop hook lives in the Executive, so they still open/close loops.
  session_access: |
    Every per-session HTTP route (GET /sessions/{id}, GET /sessions/{id}/messages,
    DELETE /sessions/{id}, POST /chat with a session_id, and feedback/followup)
    is limited to the session's owner or the principal (`is_principal_or_self`;
    a NULL-owner legacy row is the principal's alone). The sessions routes answer
    404 for anyone else, identical to an unknown id, so they are no oracle for
    which chats exist; POST /chat instead runs the turn in a fresh chat. Session ids are guessable
    (`slack:dm:<user id>`, `telegram:<chat id>`), so the id alone is no proof.
    `chat._session_access` also admits whoever started the chat in this process
    (`_session_starters` holds the starter's `_caller_keys`: Person id and/or
    verified email, else "local"), which is how an unresolved caller (fresh
    install, allowlisted but unrostered) continues their own ownerless chat.
    Matching on email too means the starter keeps access once they resolve to a
    Person, and that turn late-binds the row to them. Only the starter binds an
    ownerless row: the principal continuing it does not take it over. The record
    is in-memory; after a restart an ownerless row nobody here started is
    "orphaned": reads get 404 and POST /chat continues in a fresh chat instead
    of failing. POST /chat also ignores an unknown namespaced id (contains ':')
    rather than letting a web caller squat an id a channel adapter will later
    create (INSERT OR IGNORE keeps the first owner). A "missing" id evicts any
    cached Session under it: fixture reset and client-slot switching remove
    rows without clearing `_sessions`, and the stale transcript must not be
    handed to the next claimant. A turn whose Session was deleted mid-stream
    (no longer the cached object) skips persisting, so no orphan messages are
    left under the deleted id. Claiming an unused bare id also deletes any
    messages already stored under it (orphans from a delete/reset race or from
    before this check), so they are never loaded as the claimant's history.
    DELETE also evicts the in-memory Session so the id cannot resume its history.
    Known gap, not covered: GET /audit/sessions/{id} is not owner-scoped.
    (GET /debug/last-turn, which leaked the last turn to any caller, was
    removed in #200.)
  feedback: |
    `chat_messages.feedback` up|down (+ `feedback_note`) via
    POST /sessions/{id}/messages/{message_id}/feedback — session's own caller
    or the principal only (403 otherwise). SSE `done` carries `message_id`;
    AskOEPanel renders 👍/👎. `load_messages` adds `id` (+ `feedback`) to
    assistant rows only. Audited as event_type `attunement`, op=feedback.
    Stored for later per-person learning; nothing consumes it yet.
  followup_suggestion: |
    GET /sessions/{id}/followup → {"suggestion": str|null}. Chat composer's
    greyed placeholder after each reply (Tab / → / inline chip fills it,
    never sends). Utility-fast call (`chat._fast_json_call`, shared with
    /chat/suggested-prompts) over the last 6 messages, each capped at 1500
    chars; transcript in the user turn, no cached system blocks. Null when
    the session doesn't end on a persisted assistant reply, or on model
    failure (not cached). Owner-or-principal only (403). In-process cache
    keyed (session_id, last assistant message id), 1h TTL.
  open_loops:
    module: openexecutive.attunement.open_loops
    pass: |
      `schedule_open_loop_pass` after every turn with a resolved rostered,
      non-archived speaker (both Executive paths, beside
      schedule_extraction). Keyword prefilter → atomic daily budget
      (`attunement_usage`, ATTUNEMENT_MAX_CALLS_PER_DAY=200) → one forced
      `record_open_loops` tool call (routing model). Opens: commitment by the
      speaker (owner=speaker); ask of a named rostered person; principal-
      attributed commitment of a teammate. Closes: loops the speaker reports
      done — own loops, or any when the principal speaks.
    gates: |
      Turns carrying an attached document ("[Attached: …]") are skipped: its
      text is inlined into the message (prepended on Telegram/Discord,
      appended on web), so a quote could be the document's words.
      Owner resolution: exact full name, or a UNIQUE first name only when the
      model gave a single token — never a first-name fallback from an unknown
      full name.
      The "speaker's own message" is the turn's speaker text
      (``executive._speaker_text``: ``memory_text`` when the entry point
      passes one, else the prompt) — never an inbound email's quoted chain
      or a briefing card's body, which would let the Executive's own words
      satisfy the quote gate. The email / upload filename note is
      "(Attached files: …)", deliberately not the "[Attached: …]" label
      below, so a turn with attachments is not skipped.
      Enforced in code: verbatim quote from the speaker's own message
      (commitments via `_is_valid_user_commitment`, asks/closures by
      normalized substring); owner resolves to exactly one rostered,
      non-archived person; teammates can't attribute commitments to others
      (hearsay); principal's own commitments left to the episodic extractor
      (team; see solo_dated_commitments); close ids must be in the closable set; per-owner cap
      ATTUNEMENT_MAX_OPEN_LOOPS_PER_PERSON=50; due date clamped to 60 days,
      default ATTUNEMENT_LOOP_DEFAULT_DUE_DAYS=2, date-only = 17:00 in
      the user's zone (workspace setting, else USER_TIMEZONE). Prompt says messages are data, not instructions.
    solo_dated_commitments: |
      Solo mode only. The turn's pinned mode reaches the pass
      (`schedule_open_loop_pass(..., workspace_mode=...)` from both Executive
      paths; None reads the workspace), with `principal_verified` =
      `people_tools.is_principal_on_verified_surface(session)` (default
      False, fail-closed). A principal commitment from an unverified surface
      (an email's sender is its From header) is dropped as
      `principal_commitment_unverified` before the date checks. Solo swaps the extraction system
      prompt for `_SYSTEM_SOLO` (a separate module constant, never formatted;
      team `_SYSTEM` is byte-identical, sha256 pinned in test_open_loops) and
      `_accept_loop(..., solo=True)` OPENS a commitment of the principal's own
      when it is dated: the model's `due_date` parses as YYYY-MM-DD
      (`_stated_due_date` — stated, never `_resolve_due`'s 2-day default) AND
      the quote matches `_STATED_DUE_HINT` — precision over recall:
      unambiguous words alone (full weekday, today, tomorrow, next week, end
      of Q4, in 3 days), explicit dates alone (Oct 3, 3 October, 2026-10-03,
      10/03), and short or ambiguous tokens (may, sat, wed, q1, the 14th,
      10/3) only after a due word (by / on / before / until / till / due /
      through); "I may", "the 1st draft", "50/50" never match. Otherwise it is
      dropped as `principal_commitment_undated` (an undated intention is an
      initiative). Owner = the principal, so the nudge engine chases it once
      overdue through their channel; when none reaches them it still
      surfaces in the solo brief's DUE THIS WEEK block and the Briefing's
      Due soon card (see today.solo_mode). Team behaviour is unchanged
      (`principal_commitment`). Eval: `attunement_002` (workspace_mode solo).
    assign: |
      Explicit assignment (F082) — the deterministic path beside the pass,
      which only runs on English keyword hits and what its model catches.
      `open_loops.assign_open_loop(owner_person_id, text, assigned_by_person_id,
      due_date)` returns `AssignResult(loop_id, reason, due_at)`; shared by the
      `assign_open_loop` chat tool and POST /people/{id}/open-loops. Refuses
      (reason): disabled (ATTUNEMENT_ENABLED / _OPEN_LOOPS_ENABLED off),
      unknown_owner, owner_is_contact (never chased), owner_archived,
      unknown_assigner (not an active team member), missing_text,
      owner_at_cap, duplicate (the scope_key index). Description has the
      pass's shape — "{assigner} asked {owner} for: {text}", or "{owner}
      committed to: {text}" when self-assigned (the principal included, in
      either mode). due_date is a local date → `_resolve_due` (17:00 user
      zone, clamped [today, +60d], default 2 days). Audited op `loop_assigned`.
      When someone assigns a task to somebody else, the owner is told once
      (`attunement.assignment_notice.notify_assignee`): fixed text naming
      the assigner, the task and the due day, via
      `scheduler.runner.deliver_to_person` under `tag_proactive("task_assigned",
      "nudge:commitment:<loop_id>")`. `people.notifications.hold_for` applies
      on every channel (quiet hours / "In my briefs" → `held_messages.hold`).
      Self-assigned sends nothing; ATTUNEMENT_ASSIGN_NOTIFY_ENABLED=false
      turns it off. The tool result and the route's response carry
      `notified` {status: sent|held|not_reached|skipped, channel}; a
      teammate assigner gets channel null and `later` for held. The task is
      quoted inert (`_quoted_task`: _MARKUP_DEFANG + a code span, no model
      in between, so no links or fake Executive text). Audited
      `task_assignment_notice`, private to the owner. Otherwise the owner is
      chased once due, like any loop.
      Who: the principal or any active team member may assign anyone on the
      team. Tool gate (`open_loop_tools._assigner`): principal on a verified
      surface (`is_principal_on_verified_surface`) or a teammate on one
      (`people_tools.teammate_on_verified_surface`, shared with
      fact_tools' teammate facts); never an unattended run, a turn private to
      the principal, or an email (even the principal's own). The tool's
      `task` must appear verbatim in the speaker's own words this turn
      (`delegation.settings.own_words` of the pinned speaker text — adapter
      tag blocks stripped, attachment turns refused), the same rule as
      verbatim_text, and language-neutral. Cap 20 per turn. A contact owner
      reads as `unknown_owner` unless `contacts_reachable_now()` (no contact
      oracle for teammates). `open_loop()` swaps `<`, `>` and `"` for
      look-alikes at insert (both paths): the text is quoted into the nudge
      intent and the runner's `<scheduled_intent>` block, and the People-page
      route stores typed text with no model in between. Known: the route has
      no per-assigner rate limit beyond the per-owner cap, whose 409 tells a
      teammate the owner is at the cap. Withheld via
      UNATTENDED_WITHHELD_TOOLS and PRIVATE_TURN_WITHHELD_TOOLS. The turn's
      assigned owner ids are kept per (audit session id, turn id)
      (`note_assigned_this_turn`); `schedule_open_loop_pass` passes that
      turn key and `_apply_opens` drops `assigned_this_turn` for those owners,
      so one ask is never two loops (closes still apply). Route: caller via
      `_resolve_caller_person_id`, 403 unless an active team member, contact
      404 to non-principals (`_visible_person`); refusals 404/409/422. GET
      stays principal-or-owner, so a teammate who assigns Ben a task does
      not see Ben's other loops. UI: People page "Assign a task" form under
      Open loops (list only for the principal or the person themselves).
    due_soon: |
      `open_loops.principal_due_soon(within_days=7, limit=10)` — the
      principal's (find_principal_person) open loops overdue or due within 7
      days, soonest first, as dicts: loop_id, description, due_at, due_date
      (the user's local date), state (overdue | today | soon). Empty with no
      principal or on a read failure (logged). Read by the solo morning brief
      and the solo /today header.
    storage: |
      `scheduled_actions` row: kind='open_loop', channel='__internal__',
      channel_ref='person:{id}', status inserted as 'done' (runner never
      dispatches), assigned_to_person_id=owner, awaiting_response_since=due,
      scope_key='loop:{owner}:{sha1(text)[:16]}'. Partial UNIQUE index
      `idx_scheduled_open_loop_scope` (kind='open_loop' AND awaiting NOT
      NULL) dedupes concurrent passes. Closing clears
      awaiting_response_since (reopenable later).
    readers: |
      nudge_engine commitment source (chased once overdue);
      `list_awaiting_replies_by_person` (/today awaiting counts, reflection's
      people-waiting) — only once due; excluded from
      `last_contact_at_by_person`, engagement_activity followups_completed,
      and the /today activity feed (`list_scheduled_actions(exclude_internal=
      True)` filters in SQL so loops can't starve its window; it also drops
      `brief_delivery` rows, the done row a brief's own send writes, so no
      brief reads its last message back as work done);
      `executive_reflection` OPEN LOOPS block (≤10, overdue flagged).
    closing: |
      Owner reports done (extraction pass); `close_open_loop` chat tool or
      POST /open-loops/{id}/close (principal or owner only — unresolved
      speakers and unattended sessions refused; tool withheld from
      reflection); People page "Mark done"; `people.store.archive_person`
      closes the owner's loops (live store only); TTL expiry
      (ATTUNEMENT_LOOP_TTL_DAYS=21) at the start of every nudge scan.
      Every open/close audited as event_type `attunement`.
    tools: |
      list_open_loops, close_open_loop, assign_open_loop (see assign)
      (orchestrator/open_loop_tools.py).
      Visibility: the principal sees everyone's loops only on a private surface
      (web chat, slack:dm:, discord:dm:, telegram:<positive id>); shared
      channels/threads, Telegram groups, Google Chat spaces and email threads
      show only the caller's own; unresolved caller refused. Security review
      finding (PR #175): an ungated list leaked what everyone owed into
      public channels.
    authorization: |
      One helper, `people.store.is_principal_or_self(caller, owner)`, backs
      close_open_loop, list visibility, GET /people/{id}/open-loops,
      POST /open-loops/{id}/close and the feedback route. Owner None =
      principal only.
    verbatim_text: |
      The stored loop `text` must itself appear verbatim in the speaker's
      message (drop reason `text_not_verbatim`): it is re-injected into the
      nudge intent a tool-using turn executes, so a model paraphrase could
      smuggle instructions. The nudge intent also says to treat it as data.
    api: |
      GET /people/{id}/open-loops, POST /open-loops/{loop_id}/close (both
      principal-or-owner); POST /people/{id}/open-loops {task, due_date?} →
      201 OpenLoopOut (any active team member; see assign).
    reset: |
      Loops live in scheduled_actions and attribution in chat_messages (both
      already wiped by client-slot switches and reset_all_state);
      `attunement_usage` added to `_BLANK_WIPE_TABLES` and reset_all_state.
    tests: |
      tests/conftest.py no-ops `schedule_open_loop_pass` for every test so
      Executive turns don't call a provider or write default-DB rows; tests
      of the pass call `run_open_loop_pass` directly.
  outcomes:
    module: openexecutive.attunement.outcomes
    why: |
      Nothing measured whether proactive outreach landed, so an always-ignored
      nudge kept going and an always-answered one ranked no higher.
    recording: |
      `tag_proactive(source, ref)` ContextVar (wrap non-yielding code only —
      never across an async-generator yield). `_record_outbound_context`
      (schedule_tools) calls `record_send` after inserting the linkage: a row
      only when tagged AND the recipient resolves to a Person. Tagged: runner
      generic dispatch via `_outreach_source` (proactive_nudge → nudge_stalled /
      nudge_commitment / nudge_initiative / open_loop [commitment target is an
      open_loop], ref = scope_key; else followup, ref action:<id>); reflection
      and research around their tool execution; alert review `_dm(alert_id=)`
      → alert_review, ref alert:<id>. Untracked: briefs and dynamic-workflow
      deliveries (no session → no linkage), broadcasts (no single recipient),
      web-chat sends (no linkage by design).
    resolution: |
      replied — `mark_outbound_context_consumed`. acted — close_open_loop with
      reason reported_done or done, only when closed_by_person_id is the owner
      (principal tidy-up, or the principal saying someone else's loop is done,
      credits nobody); `resumer.apply_resolution` resolves
      nudge:stalled:<run_id> for resolution.person_id only;
      store_initiative/update_initiative resolve nudge:initiative:<id> only on
      a real change (new status or summary) and only for
      `updated_by_person_id` — the extractor passes the principal (it runs on
      principal turns only), PATCH /memories/initiatives/{id} passes nothing
      (no caller identity, no auth) so it credits nobody; alert ack or resolved
      (`alerts.lifecycle.resolve_alert_outreach`, also called by alert review
      when it closes an alert) — scoped to routed_to_person_id + principal.
      void — alert dismissed / stale / expired (expiry sweep): excluded from
      every rate, so a dismissal (POST /alerts/{id}/ack has no per-caller
      authz, pre-existing) can never push someone toward demotion. acted and
      void override an earlier ignored (done after the sweep is the truer
      verdict); replied does not. ignored — `sweep_ignored` at the start of
      each nudge scan AND lazily in acceptance()/muted_pairs() (rates stay
      honest with NUDGE_SCAN_ENABLED=false). Recording skips email cc's (only
      the first rostered `to` address) and principal self follow-ups.
    use: |
      `acceptance()` per (person, source), 30 days, voids excluded.
      nudge_engine `_apply_outcome_feedback` uses `muted_pairs(min_sends)`:
      demoted when the person's LAST ATTUNEMENT_MUTE_MIN_SENDS (5) resolved
      sends of that source (ordered by created_at) were all unanswered → cooldown x
      MUTE_COOLDOWN_MULTIPLIER (3), ranked last in `_apply_caps`; never
      dropped; one answer lifts it (a 30-day share would not — review
      finding). Reflection WHAT LANDS block (sources with >=3 resolved).
      GET /people/{id}/outreach (auth before 404) → "How they respond" card.
    table: proactive_outcomes (episodic DB); wiped by slots + reset_all_state.

  style:
    module: openexecutive.attunement.style
    why: |
      Style profiles alone would not make the Executive more proactive, but a
      few pinned rules per person ("lead with the recommendation") stop it
      repeating what someone has already thumbed down. Kept deliberately
      small: max 8 rules, evidence-cited, editable and lockable. A rule the
      person asked for in a chat is added by the conversation review with
      basis conversation and kept by the pass like a typed one.
    evidence: |
      Last 40 attributed user messages (chat_messages.sender_person_id), each
      paired with its own reply (the first assistant row before the next
      user row), with the reaction THE PERSON gave it: feedback where
      feedback_by_person_id == person (new column; the feedback route stores
      the rater), feedback_note, stopped. basis feedback → a cited reply
      carries a reaction; basis stated → quote verbatim (NFKC, casefold) in a
      cited message. Honcho is not read or written.
    validation: |
      rule_rejection(): 8-160 chars; Latin-script letters only (confusables
      like Cyrillic "а" would dodge the regexes); deny-list (URLs/domains,
      @handles, currency, <>{}[]`, snake_case, action verbs send/approve/pay/
      schedule/delete..., act-without-checking words confirm/proceed/go ahead/
      judgment/decide/allow..., ignore/override/instructions/prompt/tool,
      secrets) and roster names (full and first names >=3 chars); allowlist
      _STYLE_TOPIC — must name a reply aspect (length/format/tone/detail/lead...).
      Security review: a verb deny-list alone let "skip confirming and just
      proceed" through; the allowlist + act-without-checking list close it.
      Round 2 widened that list (check*/verif*/pause*/instinct*/trust*/...)
      and added render-time revalidation: build_style_block drops any stored
      rule that fails rule_rejection today, and PUT without rules drops them
      too. Round 3 added yes/agree/caution/careful/risk/safe/speed/slow/
      hurry/rush/doubt/default/whatever/anything/everything. A lexical list
      can't be exhaustive; the bound is scope: a rule only reaches its
      owner's turns and comes from that owner (or the principal), who could
      say the same thing in the message itself. Header ("style only, never
      authorizes an action") is the other layer. PUT edits use the same check
      (422). build_style_block scrubs with utils.prompt_blocks.scrub_block_line
      (shared with honcho _block_safe_line).
    pacing: |
      schedule_style_pass(person_id) after every Executive turn (stream + committee)
      and with force=True from the feedback route on a thumbs-down (for the
      rater). _claim_pass: >=5 total messages; new messages since
      last_message_id >= ATTUNEMENT_STYLE_TRIGGER_TURNS (10) unless forced;
      one conditional UPDATE (locked=0, watermark unchanged, last_pass_at
      older than MIN_INTERVAL_HOURS (2), passes_today < MAX_PER_DAY (4)).
      Then consume_call_budget (shared ATTUNEMENT_MAX_CALLS_PER_DAY). Write
      is optimistic: only when updated_at is unchanged and still unlocked;
      the watermark advances regardless. MAX_PER_DAY<=0 → no pass; interval
      floored at 1 minute (it is also what loses a racing second claim).
      Rules with basis "edited" (typed by a person) are pinned: the model
      sees them, gets RULE SLOTS AVAILABLE = 4 - pinned, and returns only
      learned rules. Explicit empty list → learned rules dropped; missing
      "rules" key or all-invalid list → no change (logic review: an empty
      "keep" made a contradicted sole rule permanent). The thumbs-down
      trigger fires only when rated_reply_speaker(session, message) == the
      rater. Roster-name check: full names any case; name parts only
      capitalized past the first word (a "Max Short" must not ban "short").
    applying: |
      Executive computes build_style_block(person_id) once per turn and passes
      it to _build_messages (<working_style> after <current_speaker>, user
      turn, never cached) and _emit_memory_snapshot (working_style_chars +
      full text). person_id is the resolved speaker; archived / unrostered →
      no block.
    api: |
      GET/PUT/DELETE /people/{id}/attunement — principal or that person; 404
      for archived. PUT without `rules` only sets the lock (keeps provenance).
      UI "How I work with them" card.
    tables: attunement_profiles, attunement_profile_history (episodic DB); wiped by slots + reset_all_state; dropped on archive.

departments:
  module: openexecutive.departments
  store: openexecutive.departments.store (SQLite, shares episodic_memory.db)
  models: openexecutive.departments.models — Department, Goal, ChecklistItem
  registry: openexecutive.departments.registry — in-memory cache + CRUD API
  api: /departments — CRUD for departments, goals, and checklist items
  authority_gate: |
    openexecutive.departments.authority — each department declares a mode.
    `propose_only` departments route scheduled actions to an approver as a
    briefing alert (`propose_via_alert`) instead of executing immediately;
    the scheduled_actions row is then marked done and the pending-ness lives
    on the alert. A `dept_cadence` fire is exempt (see `cadence`): the
    check-in sends nothing and gates each action it proposes. This is NOT the `wait_for_human` workflow gate — that is a
    separate primitive with its own table (`workflow_runs.status`), delivery
    path and resolver; an earlier version of this note conflated the two.
    Autonomous departments fire actions directly. The approver is
    selected by AuthorityScope: each scheduled_actions row may carry
    a `required_scope` column (e.g. `vendor_onboarding`, `spend_lt_10k`,
    `hiring_signoff`) which the runner parses and passes into
    `gate_action`; `find_approvers(scope)` then ranks non-principals
    holding that scope ahead of WILDCARD-holders, so proposals can route
    to a domain owner instead of always falling back to the principal.
    A null/unknown `required_scope` falls back to WILDCARD (principal).
    As the scheduler files a propose or escalate card it records which row
    the card holds in `alert_held_actions` (`alerts.approvals.record_held_action`).
    Approving one (`POST /alerts/{id}/approve`) queues a copy of that exact
    row with no department, so the approval is the consent the gate waited
    for and nothing re-reads the card's prose to decide what to send. The
    binding is a server-side table on purpose: a first cut used a
    `scheduled_action:<id>` topic tag, but tags, body and source can all be
    written by a model (triage reading inbound mail, the Executive's
    create_alert), and the review forwards an alert's tags onto a new gate
    card, so a forged tag could re-send a held or already-sent action.
    CHAT TURNS (orchestrator.department_gate): a team member's attended turn
    (caller is a team member, not the principal; not unattended, not private
    to the principal; or a web caller signed in but on no People entry, such
    as an archived teammate still let in, or a chat-channel turn (any
    origin_channel but email) whose sender matched no one, gated as someone
    in no department. Slack, Telegram and Discord reject unmatched senders
    before the turn, so in practice that is Google Chat. Google Chat matches
    its sender by the Google account email on its signed event and sets
    Session.gate_sender_person_id, read only by the gate (never
    caller_person_id, since Google Chat is not a verified speaker surface),
    so the principal there is not held and a teammate gets their own
    department's authority. Email is left out: inbound senders are never
    on People and the mailbox has its own recipient gates)
    wraps its sends and edits with the gate, in
    Executive._stream_agent_loop beside Take the lead's `leading` wrap:
    `turn_handlers` for GATED_TOOLS (take_the_lead.ACTING_TOOLS less
    assign_open_loop, which refuses any session but the asker's so a held one
    could never run, and run_workflow, whose action steps are approved step
    by step; under escalate those two are refused outright, since both lead
    to sends later and neither can wait on a card), and `call_tool` (chat and run_script) for every name
    `mcp_tool_acts` flags. The gate wrap sits inside guard_call_tool, so the
    gateway's recipient and mailbox gates still run first. Level = strictest
    of the speaker's department_slugs (escalate > propose_only >
    auto_execute; unknown slug = propose_only; none = propose_only, routed
    via _route_proposal). auto_execute runs; propose_only runs only when the
    speaker holds a range from EVERY group of approval ranges it needs (one
    group per kind the text touches: money, contract, people decision, board;
    or WILDCARD), since they would be the approver anyway. Every group, not
    the first: Take the lead's single-kind read let a $12 mention make a
    petty-cash holder the approver of a termination letter; escalate always holds, and an
    approver equal to the speaker is replaced by the next one
    (find_approvers, else the principal). An action reaching anyone outside
    the team goes to the principal (only their approval opens contact
    egress). A message only to the principal runs (nothing to approve). Held
    = decision class `department_action` (idempotency key per speaker+call,
    same live card on a repeat), alert source decision_scheduling routed to
    the approver, private tag when the approver is the principal (else the
    card shows the unquoted line), audit department_action_held (actor
    person:<speaker>, private to the principal or to the approver alone).
    The payload keeps `details`, every field of the call in full, and the
    UI's HeldActionCard loads it (GET /decisions/{id}) and keeps Approve off
    until it is on screen: the summary keeps only the first 117 characters,
    so an injected tail would otherwise be approved unseen. Approve (api.routes.decisions,
    principal_and_approver) runs take_the_lead.carry_out once after
    claim_for_execution and audits department_action_done/_failed;
    reject audits department_action_declined. The activity rail skips the
    class, since its payload quotes the conversation. Fails closed: a gate
    error holds. Why: gate_action used to run only for unattended work and
    propose_meeting, so a seat's Slack DM or Gmail send from chat skipped
    propose_only and escalate.
  card_approvals: |
    openexecutive.alerts.approvals + POST /alerts/{id}/approve. Approve on
    a Today card is carried out on the server for every card. A
    decision-backed card goes through /decisions as before. Every other
    proposal (the alert review's, a department gate's) is approved here:
    `approvals.claim` checks and flips the card to `ack` and inserts an
    `alert_approvals` row (alert_id, approved_by_person_id, approved_at,
    edited_body, status running|done|failed, outcome, session_id,
    finished_at) inside one BEGIN IMMEDIATE transaction, so a double click
    or two approvers never run it twice (409). A card whose last approval
    failed can be claimed again (Try again); one still running at a restart
    is marked failed on boot (`fail_stale_running`, api/main.py lifespan).
    Audit rows: alert_approved (actor person:<id>), then
    alert_approval_done or alert_approval_failed, private when the card is.
    Work: a card bound to a held scheduled action re-queues that action (see
    authority_gate); anything else runs one Executive turn as the approver
    through `chat.start_background_turn` (the code behind POST
    /chat/background), so the turn is that person's, under their own access,
    and keeps going after the tab closes; its session_id is on the row and
    the drain reports whether the stream ended on an error frame. The
    instruction text moved from Briefing.tsx to
    `api.routes.alerts.APPROVED_PROPOSAL_PROMPT` /
    `APPROVED_WITH_EDITS_PROMPT`, with the same memory line the briefing's
    other handoffs use; the card's text goes in a <proposal> block marked
    as data, since it can quote inbound mail and the turn now runs with no
    one watching. Who may approve: a routed card only its person or the
    principal; an unrouted card only the principal (Today's "principal owns
    unrouted" rule). GET /alerts/approvals/{id} answers only the approver,
    the card's person and the principal, since the row quotes an edited
    message. A failed row says the turn may have done part of the work, so
    the person checks its chat before Try again. Why: the page used to ack the card and
    paste the proposal into a new chat turn. Nothing recorded who approved
    it, and if the tab closed before the turn ran the card was gone and
    nothing was done.
  cadence: |
    openexecutive.departments.cadence — supports `daily@HH:MM`,
    `weekly@DOW@HH:MM` or `weekly@DOW-HH:MM` (DOW is a 3-letter day,
    e.g. `weekly@thu@09:00`), and `quarterly@DD-HH:MM`. Times are UTC.
    `PATCH /departments/{slug}` rejects a spec that does not parse (bad
    format, unknown DOW, out-of-range time) with a 422 naming the valid
    formats (`is_valid_cadence_spec`); an empty spec means no cadence
    (the department page's Off). A new department starts with
    `weekly@mon@09:00` (charters.DEFAULT_CHECK_IN_CADENCE, used by
    store.create_department and the catalogue seed). It was `daily@09:00`;
    departments created before the change keep their cadence (no
    migration). Why weekly: most goals do not move in a day, and a daily
    check-in meant a check-in card per department every morning. A changed
    `check_in` on PATCH re-times the department at once
    (`reschedule_check_in`: cancel its pending dept_cadence rows, then
    `enqueue_next`, which queues nothing for an empty spec or in solo), so
    switching it off does not leave one more check-in on the old schedule.
    A running check-in is left alone; its chain adds nothing because the
    new row is pending (or, when off, `enqueue_next` returns None).
    `GET`/`PATCH /departments/{slug}` return `DepartmentDetail` — the
    state plus `next_check_in_at` (`next_check_in_at()`: the earliest
    pending dept_cadence run_at, or null). The page's picker is Daily /
    Weekly (day + time) / Off over that spec (UI lib/checkInCadence.ts);
    a spec it cannot show (quarterly) is kept as-is until one is picked.
    `_parse_cadence_spec(spec, after, tz=UTC)` also takes a zone: it builds
    the wall-clock time in that zone and only then converts to UTC, so a
    local schedule is DST-safe (a time the spring-forward gap skips fires
    once, just after the jump; a time the fall-back repeats fires at its
    first occurrence). Department and dynamic-workflow cadences keep the
    UTC default; the principal's briefs and reflection pass the user's zone
    (see scheduler.kinds). In solo mode `bootstrap_cadences` is a no-op —
    the check lives inside it because the lifespan, the fixture reset and
    client-slot activation all call it — `enqueue_next` chains nothing in
    solo (a check-in running across the switch finishes without a
    successor), and `cancel_pending_cadences` cancels every pending
    dept_cadence row when the install switches to solo.
    The scheduler runner runs the `department_check_in` workflow when a
    cadence is due, then `enqueue_next()` chains the following
    occurrence. The fire is NOT passed through the authority gate
    (`kind != "dept_cadence"` in `_execute_action`): cadence rows always
    carry their department and new departments are propose_only,
    so gating it turned each check-in into a one-shot proposal card,
    marked the row done and never chained — the chain died until the next
    boot. The check-in has no outbound side effect (goal verdicts, one
    audit row, a Honcho note), and each action it proposes still gets a
    `gate_action` verdict in the artifact. Skip rule, evaluated BEFORE
    `create_run` so an idle department costs no specialist calls and
    leaves no empty run in the activity rail
    (`department_check_in.needs_check_in`): skip when the department has
    no `specialist_key`, has no Goals, or nothing is new since the oldest
    Goal's `last_reviewed_at` — no decision tagged to the department
    (`episodic.has_department_decision_since`) or audit row tagged to it
    (the check-in's own `goal_status_review` row, actor
    `department_check_in`, excluded; `AuditLogger.query(department=…)`),
    both filtered in SQL so other departments' volume cannot hide them,
    and no Goal whose `updated_at` is later than its own
    `last_reviewed_at`. A never-reviewed Goal always runs it; an
    unreadable source fails open (runs). A skipped occurrence still
    chains and is recorded `cancelled` with `skipped: <reason>` in
    `last_error` — NOT `done`, because `nudge_engine._dept_cadence_recent`
    reads a done cadence row as a check-in that covered the department's
    idle initiatives. A check-in that keeps failing is retried with
    backoff (`mark_action_failed_or_retry`); once it returns `failed` the
    runner chains the next occurrence anyway (unless this attempt already
    chained before failing), so one broken department does not drop out
    of its cycle. Chaining is idempotent (`runner._chain_dept_cadence`
    adds nothing while a `pending` dept_cadence row for the department
    exists), so a row that chained and then failed to record its outcome
    — left `running`, requeued by the boot sweep — never duplicates the
    next occurrence. Cost note: with the gate bug
    fixed, check-ins actually run — about three specialist calls each —
    bounded by the skip rule (a department with no Goals skips until
    someone adds one). Lifecycle cleanup: deleting a department cancels its
    pending `dept_cadence` rows in the same transaction, and the
    lifespan runs `cancel_orphaned_cadences()` on boot (before
    `bootstrap_cadences`) to cancel pending cadences whose department no
    longer exists — so a removed department stops firing check-in alerts.
  seeding: |
    Nothing creates departments at boot: a new install, a blank client
    slot and the factory reset all start with none. Setup's commit
    (onboarding/commit.reconcile_onboarding_departments) creates only the
    departments its draft names, so a solo workspace or a team that names
    none has zero, and the create_goal chat tool creates one when a goal
    names an area that has none. A department named after one of the eight
    catalogue areas (departments/charters DEFAULT_DEPARTMENTS) starts from
    that area's charter (store.default_charter_for, applied inside
    create_department unless a mission is given), and setup and create_goal
    wire it to the matching specialist (store.specialist_key_for_area, at
    most one department per specialist). Why: eight empty departments meant
    eight check-ins in Coming up, eight empty cards and "no head"
    warnings for companies that never had those functions. Workspaces
    created before this keep what they have; nothing is removed.
    store.seed_default_departments still inserts the full catalogue once
    per database (tracked by the `default_departments_seeded` row in
    `departments_meta`), but only tests and tooling call it.
  workspace_settings: |
    openexecutive.memory.workspace_settings — one row (id=1) in
    `workspace_settings` (episodic DB): `mode` ('team' default | 'solo'),
    `timezone` (IANA, NULL = fall back to USER_TIMEZONE, then UTC), and the
    principal's role — `role_kind` (owner | in_house | independent | other),
    `role_title`, `reports_to`, `remit`, `measured_on`, all nullable TEXT
    (PrincipalRole; WorkspaceSettings extends it). The role columns are added
    additively (_ensure_schema: PRAGMA-guarded ALTER TABLE ... ADD COLUMN,
    run by init_workspace_settings_db and every write — so a client slot
    restored from an older state.db gets them via clients.slots.
    _ensure_schemas); a read (SELECT *) of an older table never migrates it
    and reads the role as unset, and a stored role value that no longer
    validates is ignored field by field. Text is trimmed, blank = unset,
    capped after trimming at 120 (role_title, reports_to) / 500 (remit) /
    300 (measured_on) — ROLE_TEXT_MAX, shared by the API, fixtures and eval
    scenarios; validation errors never quote the value.
    Its own table, not a CompanyProfile field, because onboarding's commit
    and the form wizard rebuild the profile from scratch and would wipe it.
    Reads are fresh and read-only (a missing file/table reads as the
    defaults and is never created) and NEVER raise — the lifespan, every
    turn and the scheduler read them: a read error reads as the defaults
    with a warning (traceback at debug), and a stored zone that no longer
    loads is treated as unset. Every zone name from a user, a file or the
    DB goes through `load_zone`, which catches everything zoneinfo raises
    (not only ZoneInfoNotFoundError: "America" is IsADirectoryError,
    "Europe/" and "../etc" ValueError) — so a bad zone is a 422 on the
    API, a skipped value in a fixture, never a 500 or a failed boot.
    API: get_workspace(), read_stored_mode() (the stored mode, the default
    when nothing is stored, or None when the read fails or the value is not
    a mode — for callers that must not treat a failed read as team: the
    scheduler's weekly-review retire/chain check),
    get_user_timezone() -> ZoneInfo, set_timezone(tz) (validated like
    USER_TIMEZONE; re-times the principal's briefs in place via
    scheduler.runner.reschedule_principal_rhythm when the zone in effect
    moves), set_workspace_mode(mode) (solo cancels pending dept_cadence
    rows and seeds the weekly review; team re-runs bootstrap_cadences and
    cancels the pending weekly review; department rows stay),
    effective_workspace_mode(session) (Session.workspace_mode override,
    else the mode pinned for the session's turn, else the workspace),
    pin_turn_workspace_mode(session) (resolves override-else-workspace at
    the start of a turn and pins it on Session.turn_workspace_mode;
    Executive.stream_chat and the committee path call it, reflection and
    research pin their own run's mode on their synthetic sessions — and the
    caller's effective_principal_role as turn_principal_role),
    set_principal_role(**fields) (validates every field before writing; no
    side effects — the next turn reads it), effective_principal_role(session)
    (Session.principal_role override, else the role pinned for the turn,
    else the stored role), pin_turn_principal_role(session, mode) (at the
    start of a turn, with pin_turn_workspace_mode: solo pins the override
    else a fresh read on Session.turn_principal_role, team pins an empty
    role — so a workflow the turn starts, whose specialists read the role
    via router.load_principal_role, sees the org block's role even after a
    mid-turn PUT; the next turn re-resolves).
    HTTP: GET /workspace, PUT /workspace
    (principal-only, open before a principal exists; the role fields are
    optional in the PUT body like timezone, null/blank clears one). GET
    stays open, but returns the role only to a caller the PUT would accept
    (_caller_is_principal_or_unclaimed) and nulls to anyone else. Per company: blank
    client slots wipe it (clients.slots._BLANK_WIPE_TABLES), saved slots
    carry it in state.db, and the factory reset returns it to the defaults
    before re-bootstrapping. Fixtures: `_apply_state_from_source` reads and
    validates the source's optional workspace.yaml before swapping anything
    (bad values are logged and skipped, never abort the load); a fixture
    load resets to the defaults and applies it (optional role keys
    role_kind / role_title / reports_to / remit / measured_on, each skipped
    with a warning naming only the field when invalid; _apply_workspace
    returns the mode and zone only — model_dump(exclude=ROLE_FIELDS) — since
    it becomes the `workspace` key of the POST /fixtures/{name}/load and
    /fixtures/unload responses, which do not check the caller); the user snapshot
    writes one (every field, so the role round-trips), and a load while the live state is the user's own (no fixture, no
    client active) rewrites `_user_backup/workspace.yaml` even when an
    older backup is reused — unload keeps `_user_backup`; an unload from a
    backup with no workspace.yaml (one that predates it) leaves the current
    settings as they are instead of resetting them. The
    lifespan skips check_org_completeness in solo (it only warns about
    departments with no head).
  head_persona: openexecutive.departments.head_persona — generates a department-head voice persona when a head is assigned.
  completeness: openexecutive.departments.completeness — measures how much of a department's required state is filled in (used by the Getting Started checklist).
  prompt_block: |
    openexecutive.departments.prompt_block.render_org_block(mode="team") —
    produces the cached org block in system block 1. mode="solo" renders
    "## Your Principal" (the principal's name, person_id, reachable channels
    and preferred channel), followed — when a role is set — by role lines
    ("- Role: <title> — <kind in plain words>", "- Reports to:",
    "- Responsible for:", "- Measured on:", each only when set, _safe()
    sanitized and capped at ROLE_TEXT_MAX), opened by the static
    _SOLO_ROLE_LEAD_IN ("Their role — private to them: use it to tailor your
    advice and drafts, and don't share it with anyone else.") whenever any
    role line renders — block 1 goes out on every turn whoever sent it, and
    reports_to / measured_on are the principal's own; then "## Your Principal's Goals" grouped by area
    (area title +
    slug, each goal's period, key result, target, current, status and
    goal_id); areas with no goals are skipped; no authority levels, heads,
    cadences, channels or People roster. The principal is
    people.store.find_principal_person (the oldest non-archived principal),
    the same rule every solo check uses (principal_only_handlers, the
    follow-up rule, the meeting gate, reflection's principal line,
    research's principal roster), so the person named is the person those
    checks let through; a failed lookup drops the line, never the goals
    (nor the role lines: with no principal to name, "## Your Principal"
    holds just the role). render_org_block(mode, principal_role=None): the
    chat turn passes effective_principal_role(session) through
    build_system_blocks(principal_role=…); None reads the workspace's. Team
    mode never reads or renders it (byte-identical).
    Headings name the principal from the Executive's side ("Your
    Principal"), never "## You", which it could read as its own identity.
    Deterministic, sanitized, and held to the same 4000-char cap (the
    principal's line comes
    first so the cap only ever cuts goals).
  charters_dir: openexecutive.departments.charters — per-department playbooks loaded into the head persona.
  watched_entities: |
    `DepartmentConfig.watched_entities: list[str]` — external entities
    (vendors under evaluation, competitors in the department's lane,
    tickers) the department wants monitored. Column
    `watched_entities_json TEXT NOT NULL DEFAULT '[]'`, added additively by
    `_migrate_add_watched_entities_column` (same PRAGMA-guarded pattern as
    the channel columns); a corrupt value reads back as []. PATCH
    /departments/{slug} accepts `watched_entities` (<= 50 items, each
    whitespace-collapsed, <= 128 chars, case-insensitive de-duplicated;
    `[]` clears). Edited on /departments/{slug} ("Watched entities", one
    per line). The research watch policy treats each as a strong
    `department_entity` grounding term tagged with the department, so a
    proposal about one can be added directly and is routed to the
    department and its head — see research_watch_policy.
  channels: |
    Each department can optionally configure `slack_channel_id`,
    `discord_channel_id`, and `telegram_chat_id` on its row. When set,
    the Executive can post to the department's team room via
    `send_department_message` instead of (or in addition to) DMing
    the head. Nullable — a department with no channel configured has
    no broadcast surface and OE falls back per the "Choosing Who to
    Tell" rule (DM the head). Configure on /departments/{slug}.
    Migration in `_migrate_add_channel_columns` adds the columns
    additively on every boot (PRAGMA-guarded duplicate-column tolerance
    mirrors the episodic.py pattern).
  goal_review_persistence: |
    The `department_check_in` workflow's `goal_status` step (Phase A)
    asks the specialist to return strict JSON:
      {"verdicts": [{"goal_id": int, "status": "on_track" | "at_risk"
                     | "off_track", "rationale": "<one sentence>"}, ...],
       "narrative": "<paragraph rendered into the artifact>"}
    `_parse_verdicts` in `workflows/department_check_in.py` strips
    ```json fences, drops malformed verdicts, and degrades silently to
    `([], text)` on any JSON error — the artifact still ships even when
    nothing was parseable. Valid verdicts are persisted via
    `store.record_goal_review(goal_id, status=…, last_reviewed_at=now)`,
    a thin wrapper that updates ONLY those two columns and does NOT
    bump `updated_at`. The split lets the UI render an honest "Last
    reviewed Nd ago" — a human content edit on Tuesday and an OE
    review on Wednesday remain distinguishable. A new `last_reviewed_at
    TEXT` column on `department_goals` is added by
    `_migrate_add_last_reviewed_at_column` (additive ALTER, mirrors the
    channel-columns migration). Every workflow run emits a single
    `goal_status_review` audit row tagged `actor=department_check_in`,
    `department=<slug>`, with `details.transitions = [{goal_id, from,
    to, rationale}, ...]` — keeping audit volume bounded (~8 rows/day
    default). Always overwrites: the diff trail lives in audit, and the
    principal retains the manual UI edit path as the final override.
    The Honcho mirror fires inside `record_goal_review` with
    `transition="reviewed"` so the dept peer's notes timeline
    distinguishes cadence reviews from content edits. Also writable
    from chat via the `update_department_goal` agent tool (Phase B —
    see `routing.department_tools`), which extends `update_goal` with
    an optional `last_reviewed_at` kwarg so a chat-driven content edit
    AND review-touch land in one transaction.

people:
  module: openexecutive.people
  store: openexecutive.people.store (SQLite)
  models: openexecutive.people.models — Person (name, role, department, principal flag, kind, contact channels, availability windows, on-leave date)
  kind: |
    `Person.kind` is "team" (the default) or "contact" — someone outside
    the team (a client, contractor, advisor) the Executive may need to
    email or invite but who must get nothing a team row grants. Column
    `kind TEXT NOT NULL DEFAULT 'team'`, added by the PRAGMA-guarded
    additive migration in `people.store.initialize_db` (existing rows are
    team). The principal is always team: `upsert_person` /
    `update_person` raise `PrincipalContactError`, the API answers 422, and
    `initialize_db` repairs a hand-edited principal contact on boot. An
    unknown stored value reads as "contact". `upsert_person` with
    `kind=None` keeps the stored kind on UPDATE, so a full-row rewrite
    (onboarding, fixtures, the chat tool) never promotes a contact to the
    team — that would grant sign-in.

    DENY BY DEFAULT: `store.list_people`, every `find_person_by_*`
    (including `find_person_by_channel_ref`) and the `people.registry`
    cache return team members only unless called with
    `include_contacts=True`; `find_approvers` has no opt-in. So contacts
    are excluded from web sign-in (`/auth/allowed-emails`), the Slack /
    Telegram / Discord inbound gates and co-presence, approvers, the
    alert review's roster slice, `/today` people and insights, open-loop
    owners (an ask of a contact opens no loop the nudge engine would
    chase), workflow approval/cadence people (`dynamic_models._person_exists`),
    the post-meeting recap DM, department heads (chat tool and
    `PATCH /departments/{slug}`), and alert routing (`create_alert`
    drops a contact assignee). `get_person(id)` returns either kind; the
    callers that act on the result check `kind`.

    OPT-IN callers, and only these: the MCP gateway's egress allow-list
    (`mcp_gateway._roster_allow_set`, a `people.identity.RosterAllow`),
    calendar attendee resolution
    (`calendar_tools._resolve_attendees`), the chat DM gates
    (`schedule_tools._dm_recipient_on_roster` and person-id recovery),
    the People page listing (`GET /people?include_contacts=true`), the
    chat `list_people` tool, the org prompt block's `## Contacts`
    section, the email poller's contact lookup (to word its notice), the
    roster-request intake (each chat adapter's `_hold_unknown_sender` looks
    the sender up with contacts included only to leave a contact out — see
    `people.roster_requests`), roster-request suggestions and linking, and
    the style deny-list (`attunement.style._roster_names` — more names is
    stricter).

    PRIVATE TO THE PRINCIPAL: a contact exists only on the principal's
    own verified turn (`people_tools.contacts_reachable_now` — the #216
    roster-write rule, or `grant_contact_egress`). Everywhere else every
    opt-in above behaves as if no contact existed: `list_people` returns
    the team with the same count, a contact's id or address gets exactly
    the unknown-person error (no contact-specific refusal), and the org
    block has no Contacts section. The API decides by caller
    (`api.routes.people.caller_is_principal` — the signed-in email is the
    principal's, or no x-caller-email; unlike `_require_roster_owner`,
    nobody is while no one is principal yet): `include_contacts` is
    ignored for anyone else, a contact's id is a 404 on get and
    open-loops exactly like a missing id (patch and archive are already
    a 403 for them, before any lookup), and only the principal may
    create a contact or turn someone into one (403, a first setup with
    no principal included); `GET /people/me` returns {person_id,
    is_principal} for the UI.

    What the Executive raises about a contact stays private too
    (`alerts.models.PRIVATE_ALERT_TAG` = "private:principal",
    `is_private_alert`). A meeting with a contact is proposed to the
    principal, its payload is marked `private` (hidden from anyone else's
    `/decisions`, 404 by id and on every action) and its card is tagged.
    A turn about the principal's private mail
    (`Session.private_to_principal`, set by the email poller for contact
    mail and principal forwards) raises private alerts (`AlertEvent.private`:
    tagged, routed to the principal, persisted only — no live push, email
    or broadcast — and deduped only against other private alerts), can
    email / DM / invite only the principal (`PRIVATE_TURN_REFUSAL`), and
    is neither offered nor allowed to run
    `schedule_tools.PRIVATE_TURN_WITHHELD_TOOLS` (the chat loop drops them
    before the sort and answers a call the model emits anyway with
    `private_turn_withheld_error`, audited). The set is everything that
    reaches someone else, publishes where others read, or starts work
    outside the turn: send_company_broadcast and send_department_message
    (post to the team); cancel_calendar_event (notifies every attendee);
    create_calendar_event and create_instant_meeting (the booking is on
    everyone's /decisions, in team mode proposed to the meeting approver,
    and schedules a recap run); run_workflow and run_executive_research
    (their steps message people and department channels);
    schedule_followup and suggest_workflow (queue a later run that is not
    private and can go through a department approver, shown on the
    activity list); add_watchlist_entry (monitoring whose alerts are not
    private, the entry on everyone's /watchlist); draft_artifact (visible
    to the whole team; its handler refuses too); update_department_goal
    (goal text in every turn's org block and on /today); save_workflow
    (listed on /jobs); load_mcp_server (connects to any HTTPS URL,
    which can itself carry the turn's content — the dispatch guard covers
    MCP tool uses too). Of the MCP tools it may use only
    `schedule_tools.PRIVATE_TURN_MCP_TOOLS` (Google Workspace reads and the
    Gmail send / draft the gateway narrows to the principal): search_tools
    shows it nothing else and a call_tool naming anything else is refused
    the same way (`schedule_tools.private_turn_withholds`; see
    integrations.mcp_gateway).
    Left offered: the email / DM / invite paths
    (they reach only the principal; Gmail goes through call_tool, whose
    Gmail / Calendar / Drive gates narrow recipients to the principal),
    create_alert (private on such a turn),
    reads, propose_form_values (the caller's own screen, and email has
    none), ack_alert / close_open_loop / tune_ / remove_watchlist_entry
    (carry nothing from the turn to anyone); the roster tools and
    create_goal refuse every private turn already (principal on a verified
    surface only). A private alert shows on the principal's
    own `/today` and chat digest only: `_build_today` excludes it by
    default (digest, reflection, Discord /today; the morning brief reads it
    only on a run for the principal — morning_brief.PRINCIPAL_DELIVERY or
    their verified chat turn — and then keeps its text out of run history),
    the narrative includes it only in the principal's own `principal` scope
    (an unresolved caller gets the `company` scope), the activity rail never
    includes it, the alert review never selects
    it nor uses it as evidence, and a non-principal ack / reopen gets 404
    and their bulk sweep skips it. DMs to a contact are not written to
    the activity rail.

    THE AUDIT LOG (/audit, readable by every signed-in user) keeps what is
    private to the principal to the principal: every row a private turn
    writes, the poller's inbound rows for contact mail and principal
    forwards, a private alert's row, and any row on the principal's own
    verified turn that names one of their contacts are
    `private_to_principal`, and every read route leaves them out for anyone
    else (see `audit.private_rows`). The rows themselves carry no
    contact-specific signal either: contact mail is logged exactly like any
    outside sender's (`accepted_non_roster`, and the contact notice opens
    with the non-roster notice's sentence so memory_snapshot's
    user_message_preview matches); `upsert_person` rows are name- and
    kind-free for everyone (person_id + action); `list_people` rows count
    the team only; `list_people` / `upsert_person` inputs and results are
    redacted in the Executive's tool rows (`audit.redaction`, every call);
    `set_department_head` and `PATCH /departments/{slug}` answer a contact
    exactly like an unknown id, with no name; no outbound reply linkage is
    recorded for a contact (their reply would otherwise be hydrated with
    the principal's conversation). PEER MEMORY: a private turn writes
    nothing to peer or department memory, and a person's peer memory
    answers only them (`ask_about_person` answers fully only when
    `person_id` is the verified asker; `/memories/people` and
    `/conclusions` show each caller only their own entry, the principal
    included), unless they turned on "Share my work style with the team"
    (Settings → About you, `history_work_style_sharing`, a team member in a
    team workspace, off by default): then a verified principal or teammate
    (never an inbound email, unverified chat or unattended run) may ask how
    they work, the question wrapped in `people_tools.WORK_STYLE_FRAME` (role,
    focus, how they like updates, working style; no health, family,
    personal life or quotes; prompt guidance, not a filter) and
    `target_person_id` refused; off a contacts-reachable turn, a question or
    answer naming a contact (`_names_a_contact`) is refused or withheld. Not shared answers `shared: false` with the
    same note whether or not anything is known. Still open: a row on the
    principal's own turn that names a contact some other way than their
    address, full name, person id or chat id (a first name, a nickname)
    is not recognised and stays readable by everyone.

    Prompt block: `departments.prompt_block.render_org_block(include_contacts=...)`
    renders contacts in a compact `## Contacts` section after "People You
    Coordinate With" — name, role/company, email on file or not; no
    scopes, SLA or channel ids — capped at 25 lines plus a count, in
    both modes, on the principal's own verified turn only. Without it the
    block is byte-identical to before.

    UI: `/people` shows the principal Team and Contacts tabs (solo opens
    on Contacts and its Team tab shows only the principal) and a kind
    selector on the add form; anyone else sees the team only. A contact's
    page hides authority scopes, SLA, availability, open loops, outreach
    and working style. Adding a team member in solo offers to switch the
    workspace to team mode (`PUT /workspace`) or keep solo. Pure helpers:
    packages/ui/src/lib/peopleKinds.ts.
  contact_keeper: |
    people.contact_keeper keeps the principal's contacts current from their
    own mailbox (delegation.gmail_for, Gmail or Outlook, never the MCP
    gateway). Background only: scheduler.runner._maybe_keep_contacts calls
    maybe_run every tick, which starts one pass per RUN_EVERY (6h), throttled
    in process and by contact_keeper_state.last_run_at. A pass runs only
    when the mode is not off, the principal has Act as me on (can_delegate +
    is_enabled) and gmail_status is connected, inside rows_for_person so its
    audit rows are the principal's; it ends with one private contacts_kept
    log_event of counts, no names.
    Why headers only: names and addresses come from To/Cc and guest lists,
    never a mail's text, so a mail cannot write the roster. Adds need two
    sent mails in 60 days (no lists, bulk, auto mail, ghostwritten Handle it
    sends, over 10 recipients) or
    a meeting they organised or accepted (at most 10 guests); own, exec,
    known (archived too), role, no-reply and company-domain addresses are
    skipped. Updates: an alias under a contact's exact two-word name as the
    To line wrote it, twice, always a suggestion whatever the mode (an alias
    is an egress address, so one reply to a lookalike must not attach it;
    blocked or archived addresses never are), a
    fuller name for a one-word one, and a role read from the contact's
    newest signed, authenticated mail among their last 5 (recent_from;
    calendar invites, bounces, lists and automatic mail skipped) by one
    forced-tool call, kept only when every word is in the mail and it holds
    no link, address or instruction (capped 5 per run, 20 a day). Each run
    checks up to 20 people's newest mail, longest unchecked first, and reads
    again only when it is new, at most once a day per address
    (contact_keeper_reads keeps the message id and READ_VERSION). Typed
    fields are never overwritten (a name or role is written only when empty
    or last set by the keeper).
    people.contact_changes records each change (contact_changes) with reason
    and evidence. Mode ask stores a suggestion applied on accept. Undo
    archives an add or restores the old value if unchanged since; undo and
    dismiss block (email, field, value) in contact_keeper_blocks so it is
    never proposed again. A chat add (people_tools.handle_upsert_person) is
    recorded with reason asked so it has an Undo. Routes /contacts/* answer
    caller_is_principal only (404 otherwise). /today/activity gives the
    principal one contacts_kept row per day with changes.
    people.contact_notes keeps what the Executive remembers about each
    contact (contact_notes, one row per person): last emailed, last heard
    from (newest authenticated mail),
    last met, next meeting and its title, counts, and a note of at most 400
    characters with up to 6 topics. Why the principal's own words only: the
    note is written by one forced-tool call (ROUTING_MODEL) from their own
    sent mail to the contact (sender_new_text, no quoted mail, no
    ghostwritten sends) and the titles of meetings they organised, so a
    contact's mail cannot write it, and it can be read in chat like the
    principal's own sent mail. Rewritten only when the set of those
    messages and meetings changes (activity_key), capped 5 per pass and 20
    model calls a day (contact_note_tries counts every call, failed or
    rejected too); a note with a link, address or tag is rejected and the
    old note kept.
    A pass whose calendar read fails keeps the stored next meeting and
    meeting count (put_activity meetings_known=False).
    last_heard_at is read for up to HEARD_READS_PER_RUN (20) people a pass,
    independent of the note budget. Read on the principal's own turn by list_people and
    ask_about_person (contacts_reachable_now), and by GET
    /contacts/{person_id}/note (principal only). archive_person deletes it.
    Team members get the same note and signature read (role when empty and
    contact details, never name or addresses: TEAM_FIELDS); a teammate's
    note is still the principal's alone, from the principal's own mailbox,
    never teammate_mail or their peer memory.
    Contact details (person_details; Person.details: phone, mobile,
    website, linkedin, social, address) come from the same signature call.
    Why checked in code: each is kept only when the mail writes it (phone
    digits as one number, every word of an address, a link's host+path), a
    website only on the sender's own non-freemail domain or its subdomains
    (never a parent such as co.uk), a profile only on
    SOCIAL_HOSTS / linkedin.com (people.contact_info.detail_from_text). One
    per kind is the keeper's (last_applied); a newer value replaces it,
    a kind someone typed a value for is left alone. Each is a contact_changes row (field = kind) with Undo
    that removes it and restores the one it replaced. Details are for the
    reader only: never an egress channel.
    Who sees them: the people routes (GET /people, /people/{id},
    /people/by-scope) return details only to the principal and to that
    person (api.routes.people._shown); anyone else gets details empty, so a
    number read from a teammate's signature isn't handed to the whole team.
    A refused mailbox read (GmailAuthError / GmailRateLimited) stops that
    run's signature and last-heard reads but not its notes; the run is then
    still recorded as a mailbox failure (raised after the notes).
  aliases: |
    A Person has one PRIMARY address (`Person.email`, the one they sign in
    with) and up to 10 ALIASES (`Person.email_aliases`, table
    `person_emails`: id, person_id FK ON DELETE CASCADE, email, email_norm
    UNIQUE across the roster, source manual / chat_tool / roster_request,
    roster_request_id, created_at). An alias matches the person's mail and
    may be emailed like the primary, but INVARIANT: an alias is NOT a
    login. `store.find_person_by_email` stays primary-only and is the
    sign-in lookup (web caller resolution, `/auth/allowed-emails`,
    onboarding's owner email); mail is matched by
    `store.find_person_by_address` (primary or alias, case-insensitive,
    team row wins over a contact, archived excluded) and, on top of it,
    `people.identity.resolve_email_sender` (company-domain rule, below).
    Uniqueness: `store.address_holder` (anyone's primary or alias) and
    `store.alias_holder` (aliases only); `clean_aliases` trims, dedupes
    case-insensitively, drops the person's own primary, refuses a
    non-address (the message never quotes it) and more than 10;
    `set_person_emails` replaces the list, `add_person_email` adds one
    (False when already theirs); both raise `AddressInUseError` before
    writing when an address is someone else's. Archiving a person deletes
    their aliases so they never block the address. Writers: the People
    page ("Other addresses"; POST / PATCH /people `email_aliases`, 422 for
    a bad one, 409 for one in use — and 409 for a new primary that is
    someone's alias), `upsert_person`'s `email_aliases` (the full list,
    replacing; omit to keep), and a roster request linked to someone who
    already has a primary. Readers that now include aliases: the email
    poller, the outbound gates (RosterAllow), `_names_a_contact` (audit
    privacy), Act as me's recipient-kind map (`delegation.voice`,
    `delegation_tools`) and `/today`'s name lookup. Onboarding still
    imports no model-emitted addresses — only the owner's sign-in email,
    and an alias counts as taken there (`find_person_by_address`).
  company_domains: |
    `people.identity`: on one of the company's own email domains, an
    address's local part (lowercased, `+tag` dropped) matches a TEAMMATE
    whose primary or alias on ANY company domain has that local part —
    [email protected] is the Anna whose address is [email protected].
    Contacts never match this way. A domain alone proves nothing: an
    unknown local part on the company domain matches nobody (it becomes a
    roster request with suggested_kind "team"), and when two teammates
    would match nobody does (fail closed, logged). Exact matches win
    first. The domains are the `company_domains` workspace setting
    (workspace_settings column, JSON list or NULL; GET / PUT /workspace,
    Settings → Workspace; same caller rule as the principal's role; at
    most 10 plain DNS names; `validate_company_domains` refuses a
    free-mail provider's) or, when unset, the domain of the principal's
    PRIMARY address, if not free-mail (`identity.company_domains`) — never
    an alias's: an alias is often a personal or ISP address, and counting
    its domain would let anyone who registers anna@<that ISP> pass as Anna. Never a
    free-mail domain (`identity.FREEMAIL_DOMAINS`: gmail.com, outlook.com,
    yahoo.com, icloud.com, proton.me, …), where a local part says nothing
    about who someone is — a principal on gmail.com with no setting has no
    company domains at all. `identity.RosterAllow` is the same rule as a
    set for the outbound Gmail / Calendar / Drive gates (exact addresses of
    everyone allowed, plus company-domain local parts of teammates), so
    the Executive may email exactly the addresses inbound mail would
    match.
  roster_requests: |
    `people.roster_requests` (ledger + state machine, no channel sends) and
    `integrations.roster_intake` (acknowledgement, telling the principal,
    answers, replay). When someone NOT on the roster — and NOT one of the
    principal's contacts — writes in (an email address, a Slack or Discord
    user in a DM or mention, a private Telegram chat on a verified
    webhook), their message is HELD as a roster request instead of being
    dropped. Tables (same DB as people, created by `initialize_db`):
    `roster_requests` (one pending row per (channel, channel_ref) —
    partial unique index; display_name sanitised and unverified,
    profile_email, on_company_domain, suggested_kind "team" on a company
    domain else NULL, suggested_person_id (a chat profile email already on
    someone — never from a display name, which the sender chooses),
    status pending / resolving / approved / linked / declined / expired /
    superseded, resolved_*, token_hash, notified_*, ack_sent_at,
    alert_id, message_count, expires_at), `roster_request_messages`
    (payload_json for the replay, preview, replay_status held /
    replaying / replayed / dropped / failed / unavailable; unique per
    (request, external_id) so a redelivery is held once; at most 10 held
    per request, later ones only bump message_count) and `roster_ack_log`.

    Lifecycle. `hold` opens or extends the request (`ROSTER_REQUEST_DAILY_CAP`
    = 30 new requests a day; a sender declined within 30 days is not
    raised again). A new request gets a private /today card
    (`surface_card`: alert source "roster_request", tags
    `roster_request:<id>` + `private:principal`, routed to the principal)
    and a push to the principal (`notify_principal`: their delivery plan —
    preferred chat, other chats, email — for a chat sender or a
    company-domain email sender; an outside email sender waits on the
    card; capped by the same daily cap). The sender gets the fixed
    `ACK_TEXT` at most once per `ROSTER_ACK_WINDOW_DAYS` (7) and at most
    `ROSTER_ACK_DAILY_CAP` (20) a day overall (`claim_ack`, one BEGIN
    IMMEDIATE transaction; `release_ack` on a failed send). Unanswered
    requests expire after `ROSTER_REQUEST_TTL_DAYS` (14), swept lazily on
    every read; the same sweep returns a request stranded in `resolving`
    for over 10 minutes (the process died between claim and finish) to
    `pending`, or closes it as superseded when the sender has a newer one.

    Answers — all end in `resolve` (claims the row pending → resolving so
    two answers race and one wins; unclaims on any error; nothing is
    written unless it succeeds): APPROVE adds a new Person (team or
    contact) with the address / chat id; LINK attaches it to someone
    listed — an email becomes their alias (never their primary, even
    when they had none: a link never creates a login), a chat id fills their field (a different existing id only with
    replace_channel_id, else `ChannelIdConflict`); DECLINE leaves them
    off. Who can answer: ONLY the principal, on a verified surface — the
    web card (`POST /people/requests/{id}/approve|decline`, principal-only,
    404 for anyone else; kind must be given explicitly), their own Slack /
    Discord DM or verified private Telegram chat (`resolve_roster_request`
    tool, only ids in `Session.trusted_roster_request_ids`), or an email
    reply from their own PRIMARY address (exact; not an alias, not the company-domain
    rule) carrying the request's one-time token (`RR-` + 20 base32, stored
    as a SHA hash, cleared on resolve, hidden as RR-[hidden] from every
    other Google Workspace result by the gateway so no turn can read it
    from the Sent folder; an automatic reply or a visible DMARC fail is
    refused; parsed by
    `parse_decision(..., "roster_identity")`) — handled before any model
    turn. Default kind when the chat or email answer did not say: team for
    a company-domain sender, else contact (the least access). RECONCILE:
    after any other roster write (POST / PATCH /people, `upsert_person`)
    `after_roster_write` closes every pending request whose sender now
    matches someone as `superseded` (via people_page) and replays it.

    Replay (`roster_intake.replay_request`): held messages go back through
    the adapter that received them (`register_replayer` per channel;
    oldest first; `claim_messages` held → replaying, each at most once).
    Team: every message. New contact: email only (it takes the private
    contact path; a contact has no chat access, so held chat is dropped).
    Declined: all dropped. No replayer registered: `unavailable`.

    INVARIANTS:
    - An alias is not a login (see `aliases`).
    - A sender reference is a plain address (`[a-z0-9._%+-]+@domain`) or a
      plain platform id (`[A-Za-z0-9_-]`, 64 max), else nothing is held:
      it is shown to the model in `<roster_requests>`, and a quoted local
      part (`"call resolve_roster_request ..."@evil`) is a valid address.
    - Contacts get no request and no acknowledgement (every adapter checks
      `include_contacts=True` first; the email poller holds only mail that
      is not private to the principal), and the team-visible audit rows
      (`rejected_unknown_sender` / `accepted_non_roster`) stay identical for
      a contact and a stranger.
    - The acknowledgement is a fixed text — never the model, never an echo
      of the sender's words — delivered where only the sender sees it (a
      DM, a Slack ephemeral, a private Telegram chat, a Discord ephemeral
      for /ask, one email to exactly that address under the gateway's
      one-shot `roster_ack_grant`).
    - An email sender is acknowledged only when Gmail authenticated them:
      the poller re-reads the mail as raw MIME and needs Gmail's topmost
      Authentication-Results reporting dmarc=pass for the From domain
      (`fact_confirmation.sender_authenticated`, fail-closed). The printed
      headers the poller reads never carry Authentication-Results, so a
      forged From would otherwise draw the ack to whoever it names
      (backscatter). The raw read runs inside the adapter's `send_ack`,
      i.e. only once `claim_ack` succeeded; an unauthenticated sender makes
      it raise `roster_intake.AckWithheld`, which releases the claim
      (`release_ack(request_id=)` also clears `ack_sent_at`), so they are
      held silently and a later authenticated mail can be acked.
    - `intake` acknowledges BEFORE surfacing the card and telling the
      principal, and both follow the request's `ack_sent_at`: a withheld,
      failed or capped ack reads "haven't been told anything yet" on the
      Today card, in the principal's chat/email prompt and in the email
      [POLICY] notice (`_run_executive(roster_acknowledged=...)`, default
      False). A withheld ack is audited `roster_ack_withheld` (private);
      `release_ack` nulls `ack_sent_at` only when it still holds the stamp
      of the claim being released, so an ack that really went out earlier
      on the same request stays on record. The card goes up whatever
      happens during the ack (a failed claim or release, a lock, a failed
      re-read, even a cancelled send — `surface_card` runs synchronously
      in a `finally`, with the `roster_request_created` audit row), its
      text reading "not told" when the ack can't be confirmed: a later
      message from the sender finds the request open and would never
      surface it. Residual: a cancel or a failed `release_ack` leaves the
      claim in place, so `ack_sent_at` (the /today card's `ack_sent`, the
      [POLICY] notice on later mail) still reads told — fail-closed, no
      second ack within the window.
    - Replays run in a FRESH `contextvars.Context` (`_spawn`): the answer
      may come from the principal's own verified turn, and a stranger's
      message must never run with the principal's session (and contacts,
      and audit scope) still bound. `bind_loop` at app boot lets a sync
      route schedule the replay on the app loop.
    - Held text is purged on resolve or expiry: `_purge` blanks
      payload_json and preview on decline / expire, `finish_message` on
      each replay.
    - Private to the principal: the routes (404), the /today card
      (`private:principal`, excluded from the narrative, the chat alert
      digest, `ack_alert`, single ack — 409 — bulk ack, reopen, TTL sweep
      and alert review via `lifecycle.TTL_EXEMPT_SOURCES`), and every
      audit row (`roster_request_created`, `roster_ack_sent`,
      `roster_request_resolved`, `roster_message_replayed`,
      `roster_email_answer_refused`). The <roster_requests> block and the
      card show server-derived fields only; previews reach the web card,
      never a model.
    - Caps: ROSTER_ACK_WINDOW_DAYS=7, ROSTER_ACK_DAILY_CAP=20,
      ROSTER_REQUEST_DAILY_CAP=30, ROSTER_REQUEST_TTL_DAYS=14 (config.py),
      MAX_HELD_MESSAGES=10, DECLINE_QUIET_DAYS=30.
    - Wiped on a company swap: `clients.slots._BLANK_WIPE_TABLES`,
      `fixture_loader.reset_all_state` and `_seed_people` (with
      `person_emails`, children first).
  registry: openexecutive.people.registry — in-memory cache + lookup
  channel: |
    openexecutive.people.channel — resolves a person to a deliverable
    (channel, channel_ref) pair. Uses the person's explicit
    preferred_channel when set; when preferred_channel is "any",
    takes the first channel in people.reach.reach_order.
    `prefer_channel_for()` also enforces availability windows (returns
    None if the person is on leave or outside all configured windows;
    no windows means always-on).
  reach: |
    openexecutive.people.reach — one order for every message the
    Executive sends a person (reach_order): preferred_channel; with "any",
    last_channel, the chat app they last talked in; then slack → discord →
    telegram; then email as the backup (first when preferred). Used by
    scheduler.runner.delivery_order (briefs), schedule_tools.message_person
    and _dm_channel_for (messages, follow-ups) and people.channel
    (nudges). note_talked runs from Executive.chat on a chat app turn and
    writes people.last_channel / last_channel_at (store.note_last_channel,
    at most hourly for the same app, updated_at untouched) only when the
    turn's channel ref is the person's own stored Slack / Discord id or
    private (positive) Telegram chat id, and for Telegram only on a
    webhook only Telegram can call (channel_cards.telegram_proves_taps).
    A Telegram group id is left out of the order except for
    message_person (telegram_groups=True). last_channel_at is not
    serialised (Field exclude).
  notification_settings: |
    Each team member sets their own on Settings → Notifications
    (GET/PUT /notifications/settings, api.routes.notifications; caller
    resolved like the notes routes: a signed-in person on the People list,
    or the principal under local login, else 403). One row per person in
    `person_notification_settings` (people.notifications): quiet hours
    (enabled, start/end HH:MM in their zone, may cross midnight, start !=
    end; days every_day or weekdays — weekdays keeps the nightly window and
    makes Saturday and Sunday quiet all day), delivery instant | digest
    ("As they happen" / "In my briefs"), urgent_through (default true), and
    an IANA timezone ("" = the workspace zone). No row = defaults = nothing
    held, so existing installs behave as before.
    Scope: only the Executive's OWN outreach — a DM sent while a proactive
    source is tagged (attunement.outcomes.tag_proactive: scheduler dispatch
    of nudges, reflection, research, alert review). A reply
    in a conversation, a send someone asked for in chat, a scheduled
    follow-up (source followup, asked for at a time), the briefs, the
    cross-client digest, workflow artifacts and Act as me / note reminders
    are untagged and never held. Why not fold quiet hours into
    is_within_availability for everyone: the outbound guard's availability
    check runs on every DM, briefs included, and would refuse the brief the
    person scheduled inside their own quiet hours.
    Two mechanisms: (1) nudge routing — people.channel's
    is_within_availability / is_reachable_now / next_window_for /
    prefer_channel_for / next_available_window take `quiet_hours=True,
    urgent=` and then also treat quiet hours as unavailable; the nudge
    engine's _route_candidate and the runner's proactive_nudge re-check pass
    it, so a nudge row is deferred to the end of quiet hours (no model run
    at 3am, fresh text); (2) the send handlers' `_hold_outbound` after the
    anti-spam guard allows a send: outbound_guard.check_hold → if the
    recipient is in quiet hours or chose digest, the text is stored in
    `held_messages` (people.held_messages) and the tool returns
    {"status":"held"}; message_person returns it instead of trying the next
    channel (which would hold it twice), alert review counts it as a move
    made for a route but does not count a nudge toward the cap (and no
    second nudge is held while one about that alert waits, by `ref`). A
    store failure sends instead (fail-open, never lost). A scheduler
    dispatch whose turn held its message is audited phase `held`, not
    `delivered` (held_messages.track_holds).
    Release: rows with release_at (quiet hours) go once due, per person as
    one "While you were away" message via scheduler.runner.deliver_to_person
    (scheduler tick hook _maybe_release_held, once a minute). Every sender
    claims rows first (claimed_at compare-and-set, stale after 10 min), so a
    release pass and a brief never both send one; marked sent only after
    delivery, else the claim is freed. Postponed if quiet again, or to the
    leave end / next availability window when the guard would refuse them;
    any other failed delivery backs off 2, 4, 8 … min, capped at an hour.
    Dropped after 7 days or when the person is archived, and the oldest past
    the cap — each drop audited `held_messages_dropped`, private to the
    person, a count and reason only. Digest rows (release_at null) ride the
    principal's next morning brief / EoD digest as one block appended to the
    delivered text (not the stored run artifact), marked sent only when the
    brief went; everyone else's are made due when those briefs run
    (only the principal gets briefs); a digest row unclaimed for 36 h goes
    on its own. Switching back to instant releases what waited. Cap 50 open
    rows per person (oldest dropped).
    Urgent: source nudge_stalled (approval nudges) and alert-review DMs
    about an alert whose severity is or becomes `urgent`
    (notifications.urgent_send) are let through when urgent_through. A
    workflow approval question (gate_delivery wraps message_person in
    notifications.approval_send) is never held, whatever the setting: only
    a reply to it resolves the gate. If quiet hours cover every
    availability window in the 14-day horizon, next_window_for falls back
    to the next window rather than dropping the nudge.
    Not covered: nudges on the email channel (the MCP mail tool bypasses the
    send handlers — routing still defers them for quiet hours, but they are
    never digest-held); department channel broadcasts (rooms, not a person);
    alerts.dispatcher channels (web SSE, a self-addressed email, and a Slack
    DM stub); Act as me approval cards (untagged, and approvals anyway).
    Department check-ins send no DM: their proposals become approval cards.
  scope_tokens: |
    People can be queried by scope token via
    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. 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`).
    GET /people is team-only unless include_contacts=true, and POST and
    PATCH take kind; include_contacts, a contact's id and adding a contact
    are the principal's alone, a stricter check than the owner rule (see
    `people.kind`). POST and PATCH also take email_aliases (see
    `people.aliases`) and then reconcile pending roster requests. The
    roster-request routes — GET /people/requests (?status=, default
    pending, `all` for every status), GET /people/requests/{id}, POST
    /people/requests/{id}/approve (link_person_id [+ replace_channel_id],
    or full_name + kind [+ role]) and POST /people/requests/{id}/decline —
    are declared before /people/{person_id} and answer 404 to anyone but
    the principal (`caller_is_principal`); an answered request, or an id /
    address already on someone else, is a 409 (see
    `people.roster_requests`).
  executive_write_access: |
    The Executive can mutate the roster directly without going through the
    UI via the `list_people` / `upsert_person` / `archive_person` /
    `set_department_head` tools (openexecutive.orchestrator.people_tools) —
    but only when the principal asks from the web chat, their own Slack or
    Discord, or a private Telegram chat with a TELEGRAM_WEBHOOK_SECRET
    Telegram can send;
    anyone and anything else is refused. `resolve_roster_request` answers a
    pending roster request under the same gate, only for ids the server
    printed that turn in the `<roster_requests>` user-turn block
    (`briefing.context.render_and_trust` → `Session.trusted_roster_request_ids`,
    the principal's verified turn only; never the cached system prompt),
    and is in `UNATTENDED_WITHHELD_TOOLS`.
    See `routing.people_tools` for details.
  brief_insights: |
    openexecutive.people.insights generates a one-line per-person note for the
    /today brief via the utility-fast model (optionally enriched with a
    low-reasoning Honcho relationship snippet when HONCHO_ENABLED). Notes are
    cached in the `person_insights` table (openexecutive.people.insights_cache,
    shares episodic_memory.db) keyed by person_id and an input_hash over that
    person's structured signals plus a daily bucket — so a note regenerates
    when the person's situation changes or at least once a day. The /today
    route serves cached notes inline and regenerates stale ones in a
    background task; the hot request never makes an LLM call. Stale notes
    are only collected when the roster has more than one person: the UI
    shows the People sidebar only for more than one, so a one-person
    install (solo, or a team before anyone else is added) would otherwise
    pay a daily model + Honcho call for a note nobody sees.

scheduler:
  followup_already_handled: |
    A follow-up can be overtaken by events (the reply it waits for lands and
    the person deals with it in another chat). Two checks keep it current.
    At fire time (runner._since_scheduled_block): an ad hoc row back to the
    person who set it (runner._followup_owner: created_by_person_id, else
    the originating session's owner, the principal when it has none; only
    when the address is their own, runner._own_ref) gets their own chat
    messages since created_at (session_store.own_messages_since: role user,
    sent by them or in their own conversation from before senders were
    recorded; newest 30, 300 chars each) in <since_scheduled> tags, and is
    asked to answer ALREADY_HANDLED: <why> and send nothing when that shows
    it is done. The runner then marks the row cancelled (last_error
    'skipped: already handled (...)') and audits phase skipped. The
    teammate path (_run_teammate_followup) applies the same block and skips
    its own send. Only the person's own words are quoted, never replies, so
    mail a reply quoted cannot reach an unattended run this way. In chat:
    every turn by a verified speaker carries <pending_followups> in the user
    turn (correction_tools.pending_followups_block, list_followups' ownership
    rule, up to 10) asking the Executive to cancel_followup one the message
    shows is settled. The conversation review cannot do this for a chat that
    read mail (it skips those turns), which is the case that prompted it.
  monthly_value: |
    The owner's monthly tally (briefing/value_summary.py). A tick hook,
    `_maybe_send_monthly_value` → `value_summary.maybe_send_monthly`
    (every 15 min, one task at a time), not a scheduled_actions row. On the
    first weekday of the month (Sat/Sun roll to Monday), 09:00-18:00 in the
    user's zone, it summarizes last month and, unless every line is zero,
    claims scope `value_summary:YYYY-MM` in `briefing_narrative` (INSERT OR
    IGNORE, never released: one try) and sends `render_message` (the
    non-zero headline lines and a link to UI_BASE_URL/memories?tab=value)
    via `_deliver_to_principal` with private audit rows. Both workspace
    modes. Audited value_summary_sent / value_summary_not_sent (private).
    Off with VALUE_SUMMARY_MONTHLY_ENABLED=false.
  client_rotation: |
    New recurring kind client_rotation (multi-client practice mode; see
    clients.rotation for the full design). Scheduler-side specifics: the
    main loop checks clients.rotation.rotation_in_progress before
    claim_due_actions and sleeps through the tick while a rotation runs
    (claim pause); boot reconciles stale markers and seeds the rotation
    row (gated on CLIENT_ROTATION_ENABLED); the handler delivers the
    cross-client digest via _deliver_to_principal after the original
    client is restored, then chains the next nightly occurrence via
    seed_client_rotation (idempotent).
  heartbeat: |
    Liveness for Settings → Setup status. run_scheduler stamps
    runner._started_at on entry, and every tick ends with _beat(outcome)
    storing (finished_at, outcome) in runner._last_tick — outcome is ran,
    paused, waiting_for_company, rotating, or failed (the tick raised;
    the beat is in the except branch, after the log). In process memory
    only: scheduler_heartbeat() returns (started_at, last_tick), None for
    what hasn't happened. api/setup_checks.check_scheduler reads it: no
    start = the task isn't running (red); no tick
    _SCHEDULER_STARTUP_GRACE_S (300 s) after start = stuck (red, amber
    before that); last tick older than max(3 × poll interval, 90 s) =
    stopped (red); failed = red; waiting_for_company = amber with a link
    to /onboard. The pause switch is checked AFTER liveness, from its own
    row: a paused loop still beats, so a dead one reads as stopped (red),
    not paused. run_scheduler also clears _last_tick on entry, so a
    restart in one process never reports the previous run's last tick.
    Due actions run as their own tasks (_inflight), so a slow action
    never ages the heartbeat — only a stuck or dead loop does.
  module: openexecutive.scheduler
  pause: |
    Operator pause switch — openexecutive.scheduler.pause. One row
    (id=1) in `executive_control` (episodic_memory.db): paused,
    paused_at, paused_by, reason, updated_at. Set from the UI (sidebar
    switch, paused banner, Settings card) or POST /executive/pause |
    /executive/resume (api/routes/executive.py; shared-secret only, not
    SCHEDULED_ADMIN_TOKEN, so the UI proxy can call it; paused_by from
    x-caller-email, else "api"; audit executive_paused /
    executive_resumed). Pause is open to any signed-in caller (it only
    holds work); resume is principal-only via
    people.store.is_principal_or_self (403 otherwise; open while no
    principal is rostered so a pause can always be lifted; status
    carries can_resume for the viewer). `is_paused()` is the FIRST check of each
    run_scheduler tick — before the alert/watchlist sweep and the
    company-profile / rotation gates — so a paused tick does nothing;
    due rows stay pending and fire on the first tick after resume.
    Already-claimed actions finish. The same check gates
    integrations.email_poller (skips the poll; mail stays unread) and
    workflows.resumer (no startup sweep, timeouts or resumes;
    apply_resolution records the reply but skips _kick_resume).
    is_paused() is read-only (never creates the DB file or table). A
    missing file/table reads as running; a read ERROR reads as paused
    (fails closed — a brake must not silently release while the UI
    shows paused; the UI shows "status unknown" on a failed read). Pause re-apply is idempotent
    (keeps the original paused_at/by/reason). Persists across restarts
    (boot logs a WARNING) and across client-slot switches (listed in
    clients.slots._GLOBAL_TABLES; _ensure_schemas creates the table
    before the restore). GET /executive/status adds `held_actions` —
    due pending rows that fire on resume.
  runner: openexecutive.scheduler.runner — asyncio task started in the FastAPI lifespan. Polls every 30s; `claim_due_actions` uses an UPDATE…RETURNING claim so a row is fired at most once per process. Single-worker assumption (do not run two scheduler processes against the same DB). Each poll is gated on an active company profile via `_company_profile_active()` (true when `load_or_create_profile().is_empty()` is false) — when no profile is configured the poll loop claims and dispatches no scheduled actions, so every due row (including the recurring principal-brief rows seeded once in the startup prologue) stays `pending` and fires only once a company profile is saved (the Executive has no company context to act on before then). The hold is logged once per gap and once on resume, not every poll.
  table: |
    scheduled_actions (in episodic_memory.db). Schema (see
    memory/episodic.py):
      id, created_at, run_at, channel, channel_ref, intent_text,
      originating_session_id, status, attempts, last_error,
      department, kind, assigned_to_person_id, awaiting_response_since,
      scope_key, required_scope.
    Indexed on (status, run_at) for the due query; a partial index on
    (scope_key, created_at DESC) WHERE scope_key IS NOT NULL backs the
    nudge engine's dedup lookup.
  kinds:
    - ad_hoc — user-facing follow-ups created by the Executive's `schedule_followup` tool. Default kind.
    - "dept_cadence — internal action fired by department cadences. Not authority-gated (the check-in sends nothing). The runner first applies the skip rule (`department_check_in.needs_check_in` — no specialist, no Goals, or nothing new since the Goals were last reviewed; see `departments.cadence`) before creating any run; otherwise it invokes the `department_check_in` workflow. Every outcome re-enqueues the next occurrence via `cadence.enqueue_next` (idempotently) — a run, a skip, and a failure once its retries are spent. That last case also files one Home card (`workflows.failure_alerts`, source `workflow_failed`, tag `failed_run:<run id>`, coalesced per department) whose Run again (`POST /workflows/runs/{id}/rerun`) queues a dept_cadence row due now with `scope_key` `rerun:<run id>`, which bypasses the skip rule; a failed dynamic_workflow files the same card routed to its recipient, and its rerun row skips `schedule_dynamic_workflow_cadence`. A skip is recorded `cancelled` with `skipped: <reason>` in `last_error`, so it never counts as a check-in that ran. In a solo workspace the runner marks the row `cancelled` (reason in last_error) without running it and without chaining — ahead of the authority gate, so a propose_only department cannot turn it into an approval card; cancelled rather than done, because the nudge engine reads a done dept_cadence row as a recent department pulse. Pending rows are cancelled when their department is deleted, and orphaned rows (department no longer exists) are swept by `cadence.cancel_orphaned_cadences` on lifespan boot."
    - awaiting_human — placed by the `wait_for_human` workflow step; the run resumes when an inbound message matches.
    - "dynamic_workflow — cadence-fired run of a user-created (dynamic) workflow. Enqueued by `workflows.dynamic_cadence.schedule_dynamic_workflow_cadence` (channel=`__internal__`, channel_ref=the workflow name, assigned_to_person_id=the delivery recipient). The runner's `_run_dynamic_workflow` resolves the stored definition, runs the generic `DynamicWorkflow`, DMs the artifact to the recipient via `handle_message_person`, and re-chains the next occurrence — same crash-survival pattern as the principal briefs. Saving/updating/deleting/deactivating the definition reconciles its pending rows via `dynamic_cadence.cancel_cadence_rows`. See the `workflows:` → `dynamic_user_created` key."
    - nudge_scan — internal heartbeat row owned by the nudge engine; the runner calls `nudge_engine.run_nudge_scan()` and chains the next tick via `nudge_engine.enqueue_next_scan()`. Bypasses outbound dispatch. Emission is also capped per `scope_key` at `NUDGE_MAX_PER_SCOPE` (default 3) delivered nudges (`episodic.count_nudges_for_scope`), so a parked item is not chased forever.
    - "alert_review_scan — internal heartbeat row owned by the Executive alert review (`alerts.review`). Bootstrapped idempotently at scheduler startup when `ALERT_REVIEW_ENABLED`, fires every `ALERT_REVIEW_INTERVAL_HOURS` (default 6); the runner calls `run_alert_review(reason='heartbeat')`, marks done, and chains the next tick — same crash-resilient shape as nudge_scan. `_run_principal_brief` also runs a `pre_brief` pass before the morning brief so the brief reflects fresh verdicts (a review failure never blocks the brief). Bypasses outbound dispatch itself; the moves it makes go through the real DM / draft handlers. See the `alert_review:` key. Not a kind but loop-level: the runner also calls `_maybe_sweep_alerts` (alert TTL expiry, `alerts.lifecycle.expire_stale_alerts`) once at boot and every 15 min at the top of the tick — BEFORE the company-profile and rotation gates, so an old backlog expires even pre-onboarding — pure DB hygiene, no heartbeat row. Also loop-level: `_maybe_refresh_narrative` (AFTER the pause, profile and rotation gates, since it can spend a model call) starts `today.refresh_principal_narrative` as its own task every BRIEFING_NARRATIVE_REFRESH_MINUTES (default 10; 0 = off) between BRIEFING_NARRATIVE_REFRESH_START_HOUR and _END_HOUR (06–22) local, never while the previous one runs. It refreshes the cached calendar read and rewrites the principal's /today header only when its key moved, so the page is current before anyone opens it. Also loop-level, after the same gates: `_maybe_scan_inbox` starts the Act as me inbox watcher's due scans (`delegation.inbox.maybe_scan`) as one task, never while the previous one runs — see delegation.inbox_watcher."
    - proactive_nudge — per-channel nudge action emitted by `run_nudge_scan`. Carries a `scope_key` for cooldown dedup and `assigned_to_person_id` for a dispatch-time on-leave re-check that runs BEFORE the ad-hoc dispatch path: if the assignee has gone unreachable since the scan, the runner reschedules into the next available slot (clamped to fall after on_leave_until) or drops the nudge with an audit event rather than dispatching to a deaf channel.
    - "principal_brief_morning — Shift 3 recurring row that runs the `morning_brief` workflow and sends the artifact to the principal via `_deliver_to_principal` (preferred channel honoured, email through the MCP gateway; see `workflows` → morning_brief). When no channel can reach the principal the brief is still generated and stored as a run with its artifact (a web-only principal reads it on the Artifacts page); it is just not delivered, which is audited, and the next occurrence is chained. Seeded once per database at scheduler startup via `seed_principal_briefs()`; each fire chains the next occurrence in `_run_principal_brief()` so the recurring rhythm survives crashes. Time of day defaults to 08:00 in the user's zone (memory.workspace_settings.get_user_timezone: the workspace's zone, else USER_TIMEZONE, else UTC), computed DST-safe via `departments.cadence._parse_cadence_spec('daily@HH:MM', after, tz)`. A valid `PRINCIPAL_BRIEF_MORNING_TIME` (HH:MM) pins the time and is still read as UTC, as before zones existed, so a pinned time never moves; a malformed value is logged and ignored like an unset one. An install that set USER_TIMEZONE but pinned nothing does move to that zone, from each kind's first fire after the upgrade (rows seeded before it keep their old UTC time once). A change of zone runs `reschedule_principal_rhythm()`, which re-times each kind's PENDING, not-yet-due row IN PLACE (UPDATE run_at, guarded on the row being unchanged since it was read) and never inserts or cancels, so it cannot race the chain's mark_done → enqueue gap into a duplicate. New time: the next occurrence in the new zone after max(now, the kind's last fired run + 12h) — never two runs of a kind within 12h — except that if it is more than 12h later than the row's current time (moving would skip a day, e.g. at 07:59Z moving to Europe/London) the row keeps its time once. A kind with no such row (running, between mark_done and its chain insert, or a due row held by a pause / missing profile) is left alone; its chain times the next one in the new zone, and the chain itself starts from max(now, fired run_at + 12h) so a zone change mid-run cannot put a second brief hours after the first."
    - "principal_brief_eod — same shape as morning_brief, fires once per day at 18:00 in the user's zone (an explicitly set `PRINCIPAL_BRIEF_EOD_TIME` is read as UTC). Runs `end_of_day_digest` workflow. Both brief kinds bypass the per-channel anti-spam guards because the principal is by definition deliverable (channel_ref=`principal`, channel=`__internal__` triggers the workflow run rather than a direct send)."
    - "executive_reflection — Shift 5 recurring row. Seeded alongside the principal briefs (idempotent via `_has_pending_brief`), default 07:30 in the user's zone (an explicitly set `PRINCIPAL_REFLECTION_TIME` is read as UTC). The scheduler runs `_run_executive_reflection`: invokes the `executive_reflection` workflow, stores the artifact via `complete_run`, audits the outcome, then chains the next occurrence — same crash-survival pattern as principal briefs. Unlike the briefs, the artifact is NOT delivered to the principal — the morning brief that fires 30 minutes later surfaces what reflection decided via the existing /today/activity rail."
    - "principal_weekly_review — solo-only recurring row that runs the `weekly_review` workflow and delivers the artifact through `_deliver_to_principal`, exactly like the briefs (`runner._PRINCIPAL_WORKFLOWS` maps each kind to its workflow; the delivery outcome is recorded under `brief_delivery:principal_weekly_review` and counted by `brief_state.last_delivery_outcome` via `DELIVERY_KINDS`, so the Briefing notice and Setup status report a weekly review that was not sent). Default Friday 16:00 in the user's zone (`weekly@fri@16:00` through the DST-safe cadence parser); `PRINCIPAL_WEEKLY_REVIEW_TIME` takes a whole weekly spec (`weekly@DOW@HH:MM`) read as UTC when valid, like the other pinned times, and a malformed value is logged and ignored. Seeded by `seed_principal_briefs()` only when the workspace is solo; `set_workspace_mode('solo')` seeds it (`seed_weekly_review`), `set_workspace_mode('team')` cancels its pending row (`cancel_weekly_reviews`); a row that fires while the STORED mode is team is marked cancelled without running or chaining, and a solo run chains only while the workspace is still solo. Both checks use `_team_for_sure` → `workspace_settings.read_stored_mode()` (None when the read fails or the stored value is not a mode) and fail open: an unreadable mode is not team, so a locked DB neither retires the row nor breaks the chain (`get_workspace` would have read it as team). The weekly chain (`_enqueue_next_principal_brief`) also skips when a weekly row is already pending (`_has_pending_brief`), so a switch to solo that seeds one while a run finishes cannot leave two. Minimum gap between two runs (`_min_gap`, used by `_chain_after` and `reschedule_principal_rhythm`) is 3.5 days instead of 12h, so a zone change can neither run it twice in a week nor skip one."
    - "external_monitor_scan — heartbeat owned by the external-condition monitoring layer. Default every 5 min via EXTERNAL_MONITOR_SCAN_INTERVAL_MINUTES. The runner calls `monitoring.pipeline.run_external_monitor_scan()` which walks enabled watchlist rows whose `last_polled_at` is stale enough, fires the matching adapter (vendor_status, rss, stock, the billed standing-query `query` adapter, the `edgar` SEC-filings adapter, and the stateful `page_watch` change-detector), enriches promotable signals with capture-time relevance, writes `external_signals` rows, and promotes qualifying signals into the alerts pipeline. Bypasses outbound dispatch (channel=`__internal__`, channel_ref=`external_monitor`). Chains the next tick via `enqueue_next_external_monitor_scan` after firing — same idempotent / crash-resilient pattern as `nudge_scan`."
    - "watchlist_research_scan — periodic cron for the executive_research workflow (default every 360 min via WATCHLIST_RESEARCH_INTERVAL_MINUTES). The handler short-circuits when the company profile / initiatives / watchlist haven't changed since the last successful run, so quiet days cost zero tokens — except that a staleness floor (WATCHLIST_RESEARCH_MAX_STALENESS_HOURS, default 168 — weekly; a daily forced run re-derived the same findings from unchanged state and re-filed them as fresh alerts every morning) forces a run once that long has elapsed since the last successful run, so a static internal state can't keep the council blind to external change indefinitely. Does NOT write its own Alert — the workflow's Executive synthesis step routes findings directly via DMs / send_department_message / create_alert / add_watchlist_entry, so a separate cron Alert would duplicate the briefing. After routing, a DEDICATED watchlist-analysis pass (its own budget, separate from the routing budget) PROPOSES ongoing monitors via `propose_watch`; deterministic policy (`monitoring.research.watch_policy`, see external_monitoring) adds a proposal on its own only when it is grounded in company data and corroborated, files the rest as dry-run suggestions the principal approves on /watchlist, and refuses declined targets; the run's markdown artifact is also persisted into the separate `recent_research` knowledge collection (keep-latest) so future runs + chat can recall it. The cron's only side-effects on success are the audit row (`watchlist_research_periodic_ran`) and whatever routing tools the synthesis fired. The scheduled-action kind keeps the legacy `watchlist_research_scan` name (matched by the env var WATCHLIST_RESEARCH_INTERVAL_MINUTES + the three audit event_types) even though the workflow itself is registered as `executive_research` — naming is mixed intentionally to avoid a migration on already-pending heartbeat rows. Bypasses outbound dispatch (channel=`__internal__`, channel_ref=`watchlist_research`)."
    - "notion_sync_scan — optional heartbeat (NOTION_SYNC_ENABLED, default off) that incrementally re-indexes Notion pages shared with an internal integration into the isolated `notion_wiki` collection (NOT COMPANY — synced pages are multi-writer and unreviewed). Interval NOTION_SYNC_INTERVAL_MINUTES (default 60). Caps ingest per tick via NOTION_MAX_PAGES_PER_SCAN; overflow is retried and the watermark does not advance past failed or uningested pages. Each tick reconciles: un-shared/deleted pages have files + chunks purged. Bypasses outbound dispatch (channel=`__internal__`, channel_ref=`notion_sync`). Chains the next tick via enqueue_next_notion_sync_scan. See knowledge.collections NOTION_WIKI."
    - "confluence_sync_scan — optional heartbeat (CONFLUENCE_SYNC_ENABLED, default off) that lists the pages in CONFLUENCE_SYNC_SPACE_KEYS and re-indexes those whose version changed into the isolated `confluence_wiki` collection, leaving out pages with read restrictions (own or inherited) unless CONFLUENCE_SYNC_SKIP_RESTRICTED=false. Interval CONFLUENCE_SYNC_INTERVAL_MINUTES (default 60), at most CONFLUENCE_MAX_PAGES_PER_SCAN fetches per tick. Each tick reconciles unless a listing failed or was cut short. Bypasses outbound dispatch (channel=`__internal__`, channel_ref=`confluence_sync`). Chains the next tick via enqueue_next_confluence_sync_scan. See knowledge.collections CONFLUENCE."
  channel_routing: |
    The delivery channel is stored ON the scheduled_actions row itself
    (the `channel` and `channel_ref` columns). The runner dispatches
    through whichever channel was specified when the row was enqueued —
    `telegram`, `slack_dm`, `discord_dm`, `email` (requires MCP gateway
    for Gmail), or `__internal__` (bypasses outbound dispatch; used for
    workflow steps and the nudge_scan heartbeat). Rows a REMOVED feature
    left pending drain two ways: `__internal__` kinds (the old
    `onboarding_ramp` / `onboarding_kickoff` / `onboarding_checkin`) fall
    through the generic short-circuit — marked done, logged once, no
    dispatch; but the removed talent workflows scheduled `ad_hoc`
    reminders on the principal's REAL DM channel, which the short-circuit
    never sees, so `memory.episodic.cancel_orphaned_talent_reminders`
    cancels them by intent-text prefix at API startup and on slot schema
    init, bounded by an `app_migrations` marker row (runs once per DB).
    Department-scoped
    actions pass through the authority gate first
    (`departments.authority.gate_action`), which can `execute`
    (auto_execute: dispatch), `propose` (route to an approver via alert,
    not dispatched; deferred to the approver's next available window when
    they are outside it) or `escalate` (an urgent "[ESCALATION]" alert to
    the approver right away, never deferred, and NOT dispatched — the row
    is marked done and the card's "If you approve: … right away" line is
    what sends it). Because that card is the action's only trace, it is
    never silently lost: severity high, filed unrouted when nobody holds
    the scope and no principal is set (the Briefing lists every unread
    card), and deduped on the whole action — kind, channel, recipient and
    intent (`escalate_via_alert` → `propose_via_alert(dedup_on=...)`) — rather than the summary's
    first 60 characters, so another escalation that shares an opening, or
    the same text for someone else, cannot swallow it. An identical
    escalation folds into a still-open card and gets a fresh one once that
    card was handled (the action id is the external-id suffix), and a card
    that cannot be written (`raise_errors=True`) retries the row with
    backoff and, once the retries are spent, marks it `failed` (logged as
    an error) — never `done`. `escalate` used to raise the alert AND dispatch, which
    contradicted the UI's "the specialist will not act" and sent the
    action twice once the card was approved. A `dept_cadence` row is not
    gated at all: the check-in it runs sends nothing, and gating it used to
    turn every check-in into a one-shot card that never chained its next
    occurrence. Nudge engine emissions set `department=""` to bypass the gate — they
    are about reaching the approver, not a dept-scoped operation.
    Cancelling: DELETE /scheduled/{id} (the Pulse page's Cancel) soft-
    cancels a `pending` row (409 otherwise; the UPDATE is itself guarded
    on status='pending', so a row the scheduler claimed in between is
    never overwritten). Like pause it only stops
    work, so any signed-in user may: `require_cancel_permission` accepts
    a matching X-Admin-Token (SCHEDULED_ADMIN_TOKEN, scripts), a signed-in
    user through the UI proxy — `x-caller-email` trusted only when the
    request also carries the BACKEND_SHARED_SECRET `x-api-key` — or a
    loopback caller when no admin token is set; else 401 (token set) /
    503. Each cancel is audited `scheduled_action_cancelled` with the
    caller's email, "admin-token" or "local" as actor. Before this the UI
    could never send the admin token, so Cancel failed on every deploy.
  held_messages: |
    Loop-level hook `_maybe_release_held` (like the reminders): at most once
    a minute it starts people.held_messages.maybe_release, which sends each
    person their due held messages (quiet hours ended, or a digest made due
    when the briefs ran) as one "While you were away" message through
    deliver_to_person, private audit rows (`held_messages_released`). The
    principal-brief handler appends the principal's digest rows to the
    morning brief / EoD digest it delivers (_with_held_messages), marks them
    sent only on delivery (_mark_held_sent), then _release_others_digests
    makes everyone else's due. The proactive_nudge re-check calls
    prefer_channel_for / next_available_window with quiet_hours=True
    (urgent for `nudge:stalled:` scope keys). See people.notification_settings.
  nudge_engine: |
    openexecutive.scheduler.nudge_engine — periodic heartbeat (kind=
    `nudge_scan`, default every 15 min via NUDGE_SCAN_INTERVAL_MINUTES)
    that scans three sources and emits `proactive_nudge` rows:
      a) Stalled `awaiting_human` workflow runs whose `awaiting_until`
         is within NUDGE_STALLED_LEAD_HOURS (default 24h) and whose
         `updated_at` is older than NUDGE_STALLED_MIN_QUIET_HOURS.
      b) Stale commitments — `scheduled_actions` rows whose
         `awaiting_response_since` is older than NUDGE_COMMITMENT_STALE_DAYS.
         `kind='open_loop'` rows (see `attunement:`) use it as a DUE time
         and are chased as soon as it passes, with a check-in intent to
         the loop's owner. Each scan first expires loops older than
         ATTUNEMENT_LOOP_TTL_DAYS. Before open loops, nothing in
         production set `awaiting_response_since`, so this source was idle.
      c) Idle initiatives — active initiatives untouched for
         NUDGE_INITIATIVE_IDLE_DAYS, owner resolved via the department's
         `head_person_id`. With no head to resolve (no department — which
         is what the episodic extractor stores — an unknown department, or
         no head) the principal owns it (`people.store.find_principal_person`),
         and a principal recipient (also when the head IS the principal)
         gets self-addressed wording: "<title>" has not moved since
         <date>, still active, done, or dropped? No principal → skipped.
         When channel routing cannot reach the principal (no channel ref,
         or unreachable beyond NUDGE_MAX_DEFER_DAYS) the nudge becomes an
         unrouted Briefing card (`propose_via_alert(person_id=None,
         dedup_on=<scope_key>, external_id_suffix=<ISO year-week>)`, tag
         `initiative`, and no `department:` tag when the initiative has no
         department — `propose_via_alert` now omits an empty one, which
         "mute this topic" would pick and which would substring-match, and
         so mute, every department card) — at most one per initiative per
         week; while one is still unread the scan leaves it alone
         (`alerts.store.has_open_alert` on `authority.proposal_dedup_key`)
         rather than coalescing into it every 15 minutes. Cost note: this source used to never fire on
         installs without department heads; it now reaches the principal,
         bounded by the per-scan / per-person caps, the 7-day cooldown and
         NUDGE_MAX_PER_SCOPE. Skipped when the owning department's
         `dept_cadence` ran within the idle window (a done/running row); a
         skipped check-in is recorded `cancelled`, so it does not count.
         The card wording is neutral ("I couldn't reach you about this
         directly") since the cause may be leave or availability windows,
         not a missing channel, and it is filed in the scan's own database
         (`db_path` passed to `has_open_alert` / `propose_via_alert`).
    Each candidate is routed via `people.channel.prefer_channel_for` —
    honouring preferred channel + availability windows. Persons currently
    outside their window are deferred into `next_available_window` up to
    NUDGE_MAX_DEFER_DAYS; persons with no resolvable channel are skipped.
    Caps: NUDGE_MAX_PER_SCAN global per tick (default 10) and
    NUDGE_MAX_PER_PERSON_PER_SCAN per person (default 2). Dedup: each
    candidate carries a `scope_key` (e.g. `nudge:stalled:{run_id}`) and
    the engine refuses to re-emit any scope still inside its per-source
    cooldown. The dispatch-time on-leave re-check in the runner reschedules
    a `proactive_nudge` row instead of delivering to a deaf channel when
    the assignee has gone unreachable since the scan emitted it.
  api: |
    GET /scheduled?status=…&limit=…&order=asc|desc — list scheduled actions by
    status; `order` flips the run_at sort (asc default = soonest-first for the
    upcoming queue; desc = most-recent-first so a terminal-status history view
    surfaces recent rows rather than the oldest within `limit`). DELETE
    /scheduled/{id} cancels a pending action. The Pulse page's Cadence section
    uses this: one status filter (pending/done/failed/cancelled/all) governs all
    rhythm groups, fetching asc for pending and desc for terminal statuses.

today:
  module: openexecutive.api.routes.today
  endpoints:
    - "GET /today — JSON aggregation. Returns TodayResponse(departments, people, proposals, narrative, in_flight, awaiting, caller_person_id). `departments` rolls up each department's goal counts (total, at_risk, off_track) and awaiting workflow count, PLUS `attention_goals` — the actual off_track/at_risk Goal rows themselves (worst first, capped at 3), each carrying `key_result`, `current`, `target`, and `status`, so the briefing's Department card is insightful at rest (shows which goal is off and how far) instead of a count you must click into; empty for healthy/inactive departments and additive (older clients ignore it). `people` is an attention-ranked roster: each person carries the original preferred channel, awaiting-action count and soonest SLA PLUS enrichment signals — `status` (on_leave | needs_reply | awaiting | clear), `awaiting_reply_count`/`oldest_awaiting_reply_at` (open scheduled_action commitments we're waiting on THEM to answer, mirroring the nudge engine's awaiting_response_since set), `on_leave_until`, `reachable_now`/`next_window_at` (from people.channel availability windows), `authority_scope`, `department_slugs`, `last_contact_at` (most recent done outbound assigned to them), `overdue` (any SLA or awaited reply past deadline), `priority` (server sort key — overdue replies/work float to top, on-leave sinks), and `insight` (a one-line utility-fast note, see people.insights — null until the background cache warms). Rows are returned sorted by (-priority, full_name). `proposals` is the org-wide set of ALL unread alerts (workflow approvals, triage-classified inbound, Executive-created operational signals, and research artifacts the Executive flagged for review via `draft_artifact` — source=`artifact`, tagged `artifact`, which the UI renders as a Markdown document card rather than a terse proposal — and which also persist into the dedicated artifacts section (`/artifacts`, labelled Documents in the UI) so they remain browsable after they leave this unread queue — anything in the alerts table with status='unread'); the UI splits it into 'mine' vs 'across the team' using `caller_person_id` plus a 'principal owns unrouted' rule (alerts with `routed_to_person_id == null` fall to the principal's queue by default). Each proposal also carries presentation signals from `openexecutive.briefing.ranking`: `score` (attention sort key — severity-weighted, with a bonus for routed alerts) and `category` ('action' = a human should look, vs 'monitoring' = passive watchlist/external signals that are unrouted and not high/urgent), plus `surfaced_reason` (a short human note, null for most items) — set only when an external/watchlist signal was pulled into the 'action' lane *by its severity* (the high/urgent escape hatch in `categorize`, e.g. a ≥5% stock move), so the UI can render a per-item explanation of why a normally-Monitoring signal is in 'Needs you'. A proposal also carries `decision_instance_id` (parsed from a `decision_instance:{id}` topic tag), non-null only for gated calendar bookings surfaced from the decision ledger (source=`decision_scheduling`); the UI routes those cards' Approve/Reject to the /decisions endpoints (which book or cancel server-side and clear this alert) instead of the ack-and-hand-off-to-chat flow, so meeting bookings are reviewed in the briefing itself (the standalone proposals page was removed). `_build_today` sorts action items first (by score), monitoring last; the UI collapses the 'monitoring' tail into a separate section so it stops crowding the 'Needs you' queue. `narrative` is a PER-VIEWER Executive-voice 'what's going on' header (see `openexecutive.briefing.narrative` + `today._attach_narrative`). It is a SYNTHESIS, not a re-list: the actionable items render as cards below it, so the narrative gives the connective tissue a list can't (how items relate, what's most urgent and why, the single recommended focus) and deliberately does NOT enumerate a 'Needs you' section that would duplicate the cards. The resolved principal gets the whole-company synthesis in cache scope `principal` (which may carry their private rows), and an unrostered/unresolved caller the same synthesis in the shared scope `company` (never a private row), over ALL action-category proposals (mine + across the team; monitoring/watchlist noise is excluded) plus company-wide at-risk depts + activity; each non-principal teammate gets a role-scoped synthesis (cache scope `person:<id>`) over ONLY the action items routed to them + their departments' goal health + their department activity, written in their perspective. Synthesized by `synthesize_briefing_narrative`, which also produces the standalone morning_brief DM but via a DIFFERENT prompt (`standalone=True` → an enumerated brief with a 'Needs you' section, since the DM has no cards beside it to carry the list; the EoD digest still has its own prompt); the /today header path uses the synthesis prompt and never re-lists. Served from the per-scope `briefing_narrative` cache (`openexecutive.briefing.narrative_cache`, keyed by a hash of the viewer's scoped state + the activity rows the narrative reasons over + scope + the principal's LOCAL date (`narrative_cache.local_today`) + `NARRATIVE_PROMPT_VERSION`, the last so a prompt rewrite invalidates every cached narrative on the next view). The key is a hash of the RENDERED context string itself (`today._narrative_context` builds it once; the hot path hashes it, the background task hands that same string to the model as `rendered_context`). So the key is a function of the model's input: everything the prompt renders is covered, nothing it omits can cause a regeneration, and both properties survive edits to `render_briefing_context` with no field list to maintain. Hand-picked field lists broke one half or the other each time — proposal headlines alone left the rendered activity block uncovered (the header then described a rail that had moved on), while the proposals' review fields (review_verdict / review_note / why_now / recommended_move / due_at) are NEVER rendered by this header (the `since is None` branch prints headline[:160] and nothing else) yet `alerts.review` rewrites them with fresh LLM prose on every pass INCLUDING its 'still relevant, nothing changed' path, so keying on them regenerated every viewer's narrative several times a day to re-synthesize byte-identical input. A quiet board keys off the fixed `narrative_cache.QUIET_CONTEXT` sentinel and builds no activity at all, so a moving rail cannot re-key an entry whose text is a constant. The narrative's activity is built with `include_alert_raised=False`, dropping that source entirely: closed alerts read as settled work, and live ones are already the proposal cards (`is_live` IS the `list_live_alerts` predicate) that the header prompt forbids re-listing — the `/today/activity` rail keeps them. It is a source opt-out rather than a post-pull filter so `recent_alerts` cannot burn its pool on closed rows. `render_briefing_context` only labels that block 'SINCE LAST BRIEF' when the caller bounded it with `since`; an unbounded rail is labelled 'RECENT OE ACTIVITY' and explicitly marked as not a delta. When the viewer's slice has no action proposal, no at-risk/off-track department and nobody awaiting, the regen writes a fixed quiet line and spends NO model call — that, not the hash, is what keeps a frozen header from recurring. Together these stop a fully-dismissed board from yielding a confident header synthesized entirely out of closed items. Served from cache on the hot path and regenerated per-viewer in a FastAPI BackgroundTask when that viewer's hash moves; null on a cold cache. `in_flight` is the Executive's upcoming user-facing commitments — pending scheduled_actions (follow-ups, nudges) from `episodic.list_pending_scheduled_actions` (excludes the `__internal__` channel and `nudge_scan` heartbeat, the same set the activity feed hides), each with the resolved recipient `target` (person name via the shared channel→name lookup, or department/raw ref), `kind`, `run_at`, and `overdue` (run_at already passed). `awaiting` is the people we're waiting on a reply from, derived from the same open-commitment set behind each person's `awaiting_reply_count` (name, role, count, oldest_at, overdue), sorted most-overdue/oldest first. Together they power the briefing's 'In flight' section so cross-team work in progress is visible without opening the Scheduled Actions page. Both are additive and default to empty. `caller_person_id` is the signed-in caller resolved from `x-caller-email` via chat._resolve_caller_person_id; null when no caller could be resolved (unrostered signed-in user, or a CLI hit without the header). The route is async: it serves insight notes from the person_insights cache and, after resolving the caller, attaches the viewer-scoped narrative via `_attach_narrative`, scheduling regeneration of stale entries as FastAPI BackgroundTasks so the request never blocks on an LLM call. `_build_today()` stays synchronous and caller-agnostic — no insight regen and NO narrative (that is attached per-viewer by the endpoints) — for the morning_brief workflow and the deprecated /morning-brief alias that call it directly; the alias resolves the caller and serves the cached narrative but cannot schedule a regen. RIGHT NOW: the header is rewritten through the day, so Home shows it as a Right now card rather than a 'today's brief' link. `briefing.right_now.split_narrative` splits the served text into `narrative_lead`, `narrative_points` [{text, since}] and `narrative_move`; `since` is when the point (keyed by its bold subject) first appeared today, kept in `briefing_point_seen` (written beside each header write, earlier days pruned then). `narrative_seen_at` is the reader's last look per scope (`briefing_reader_seen`, set by POST /today/seen); the page holds it as the visit's baseline and counts only a look from earlier the same day. For the principal, `morning_brief` (today's delivered morning brief) and `calendar_next` (up to 3 meetings still ahead from the cached calendar read, no fresh call) fill the side panel. No model call on this path."
    - "Live header (briefing.live_signals) — the whole-company narrative scopes (`principal`, `company`) open their context with the principal's world as it is happening, under a NOW line bucketed to the local hour: INBOUND (integration_inbound audit rows whose summary starts 'Inbound ', one row per message id, grouped by sender + subject with a count; an email carries its subject and first line, the principal's own mail reads 'from the principal', an email from the roster says 'the Executive replied' or 'no reply went out' (an open integrations.unanswered_mail card for its thread; principal scope only, the cards are private), and a time on another local day carries its weekday and date — a brief that read yesterday's 'Re: call tomorrow' subject at a bare time put a past meeting under Today, called its reader by name and counted one email handled twice as two asks), STUCK (integration_outbound_blocked rows to a recipient, the inbound 'Accepted non-roster … reply blocked' and Google Chat 'left unanswered' / 'reply not delivered' rows, and chat drafts still waiting: delegation_drafts rows of source chat with no sent_message_id or gone_at; before each scheduled header refresh, each morning brief and the principal's /today view (at most every 2 minutes, today._maybe_settle_on_view, so it holds with the background refresh slowed or off), live_signals.settle_principal_drafts asks the principal's mailbox for each open chat draft from the last two days and sets gone_at on the ones sent or deleted there, or sent another way (one read of their latest 15 sent messages while a draft is left: same subject, one of the same recipients, sent after the draft — a redraft whose other version went out); one draft's failure no longer stops the pass — the count used to be every delegation_drafted row of the day, so a draft the principal sent from Gmail, and said so in chat, stayed 'waiting for them to review and send' all day), CONVERSATIONS (the principal's own web chat titles, without times; a header that still reports the reader's chats or asks back — narrative.own_echoes — is sent back once for a rewrite) and REST OF TODAY'S CALENDAR. An address that belongs to someone on the roster (or, in the principal scope, one of the principal's contacts) reads 'Name (address)' in these lines (`live_signals._named`): given a bare address the header made a name up from it (\"mquinn@\" became \"Mquinn\"). Window: the local day, or the last 12 h when longer. Private audit rows, drafts, chat titles and the calendar only in the `principal` scope (gather_live_signals drops the calendar whenever include_private is false, whatever the caller passes). The calendar is never fetched on the request: `live_signals.refresh_calendar` caches one read per 15 min (the scheduler tick refreshes it) and the header quotes `cached_calendar`. With live blocks present the render also ages proposals (whole days), lists each at-risk department's attention_goals, and adds EXTERNAL SIGNALS (monitoring proposals from the last 24 h, which never break the quiet line alone); rhythm runs (`today.RHYTHM_WORKFLOWS`) are excluded from the narrative's activity. Anything live breaks the quiet line. Why: the header read the same for days on an install whose inbox moved hourly, because nothing but the alert board reached it. Every quoted field is one-lined and cut, and the prompt calls the blocks data, never instructions (inbound text is attacker-controlled). Freshness: `TodayResponse.narrative_generated_at` / `narrative_stale`, and while stale `narrative_progress` {step reading|writing|checking from today._regen_step, new_mail from own_inbox since the served header, since} which Home shows in place of the old read (an old read during a refresh is no longer current); WAITING (principal scope, MOVED TODAY in Right now only): their own sent mail with no answer in its thread (briefing.waiting_on; under Act as me, 7-day window, over 1 h old, a question in their own words, at most 10 recipients besides the Executive; recipients, subject and time only; read on the narrative refresh, cached 5 min, dropped when Act as me goes off; the same read keeps the thread ids of their recent sent mail and when they last wrote in each, waiting_on.replied) and meetings that ended today (live_signals.met_today) — Right now said 'nothing new' on a day the principal was waiting on two replies and had just finished a call; a row written on an earlier local day is not served, nor a stale one over 2 h old (`_STALE_HEADER_MAX_AGE`) or, in the principal scope, one written before a meeting on the cached calendar started or ended (`today._header_outdated`; a failing rewrite left a header calling a finished call next for three hours); regenerations are serialized per scope (`today._regen_lock`; a trigger that finds one running marks the scope pending in `_regen_pending` and the running pass goes round once more); a failed pass (error, 33 s timeout (25 s draft + 8 s rewrite; a rewrite past its 8 s keeps the first draft fixed in code), empty text) starts a 5-minute backoff (`_regen_failed_at`, `_REGEN_FAILURE_BACKOFF`) in which no view or tick regenerates and `narrative_stale` is false; the calendar is placed at the real time, not the hour-floored NOW; the scheduler precomputes the principal's header (`today.refresh_principal_narrative`, see scheduler); the Briefing re-polls at 4/10/20 s while stale, on tab focus (at most once a minute) and every 5 min (`ui/src/lib/narrativeFreshness.ts`). Logs: 'today: narrative served scope=… age_s=… stale=…', 'today: narrative regenerated scope=… ms=…'."
    - "Right now pings (briefing.right_now_ping): when a rewrite of the principal's header adds a point (right_now.record_points returns Recorded.new), one short chat message goes to the principal (runner.deliver_to_person(chat_only=True), never email; proactive source right_now). NotificationSettings.right_now: important (default; a new point citing a MOVED TODAY line in header_context.NEEDS_YOU_PREFIXES, mapped by point_key through point_citations before keep_cited_points strips the tags) / everything / off. Skipped for the first header of the day (morning brief covers the night), capped at 4 a day (right_now_ping audit rows with status sent), dropped (not held) when people.notifications.hold_for would hold it. Text is plain_point: links, addresses and bare domains stripped, since points are model text over quoted mail. Why: Rufus asked to be told when Right now changes significantly instead of only seeing it on Home."
    - "Own inbox in Right now (live_signals.own_inbox, principal scope, MOVED TODAY in Right now only): the Act as me watcher (delegation.inbox) writes a private delegation_inbox_mail audit row for each message it records (not the reader's own, the Executive's, pre-switch, stale or already answered mail) and for newer mail from someone else on a thread whose reply card is still open (_note_later, from reconcile; a scan passes those threads over, so before this nothing recorded them): sender, subject, received_at, relation, skip reason, card id, never a body. From people the principal deals with (team, contact, correspondent, or any mail drafted/answered or on a card) one line each with the watcher's outcome (delegation.inbox.outcomes), left out once the principal wrote in its thread after it came (waiting_on.replied, checked once per read; an email judged no reply needed gets no card, so nothing else noticed their answer and Right now kept listing two emails the principal had already answered); the rest (strangers, mail not addressed to them) never a point; bulk, list and Gmail-tab mail is not recorded at all, so a busy day of it never crowds real mail out of the rows read: /today returns up to three 'Name: subject' labels + a count (inbox_also / inbox_also_total) for Home's 'Also in' line. Why: Braden's Right now read 'Quiet right now' from 6 am on a day a contact replied asking for a call, because it read only mail to the Executive's own address. narrative_checked_at is the request time when the header's key has not moved, so the card says 'Checked 2:20 PM' instead of the hour a quiet header was written."
    - "Acting on a Right now point: header_context.HeaderContext.sources maps a MOVED TODAY tag to the item it is about (own-inbox mail from OwnInbox.refs: message_id, thread_id, card id; a card raised or re-raised today: alert_id), never in the text. After a rewrite, point_sources (before keep_cited_points strips tags) gives point_key -> item; right_now.record_sources replaces the scope's rows in briefing_point_source; /today serves NarrativePoint.source. Home: View email (GET /delegation/mail, the caller's own mailbox only, the sender's new words, attachment names, their last words, mailbox link, open reply card on the thread) and Reply (POST /delegation/mail/reply -> inbox.draft_on_request: the thread's open card, else the watcher's _draft_card with asked=True, so never sent on its own under Handle it for me; refusals ASK_REFUSALS). Show me jumps to the alert in Needs you. Why: Rufus (2026-10-27) wanted to act on each point; Andrew's reply delivering the LOIs he asked for read 'Nothing is owed back' because the classifier filed it fyi: render_email now names attachments and the prompt says an email delivering what they asked for is a follow_up that needs a short reply."
    - "GET /today/activity?limit=N — Returns ActivityResponse(items). Each item is one recent self-initiated Executive action — a fired scheduled_action (DM dispatched, follow-up fired, cadence run, paused workflow resumed) or an extracted decision/advice row. Items carry `kind` (coarse classifier the UI maps to verb + icon — dm_sent, email_sent, nudge_sent, cadence_sent, workflow_resumed, proposal_routed, decision_logged, advice_given, workflow_done, initiative_started, decision_resolved, alert_raised, or action for unclassified), `summary`, `actor` (always Executive for now), `target` (channel ref / person, or null), `department`, `at` (ISO timestamp), and for workflow_done `detail` (one line on what came of the run) and `artifact_id` (`run:<id>` when it kept a write-up); a run's `summary` is its plain name from workflows/run_outcome.py, never its log title. Sources merged — `scheduled_actions` with status=done (excluding `nudge_scan` heartbeat and `__internal__` channel), `decisions`, `advice_given`, completed `workflow_runs` (status=done — briefings/check-ins/research, bucketed at `updated_at`), `initiatives` (kicked-off projects, at `created_at`), resolved `decision_instances` (terminal gated-decision outcomes — approved/rejected/reversed, at `resolved_at`; pending ones stay in `proposals`, not the rail), and `alerts` raised (excluding source=`decision_scheduling`, which is the companion alert for a gated booking already represented by its `decision_resolved` row). `_build_activity(..., include_alert_raised=False)` omits this source entirely. The rail keeps it (history is the point there); only the briefing narrative opts out. This broadens the feed beyond the original messaging-heavy three sources so it reflects all self-initiated Executive activity, not just dispatched messages. Actions on `propose_only` departments are reclassified to `proposal_routed` because the runner marks them done without dispatching (the proposal is surfaced via /today's `proposals` field; the activity rail shows it as 'proposed to <approver>' rather than implying a DM was sent). Sorted by `at DESC`, then capped at `limit` (default 20, clamped to 1..100 via FastAPI Query validation — 422 on out-of-range). The Pulse page polls this endpoint (limit=100) every ~20s so new activity streams into the 'Recent activity' card without a reload; the card scrolls internally at a fixed max-height rather than growing the page."
    - "GET /today/activity/daily?days=N — Returns DailyActivityResponse(days), the per-day counts behind the Pulse page's 'heartbeat' heatmap (the GitHub-contributions-style grid at `/memories`). Same source set and exclusions as /today/activity — the union of `decisions`, `advice_given`, status=done `scheduled_actions` (excluding the `nudge_scan` heartbeat and `__internal__` channel), completed `workflow_runs`, `initiatives`, resolved `decision_instances`, and `alerts` — but bucketed by calendar day (UTC) in `episodic.count_activity_by_day` rather than returned as individual items — decisions/advice by their `timestamp`, fired actions by `run_at` (fire time, not `created_at` queue time, so a cadence queued the night before counts on the day it fires), workflow runs by `updated_at` (completion), initiatives by `created_at`, resolved decisions by `resolved_at`, alerts by `created_at`. The `workflow_runs` and `alerts` tables are owned by other stores (not `episodic.initialize_db`), so each UNION arm is included only when its table exists — `count_activity_by_day` checks `sqlite_master` and still counts the sources episodic owns on a DB initialised by episodic alone. The response is DENSE: every calendar day in the window is present (count 0 when nothing fired), oldest→newest, so the UI renders a gap-free grid without client-side fill. A decision instance whose proposed payload is private (`\"private\": true`) and an alert tagged `private:principal` are not counted, as the feed leaves them out. `days` defaults to 90, clamped to 1..365 via FastAPI Query validation (422 on out-of-range). Read-only, unauthenticated (matches /today/activity and /memories/*), uncached."
    - "GET /today/top-three — solo only, principal only. Returns TopThreeToday {items: [{key, kind, text, why, slot}]} or null: null in team mode (effective_workspace_mode) and for anyone the stricter principal-only-run rule (`workflows._caller_is_the_principal`: own email on a non-archived principal entry, or no x-caller-email; never an unclaimed roster) does not admit. Built from the morning brief's own inputs and code — `open_loops.principal_due_soon()` handed to `briefing.top_three.build_top_three` — so the items, order and free slots match the solo brief. `slot` is the free block ('10:00–11:00', the user's zone), '' when no block is left, null when no calendar was read (none connected, a failure or the 4 s timeout, a non-business day). A separate route, never part of GET /today, so the Briefing never waits on the calendar read; the UI loads it after /today."
    - "GET /today/weekly-review — solo only, principal only (same gate). Returns WeeklyReviewSummary {run_id, completed_at, period, top_three, excerpt} for the latest completed weekly_review run — `persistence.list_runs(workflow_name='weekly_review', status='done', limit=1)` (newest updated_at; failed, running and other workflows never count) then `get_run` — or null when none has completed or the store cannot be read. `weekly_review.summarize_review` reads the artifact back as plain text: `period` from the title line (TITLE_PREFIX), `top_three` from the last TOP_THREE_HEADING section, and `excerpt` when that list is empty (the section's own note, else the first lines). `completed_at` is the run's updated_at. The UI links the run page, /jobs/runs/{run_id}."
    - "GET /today/value?period=month|week&offset=N — owner only (people.caller_is_principal; 403 otherwise). Returns ValueSummary {period, label, start, end, lines: [{key, label, count, previous}], deliverables: [{run_id, title, workflow_name, finished_at}], deliverables_total} from `briefing.value_summary.summarize`: the calendar month or Monday-first week in the user's zone, offset periods back (0-24), each line beside the period before. Every count is SQL over rows that prove the thing happened, never a model: messages_sent (DM handlers' kind=outbound ok rows, not held or suppressed, to anyone but the owner's own Slack/Discord/Telegram ids, plus Gmail/Outlook send-tool mcp rows whose result_preview has no error, so chat-sent mail counts though Done recently misses it), inbox_drafted / inbox_sent (the owner's delegation_reply_drafted, delegation_drafted, delegation_reply_sent rows), meetings_booked (create_calendar_event / create_instant_meeting skill rows not ok=false), briefs_delivered (scheduled_action phase=delivered, kind principal_*), reports (done workflow_runs with owner_person_id NULL, minus RHYTHM workflows; a teammate's own run is theirs alone; latest 10 listed), follow_ups (scheduled_action rows with action_id, phase delivered|held), tasks_tracked (open_loop rows created), tasks_closed (op=loop_closed reason=done), decisions (decision_instances resolved to a verdict), alerts (created), answered (chat_turn direction=out). Audit rows private to another member (private_to_person set) never count. Tables are existence-guarded; a missing one reads as zero. No hours-saved and no cost line (cost next to value reads as a bill; GET /audit/usage has it). UI: the top line of Pulse's Done for you panel and /memories?tab=value. The monthly message: see scheduler.monthly_value."
    - GET /morning-brief — deprecated alias for GET /today, kept for one release for older UI builds and bookmarks. Sends a Deprecation header with a Sunset date.
  lifecycle: |
    `proposals` is now the LIVE unread set (`alerts.lifecycle.list_live_alerts`:
    unread ∧ inside TTL ∧ not snoozed — the read-side twin of the scheduler's
    expiry sweep, so the page is right before the sweep runs), never
    `expired` / `resolved` rows. Each ProposalItem additionally carries
    `occurrence_count` / `last_seen_at` (coalescing), `last_reviewed_at`,
    `review_verdict` ('' | relevant | changed | likely_stale | drafted |
    routed | merged), `review_note` (the one-line "what changed since you
    last looked"), `recommended_move`, `why_now`, `due_at`,
    `superseded_count` (rows folded into it) and `suggested_workflow`.
    `briefing.ranking.score` now subtracts 30 for `likely_stale`, adds 20
    when `due_at` is within 24 h, and discounts up to 10 by the watch's
    `trust_score` (looked up once per distinct `external:<slug>` tag).
    `TodayResponse.handled_overnight` (additive) lists the alert review's
    COMPLETED autonomous moves since the last delivered morning brief
    (`brief_state.handled_since`, `changed` excluded; rows private to the
    principal only on the principal's own /today, never in a written
    brief) as structured rows:
    kind, summary, at, alert_id, event_type, headline, target, detail,
    outcome (resolved | dismissed | proposed), evidence_ref,
    superseded_by_alert_id and `status` (the alert's state NOW, so an undone
    close renders "Reopened" rather than a second Undo). The UI's handled
    rail is first-person and count-based ("Since your last brief: N off your
    plate, N in others' hands, N waiting on you", plus drafts ready /
    workflows suggested / watch changes / other moves / back on your plate
    when present) shown as ONE sentence by default (logic in
    `packages/ui/src/lib/handled.ts`, tested by `npm test`), rows behind a "details" disclosure (escalations first, one row
    per alert, each linking its evidence to `/audit?event_type=…&q=…` and a
    still-open row to `#alert-<id>`; Undo → `POST /alerts/{id}/reopen`),
    nothing rendered when empty. The "Executive handled N overnight" status
    pill is unchanged. UI: cards lead with `review_note`
    (amber "Likely stale" / "Updated" / "Since you last looked"), chips for
    age, seen ×N, why-now / due, folded-in, draft-ready, a "Reviewed <ago>"
    footer, a primary move control (Nudge <owner> → chat handoff; Run
    <workflow> → /jobs/<name>); "Needs you" shows "Start here" + 8 cards +
    "Show N more", a "Dismiss N older than 7 days" footer that sends
    explicit ids to `POST /alerts/bulk-ack` (never a server-side age sweep),
    and "Re-check relevance" (`POST /alerts/review`); Monitoring gets the
    same footer at 3 days; the ack body may carry `mute_topic`.
  ui_route: / (Next.js app router root) — the briefing is the default landing surface. `/today` still renders the same content as a standalone route (no sidebar shell) for bookmarks and the sidebar Briefing button. The chat lives at the same root behind a `mode` toggle — entering chat from "New chat" or by selecting a session swaps the main content; clicking the sidebar brandmark or the "Briefing" sidebar button returns to the briefing. Every signed-in route renders ONE sidebar component (`components/shell/AppSidebar.tsx`). The AppShell renders it for inner routes, and `/` (exempt from the shell for its own top bar and debug panel) renders the same component with in-page callbacks. On `/` its entries switch the page's in-memory mode; elsewhere they are links (`/?new=1`, `/?session=<id>`) that the home page applies on mount and then strips from the URL. `/?new=1&draft=<text>` (Playbooks "Try in chat") also seeds the new chat's input, capped at 2000 chars, WITHOUT auto-sending — unlike briefing handoffs, the text comes from a URL the user didn't type. The sidebar's "Recent" list is deliberately short — the 7 newest WEB chats only (channel sessions are recognised by their `slack:` / `telegram:` / `discord:` / `email:` / `google_chat:` session-id prefix, `lib/sessionChannel.ts`, since `sessions` has no channel column) — with an "All chats" link to `/chats`, the full history page with channel filter tabs, title search, date groups, a channel tag per row, and delete. The session list is held app-wide by `SessionsProvider` (root layout) over the unchanged `GET /sessions`, so the chat home refreshes it after each turn and every route sees the same list. A standalone "Pulse" link (→ `/memories`, the page titled "Pulse") is pinned directly beneath Briefing in the sidebar and the mobile bottom bar — an always-visible top-level destination rather than a Knowledge-group entry (the Knowledge group now lists "RAG" → `/knowledge`; Skills moved to the Playbooks tab of Workflows, `/jobs?tab=playbooks`), rendered from the shared `PULSE_NAV_ITEM` in `navConfig.ts`. In solo mode (read app-wide from `components/workspace/WorkspaceContext.tsx`'s WorkspaceProvider, mounted in the root layout next to ExecutiveStatusProvider, which reads team while loading or on error so a team install never flashes solo UI) `buildPrimaryNav({mode, roleKind})` swaps the Company group (Departments, People, Company profile) for "You" (Goals → `/goals`, People, and the profile — "Business profile" when the principal's role kind is owner, "Your work" for any other kind, an unset role, or one GET /workspace hides from a non-principal; `profileWording(mode, roleKind)` in navConfig.ts is the one rule, and the `/company-profile` breadcrumb, intro and section headings, the form wizard and the draft review follow it, copy only with no field renamed), `buildMobilePrimary(mode)` swaps People for Goals, and the briefing drops the Departments card, the People card, the "Across the team" lane (all action proposals land in "Needs you"), the people-awaiting, people-overdue and departments-at-risk pills and the quiet-day "Set up a check-in" link (a "N goals at risk" pill links to `/goals` instead), and shows a "Your projects" card of active initiatives (Done = PATCH status completed, Drop = DELETE after a confirm) where the Departments card was. `/goals` lists every goal from GET /departments grouped by area (a department row; areas with goals first, the rest offered as "Other areas") and adds, edits and deletes goals through the slug-scoped goal routes, sharing `components/goals/GoalEditor.tsx` with the department page. Team mode also lists Goals → `/goals` in the Company group (after Departments), and the page words it "department" there. The add-goal form asks only for the goal (`key_result`); the timeframe is a row of chips (This week … Ongoing, default This quarter) that fill the current period's label, target and current are optional, and there is no status picker (a new goal starts on_track). POST /departments/{slug}/goals matches it — only `key_result` is required, a blank `period_value` becomes the current period in the user's zone (`default_period_value`, the create_goal helper), `target` defaults to "", and PATCH rejects a blank `key_result` / `period_value`. Pulse hides "Department check-ins" and "Awaiting people" in solo. Settings has a Workspace card (mode with a confirm, "Your role" in solo — the principal's role kind, title, reports to, remit and measured on, saved with PUT /workspace —, and time zone; the meeting_scheduling class mode, bound to GET/PUT `/decisions/classes/meeting_scheduling` and hidden when that returns 404, is now "Meetings asked for in chat" in Take the lead's Always asks first). Team rendering is unchanged.
  briefing_first_landing: |
    The root page (`packages/ui/src/app/page.tsx`) defaults to `mode="briefing"`
    and renders `<Briefing>` (`packages/ui/src/components/Briefing.tsx`) in the
    main area instead of `<Chat>`. The component fetches /today; a failure
    surfaces an inline error. The briefing shows: "Needs you" proposal cards,
    active department cards (with goal health pills), and a People sidebar
    (visible only for multi-Person setups). The "Recent activity" rail of the
    Executive's recent actions used to live here too, but now lives ONLY on the
    Pulse page (`/memories`) to avoid two divergent-looking lists of the same
    feed; both consumed `GET /today/activity` (unchanged) — the Pulse renders it
    with richer rows (time + verb + who/department + summary).
    The People sidebar is attention-ranked: a one-line roster summary
    ("2 to reply · 1 overdue · 1 on leave"), and per-person a status chip
    (awaiting reply / to action / on leave, red when overdue), a
    reachable-now indicator with next-window fallback, authority-scope pills,
    and the cached one-line insight note when present.
  continue_from_briefing: |
    Each briefing item — Department card, proposal, activity row — is
    clickable. The root page passes an `onContinue(prompt)` callback to
    `<Briefing>`; clicking an item invokes it, which switches `mode` to
    "chat", clears any active session, and seeds the chat input with a
    pre-filled "Tell me about: <summary>" via the new `initialInput` prop
    on `<Chat>`. The user can edit before sending or just hit send. No URL
    state — the seeding is in-memory and clears on any subsequent mode
    transition. The standalone `/today` route renders `<Briefing>` without
    `onContinue`, so items fall back to plain navigation links.
  solo_mode: |
    In solo mode (get_workspace().mode) the /today header narrative uses
    BRIEFING_NARRATIVE_SOLO_SYSTEM over a context rendered with
    mode="solo" (GOALS AT RISK BY AREA, no PEOPLE WAITING block), and the
    quiet check ignores who is awaiting. narrative_cache.
    build_narrative_input_hash(context, scope, mode) folds the mode into a
    solo key only — solo and team never share a cached narrative, and a
    team key is exactly what it was before solo existed (no team cache is
    invalidated, NARRATIVE_PROMPT_VERSION unchanged). The response shape is
    unchanged.
    DUE THIS WEEK: for the principal's own (whole-business) view,
    `today._with_due_soon` adds `due_soon` (open_loops.principal_due_soon)
    to the narrative's today_data; `render_briefing_context(mode="solo")`
    renders it as a DUE THIS WEEK block (OVERDUE (was due D) / due today (D)
    / due <weekday> D, quoted as data), and `_nothing_needs_attention` counts
    it in solo. A teammate's scoped view and team mode never get it, so team
    contexts and keys are unchanged. The solo morning brief adds the same
    list (STANDALONE_BRIEF_SOLO_SYSTEM has a "Due this week" section) and its
    fingerprint carries `(loop_id, state)` pairs only when there are any.
    UI: the solo Briefing's "Due soon" card (under Needs you) reads the
    principal's loops from GET /people/{id}/open-loops (the oldest principal
    in `people`), shows those overdue or due within 7 days via
    `lib/dueSoon.ts` (npm-tested) with a count of later ones, and "Done"
    calls POST /open-loops/{id}/close (which stops the chase).
    Solo focus cards: a solo principal who only uses the web app (no chat
    channel, no Google Workspace) never saw the morning brief's top three
    or the weekly review outside Workflows run history. The solo Briefing
    now shows both: "Top three today" (above Due soon) from GET
    /today/top-three, numbered, each with its why and, when a calendar was
    read, its slot or "No free time left today"; and "This week's review"
    (top of the right-hand column) from GET /today/weekly-review, with the
    period, when it ran, next week's top three (or the excerpt) and a link
    to /jobs/runs/{run_id}. Each card fetches on its own after /today and
    renders nothing on null or an empty list, so a slow calendar never
    delays the page and teammates see neither. A commitment's text is
    rewritten for its owner with `lib/dueSoon.ts` loopText; the wording
    lives in `lib/rhythmCards.ts` (npm-tested). Team rendering, GET /today
    and the header narrative are unchanged; no prompt changed.
  intent: |
    Give the user a one-screen "what's happening across the org right
    now" view: how each department is doing against its goals, who has
    work waiting on them, what the Executive has done recently on its
    own initiative, and which proposals are sitting in someone's queue.
    Read-side only — no writes happen here.

chat:
  chats_preview: |
    GET /sessions (no q) gives each chat a preview: the last message as
    one plain line (Markdown marks stripped, cut at a word near 120
    chars), "You: " before the person's own words, null for an empty
    chat. The list's GROUP BY takes MAX(m.id) per chat, then one
    primary-key IN (...) lookup (batches of 500) reads those messages.
  chats_search: |
    GET /sessions?q= searches the caller's own chats (same scope as the
    list) by title and message text, case-insensitive with LIKE
    wildcards escaped. Each result adds match_count (0 = title only) and
    snippet (newest matching message around the match). The Chats page
    debounces it and opens a message match with /?session=…&find=…, and
    the chat starts on that message with previous/next and highlights
    the words (CSS Custom Highlight API where the browser has it).
  pushback_model: |
    After pushback, a stronger model for one answer (orchestrator/pushback.py).
    At turn start the Executive checks the message for pushback on the last
    answer: a thumbs down on the last saved reply (or typed), words that say
    it missed, the same ask again, or a claim_check row on the last reply.
    Then this turn runs on the pushback model (Council Executive card
    agent_overrides.pushback_model, else PUSHBACK_MODEL; empty or "off" =
    off) and logs a pushback_model audit row; the next turn is back on the
    normal model. No model call, fails open. Why: most misses were followed
    by the person pushing back, and a stronger model on just those turns
    costs far less than running every answer on it.
  claim_check: |
    Do what it says (orchestrator/claim_check.py). At the end of the
    agent loop, a reply that uses a word able to claim a change (done,
    removed, closed, I'll remind you…) is checked by one forced-tool call
    on ROUTING_MODEL against the turn's tool calls (name + first 160 chars
    of each result). A claim no call made, copied word for word from the
    reply (code-checked), gets one more round with a user-turn note: make
    the change or say it isn't done. Once a turn, never on the last
    iteration, fails open. Why: replies said "Done" or "I'll treat it as
    closed" with no tool call, and the brief kept the item.
    CLAIM_CHECK_ENABLED (default true).
  chat_review: |
    Conversation review (memory/chat_review.py). The post-turn block keeps a
    verified speaker's turn (principal on a people_tools-verified surface, or
    a rostered teammate on their own web chat, Slack or Discord; never an
    email, unattended run, private-to-principal turn or an attachment) in
    chat_review_turns: own words, reply, tools run. A turn that touched the
    speaker's mailbox, and every turn of a mail-private conversation, is kept
    too, for their own review only: tools kept by name with only a failure
    marker (no result text, the results are other people's mail), no
    remember_fact in its fix loop, its lessons never shared, the Reflection
    screen shows it to its owner alone (_session_access), and the review and
    replay passes over it write every audit row as that person's own
    (chat_review_turns.mail, mail_private_turns, rows_for_person). One
    chat_review __internal__ action per conversation fires 30 minutes after
    the last turn (pushed back while the chat goes on) and runs one small
    tool loop per person (CHAT_REVIEW_MODEL, default ROUTING_MODEL; 5 rounds,
    8 changes, CHAT_REVIEW_MAX_PER_DAY 10 per person) on the unreviewed turns
    only. Replies are shown as untrusted content, tool results not at all.
    Tools replay through the chat handlers in a session rebuilt from the
    recorded surface, so their checks hold; every change needs a source_quote
    of 4+ of the person's own words and its target named in their words,
    code-checked. It closes loops, keeps facts, cancels or moves follow-ups
    the person scheduled (never by sharing a thread),
    leaves an item out of the brief, learns a reply-style rule
    (attunement.style, basis conversation) or a writing habit (delegation.voice),
    and raises what it cannot fix in the next brief (briefing.brief_requests).
    Never sends, books, deletes or grants permission; says nothing in chat.
    Before the fixes, the same review grades every unreviewed turn with one
    forced grade_turns call (actor chat_review_grade): fine, miss (kind
    company = a fact or preference it lacked, product = something it could
    not do, plus a finer cause: term, fact, preference, specialist or do_it
    for company, tool or cant for product, stored empty when missing or
    from the other kind) or unclear, with what the person wanted instead and a 4+ word
    quote that must appear in that or a later turn, or a signal other than a
    thumbs up on the turn, else the grade is unclear.
    The grader reads the signals the product recorded about each turn:
    thumbs up/down and the note (chat_messages.feedback, joined by the saved
    reply's first 120 characters, or typed or said as the whole next message
    in a chat app, which has no buttons), stopped replies, a rewind
    (session_rewound audit row after the turn), a claim-check nudge
    (claim_check audit row by turn_id) and failed tool calls. Grades land on
    chat_review_turns (verdict, kind, cause, wanted, signals, graded_at, message_id)
    and per-person weekly counts in chat_review_weeks; misses are kept 90
    days, other rows 7. A failed grade never stops the fixes. GET/DELETE
    /memories/reflection (api/routes/reflection.py) serves them to the Pulse
    "What it got wrong" screen: each person their own, the principal also those
    from chats _session_access lets them open (never a teammate's own web
    chat or DM, nor a mail-private conversation).
    Lessons (memory/lessons.py): for a turn graded a miss the fix loop is
    offered learn_lesson (the turn is marked MISS in what it reads): one
    sentence this workspace wants done differently, quoted from the
    person's words (from that turn or later; the lesson must be what the
    quote says, and at most two content words beyond it), through the
    working-style deny-list plus the lessons' own (information-moving
    verbs, everyone/everything words) without the about-the-writing
    requirement, re-checked on every render. Stored in chat_review_lessons
    (shared = learned in a channel or group thread that never read mail); chat_review_lesson_uses
    records which turn id, and whose, saw which lesson. Reaches a turn by keyword match (two shared content words
    between lesson+quote and the message, or the name the lesson defines, like
    "Atlas means ..." or "your name is R2", written mid-sentence in the message;
    no vector index): the Executive's
    turn as a <lessons> user-turn block (build_lessons_block, counted as
    shown against the active turn id), each specialist call under its
    <failure_cases> block (router._lessons_for_call). A lesson reaches its
    own person's turns; the principal's reach everyone's only when shared.
    When the review grades a turn that saw a lesson, note_outcome bumps
    fine_after or miss_after for the lesson's own person's turns only;
    shown 5+ times with more misses than fine it retires itself
    (unhelpful). 40 live lessons per person (their oldest retires: room);
    Forget retires by hand (forgotten). Listed on the Reflection screen with the misses,
    retired ones as "stopped saying it". Never a cached block, never an
    authorization: the acting gates run on every call whatever it says.
    Replay (memory/replay.py): the nightly chat_replay action (CHAT_REPLAY_TIME
    03:30 user zone, seeded and chained like the reflection) runs the misses
    of the last 30 days again, today: a miss the night a lesson is written
    for it, when a lesson learned since the last night reaches it, else
    weekly; at most CHAT_REPLAY_MAX_CASES 30 within CHAT_REPLAY_MINUTES 20.
    Thumbs-up fine turns are kept (chat_review_turns.kept, 300 max, as long
    as a miss) as protected cases; 20 of them plus closed misses run only on
    a night a new lesson landed. Each case runs Executive.chat on a session
    rebuilt from the recorded surface with the saved conversation before the
    turn, Session.replay=True: reads run through every gate, the tools a
    read-only turn is denied (MCP_CLIENT_WITHHELD_TOOLS, gateway calls outside
    MCP_CLIENT_MCP_TOOLS) answer "done" and land in Session.replay_calls,
    scripts/jobs/load_mcp_server/Act as me/recall_history/extension tools are
    not offered, no post-turn pass runs and no lesson showing is counted.
    Judge (CHAT_REPLAY_JUDGE_MODEL, else EVAL_JUDGE_MODEL, else Sonnet)
    reads scrubbed content (content_trust._scrub, own tag names renamed)
    and scores intent and action, not figures: {passed, time_bound, notes}.
    Gate: pass closes the miss (replay_state closed, closed_at); time_bound
    marks it evidence; a lesson whose own miss fails 2 judged replays after
    it was learned retires (replay); a protected case that fails reopens a
    closed miss and strikes each new lesson of the same person that reached
    it (never the principal's shared ones from a teammate's turn), retiring
    it at 2 strikes; a case that didn't run (error, timeout) is recorded
    (ran=0) and settles nothing. chat_review_replays holds each replay
    (pruned with its turn), chat_review_replay_runs each night, written
    before the first case (the "since last night" marker). MAX_KEPT 300
    pass cases per person. The runner passes its MCP gateway for the reads. GET /memories/reflection carries
    replay_state/replayed_at/closed_at/replay_notes per miss and replay
    {misses, would_pass, evidence, last_run_at}: "of the N things that went
    wrong in the last 30 days, M would go right today".
    Why: the claim check only sees one turn; "I sent it" answered with
    "noted" left the draft waiting, and stated style was lost. Grading turns
    the same read into a record of where it fell short, and a lesson is how
    the Executive changes what it does next time in this workspace without a
    prompt change or a person approving it; the counters are the check that
    it helped.
  module: openexecutive.api.routes.chat
  endpoint: POST /chat — server-sent events stream of the live turn. POST /chat/stop halts one mid-flight. POST /chat/add hands it a message the person typed while it works. POST /chat/background starts a new chat the server answers to the end with no reader (202 + session_id; the caller request is wrapped so is_disconnected is always false, the stream is drained by a task kept in _background_tasks; at most 3 per owner key in _background_counts, claimed before the first await so a burst cannot pass together, else 429).
  sse_event_types:
    - "chunk — one text delta from the assistant response stream. Fields: type, content, session_id."
    - "thinking — keepalive emitted at the start of EVERY tool-use round, not just specialist ones. Fields: type, session_id. It carries no tool information, so the UI uses it purely as an in-flight boolean and takes the wording from the `activity` event that immediately precedes it. It used to be the sole driver of a hardcoded 'Consulting specialists…' string, which is why an MCP or calendar round looked like a specialist fan-out."
    - "activity — names the tool round that is in flight. Fields: type, label, tool, iteration. Emitted once per tool-use iteration, always immediately before `thinking`, so an ordered consumer has the label before it turns its indicator on. `label` is present-progressive, already ends in an ellipsis, and is capped at 60 chars for the one-line indicator — render it verbatim. `tool` is the canonical tool behind the label; for MCP `call_tool` the label comes from `orchestrator/tool_labels.py` in plain words (never the raw name) and `tool` is the UNDERLYING tool name (matching the `action_taken` convention), sanitized and truncated to 48 chars because it is model-authored text bound for the DOM. Labels come from `openexecutive.orchestrator.activity_labels._LABELS`; an unmapped tool falls back to 'Working…' rather than going silent. A mixed round collapses to ONE label by priority rank (`_PRIORITY`), never by joining clauses — the indicator is a single muted line. Rank 0 is `consult_specialist`, so a round containing a real fan-out always renders the generic 'Consulting specialists…' and NEVER names an individual specialist (the one-voice invariant). Ephemeral: unlike `action_taken` it is progress only and is never persisted with the assistant message."
    - "phase — committee phase transition (drafting | reviewing | finalizing) when committee_review=true. Fields: type, phase, session_id."
    - "committee_critique — severity preview from a committee reviewer. Fields: type, reviewer, severity."
    - "action_taken — emitted whenever the Executive's tool-use loop completes a side-effecting tool call. Fields: type, tool, summary (≤80 chars, human-readable), target (person / channel ref / resource), link (optional in-app path the UI drills into), iteration. See `openexecutive.orchestrator.action_chips.SIDE_EFFECTING_TOOLS` for the canonical instrumented set; read-only tools (consult_specialist, lookup_person, list_people, search_skills, load_skill, search_tools, web_search, ask_about_person, list_workflows) never emit this event. The chip is suppressed when the handler returned an error payload — no green ✓ over a red outcome."
    - "debug_event — internal observability for the Agent Activity panel (knowledge_retrieved, routing_decision, specialist_start/done, synthesis_start, skill_invocation, mcp_invocation, web_search_invocation, committee_*). Not part of the user-visible conversation."
    - "form_patch — emitted when the Executive calls `propose_form_values` (Ask OE panel form-fill tier). Fields: type, form_id, fields (name → proposed value map), rationale, iteration. The panel applies the values into the registered on-screen form as highlighted suggestions; nothing is saved server-side and the user submits through the form's normal Save. NOT persisted with the assistant message (same deferred-persistence bucket as the action-chip note below predating chip persistence) — reopening a panel session loses the proposal cards, though values already applied to a form are unaffected."
    - "stopped — the user halted the turn via POST /chat/stop. Carries type + session_id. ALWAYS followed by `done` over the same still-open stream: the server winds the turn down and reports, rather than the connection simply dying, so a consumer's state machine reaches its normal terminal state and there is no abort path to special-case. Deliberately NOT an `error` — a stop is a user decision, not a failure — so a consumer that ignores the event degrades to 'the turn ended normally', which is the safe reading. Whatever the Executive produced before the stop is persisted and flagged (chat_messages.stopped)."
    - "sources — sent by the route once per turn after the reply, also when it was stopped or timed out, before the stopped / error / done frames; only when the reply has text and the turn looked at something or had to leave an area out. Fields: type, session_id, sources ([{kind: company|knowledge|notion|research|document|web, title, url: http(s), /artifacts/<id> for a document, or null}], ≤12, ≤6 web, cited pages first), unavailable ([area], e.g. \"finance\" — never a specialist name). Persisted as chat_messages.sources; see routing.answer_sources."
    - "message_added — the running turn took messages the person sent while it worked (POST /chat/add). Fields: type, ids (the client-minted message ids). Emitted by the agent loop at the step boundary where it took them. A message the client queued that no `message_added` names was never seen, and the client sends it as the next turn."
    - "done — final marker carrying the resolved session_id; UI uses this to commit the streamed assistant message and clear the pending-prompt state."
    - "error — terminal error before/after streaming. Always followed by `done` so the stream consumer's state-machine reaches a clean end."
  added_messages: |
    The chat box stays open while the Executive works. A message typed then
    goes to `POST /chat/add` with the turn's `client_turn_id` and a
    client-minted message id, not to a second /chat. Each stop-registry
    entry carries a `TurnInbox` (orchestrator/turn_inbox.py); the endpoint
    checks the same owner key as /chat/stop, with the same 404 for unknown,
    not yours, stopped or closed. The agent loop takes whatever arrived at
    each step boundary (after a round's tool results, before the next model
    call) and appends it as a text block after the tool_result blocks, so the
    answer it is writing follows the newer message, and the cached prefix is
    untouched. A message arriving while the final answer is written is never
    taken: the route closes the inbox when the turn ends and the client sends
    leftovers as the next turn. Taken messages are audited as the person's
    words, persisted as their own user rows between the turn's message and
    its reply, mirrored into the live Session, and fed to the memory passes
    with the turn's own words. `_build_messages` merges consecutive user
    history rows so the prompt still alternates. A stop before any output
    saves none of it, and the UI returns everything to the composer.

    One turn at a time per conversation: `_run_chat_turn` takes a
    per-session asyncio.Lock (`_session_turn_locks`) before loading the
    session, so a second /chat on the same conversation (another tab, a
    retry) waits for the first to finish and persist instead of running on
    the same history. The wait is bounded by the whole-turn deadline; past
    it the turn runs anyway, so a stranded lock can't wedge a conversation.
    Single-process, like the stop registry.
  stop_control: |
    The Stop button. The CLIENT mints a `client_turn_id` (uuid4) and sends it
    with the turn; `POST /chat/stop` takes that id and sets an asyncio.Event
    the SSE driver loop races against `stream.__anext__()`.

    Why a client-minted id rather than the server's `turn_id`: `_run_chat_turn`
    runs its context fan-out (RAG + episodic + Honcho prefetch + briefing)
    BEFORE constructing the StreamingResponse, so no header and no SSE byte —
    and therefore no server-issued id — reaches the client for several seconds.
    That is exactly the window where stopping is free, because the Executive
    has not been asked for a first step and no model call has been made. A
    client id is live from the moment Send is pressed and closes it.

    The client id is NOT reused as the audit `turn_id`: that keeps its
    server-minted `t-` + 12-hex shape, which audit queries filter on, and
    letting a client choose an audit key is the thing `_clean_session_id`
    exists to prevent. `_CLIENT_TURN_ID_RE` is deliberately narrower than
    `_SESSION_ID_RE` (the value reaches log lines). A malformed id is DROPPED,
    not rejected — it only means that turn is not stoppable, which is never a
    reason to fail the turn.

    Authorization: the registry stores an OWNER KEY, not the raw
    `caller_person_id`. That id is None for a signed-in user not yet on the
    People roster, for a fresh install with no principal, and on any transient
    DB error during lookup — so comparing person ids directly would make every
    such caller the owner of every other such caller's turn. `_stop_owner_key`
    falls back person id -> verified email -> "local" (no caller header at all,
    i.e. CLI/curl against a local API). The UI proxy strips client-sent
    `x-caller-*` and re-stamps from the verified NextAuth session, so the email
    cannot be spoofed. Unknown id and "not yours" both return 404, on purpose —
    distinguishing them would make the endpoint an oracle for which turn ids
    are live.

    Registration is refused rather than forced on two conditions, and a refused
    turn simply isn't stoppable (it always still runs): an id already held by a
    live turn (overwriting would make the first turn unstoppable and point Stop
    at the wrong one), and a full registry. At the cap the NEW turn is refused
    rather than the oldest evicted — entries are popped when their turn ends,
    so the oldest is typically a long-running live turn whose owner is the most
    likely person to reach for Stop.

    A malformed `client_turn_id` on /chat is DROPPED, never rejected: failing a
    whole chat turn over an unstoppable id would be the wrong trade. On
    /chat/stop the id *is* the payload, so a bad one is a 422.

    How the work actually stops: the route cancels the pending `__anext__`
    task and AWAITS it before touching the generator again (cancel() only
    requests cancellation, and `aclose()` on a generator whose step is still
    running raises RuntimeError). The CancelledError propagates into whatever
    the Executive is awaiting — the Anthropic stream, a tool call, a specialist
    gather — which is why executive.py re-raises CancelledError out of its
    `gather(return_exceptions=True)` calls rather than treating it as a tool
    failure.

    `asyncio.wait` carries a duty `wait_for` used to discharge: it does NOT
    cancel its futures when the task awaiting it is cancelled, and Starlette
    cancels the SSE body on `http.disconnect`. `_next_stream_step` therefore
    cancels the pending step in a `finally`, so a closed tab cannot leave
    `__anext__` running a full specialist or tool round with no deadline, no
    registry entry and no persistence. That `finally` is the load-bearing part
    of the function; tests/unit/test_chat_stream_step.py pins it.

    The route persists BEFORE emitting the terminal frames on every path,
    including the stop: closing the tab in the gap between a `stopped` frame
    and the write would lose the partial reply, which is the one thing the
    feature exists to preserve. The first-turn session-title call (a Haiku
    round-trip with a ~10s budget) is skipped on the stop path, so persisting
    first does not make the button feel dead.

    `_active_stops` is single-process, exactly like `_sessions` in the
    same module and `_active_cancellations` in
    api/routes/evals.py (the pattern this copies). A second uvicorn worker
    would break in-flight session continuity before it broke stop. It is
    bounded (`_STOP_REGISTRY_MAX`) so a leaked entry cannot grow without limit.

    Two accepted consequences, by design rather than oversight:
      - A stopped turn writes the inbound `chat_turn` audit row plus an
        explicit outbound one marked `stopped`. The Executive's own outbound
        row never happens, because it is cancelled before its post-turn block.
      - A side-effecting tool cancelled mid-flight may already have fired (the
        DM sent, the event booked) without emitting its `action_taken` chip.
        Identical to the pre-existing whole-turn timeout behaviour.
      - A stop landing before the Executive produces anything saves nothing —
        not even the user message, since storing it alone would break the
        user/assistant alternation the stored history relies on. The UI matches
        that by taking the message back and returning its text to the composer
        (unless files were attached, where silently dropping the selection
        would be worse), so the live view and a reload agree.
      - A stopped FIRST turn is renamed detached rather than inline. The rename
        only ever runs on a first turn, and the stopped turn is part of the
        history, so simply skipping it would leave the placeholder title
        forever; awaiting it would add a ~10s Haiku round-trip to a stop.
      - Stopping a COMMITTEE turn during its silent draft phase saves nothing.
        `stream_chat_with_committee` accumulates the draft into a local and
        never yields it (only the revised stream reaches the client), so
        `full_response` is empty and `_persist_turn` returns on its empty
        guard. The turn simply ends with no assistant message. The UI matches
        this by not appending an empty bubble, so the live view and a reload
        agree. Changing it means restructuring the draft phase.

    The route also mirrors a broken-out turn into the live in-memory Session.
    The Executive's post-turn block is skipped whenever its generator closes
    early, so without this the live Session would disagree with what was saved.
    This applies to the disconnect and timeout paths too.

    `_get_or_create_session` re-reads the stored transcript into a cached
    Session on every web turn (under the conversation's turn lock, so the
    previous web turn is saved). The store, not the cache, is the
    conversation: a chat app's adapter (Telegram, Slack, Discord, Google Chat,
    Teams) saves its turns straight to `chat_messages`, so a chat continued in
    the app and then reopened on the web or phone would otherwise be answered
    without them. The rest of the cached Session (seen channel refs, mail ids)
    is kept.

  ask_oe_page_context: |
    The Ask OE side panel (packages/ui/src/components/askoe/*, available on
    every AppShell route — not `/`, which IS the chat) sends an optional
    `page_context` field on ChatRequest: route, page title, the matching
    /guide section id, and — when the page registered a form — a
    PageFormDescriptor with field names/types/descriptions/current values.
    chat.py renders it via `_build_page_context_block` (inlining the guide
    section's prebuilt markdown, truncating the form JSON at ~12k chars)
    and the Executive appends it to the USER turn as a `<page_context>`
    block — never a cached system block (caching invariant). The
    `propose_form_values` tool is ALWAYS present in the sorted client tool
    list for the same reason: tools precede the system blocks in the cache
    prefix, so conditional inclusion would invalidate the cache whenever
    panel and non-panel turns alternate. Guarded by
    tests/unit/test_executive_form_patch.py::test_tool_list_is_cache_stable_and_includes_form_tool.
  persisted_message_fields: |
    These per-message fields survive a reload alongside the prose, each
    attached by `load_messages` only when set so an untouched row keeps the
    exact dict shape every consumer expects:
      - `chat_messages.action_chips` — JSON list of the turn's action chips.
      - `chat_messages.stopped` — 1 when the user halted the reply mid-stream,
        so a truncated answer is not read back as a complete one. Additive
        migration guarded by a PRAGMA check, same shape as action_chips.
      - `chat_messages.sources` — JSON {sources, unavailable} from the
        turn's `sources` event (routing.answer_sources); assistant rows only.
        Same additive migration shape.
    Safe to ride along into `Session.conversation_history`: the Executive
    rebuilds each history turn as {"role", "content"}, so neither key ever
    reaches the Anthropic payload.

  activity_labels: |
    The in-flight progress line. `orchestrator/activity_labels.py` is the
    sibling of `action_chips.py`: same tool -> phrase mapping, but
    present-progressive, covering every tool including read-only ones,
    because it describes work that has not finished yet.

    Emission is one place — the agent loop, immediately before it yields the
    `_THINKING` sentinel. The call is wrapped in try/except: a labelling bug
    costs the label, never the turn (the UI then falls back to "Working…").
    The sentinel itself is deliberately unchanged; it is also the
    "don't accumulate this into full_response" marker read by
    `stream_chat`, the committee draft pass, and the non-streaming `.chat()`
    wrapper that every channel adapter uses.

    Text across rounds: every consumer (the SSE route, `stream_chat`'s
    full_response, `.chat()`, the UI) joins the text deltas as they come, so
    the agent loop itself starts each round's text with a paragraph break
    after the text streamed before it (`_round_separator`, from the last two
    characters streamed: two newlines, less any newline either side already
    has).
    Words the model writes before a tool call were running into its answer
    ("...Check actual stock.Yes. ITEM-1...", seen in evals against a live
    install, 2026-10-19).
    Decided with the owner: keep every round's text, never drop it, since an
    answer written before a final tool call would otherwise be lost.

    Rendered in `packages/ui/src/components/Chat.tsx` with precedence
    committeePhase > activity label > nothing, and in
    `components/askoe/AskOEPanel.tsx`, where it fills the streaming
    placeholder that used to be a bare ellipsis. The label clears on the
    first text chunk, on a committee phase change, at turn start, and in the
    turn's finally — but deliberately NOT on `action_taken`, since a chip can
    land while the same round is still running.

    Known limitation: `Chat.tsx` gates the whole indicator row on
    `!streamingContent`, so a tool round that happens AFTER prose has started
    streaming shows nothing. Pre-existing, and unchanged by the label work.

  action_taken_chips: |
    Rendered as inline pills under each assistant message in
    `packages/ui/src/components/Message.tsx`. Each chip shows a ✓
    glyph + summary + optional link → in-app drill-down. The list
    accumulates during the in-flight turn and freezes when the
    `done` event arrives. Chips are persisted alongside the assistant
    message: the `/chat` SSE loop collects the `action_taken` items as
    they stream and stores them as JSON in the nullable
    `chat_messages.action_chips` column; `session_store.load_messages`
    re-attaches them as `actions`, so reopening a saved session restores
    the pills (legacy rows that predate the column stay chip-less). The
    audit log remains the independent durable record (every
    side-effecting tool also emits a `tool_invocation` row).

    Chips with the same summary collapse into one chip with a count
    (`packages/ui/src/lib/actionChips.ts`); tapping a repeat, or a single
    connected-tool chip that has a target, lists what each run looked at
    (its `target` and `link`): a bottom sheet on a phone, a card under the
    chips on wider screens. Saved rows from before connected tools had
    plain names ("Called server__tool") are turned into words client-side.

  connected_tool_labels: |
    A connected (MCP) tool reaches the Executive as `call_tool` wrapping a
    raw name like `google_workspace__search_drive_files`. Users never see
    that name: `orchestrator/tool_labels.py` holds one table of
    (done, doing) phrases ("Searched Drive" / "Searching Drive"), read by
    both `action_chips` (the chip summary) and `activity_labels` (the
    progress line), so the two always agree. An unlisted tool is turned
    into words with its service ("Listed task lists · Google"). The chip's
    `tool` keeps the raw name; its `target` comes from
    `tool_labels.detail_for`: the search words, the Drive file it opened,
    or an email subject, cleaned to one short line.

audit:
  purpose: Persistent, searchable record of valuable events. Separate from episodic memory (which biases future LLM behaviour) — audit is for humans to inspect what the system did.
  db: ./episodic_memory.db (shares the SQLite file used by episodic/alerts/cache — one file to look in)
  table: audit_log (id, ts, event_type, session_id, turn_id, actor, summary, details_json, full_json, department, private_to_principal)
  department_filter: AuditLogger.query(department=…) filters on the department column in SQL. The department check-in skip rule uses it; a Python filter over the newest page missed department rows on a busy day.
  private_rows: |
    `private_to_principal` (INTEGER NOT NULL DEFAULT 0, added by the
    PRAGMA-guarded migration) marks a row only the principal may read.
    Every signed-in user can read /audit, and the principal's private
    matters (mail from their contacts, mail they forward, who their
    contacts are) must not reach them through it. Set at write time by
    AuditLogger.log: `private=True` from the caller (the email poller's
    two inbound rows for contact mail and principal forwards;
    create_alert's row for a private alert), OR
    people_tools.audit_row_private_to_principal(summary, details, full):
      - True for every row written while the turn is private to the
        principal (turn_is_private_to_principal — Session.private_to_principal
        on current_session): the chat_turn reply, tool_invocation rows,
        cache_event rows, and background passes whose task inherited the
        turn's context.
      - True for every row written once an Act as me turn has touched the
        speaker's own mailbox (delegation.settings.turn_touched_delegate_mail
        — TurnDelegation.touched_mail, which ghostwrite_email sets before its
        first read): the tool_invocation row, the chat_turn reply carrying the
        draft's preview, cache_event rows, and the post-turn passes, which the
        turn starts under private_rows(touched_mail) (it runs no learning
        passes). Only the principal can have Act as me for now, so private to the principal is the right
        visibility; a teammate phase needs rows private to that person.
      - While contacts are reachable (contacts_reachable_now: the
        principal's own verified turn, or grant_contact_egress), True for
        a row that names one of their contacts: their email address or
        full name (two words or more; case- and spacing-insensitive, word-
        bounded so "[email protected]" never matches "[email protected]") anywhere in the
        text, or their person id or Slack / Discord / Telegram id in a
        person or recipient field (key ending person_id / person_ids /
        user_id / chat_id / channel_ref). Dicts, lists and JSON strings
        (tool results) are walked.
      - Otherwise False. On anyone else's turn a contact is a stranger, so
        a row naming one keeps its visibility: hiding it would tell the
        teammate who wrote it that the address is a contact.
    Some rows are written before their turn binds its session, so the rule
    also reads two scopes in audit.context (save/restore contextvars; an
    inner scope never lifts an outer one; tasks and asyncio.to_thread calls
    started inside inherit them; neither changes who the turn may reach):
      - private_rows: every row is private. email_poller._handle_one_email
        holds it for the whole handling of a mail from a contact or a
        principal forward, from the privacy decision to _mark_read. Without
        it the knowledge_retrieval row (retrieve(raw_email[:500]) is an
        argument evaluated before Executive.chat binds the session) carried
        the From line, subject and opening of the mail to every reader.
      - principal_turn_rows: rows naming a contact are private, as on the
        principal's own verified turn. people_tools.audit_rows_on_senders_turn
        decorates the Slack, Discord and Telegram handlers: it resolves the
        sender (off the event loop) and holds the scope when
        people_tools.sent_by_principal (the sender is the principal and the
        surface verifies them; Telegram only with a valid webhook secret and
        a private chat). The web chat route holds it around its "User:" row,
        its context fan-out and the SSE body when is_principal_on_verified_
        surface(caller) — the Executive binds the caller to the session only
        inside stream_chat. Covers the integration_inbound row, the
        knowledge retrieval and alert triage, which all ran with no session.
        A sender lookup that fails counts as not the principal (logged with
        its exception type), as is_principal_on_verified_surface answers on
        an error, so those rows keep the ordinary rule.
      - unscoped_audit_rows clears both for unattended work started inside
        a scope, which copies the context but is not part of the turn: the
        run a chat reply resumes (resumer._kick_resume's task) and each
        scheduled action (run_scheduler starts every task under it). The
        poll loops (resumer, scheduler) start from the lifespan with no
        scope anyway. Work that belongs to the turn keeps it: its alert
        triage, post-turn passes, a workflow run_workflow runs inline, the
        title rename.
    Known signal, accepted: audit ids are one AUTOINCREMENT sequence, so a
    reader who is not the principal can see a gap where a private row was
    written (that one was, and roughly when), never what it says.
    A caller can add privacy, never remove it (`private=False` on a
    private turn still writes a private row), and the check fails closed:
    if it raises, or the roster cannot be read, the row is private.
    Reads: query / count / usage_summary take include_private (default
    True for internal readers; the department check-in passes False, since
    its report goes to the department, both for the activity it reports and
    for its "nothing new since the review" skip rule, whose run-or-skip the
    department sees); api.routes.audit passes
    `caller_is_principal(request)` — the /alerts and /decisions rule: the
    principal's signed-in email, or no x-caller-email (CLI, curl, local
    login) once a principal is on the roster; nobody before one is. The
    filter is SQL, so `total` and pagination stay honest.
  event_types:
    - chat_turn — one row per user-facing turn (latency, tokens, session)
    - specialist_consult — one row per consult_specialist tool call; full payload includes `active_prompt_blocks` so the flow-chart view can show which cached system blocks were live
    - tool_invocation — generic skill/MCP/alert/schedule tool calls; full payload includes `active_prompt_blocks`
    - scheduled_action — proactive nudge fired by the scheduler
    - alert — alert created by the triage pipeline
    - integration_inbound — Slack / Discord / email / Telegram / Google Chat message received. The chat adapters put the first 160 characters of the message in the summary; the email poller keeps the summary to sender and subject and stores the text in the full payload (`message` — the sender's new text, cut at 20,000 escaped JSON chars, the measure the 64 KB cap uses; `attachments` — filenames, 8,000 escaped chars; `body` — the whole body with its quoted chain, only on a row private to the principal, since the chain quotes other people's mail and a public row is every signed-in user's) with `details.preview` (120 chars of the new text) and `details.body_len`, so /audit shows the request next to the reply's `chat_turn` row. `details.outcome` distinguishes the non-reply paths — `rejected_unknown_sender` (not on the People roster), `skipped_gate` (response gate said no), `dropped_thread_unreadable` (Slack wouldn't return a thread the bot is in, so a continuation went unanswered; the sender was told), and `handler_error` (the turn raised; the user got the generic apology). The error row carries the same `session_id` as the inbound row, so /audit can join a failed turn to the message that caused it.
    - knowledge_retrieval — one row per `knowledge.retriever.retrieve()` call; details carry chunk counts + domains, full payload carries each chunk's source, distance, and text preview so the session view shows "which RAG chunks influenced this response"
    - cache_event — one row per model call, from every call site (`audit.usage.log_model_usage`): Executive iterations and the committee revision pass (`actor` executive / committee_revision), `BaseAgent.analyze` callers — chat-turn consults via `route_parallel` (`actor` specialist), workflow steps and other direct `route_to_specialist` callers (specialist_workflow), the MCP `consult_specialist` tool (specialist_mcp), and both Council test boxes (agent_test) — `BaseAgent.analyze_with_tools` callers (specialist_research, query_watch, signal_enrichment), the research synthesis and watchlist passes (research_synthesis / research_watchlist), triage, the chat memory extractor (memory_extractor), alert review (alert_review), the brief's narrative and grounding repair (briefing_narrative / briefing_grounding), the end_of_day_digest, executive_reflection and weekly_review workflows, wait_for_human reply parsing (workflow replies and roster answers) and the inbound_resolver, committee reviewers (committee_reviewer), the fixture and engagement generators (their agent names), and the utility calls — session_title, watchlist_describe, response_gate, person_insight, initiatives_consolidation, pdf_reader, the chat page's suggested_prompts / followup_suggestion, and the eval runner's eval_judge. `tests/unit/test_usage_recording.py::test_every_model_call_records_usage` walks the package's AST and fails on any function that calls `messages_create` / `messages_stream` without calling `log_model_usage` (directly, through a same-module wrapper such as the Executive's `_emit_cache_event`, or from an enclosing function), so a new call site cannot skip the row silently; `providers/` and the runtime-dead `architecture/generator.py` are exempt, and the repo-root `evals/` harness is out of scope (its judges call the package's `evals.judges.judge_message`, which records the eval_judge row and uses `EVAL_JUDGE_MODEL`, default Opus). Captures `input_tokens`, `output_tokens`, `cache_creation_input_tokens`, `cache_read_input_tokens`, `cost_usd`, `web_search_requests` (from `usage.server_tool_use`), `stop_reason`, and — inside a research run — the run's `run_id`, so prompt-cache hits are visible per turn, plus `cost_usd` — the actual USD OpenRouter charged for the call (read from `usage.cost`; null on the Anthropic-direct path or for rows logged before cost capture shipped). This is the token-usage + cost source of truth aggregated by both `/audit/sessions/{id}` (per session) and `/audit/usage` (cross-session).
    - memory_snapshot — one row at Executive turn entry; captures the system-block layout, conversation history length, episodic context (full text in `full_json`), and a company-profile hash so the session view can render "what the agent saw" before any API call
    - committee_review — one row per committee-reviewed turn; carries draft length, final length, per-reviewer critiques and timings (previously emitted but newly declared as a recognised event_type)
    - peer_memory — one row per `openexecutive.memory.honcho_client` call (prefetch / sync_turn / seed_identity / directional_chat / prefetch_department / sync_department_turn / append_department_note); carries `op`, `person_id`, optional `department_slug`, `outcome` (ok / timeout / error / disabled / no_person / no_department / no_loop / empty), `duration_ms`, plus op-specific details (query preview, reasoning_level, peer count, co_present_person_ids, co_present_department_slugs, originating_person_id, target_person_id, session_id, kind) so the flow-chart view renders the peer_memory path alongside `<retrieved_context>` and `<past_decisions>`. Disabled / no-Person / no-Department turns still emit (outcome marker) so audit absence equals "code path never ran" instead of "the provider was down."
    - external_signal_received — one row per signal an external-monitor adapter wrote to `external_signals`. Carries `signal_id`, `watchlist_id`, `watchlist_slug`, `source_kind`, `severity_hint`, `dedup_key`. The audit trail of what the monitor noticed, separate from what it surfaced.
    - external_signal_deferred — one row per poll that skipped entries whose published_at is more than the row's future-skew tolerance ahead (aggregated — `count`, `future_skew_hours`, `race_tick`, and up to 10 `entries` each with `dedup_key`, `published_at`, `summary` and `provenance_url`, so an operator can tell WHAT was held back). Emitted from the scan loop's finally, so it survives a poll that raises later in the same row. A deferred entry is by design NOT written to external_signals (that would burn its dedup key and mute it for good), so this row is its only trace until its date passes and it is judged normally.
    - external_signal_promoted — one row per signal promoted into the alerts pipeline (post-suppression cascade). Carries `signal_id`, `watchlist_id`, `watchlist_slug`, `source_kind`, `severity_hint`, `dedup_key`, `provenance_url`. Pair with `external_signal_received` to compute promotion rate per watchlist row.
    - external_monitor_poll — one row per watchlist row polled in a scan tick, emitted even when the row's poll raised or was cancelled (`failed` set to true, with `signals_emitted` still counting rows that landed before the failure, so the audit log stands on its own); `failed` is also true when the adapter crashed or no adapter is registered. A row with no registered adapter is still marked polled so it honours the cadence rather than re-firing every heartbeat. Carries `watchlist_id`, `watchlist_slug`, `signal_type`, `signals_emitted`, `duration_ms`, `failed`. Enables per-source health drill-down (`GET /audit?event_type=external_monitor_poll`) without needing a dedicated debug endpoint.
    - watchlist_research_periodic_ran — emitted by the periodic cron whenever the workflow actually fires. Carries `state_hash` (the input fingerprint at run time), `trigger` (`cold_start`, `state_changed`, or `staleness_floor`), `findings` count, `tool_calls` count, `ok_tool_calls`, `run_id`. The next tick reads the most recent row to decide skip-or-run (its `state_hash` for the fingerprint compare, its `ts` for the staleness floor). These three research run-history rows are the ONLY audit_log rows a fixture load/unload clears (via `monitoring.research.scheduler.clear_research_run_history`, called from `cli.fixture_loader._apply_state_from_source`): load wipes the profile/initiatives/watchlist that feed the fingerprint but otherwise preserves audit_log, so without this reset a same-fixture reload within the staleness floor would make the freshly-seeded scan skip itself and surface zero findings. A full reset still wipes all of audit_log. Also carries `usage` — the run's rollup of every model call it made (`calls`, token classes, `web_search_requests`, and `by_source` per actor), copied from the workflow's `result` event — so a run's weight is readable from the audit log."
    - watchlist_research_periodic_skipped — emitted when the state_hash matches the last `_ran` row. Carries `state_hash`. Visible cost-saving signal in the audit log.
    - watchlist_research_periodic_failed — emitted on workflow timeout / crash. Carries `state_hash` + `error` or `reason`.
    - watchlist_research_added / watchlist_research_suggested / watchlist_research_rejected — one row per `propose_watch` the research watch policy decided (`monitoring.research.watch_policy`). Carries `slug`, `target`, `signal_type`, `rationale`, `entity`, `grounding_kind`, `score`, `reasons`, and for adds the quiet defaults applied (`cadence`, `severity_floor`, `trigger`). `_added` also renders in the brief's HANDLED block as `watching`.
    - watchlist_suggestion_approved / watchlist_suggestion_declined / watchlist_suggestion_expired — the principal's verdict on a research suggestion (`POST /watchlist/{slug}/approve|decline`, reason on decline) or the sweep removing one unreviewed after WATCHLIST_PROPOSAL_TTL_DAYS. Each also writes a `watchlist_policy_outcomes` row so the policy calibrates.
    - watchlist_auto_disabled — the sweep disabled a research-origin watch (`reason`: dismissed N of M alerts with low trust; no signals in 30 days; 3 consecutive poll failures). Renders in the HANDLED block as `stopped_watching`; re-enable from /watchlist.
    - auth_login / auth_logout — admin auth events
    - executive_paused / executive_resumed — the operator pause switch flipped (scheduler.pause). actor is the caller's email (else "api"); details carry the reason on pause, and paused_at / paused_by / held_actions on resume. Re-pausing or re-resuming writes nothing.
    - scheduled_action_cancelled — a pending scheduled action cancelled via DELETE /scheduled/{id} (the Pulse page's Cancel, or a script). actor is the signed-in caller's email, "admin-token" or "local"; details carry action_id, kind, channel and department. A refused or 409 cancel writes nothing.
    - decision_class_mode_changed — a decision class's mode changed (propose ↔ auto_execute) via PUT /decisions/classes/meeting_scheduling. actor is the caller's x-caller-email or "api"; details carry decision_class and mode as from/to. Setting the current mode writes nothing.
    - workspace_settings_changed — solo/team mode, the user's time zone or the principal's role changed via PUT /workspace. actor is the caller's x-caller-email or "api"; details carry mode and timezone, each as from/to, plus role_fields_changed (the names of the role fields that changed, never their text — it is the principal's own and may name their manager) when the role changed. The summary names only what moved ("mode A → B, time zone X → Y" and/or "principal's role updated"). A PUT that changes nothing writes nothing.
    - roster_request_created / roster_ack_sent / roster_ack_withheld / roster_request_resolved / roster_message_replayed / roster_email_answer_refused — the roster-request lifecycle (people.roster_requests, integrations.roster_intake). Always private to the principal; details carry ids, the channel and statuses, never what the new sender wrote. roster_request_resolved's actor is where it was answered (web / slack / discord / telegram / email / people_page); roster_message_replayed is one per held message (replayed / dropped / failed / unavailable). The fixed acknowledgement email is an integration_outbound row (details.kind roster_ack, private).
    - delegation_settings_changed — a person turned Act as me on or off for themselves via PUT /delegation. actor "user"; details carry person_id and enabled. Always private. Setting the current value writes nothing.
    - delegation_gmail_verified — their own Gmail was checked (connected, and the mailbox on their People entry) just before Act as me was turned on. details carry person_id and status. Always private.
    - delegation_voice_changed — "How I write" learned from their sent mail (actor "delegation"), or edited, locked or reset via /delegation/voice, or its signature read from Gmail again via /delegation/voice/signature (actor "user"). details carry op (learn, edit, reset or signature), person_id, and counts, the names of the fields changed or whether a signature was found — never their text. Always private.
    - delegation_drafted — one per draft ghostwrite_email saved in someone's own Gmail. details carry person_id, thread_id, draft_id, reply, the recipient count and flags — never the draft, the intent or the thread. Always private; the daily draft cap counted these rows before delegation_drafts (the voice learner still reads them for older drafts).
    - delegation_inbox_changed — a person turned Draft replies to my inbox on or off via PUT /delegation/inbox (or off by turning Act as me off). actor "user"; details carry person_id and enabled. Always private.
    - delegation_inbox_scanned — one per completed inbox scan. actor "executive"; details carry person_id, the status and the counts (drafted, skipped, not_needed, deferred, failed, closed). Always private.
    - delegation_reply_drafted — the inbox watcher saved a reply in someone's own Gmail and made its card. details carry person_id, thread_id, draft_id, decision_id, relation, kind and flags — never the email or the draft. Always private.
    - delegation_reply_dismissed — a reply card was dismissed. details carry person_id, decision_id and what happened to the draft (deleted, kept_edited, already_gone, not_connected, gmail_error). Always private.
    - delegation_reply_closed — the reconciler (or a Send that found it settled) closed a card Gmail settled. details carry person_id, decision_id and the reason (expired, sent_in_gmail, draft_deleted, draft_gone, you_replied, thread_gone). Always private.
    - delegation_handle_it_changed — a person changed Handle it for me via PUT /delegation/handle-it (or it went off with the inbox watcher). actor "user"; details carry person_id, enabled and mode. Always private.
    - delegation_reply_handled — Handle it for me sent an inbox reply on its own. details carry person_id, decision_id, thread_id, sent_message_id and recipient_count, or confirmed_later from the reconciler. Always private.
    - delegation_reply_allowed — Send with the on-its-own-next-time tick, in training: the person allowed replies to a sender (or follow-ups to those people) after sending one. details carry person_id, decision_id, allowed_id and setting. Always private.
    - delegation_example_kept — Drafts in training: a reply the person changed in their mailbox and sent was kept as how they write to that person. details carry person_id, decision_id and allowed_id. Always private.
    - delegation_actions_allowed / delegation_actions_handled / delegation_actions_held — Suggested actions in training: Approve with the tick allowed those actions; a card of allowed actions (or any card it may carry out with Suggested actions On) was carried out on its own (details.outcomes); or it waited after all (details.reason). Always private.
    - delegation_training_changed — a person put Act as me settings in or out of training, or Suggested actions On or off (PUT /delegation/training). details carry person_id and each setting changed. Always private.
    - delegation_learned_removed — a person removed something Act as me had learned (DELETE /delegation/learned/{id}). details carry person_id and allowed_id. Always private.
    - take_the_lead_changed — a Take the lead switch, Ask first switch or company rule changed (PUT /take-the-lead, its rules, PUT /delegation/take-the-lead). actor "user"; details carry the scope and what changed.
    - delegation_reply_sent — the person tapped Send and their draft went, exactly as it was in Gmail. details carry person_id, decision_id, thread_id, sent_message_id, recipient_count and edited, or confirmed_later when the reconciler found an unconfirmed send had gone. Always private.
    - grounding — unattended prose that named people or figures its inputs don't hold (briefing/grounding.py). One row per brief or digest that held back lines or used its repair call (details — surface, kind, mode, repaired, cited, names_bad, figures_bad, up to 5 held-back lines cut to 200 chars), per refused outward tool call in the reflection (tool, names_bad, figures_bad, a 200-char preview), per reflection flag section filtered, and per triage / review rewrite it replaced. actor=executive; private when the brief read the principal's private rows or the alert is private. In `report` mode the rows are written and nothing is changed — the way to measure false positives before enforcing.
  turn_id: Set per Executive turn (`f"t-{uuid12}"`) and propagated automatically to retriever / specialist / tool / cache / committee emits via `openexecutive.audit.context` ContextVars. Groups every row in one user-assistant exchange under the same `turn_id`; the session view derives causal edges from this.
  writer: openexecutive.audit.AuditLogger — synchronous SQLite writer; uses WAL + 5s busy_timeout so concurrent webhook/scheduler/poller threads don't see "database is locked".
  failure_mode: All writes swallow exceptions and log a warning — an audit failure must never break a chat turn or tool call. The post-response cache_event emit also `getattr`-guards every usage field so a provider that omits one still produces a row.
  read_path: openexecutive.api.routes.audit — `GET /audit/logs` (filtered list), `GET /audit/logs/{id}` (un-truncated `full_json` drill-down), `GET /audit/sessions/{session_id}` (full ordered timeline + server-derived graph of nodes/edges for the /audit/session/[id] flow-chart view), and `GET /audit/usage` (cross-session token + cost aggregate — totals plus by-day and by-model breakdowns, summed from cache_event rows in SQL via `AuditLogger.usage_summary()` so it scales past the 1000-row `query()` cap). For a caller who is not the principal every route leaves out rows private to the principal (see `private_rows`) — the list and its total, the usage totals, a session's timeline (404 when nothing is left) — and a private row's id answers 404 exactly like a missing one.
  redaction: openexecutive.audit.redaction strips secrets and bounds detail blobs (`_DETAILS_MAX_LEN`) so a runaway tool input never bloats the index.
  ui_surfaces:
    - /audit — filterable list with optional "Group by session" toggle, clickable session pills, and a per-group mini node-strip with "Open full view →" link
    - /audit/session/[id] — three-pane flow-chart view (React Flow canvas + selected-node detail + collapsible JSON drawer)
    - /audit/usage — cross-session token-usage dashboard (totals cards incl. cost + cache-hit %, by-source, by-model and by-day tables with a UTC date-range filter; the by-source table groups on the row's `actor` and shows server-side searches); reached from the Settings hub (ADVANCED_ITEMS), not the primary nav
  invariants:
    - Audit is append-only — no UPDATE or DELETE paths from product code.
    - summary is the searchable column (LIKE on indexed text), capped at ~300 chars; details_json carries opaque structured fields and is NOT searched.
    - The module-level `_default_logger` is set during FastAPI lifespan via `set_audit_logger()` so non-FastAPI call sites (Executive, integration handlers, scheduler) can log without threading an instance around.
    - Instrumentation observes only — cache_event reads from `final_msg.usage` AFTER each response. The one request-side touch is a top-level usage-accounting flag (OpenRouter's `usage.include`) added by the translator (`to_openai_request`) so the provider reports `usage.cost`; it leaves the messages and the cache_control system blocks byte-identical, so prompt caching is unaffected. Adding new event types must not modify the system-prompt blocks or message construction, or prompt caching will regress.

external_monitoring:
  module: openexecutive.monitoring
  one_liner: Polls external sources and turns detected changes into proposals via the existing alerts pipeline.
  status: |
    PR-A (this PR) ships the foundation: watchlist + external_signals tables,
    Source-adapter Protocol, vendor_status adapter, external_monitor_scan
    scheduled-action kind, and the heartbeat/chain pattern. PR-B adds RSS
    + stock adapters and the chat tools (add_watchlist_entry, ...). PR-C
    extends executive_reflection to include external signals in its
    context and the briefing UI to badge external:* topic_tags.
  research_watch_policy: |
    The executive_research watchlist pass only PROPOSES (tool `propose_watch`:
    slug, signal_type, target, grounding_entity, rationale, certainty,
    finding_index). `monitoring.research.watch_policy` decides deterministically:
    - grounding vocabulary = company name + competitive_landscape.primary_competitors
      + profile.vendors + profile.tickers + active initiative titles +
      strategic_priorities.current_year + each department's `watched_entities`.
      Named-entity lists are PARSED (watch_policy.entity_names, input
      whitespace-collapsed and capped at 256 chars): only the name(s) before
      an em/en dash (any spacing), " - ", ":" or ";" ground, "A / B" yields
      both names, a parenthesised group that is ONE ticker-shaped token
      ("Tesla (TSLA)", "BYD (1211.HK)", not "(US, EU)" nor ordinary
      abbreviations such as US/EV/IT/NOW) becomes a ticker term, and
      parenthesised hosts ("Brex (brex.com, status.brex.com)") PIN the
      entity's own domains. A bare URL / host entry grounds as its site label
      with the host pinned. The description is dropped (it hid short names
      such as BYD inside a sentence and would have made "global" BYD's
      own-source word); parenthesised brand names ("Alphabet (Google)") are
      not aliases — list them as entries. profile.tickers are taken as typed.
      Short names (BYD, GM, Kia, AWS) match as whole words because a
      vocabulary term of any length is a distinctive token; a TICKER term
      grounds only when it IS the entity ("US" never grounds "US Foods").
      Only parentheses in the NAME part are read: description text can
      neither pin a domain nor mint a ticker, and a capitalised brand
      ("(Waymo)", "(Siri)") is never a ticker — tickers are typed in
      capitals ("(TSLA)", "(F)", "(1211.HK)"); an all-caps host ("(GM.COM)")
      is a host. profile.tickers entries keep their symbol and drop any
      trailing note ("NVDA — our supplier"). Own source with pinned domains:
      those hosts and their subdomains only (a look-alike such as gm.co.ke,
      which carries the same site label, no longer qualifies; primary-source
      hosts such as sec.gov still count for every entity); without pinned
      domains the site label must be the entity's leading name, as before —
      pin domains for any short-named entity. The auto-link ranking honours
      pinned domains too, so a planted page cannot win the evidence slot.
      A cited finding that does not concern the source still marks the
      proposal as research-derived (a suggestion at most) but is never the
      row's source_url.
      (kind department_entity, strong) + each department's charter scope
      phrases and goal key results (kind department_scope, suggestion-only)
      (+ existing watch labels, which only corroborate). The entity MUST
      match a company-data term for a direct add. Every vocabulary value is
      a VocabEntry(kind, department): terms that came from a department carry
      its slug, and a profile term a department also lists keeps the profile
      kind but gains the department (stronger kind wins, department is kept;
      between two departments the one supplying the winning kind owns it).
    - vocabulary precedence when a term appears in several sources:
      company > competitor > vendor > ticker > department_entity > initiative
      > priority > department_scope > watch. Profile kinds outrank department
      kinds so the policy's (signal_type, kind) history keeps applying.
      Partial (token) matching ignores stopwords and tokens < 4 chars.
    - episodic decisions: the run loads the 10 most recent `decisions` rows
      from the last 90 days (watch_policy.recent_decisions; an unreadable
      timestamp means not recent); a proposal whose matched COMPANY-DATA
      entity (never a bare watch label) is named in one scores +1 ("named in
      a recent decision"), and when the term has no department but the
      decision was recorded for one, that department becomes the routing
      hint. "Named" = the whole term as a phrase, or EVERY distinctive token
      of the term as a whole word — a common word shared with the term is
      not a mention. Decisions are rendered to every specialist as RECENT
      DECISIONS (user turn) whether or not they match; only matching ones
      move the research fingerprint (a decision that names nothing the
      policy knows cannot change what it would do).
    - score ledger: +2 entity in company data (mandatory), +1 entity already
      watched under another source, +1 target is the entity's own source (for
      stock/edgar the grounding entity IS the ticker / a URL whose SITE LABEL —
      "acme" in status.acme.com, acme.co.uk; never a subdomain or TLD — is the
      entity's NAME: its leading distinctive word or all its words run
      together, never a generic trailing word ("Acme Payments" is not
      payments.io) / a primary-source host: sec.gov, federalregister.gov,
      eur-lex), +1 finding confidence high, +1
      cross-specialist consensus, ±1 policy history for (signal_type,
      grounding_kind) at >= 5 samples (>= 0.7 / <= 0.3 approval rate).
    - finding points (high / consensus) count only when the cited
      finding concerns THIS source: a URL target shares its site with a cited
      URL; a ticker/query target appears in the finding text (as a phrase —
      "1211.HK" is two words once normalized) or is the named entity. A strong
      finding cannot be borrowed for an unrelated page.
    - `finding_index` is REQUIRED in the propose_watch schema and the pass's
      RULES say so; when the model still omits it, or cites a finding that
      does not concern the source (three dev runs on Haiku and Sonnet omitted
      it on every proposal), apply_proposals links the finding that best
      concerns the source by the same test the score uses
      (watch_policy.auto_link_finding: with the entity term classify would
      use; ranked by citing the target's site / naming the ticker, then
      citing the entity's own site, confidence, order) and
      records "linked to finding #N, which concerns this source" as the
      first reason. The caller's proposal is not mutated. A proposal nothing
      cites is still rejected as having no evidence.
    - direct add at score >= 4 with the mandatory match AND the entity's OWN
      source AND a linked finding that concerns this source (company data
      plus a decision mention can reach the bar alone; nothing goes live on
      hearsay) AND a strong kind (company / competitor / vendor / ticker /
      department_entity — initiative-, priority- or department_scope-grounded
      proposals are suggestions at most); model
      `certainty` can only downgrade; `query` never direct; a suggestion needs
      a linked finding and score >= 1 (SUGGEST_THRESHOLD) — nothing vouching
      for it is rejected; at or above WATCHLIST_MAX_ENABLED (40) enabled rows
      EVERY proposal is rejected (suggestions poll too, so the ceiling must
      stop them or it latches); WATCHLIST_RESEARCH_MAX_DIRECT_ADDS (2) and
      WATCHLIST_RESEARCH_MAX_PROPOSALS (2) per run (a direct add past its
      budget is filed as a suggestion and charged to that budget). Budgets
      and the ceiling are spent strongest first: apply_proposals classifies
      every proposal against the run's starting state, then persists them
      in order of tier (direct, suggest, reject) and descending score, ties
      in file order; a duplicate target keeps its strongest filing. The
      score does not depend on earlier inserts, but the tier does, so the
      persisting pass classifies again and a row inserted for a stronger
      proposal counts as "already watched" for a weaker one on the same
      site. Before this a dev run rejected a score-4 Finance watched-entity
      proposal (Brex) as over budget because two score-3 proposals had been
      filed earlier in the same call. The returned summaries keep file
      order.
    - quiet defaults on every research row (model cannot loosen): cadence
      daily (vendor_status hourly; page_watch/query weekly), severity_floor
      medium, keyword trigger (rss/query only — a page_watch summary is
      "page changed" and would never match) = material-event words +
      priority terms (NEVER the entity name: feed summaries carry the feed
      label, so it would match every entry), stock abs_change_pct_gte=5.
      Vocabulary: URL targets contribute their site label only; short
      whole-term names (IBM, AWS) still match in longer forms; the policy
      stamp keeps the model's entity string when nothing matched, so a
      not_relevant decline on an ungrounded suggestion still blacklists it.
    - direct → mode=active, origin=research; suggestion → mode=dry_run,
      origin=research_proposed; rationale in `notes`; policy stamp (entity,
      grounding_kind, department, specialist, score, reasons, source_url) in
      config_json._policy. Reject: invalid target, same site + signal_type
      already watched, declined target, spent budget.
    - routing: a department-grounded row is inserted with
      route_to_department=<slug> and route_to_person_id=<the department's
      head at insert time> (a later head change does not re-route existing
      rows). monitoring.pipeline._signal_to_alert_event maps these onto the
      AlertEvent (routed_to_person_id, department=<slug>) for EVERY watch,
      manual ones included, so alerts.pipeline routes the alert to the head
      and tags it department:<slug> and it queues on the head's /today.
      AlertEvent.department is a TAG hint only — the slug is deliberately
      not put in `channel`, which triage renders as the room a message came
      from and may answer with a department_channel broadcast; a watch alert
      must reach the head, not the whole team room. Because briefing.ranking
      treats any routed alert as "action", a department watch's alerts land
      in the head's Needs-you lane (their volume is bounded by the research
      rows' quiet defaults). route_to_person_id is not re-validated against
      the roster: an archived or replaced head keeps the watch's alerts until
      the row is re-routed.
    - department head approval: after the apply loop, suggestions are grouped
      by department and ONE "Watch suggestions for <Title>" card per
      department is filed via departments.authority.propose_via_alert
      (source=authority_gate, routed to the head, or to the principal when
      the department has no head; tags department:<slug>, person:<id>,
      watchlist). propose_via_alert's new `external_id_suffix` (the ISO week)
      makes the card recurring: an open card is refreshed in place
      (coalesce_alert), an acknowledged one is not re-minted until the next
      week; an open card is refreshed whatever the week, so one department
      never has two open cards. The principal's pile-up nudge counts only
      suggestions that reached no head (route_to_person_id NULL — the
      principal's own, and rows for a department without a head), so a
      suggestion can never become invisible. /watchlist shows
      "for: <department>" on routed suggestion and research cards.
      Approve/decline stay identity-free.
    - declines (`watchlist_declines`, keyed by normalized target — https
      forced, www. dropped, host/path lower-cased, query/fragment/trailing
      slash removed): explicit (Decline button, "Stop watching…",
      remove_watchlist_entry / DELETE on a research-origin row) is permanent;
      expired_unreviewed (sweep expiry, and auto-disable) retries once after
      90 days. Enforced in the propose_watch handler BEFORE any fetch — by
      target, and by entity for not_relevant declines (token match) —
      and rendered to the model as DECLINED. Decline reasons: not_relevant
      (blacklist entity), wrong_source (blacklist target), too_noisy (keep
      live at floor=high; response result=kept_high_floor; recorded as a
      DECLINED outcome for calibration). Tool-supplied reasons outside the
      explicit set fall back to not_relevant.
    - isolation: the routing/synthesis pass has NO watchlist write tools
      (add/tune/remove are in _SYNTHESIS_EXCLUDED_TOOLS, as are
      run_executive_research, run_workflow and send_company_broadcast), so every watch a
      research run creates goes through the policy; tune_watchlist_entry
      accepts only notes on a pending suggestion (approve/decline move it;
      its quiet defaults cannot be loosened while it waits); URL-typed
      targets pass validate_target_url at insert time; approve / decline /
      expiry are compare-and-act on "still pending" (the guarded delete runs
      under BEGIN IMMEDIATE). Normalized URL keys also fold percent-encoding,
      dot segments and a trailing host dot.
    - outcomes (`watchlist_policy_outcomes`: approved / declined / expired /
      auto_disabled by signal_type, grounding_kind, specialist) feed the
      history term and are rendered to the model as HOW PAST PROPOSALS TURNED OUT.
    - sweep (watch_policy.sweep, on the scheduler's 15-min alert sweep):
      expire suggestions older than WATCHLIST_PROPOSAL_TTL_DAYS (14)
      (compare-and-delete: an approve in flight wins); auto-disable
      research-origin watches (fired >= 5 & dismissed >= 2 & trust <= 0.5;
      3 consecutive failed polls — silence is NOT a rule, an unchanged page
      or a healthy vendor is a working watch) and record the target as a
      90-day decline; one `watchlist_suggestions` nudge alert when >= 3
      suggestions have waited >= 7 days — dedup_key watchlist_suggestions:pending
      (an open card is coalesced in place), external_id per ISO week (a
      dismissed card is not re-minted until next week), so acting on one
      suggestion never spawns another nudge.
    - the research state fingerprint hashes only enabled + active rows, so
      approving / declining a suggestion never triggers a fresh research run.
      It also hashes each department's watched_entities / charter scope /
      goal key results, and the recent decisions whose summary names a
      vocabulary term — the same vocabulary the policy grounds with
      (profile + initiatives + departments; watch labels never ground) —
      only those: the chat extractor writes decisions freely, and one
      naming nothing the policy knows cannot change what the policy would
      do. A matching decision ageing past 90 days moves the hash once.
    - surfaces: /watchlist "Suggested by the Executive" (Approve / Decline…
      with reason), "Added by the Executive · rationale" on research cards
      with "Stop watching…", the morning brief's HANDLED block (watching /
      stopped_watching) and a one-line WATCH SUGGESTIONS WAITING count.
  plain_words_setup: |
    The /watchlist page starts from a sentence ("What should I watch?").
    POST /watchlist/describe {text} calls monitoring.describe.describe_watch:
    one forced draft_watch tool call on the utility-fast model (actor
    watchlist_describe), whose field guidance is copied from the chat
    add_watchlist_entry tool. The system prompt is a constant; the company
    profile's name, competitors, vendors and tickers go in the USER turn
    (company_context block) beside the request block, never a cached block.
    - the model's fields go through the create route's checks before the
      person sees them: registered kind, ticker shape, the SSRF URL guard
      (in a worker thread, it resolves the host), the rss feed check
      (validate_and_normalize_target, which may turn a feed-less page into a
      page_watch or refuse it), cadence / severity (a floor above the
      ceiling lifts the ceiling), trigger keys the adapter doesn't read
      dropped, and a free slug (validation.suggest_watch_slug, the same rule
      as the UI's suggestWatchSlug, with -2, -3 ... when taken).
    - the four plain lines (watching, tell_you_when, how_often, how_loud)
      are written by code from the checked fields, never by the model, so
      they describe exactly what POST /watchlist stores. The UI's
      lib/watchWords.ts says triggers the same way on the detail page.
    - nothing is saved: Start watching POSTs the draft to /watchlist,
      Change something opens the by-hand form filled in from it.
    - errors are plain: 422 (empty, too long, or the model's own "cannot"
      reason / a failed check), 429 past DESCRIBE_PER_HOUR (30, in-process) or
      DESCRIBE_PER_CALLER_PER_HOUR (10 per signed-in caller),
      502 / 504 when the model call fails or times out.
    - create's display_label now maps to the adapter's label key for every
      kind (validation.display_label_config, shared with the chat tool), so
      a drafted query / edgar / page_watch keeps its name.
  noisy_watch_question: |
    monitoring.noise.watch_noise reads the statuses of the newest 8 alerts a
    watch promoted (alerts joined through external_signals.promoted_alert_id,
    one row per alert). At 6 dismissed GET /watchlist/{slug} returns
    noise.noisy and the detail page asks "Only tell you about bigger
    changes?": double a stock's abs_change_pct_gte (whole percent, at most
    100), otherwise one step up the severity floor; Stop watching (the
    delete confirmation); Keep as is. Each answer PATCHes
    quiet_noise_nudge: true, which stores the newest alert id in
    config_json._noise_nudge_after_alert_id (json_set, no read-modify-write);
    only later alerts count, so the question comes back only after a fresh
    run of dismissals. Separate from the research sweep's auto-disable,
    which reads dismiss_count and trust_score and only touches research rows.
  data_model:
    watchlist (in episodic_memory.db): |
      One row per condition the user wants monitored. Mutable per-row
      state (last_polled_at, last_fired_at, fired_count, dismiss_count,
      trust_score) lives on the row so the tuning loop in PR-B/PR-C can
      update entries cheaply.
      Columns: id, slug, signal_type, target, config_json, trigger_json,
      cadence, severity_floor, severity_ceiling, route_to_specialist,
      route_to_department, route_to_person_id, mode ('active' | 'dry_run'),
      enabled, created_at, last_polled_at, baselined_at, last_fired_at,
      fired_count, dismiss_count, trust_score, notes, origin ('manual' |
      'executive' | 'research' | 'research_proposed'; additive ALTER,
      default 'manual').
    watchlist_declines / watchlist_policy_outcomes (in episodic_memory.db): |
      Research watch policy memory — see research_watch_policy above.
      watchlist_declines(normalized_target PK, entity, signal_type, slug,
      kind 'declined_explicit' | 'expired_unreviewed', reason, declined_at);
      watchlist_policy_outcomes(id, signal_type, grounding_kind, specialist,
      outcome 'approved' | 'declined' | 'expired' | 'auto_disabled', at).
      baselined_at (nullable, additive ALTER; backfilled from
      last_polled_at for rows that were already being polled when the
      column landed) is set once a seeding source's first poll that
      returned entries has been recorded — see external_signals below.
      UNIQUE(slug). Indexed on (enabled, signal_type) for the scan
      walker.
    external_signals (in episodic_memory.db): |
      One row per signal an adapter emitted. Persisting suppressed signals
      is intentional — the briefing layer can answer "what did you ignore
      overnight" and the trust loop has a denominator for hit-rate metrics.
      Columns: id, watchlist_id, source_kind, source_external_id,
      captured_at, published_at, normalized_summary, raw_payload_json,
      provenance_url, severity_hint, dedup_key, processed_at,
      processed_outcome
      ('alerted' | 'suppressed_baseline' | 'suppressed_stale' |
      'suppressed_dry_run' | 'suppressed_below_floor' |
      'suppressed_dup' | 'suppressed_triage' | 'suppressed_low_relevance' |
      'failed'),
      promoted_alert_id, enrichment_json.
      captured_at is when the monitor first saw the event; published_at
      (nullable, added via the same idempotent additive ALTER pattern) is
      when the upstream says it happened — RSS <pubDate>/<updated>, EDGAR
      filing date; NULL for stock / page_watch / query. The two are never
      conflated (issue #80). Two freshness gates run FIRST in the
      suppression cascade, before dry_run / floor / enrichment, so they
      never spend an LLM call: (1) `suppressed_baseline` — on the first
      poll that RETURNS ENTRIES for a row whose adapter declares
      `seed_on_first_poll` (rss, edgar) and whose `baselined_at` is NULL,
      every entry in the feed is recorded as seen and nothing is promoted.
      The claim and the recording are ONE transaction
      (store.record_baseline, BEGIN IMMEDIATE): a compare-and-swap on
      `baselined_at IS NULL` stamps the row, then EVERY fetched entry —
      trigger misses included, so the first entry that ever matches a
      keyword is news rather than "back-catalogue", and widening a
      trigger later can't resurface what was already in the feed — is
      inserted and marked suppressed_baseline; a failure part-way rolls
      the stamp back with the rows, so the next tick baselines the whole
      feed again rather than replaying an unrecorded tail. One row's
      store failure is logged and skipped so the rest of the scan runs.
      A scan that loses the race (overlapping heartbeat + client
      rotation, or a slow tick) re-reads the winner's stamp and treats
      entries published at or before it — and undated ones, since the
      feed controls published_at — as baseline, promoting entries dated
      after the stamp (and deferring, not recording, any dated more than
      a few minutes past its own clock), so neither the back-catalogue replays as news
      nor real news gets buried; later ticks process normally. The
      net effect is that a new watch reports what changes
      from now on rather than replaying the feed's back-catalogue
      (mirrors page_watch's first-observation baseline). Keyed on
      baselined_at, not last_polled_at, so a failed/empty first fetch
      leaves the next successful poll as the baseline; baseline rows are
      written but do NOT count against max_signals_per_scan, so a big
      feed can't be half-baselined and replay its tail next tick;
      (2) `suppressed_stale` — a signal whose published_at is older than
      EXTERNAL_MONITOR_MAX_SIGNAL_AGE_DAYS (default 7; 0 disables) at
      capture time is recorded but never promoted. An entry dated more
      than EXTERNAL_MONITOR_MAX_FUTURE_SKEW_HOURS (default 24; 0 disables;
      overridable per row via config_json.max_future_skew_hours, 0..8760,
      for a calendar or maintenance feed that legitimately dates ahead; an
      out-of-range or unparseable override is ignored with a warning, never
      coerced — the adapters use the same value when choosing between an
      entry's date keys) in the FUTURE is instead
      deferred — skipped for the tick and NOT recorded, since recording
      burns the dedup key and would let a feed mute an announcement for
      good by post-dating it; the poll emits one aggregated
      `external_signal_deferred` audit row so the skip is visible, and
      once the date passes the entry is judged like any other. On a
      lost-race tick the bound is a tight 5-minute drift tolerance
      instead (nothing the scan fetched can honestly be dated later). The alert body handed
      to triage carries `Published:` (when known) and `Discovered:`
      lines so anything inside the window is still judged on when it
      happened, not when it was found. Adapters prefer a plausible
      date key over one more than a day in the future, and keep the
      future value when every key is implausible so the pipeline can
      defer it rather than wave an undated entry through; they also
      collapse whitespace in feed titles so an entry can't
      forge its own labeled body line.
      enrichment_json holds the capture-time relevance read
      (relevance_score 0..1, why_it_matters, matched_initiative) written by
      the enrichment stage; '{}' when enrichment is off or missed. Added via
      an idempotent additive ALTER in initialize_db (no migration framework).
      UNIQUE(dedup_key) is the canonical anti-replay guard — adapters
      compute deterministic keys; re-polling the same upstream event is
      a no-op at insert time.
    page_watch_state (in episodic_memory.db): |
      State for the stateful `page_watch` adapter: one row per watchlist slug
      holding the last-seen normalized-content hash + a text snapshot used to
      summarise the next diff. Columns: slug (PK), content_hash, text_snapshot,
      updated_at. The adapter reads/writes it via the db_path threaded through
      Source.poll so its state lands in the same DB as the scan's signals.
  sources:
    contract: |
      `monitoring.sources.base.Source` Protocol — every adapter declares
      `kind`, `default_poll_interval_minutes`, an async
      `poll(item, *, db_path=None)` that returns `list[Signal]`, and a
      `matches_trigger(signal, item)` filter. `db_path` is the scan's DB —
      stateless adapters ignore it; stateful ones (page_watch) thread it into
      their store calls. Each adapter MUST be read-only upstream, MUST compute a
      deterministic dedup_key, MUST set provenance_url on every Signal,
      and MUST bound its fetch via
      `settings.external_monitor_max_fetch_bytes`.
    registry: |
      `monitoring.sources._REGISTRY` is the runtime map from
      `signal_type` (free-text string on the watchlist row) to the
      `Source` instance that handles it. New adapters register here;
      add a top-level fact in this YAML when they ship.
    shipped:
      - "vendor_status — polls Statuspage Atom/RSS history feeds (AWS, Stripe, Twilio, GitHub, Cloudflare, …) and emits one Signal per incident entry. Severity hint HIGH by default. Optional `trigger_json.keywords` narrows to entries whose title contains a keyword. Dedup key is sha256(slug + NUL + entry id + NUL + <updated>) — the <updated> component is load-bearing (issue #90): an incident's entry id never changes across its updates, so keying on the id alone made every suppression permanent, which is why this adapter used to sit outside BOTH #80 freshness gates and replayed a vendor's resolved archive as HIGH alerts on the first poll. With the state in the key a suppressed insert burns one state of an incident rather than the incident, so both gates now apply: published_at is parsed from <updated>/<pubDate> (age gate + future deferral), and the row is seeded on its first poll. The adapter reads each incident's CURRENT status out of the entry body (Statuspage renders the newest update first as <strong>Resolved</strong> / Investigating / Monitoring / …; the classifier is deliberately ASYMMETRIC and position-independent. Evidence that an incident is OVER counts from anywhere — an AWS-style [RESOLVED] title marker, a status label, or an update's prose; evidence that it is still OPEN counts only from a label the vendor marked up (<strong>Investigating</strong>), never from prose. Nothing tries to work out which update is newest: four review rounds each found a different way to get that wrong (scanning past an unrecognised label, mining prose for status words, skipping an unlabelled update in the element tree, and reading past a block whose end tag HTML lets you omit), and each reported a long-resolved incident as live, promoting an archive at HIGH. Position is not a property tag soup can express, so the rule does not depend on it and is monotone: more evidence only ever makes the answer safer. Bodies are parsed by html.parser.HTMLParser (a label in a comment, a script or an attribute value is not a label; <b> counts as <strong>), off the event loop via asyncio.to_thread, from ONE element chosen by its text (_entry_body), with an xhtml-typed <content> re-serialised — escaped — so both feed shapes reach the parser identically. Known residual: an unrecognised or empty label on the newest update, with an older open label and no sign of closure anywhere, reads as open — which is why an exempt entry is NOT excused the age gate, bounding that to an entry the feed dates inside the age window) and implements the optional `promote_on_baseline` hook, which exempts incidents that are still OPEN from its own baseline — so a new watch added during an outage surfaces that outage immediately while the resolved archive is recorded as suppressed_baseline. Unrecognised status counts as CLOSED (fail closed: a vendor changing feed format must not be able to promote its archive; the next <updated> bump mints a new key and surfaces normally). Exempt entries must also pass the row's trigger filter — one that misses stays in the baseline, or widening the trigger later would resurface it as news — and they bypass the age gate, since an incident the adapter calls still-happening can have an <updated> stamp days old and recording it as stale would burn its key. The dedup key hashes the NORMALISED stamp (the same parse that fills published_at), so Z vs +00:00 is one key and a serialisation change does not rekey a vendor's open incidents. One-time migration `vendor_status_dedup_rekey_90` (marker row in `monitoring_migrations`) clears `baselined_at` on existing vendor_status rows so the upgrade tick re-seeds under the new key scheme instead of replaying."
      - "rss — generic Atom/RSS feed adapter via feedparser; handles competitor changelogs, layoffs.fyi, USPTO patent feeds, regulatory filings, blog RSS. Severity hint LOW by default (most RSS is noisy). Optional `trigger_json.keywords` filters by title + summary. Each entry's <pubDate>/<updated> is parsed into Signal.published_at; declares `seed_on_first_poll` so a new watch baselines the feed's existing entries instead of firing them, and entries older than EXTERNAL_MONITOR_MAX_SIGNAL_AGE_DAYS are recorded as `suppressed_stale` (issue #80)."
      - "stock — Yahoo Finance Chart endpoint (the same endpoint yfinance scrapes, used directly via httpx to avoid pandas/numpy). Watchlist `target` is the ticker; signals fire when |intraday vs previous close| ≥ `trigger.abs_change_pct_gte` (default 5%). Severity hint scales with the magnitude of the move (≥10% URGENT, ≥5% HIGH, ≥2% MEDIUM, else LOW). v2 candidate: swap behind the same Source interface for a paid Alpha Vantage / Finnhub feed if Yahoo brittleness bites."
      - "query — standing web-search query. Watchlist `target` is a natural-language query (e.g. 'Acme Corp layoffs OR restructuring OR funding'); each poll runs it through `BaseAgent.analyze_with_tools` with the web_search tool (model pinned to `get_research_model()`, honouring an OpenRouter Council override — the provider layer translates native web_search into OpenRouter's `plugins:[{id:web}]`, see providers/translator). The model reports distinct results via the `emit_query_results` tool; each result with a valid clickable URL becomes a Signal (the adapter emits a flat severity hint LOW because it can't judge materiality per-hit — the pipeline regrades this from the capture-time relevance read BEFORE the floor gate via `_grade_query_severity`, so a material hit clears a medium/high floor instead of being suppressed; dedup key `query:` + first 32 hex chars of sha256(slug + NUL + canonical_url); URL-less results dropped to uphold the provenance invariant). UNLIKE the keyless feed adapters this source is BILLED (one LLM call + web searches per poll), so it polls slowly (default 360 min), is bounded by `web_search_max_uses` + per-row `config.max_results` (default 5, ceiling 10), and has its own kill switch `EXTERNAL_MONITOR_QUERY_ENABLED`. Optional `trigger.keywords` filters like rss; `config.allowed_domains`/`blocked_domains` are best-effort prompt hints only (NOT enforced, and not honoured by the OpenRouter web plugin). This is the 'watch arbitrary conditions' primitive that no feed publishes."
      - "edgar — SEC EDGAR filings. Watchlist `target` is a ticker (e.g. 'AAPL') or CIK; polls SEC's browse-edgar Atom feed (`/cgi-bin/browse-edgar?action=getcompany&CIK=…&output=atom`, whose CIK param resolves a ticker server-side, so no ticker→CIK table is shipped), parsed with feedparser. Emits one Signal per new filing whose form is in the filter (`trigger.forms`, default {8-K, 10-K, 10-Q}; amendments like 8-K/A match their base form). Dedup on the filing's accession number (globally unique — the cleanest natural key of any source). Provenance is the filing-index URL. Severity hint: 8-K HIGH (material-event report), 10-K/10-Q MEDIUM, else LOW. Keyless, but SEC's fair-access policy requires a descriptive User-Agent with a contact — sent via the EDGAR_USER_AGENT setting (operators should override the default with a real contact). Reuses fetch_bounded (now with a per-call user_agent override), validate_target_url, and the standard dedup/Signal pattern. The entry's <updated> lands on Signal.published_at and the adapter declares `seed_on_first_poll`, so a new watch baselines past filings instead of replaying them and filings older than EXTERNAL_MONITOR_MAX_SIGNAL_AGE_DAYS are `suppressed_stale`."
      - "page_watch — generic web-page change detection for feed-less pages (pricing, careers, leadership, ToS). Watchlist `target` is the page URL. STATEFUL (the first stateful adapter): each poll fetches the page (bounded, SSRF-guarded), reduces it to normalized visible text (drops script/style/comments/tags, unescapes entities, collapses whitespace — so markup/layout churn doesn't register), hashes the FULL normalized text (so a change anywhere registers — no length blind spot), and compares to the last-seen hash in `page_watch_state`. First observation stores a baseline and emits NOTHING; an unchanged page emits nothing; a changed page emits ONE Signal carrying a difflib-based change summary (~N% differs + the added text; the diff/snapshot are length-capped but detection is not) and updates the baseline. Severity hint LOW (page diffs are noisy — enrichment + severity_floor filter). Dedup key folds slug + UTC date + content hash (mirrors stock — a state seen again on a later day re-alerts; same-day repeats dedup). Optional `trigger.keywords` only surfaces a change when the change itself (summary + added text) matches. Reads/writes its state via the db_path threaded through Source.poll. The reduction (html_to_text, which insert-time validation also runs on the request path) takes whatever the server sends and runs synchronously on the event loop, so every step is one forward pass: comments and script/style/noscript blocks by a scan (_strip_blocks), the remaining tags by utils.html_tags.strip_tags (shared with delegation.gmail), never a backtracking regex. The `<[^>]+>` strip it replaced rescanned to the end of the page from every '<' that nothing closed — about 40 minutes of CPU for a 2 MB page, with the API frozen meanwhile. Such a '<' stays text, and a unit test times crafted pages. The keyless httpx fetcher is the only fetch path. A row written before the xcrawl scrape path was removed still carries `config.fetch = \"xcrawl\"` (PAGE_WATCH_FETCH_LEGACY_XCRAWL) and a baseline hashed from scraped markdown; the adapter treats that marker as a stale baseline — the next poll re-captures the baseline from the plain fetch WITHOUT emitting a signal and clears the marker in place (store.remove_watchlist_config_key, a SQL json_remove so a concurrent edit to another config key is kept), so the change of fetcher is never reported as a page change. An unsaved item (no id) cannot have its marker cleared and is compared normally."
  insert_validation: |
    monitoring.target_validation.validate_and_normalize_target — runs at
    insert time on BOTH watchlist surfaces (POST /watchlist and the
    add_watchlist_entry chat tool) before a row lands. Only `rss` targets
    are validated (every other signal_type passes through with no network
    I/O). The target is fetched (bounded, SSRF-guarded) and feedparsed:
      - recognized as a feed (parsed.version set, incl. an empty/new feed)
        → kept as rss;
      - a public server answered but it is not a feed → CONVERTED to a
        page_watch when the body the feed check already fetched reduces to
        readable text (page_watch.html_to_text — same SSRF guard and byte
        cap the adapter itself uses; no second fetch, no fetch marker
        written), else REJECTED (WatchlistTargetError → HTTP 422 / tool
        error). An oversized body or an HTTP error status has no body to
        inspect and is rejected;
      - SSRF-rejected / unparseable URL → 'blocked' → rejected outright,
        never fetched;
      - transient fetch failure → inserted unverified (don't penalize a
        feed that's merely down right now; the scan loop retries).
    Exists because executive_research proposes feed URLs the model never
    verified — historically the great majority were dead, which is what
    left the briefing's monitoring section empty.
  no_external_fetch_service: |
    There is no third-party scrape / render service. The xcrawl client, the
    read-before-cite scrape loop (`monitoring/research/agentic.py`), the
    post-dedup verify pass (`monitoring/research/verification.py`) and the
    `XCRAWL_*`, `EXTERNAL_RESEARCH_VERIFY_*`, `RESEARCH_AGENTIC_*`,
    `RESEARCH_SCRAPE_*` and `RESEARCH_LOOP_*` settings were removed: the
    service had been failing on every call for weeks with nothing noticing
    (every failure degraded silently to "unverified"), and it was the only
    outbound fetch that bypassed the on-box SSRF guard. Every watchlist
    fetch is now the keyless, SSRF-guarded, byte-capped httpx fetcher, and
    research grounding is the provider web_search path (Anthropic native /
    OpenRouter web plugin). A deployment that still sets the removed
    variables is unaffected (unknown env vars are ignored).
    The guard holds across redirects and DNS changes: fetch_bounded
    (`monitoring/sources/_http.py`) follows redirects itself, at most
    MAX_REDIRECTS (3), and resolves and checks every hop, the first
    included, against the same public-address rule as
    validate_target_url. It then connects to the address it checked,
    keeping the hostname in the Host header and the TLS server name, so a
    public URL that redirects to 127.0.0.1, 169.254.169.254 or a private
    IPv6 address, or a name that resolves differently on a second lookup,
    is never fetched. A refused hop raises BlockedTargetError, an
    httpx.HTTPError, so adapters log it and skip the tick.
  pipeline: |
    openexecutive.monitoring.pipeline — `run_external_monitor_scan(now)`
    is the per-tick entry point. It walks
    `store.list_watchlist(enabled_only=True)`, skips rows whose
    `last_polled_at` is fresher than the per-source cadence floor
    (`external_monitor_{vendor_status,rss,stock}_poll_minutes`), and
    fires the adapter for the rest. Each Signal is:
      1. Trigger-filtered (`Source.matches_trigger`).
      2. Severity-clamped to the watchlist's [floor, ceiling].
      3. INSERTed into `external_signals` (UNIQUE(dedup_key) drops dups).
      4. Routed through the suppression cascade:
         - watchlist.mode == 'dry_run' → suppressed_dry_run
         - QUERY EXCEPTION: a `query` signal arrives flat-LOW (the adapter
           can't judge materiality), so for query signals enrichment runs
           BEFORE the floor gate and `_grade_query_severity` maps the relevance
           read onto a band (>=0.8 HIGH, >=0.5 MEDIUM, else LOW, capped to the
           row ceiling). This lets a material hit clear a medium/high floor and
           reach the Monitoring lane; noise stays LOW and is floor-suppressed.
         - signal.severity_hint < severity_floor → suppressed_below_floor
         - capture-time ENRICHMENT (see enrichment key) runs HERE for the
           pre-graded sources — after the dry_run/floor gates so a suppressed
           signal never costs an LLM call (query was already enriched above to
           grade severity, so it is not enriched twice) — scoring relevance +
           writing why_it_matters; if relevance_score <
           EXTERNAL_MONITOR_ENRICHMENT_MIN_RELEVANCE (default 0.0 = off) →
           suppressed_low_relevance
         - else → promote_signal_to_alert (status: alerted), with the
           enrichment's why_it_matters line added to the alert body
    Total signals per tick are capped at
    `external_monitor_max_signals_per_scan` (default 50). Adapter
    crashes / fetch failures are caught per-row so one bad source can
    not poison the others — identical pattern to nudge_engine.
  enrichment: |
    `monitoring.enrichment` — capture-time relevance scoring that runs on
    EVERY source (stock / rss / vendor_status / query), not just query. The
    pipeline loads company context ONCE per scan (`build_company_context`:
    the profile prompt block + active initiative titles/statuses — the same
    two inputs the research scheduler fingerprints) and threads it into
    `enrich_signal` for each promotable signal. `enrich_signal` makes one
    cheap LLM call with NO web_search (it scores what was captured) via the
    shared `BaseAgent.analyze_with_tools` path (model pinned to
    `get_research_model()`, so an OpenRouter Council override is honoured),
    emitting a `SignalEnrichment` (relevance_score 0..1, why_it_matters,
    matched_initiative) through the `emit_relevance` tool. The result is
    persisted to `external_signals.enrichment_json`, `why_it_matters` is added
    to the promoted alert body, and the relevance gate may suppress
    (suppressed_low_relevance) when below the configured floor. Fail-open: any
    enrichment error leaves it None and the signal promotes unchanged —
    enrichment never blocks a real alert. Cost discipline: for the pre-graded
    sources it runs AFTER the dry_run/floor gates, so suppressed signals cost
    nothing; the one exception is `query` signals, which are enriched BEFORE the
    floor gate (their flat-LOW hint must be regraded from relevance or a
    medium/high floor would suppress every hit) — so a below-floor query signal
    does cost one enrichment call, by design. Gated globally by
    EXTERNAL_MONITOR_ENRICHMENT_ENABLED and per-row by config_json.enrich; when
    enrichment is off, query signals stay LOW and a medium/high floor suppresses
    them as before.
  alerts_integration: |
    `promote_signal_to_alert` builds an `AlertEvent(source=signal_kind,
    external_id=dedup_key, subject, body)` whose body interleaves the
    normalized summary, the underlying source URL, and the
    provenance_url. The event is handed to
    `alerts.pipeline.schedule_evaluation` — the existing triage agent
    decides severity / channels / suggested_action / topic_tags exactly
    as it does for inbound email/Slack. The triage prompt's "External
    Signals" rule covers every adapter source kind (vendor_status, rss,
    stock, query, edgar, page_watch): for those it trusts the source,
    starts from the `Severity hint:` body line, and ALWAYS emits an
    `external:<source>` + `external:<watchlist_slug>` topic tag — those tags
    (and the source itself, via briefing.ranking `_is_external_signal`) are
    what land an unrouted low/medium signal in the briefing's Monitoring lane
    rather than the "Needs you" action queue. The event also carries
    `dedup_hint="watch:<slug>"`, which `alerts.pipeline` uses as the ALERT
    dedup_key (overriding the triage model's free-text key): a repeat from
    the same watch coalesces into the open card (`occurrence_count`,
    `last_seen_at`, severity max) instead of a new one, re-pinging only when
    severity rose into high/urgent — the signal-level `dedup_key` (stock's
    UTC-date bucket, vendor_status's `<updated>`) is untouched, so every
    observation still lands in `external_signals`. Feedback: dismissing a
    watch-sourced alert (HTTP ack or the `ack_alert` tool) calls
    `store.record_dismissal(slug)` — `dismiss_count += 1`, `trust_score =
    max(0.2, trust_score × 0.8)`; an ack calls `record_confirmation`
    (+0.05, capped at 1.0). `trust_score` discounts `briefing.ranking.score`
    (up to −10) and is shown to the alert review as WATCH TRUST evidence.
  heartbeat:
    kind: external_monitor_scan
    channel: __internal__
    channel_ref: external_monitor
    interval: EXTERNAL_MONITOR_SCAN_INTERVAL_MINUTES (default 5 min)
    lifecycle: |
      `bootstrap_external_monitor_scan()` is called from the FastAPI
      lifespan and the fixture-loader reset path. Idempotent — checks
      for an existing pending/running heartbeat before inserting. After
      each fire the runner calls `enqueue_next_external_monitor_scan` to
      schedule the next tick, each step in its own try/except so a
      chain-step failure cannot retroactively mark a successful scan as
      failed.
  config:
    settings_prefix: external_monitor_
    knobs:
      - "external_monitor_enabled (EXTERNAL_MONITOR_ENABLED, default true) — master switch read at boot to decide whether to seed the heartbeat."
      - "external_monitor_scan_interval_minutes (default 5) — heartbeat tick floor."
      - "external_monitor_{vendor_status,rss,stock}_poll_minutes — per-source poll cadence floors. Heartbeat ticks at the scan interval but each watchlist row only re-polls when its own floor has elapsed."
      - "external_monitor_max_signals_per_scan (default 50) — global cap per tick. Misbehaving sources cannot flood the alert pipeline."
      - "external_monitor_max_fetch_bytes (default 2_000_000) — per-fetch body ceiling. Defends against runaway feeds / XML-bomb shapes."
      - "external_monitor_query_enabled (EXTERNAL_MONITOR_QUERY_ENABLED, default true) — kill switch for the BILLED standing-query adapter, independent of the keyless feed adapters; query rows are skipped at scan time when false."
      - "external_monitor_enrichment_enabled (EXTERNAL_MONITOR_ENRICHMENT_ENABLED, default true) — capture-time relevance enrichment (one cheap LLM call per new, post-dedup, pre-promotion signal across ALL sources). Per-row opt-out via config_json.enrich=false."
      - "external_monitor_enrichment_min_relevance (EXTERNAL_MONITOR_ENRICHMENT_MIN_RELEVANCE, default 0.0) — optional relevance gate; signals scoring below it are recorded as suppressed_low_relevance and not promoted. 0.0 = gate off (surfacing unchanged) until calibrated."
  dry_run_mode: |
    Each watchlist row carries a `mode` column: 'active' (default in v1)
    or 'dry_run'. Dry-run signals land in `external_signals` with
    `processed_outcome='suppressed_dry_run'` — they are captured + scored
    + audited but never promoted to alerts. Intended for the calibration
    pattern: enable a new source in dry-run, let it run for a week,
    review what would have surfaced, then flip to active. The default
    is `active` per the v1 user instruction; the plumbing exists for the
    operator to opt in per-row.
  invariants_inline:
    - Adapters are read-only — never write upstream.
    - Every Signal carries a deterministic dedup_key (UNIQUE constraint enforces).
    - provenance_url is mandatory on every Signal.
    - Per-fetch body is bounded by settings.external_monitor_max_fetch_bytes.
    - Suppressed signals are still persisted so audits show the full picture.

  management_surface: |
    Watchlist rows can be created, listed, inspected, tuned, and deleted
    from two equally-privileged surfaces:

    - **Chat tools** (`orchestrator/watchlist_tools.py`):
      `add_watchlist_entry`, `list_watchlist`, `remove_watchlist_entry`,
      `tune_watchlist_entry`. Used by the Executive in chat turns and by
      the executive_research workflow synthesis step. Audit actor =
      `"executive"`.

    - **HTTP routes** (`api/routes/watchlist.py`, mounted at `/watchlist`,
      gated by the same `x-api-key` middleware as every other API
      endpoint): `GET /watchlist`, `GET /watchlist/{slug}`,
      `GET /watchlist/{slug}/signals?limit=…`, `POST /watchlist`,
      `PATCH /watchlist/{slug}`, `DELETE /watchlist/{slug}`. Powers the
      `/watchlist` Next.js page (list + detail with signal history).
      Audit actor = `"api"`.

    Both surfaces share `monitoring/store.py` (`insert_watchlist_item`,
    `update_watchlist_fields`, `delete_watchlist_item`,
    `get_watchlist_item_by_slug`, `list_signals_for_watchlist`) and the
    same input validators in `monitoring/validation.py`
    (`WATCHLIST_SLUG_RE`, `VALID_SEVERITY_VALUES`). That guarantees a
    slug the chat tool would reject is rejected by the HTTP route too,
    and that audit rows tagged `tool=watchlist.*` (api) or
    `tool=add_watchlist_entry`/`tune_watchlist_entry` etc. (chat) trace
    every mutation regardless of origin.

  research:
    module: openexecutive.monitoring.research
    one_liner: Specialists research, Executive routes — the 7-specialist council surfaces findings that the Executive's outbound toolkit then routes (DM heads of departments, DM principal, briefing alert, watchlist add, follow-up, workflow suggestion).
    workflow: |
      `executive_research` (registered in WORKFLOW_REGISTRY). Pipeline
      mirrors `executive_reflection`'s architecture: research phase
      produces structured findings, then the Executive runs a tool-use
      loop with its full outbound toolkit and decides per finding.

      1. gather_context — load company profile, active initiatives,
         existing watchlist, departments and the ten most recent episodic
         decisions (90 days). `_render_research_context` turns these into
         the user turn every specialist gets: today's date + the 30-day
         window, the profile block, ACTIVE INITIATIVES, ALREADY ON THE
         WATCHLIST, RECENT DECISIONS and DEPARTMENT WATCH INTERESTS (one
         line per department listing its `watched_entities`, via
         `_render_department_interests`, shared with the watchlist turn).
         The prompt's REQUIRED GROUNDING list admits a department interest
         or a company named in a recent decision, so a specialist can
         surface a finding about an entity a department head asked for —
         before this, the grounding rule dropped exactly those.
      2. research_specialists — fan out via asyncio.gather to seven
         specialist slugs (cso, cfo, cmo, coo, chro, cpo, gc). Each
         runs through `specialist_research.research_one_specialist`
         with its normal `effective_system_prompt()` + a research-mode
         addendum (`prompts.research_addendum_for`) + the Anthropic
         web_search tool + a structured `emit_research_findings` tool.
         Findings per specialist are capped at PER_SPECIALIST_FINDING_CAP
         (3) three ways: the prompt says so, the tool schema carries
         `maxItems`, and `_extract_findings` keeps the first N for a
         provider that does not enforce the schema.
         Controls: the fan-out's web_search tool takes its `max_uses` from
         `RESEARCH_WEB_SEARCH_MAX_USES` (default 3) — separate from the
         chat / query knob `WEB_SEARCH_MAX_USES`, because here it is
         multiplied by the number of specialists; `RESEARCH_SPECIALISTS`
         (comma-separated slugs, empty = all seven) filters the fan-out via
         `active_research_specialists` (unknown slugs are logged and
         dropped; an all-unknown value runs every specialist). The tool is
         the basic `web_search_20250305` variant on purpose: it is accepted
         by every Claude model the Council can pin as the research model
         (the newer dynamic-filtering variant and the web_fetch server tool
         are not — web fetch is unavailable on Opus 5 — and a research run
         must not fail on a model switch).
         The research turn's model + deep-reasoning are controlled by the
         `research` virtual Council agent (get_research_model() /
         get_research_use_deep_reasoning(): Council override → `RESEARCH_MODEL`
         env, default claude-sonnet-5-5 with deep reasoning OFF) — pinned
         per-call via analyze_with_tools' overrides, NOT the agent's chat-time
         deep_reasoning_model (Opus 5.5). The research turn is
         retrieve-from-web-search + summarize, so the cheaper tier is the
         dominant cost lever for the 7x fan-out; the chat path is unchanged.
         The addendum's per-domain focus tail is Council-editable per
         specialist (agent_overrides.research_focus, see
         per_specialist_research_focus); the shared contract is fixed code.
         Specialists DO NOT route — they surface what their domain
         turned up. The specialist turn is single-shot: there is no
         scrape loop and no separate verify pass any more (see
         no_external_fetch_service); the finding contract's "cite a dated
         source you retrieved" rule is enforced by the prompt and the
         low-confidence filter below.
      3. dedup — light cross-specialist collapse on
         (lowercased title, summary[:80]). Consensus boosts severity +
         confidence; source_specialist becomes a comma-joined attribution.
         The low-confidence filter (drop confidence=='low') runs here; the
         step's summary reports after_dedup / low_conf_dropped /
         to_synthesis.
      4. executive_synthesis — Executive's tool-use loop (mirror of
         executive_reflection._run_executive_reflection):
         system prompt built per-run by `_build_synthesis_system`,
         tools = `_ALL_SKILL_TOOLS` minus the research tool itself AND
         minus the raw per-channel DM tools (send_slack_dm /
         send_discord_dm / send_telegram_message are in
         `_SYNTHESIS_EXCLUDED_TOOLS`). DMs to a person go ONLY through
         `message_person(person_id, text)`: the synthesis user turn now
         carries the active roster (`_render_team_roster`: person_id,
         name, role, dept) so the model picks a `person_id` directly and
         is told NOT to call lookup_person — without this it burned its
         bounded iterations on lookup_person (often 0-match for names not
         on the roster) and never reached message_person ("looks up,
         never routes"). The handler resolves that person's configured
         channel + real channel id server-side (preferring
         `preferred_channel`), so the model never supplies — and cannot
         fabricate — a channel id. This replaced the prior
         approach where the model passed raw channel ids and kept
         sending the wrong identifier (a person_id, another channel's id,
         or an invented Slack-style handle), which silently failed the
         roster gate. Routing option (a) offers message_person whenever
         ANY DM channel is configured (`configured_integrations`), and is
         marked UNAVAILABLE when none is. The Executive decides per
         finding whether to message_person (a specific Person),
         send_department_message (dept channel), create_alert (briefing
         card), add_watchlist_entry (ongoing monitor), schedule_followup,
         suggest_workflow, or ignore. Trusts the specialist's
         `suggested_audience` hint but can override (especially under the
         persona's privacy invariant for board / comp / legal).
      5. emit_artifact — short Markdown: "what I researched + what I
         did with it" — plus a `result` WorkflowEvent with the
         structured findings, the tool-call log, and the Executive's
         narrative for programmatic consumers.
    triggers:
      - "Manual chat — the principal asks 'what should we look into?'; the Executive calls the `run_executive_research` chat tool. The tool runs the workflow, which both researches AND routes; the chat tool returns the structured summary so the Executive can describe to the principal what it researched and what it did with each finding."
      - "Onboarding completion — when the user saves the reviewed draft (POST /onboard/interview/commit, or the wizard fallback's final answer), `api/routes/onboarding._fire_post_onboarding_research` schedules the workflow as a background task. Both paths share the same helper and the same `_onboarding_research_fired` dedup set, so it fires at most once per setup session. The workflow's synthesis step fires whatever routing tools it deems necessary (DMs to heads, briefing alert, watchlist additions) — the wrapper just runs the workflow with a wall-clock ceiling and creates / completes the workflow_run row."
      - "Periodic cron — `watchlist_research_scan` scheduled-action kind (default every 360 min via `WATCHLIST_RESEARCH_INTERVAL_MINUTES`). Each tick computes a state fingerprint (company profile + active initiatives + watchlist slugs/targets) and SKIPS the run when nothing has changed since the last successful periodic research. Quiet days cost zero tokens; first tick after any material profile / initiative / watchlist change fires immediately. A staleness floor (`WATCHLIST_RESEARCH_MAX_STALENESS_HOURS`, default 168, i.e. weekly) overrides the skip once that many hours have elapsed since the last successful run, so a static internal state cannot keep the council blind to purely-external change forever (set <= 0 to disable). The cron does NOT write its own Alert — the workflow's synthesis step already routes findings directly. After routing, a dedicated watchlist-analysis pass (separate budget) proposes ongoing monitors via `propose_watch`; `monitoring.research.watch_policy` decides per proposal — direct add (grounded in company data: competitor / vendor / ticker / initiative / priority, score >= 4 on a fixed ledger, quiet defaults) vs dry-run suggestion for the principal vs reject — and the run artifact is persisted into the separate `recent_research` knowledge collection (keep-latest). Cron's only side-effects on success are the `watchlist_research_periodic_ran` audit row + whatever the workflow's Executive synthesis + watchlist pass fired."
    skip_if_unchanged: |
      The periodic cron handler (`monitoring.research.scheduler.run_watchlist_research_scan`)
      computes a sha256 over (`CompanyProfile.to_prompt_block()`,
      active initiatives sorted by title, watchlist rows sorted by slug)
      and compares against the `state_hash` field on the last successful
      `watchlist_research_periodic_ran` audit event. Equal hash → log a
      `watchlist_research_periodic_skipped` event and return without
      firing the workflow. Different hash (or no prior run) → fire the
      workflow, then audit with the new hash so the next tick can
      short-circuit. Persistent profile-load failures fall back to a
      static `"error:profile"` sentinel so a broken profile doesn't
      burn 7 specialist calls every 6h.

      The `state_hash` stored on a successful run is recomputed *after*
      the workflow finishes, NOT the pre-run hash used for the skip
      decision. The workflow's watchlist pass adds watches (via the watch policy),
      mutating a fingerprint input; storing the pre-run hash would leave
      every later tick seeing a "changed" state and re-running a full
      research pass each interval. Capturing the post-run state as the
      baseline is what makes quiet days actually free — genuine
      profile/initiative/user-watchlist edits still diverge and re-run.

      Staleness floor: the fingerprint only sees *internal* state, so a
      static profile would otherwise let the council stay blind to
      purely-external change (a competitor move, a regulation shift)
      indefinitely. `WATCHLIST_RESEARCH_MAX_STALENESS_HOURS` (default 24)
      bounds this — once that many hours have elapsed since the last
      successful run, the next tick fires even when the hash is unchanged.
      The `watchlist_research_periodic_ran` audit row records a `trigger`
      of `state_changed` vs `staleness_floor` so cost/freshness dashboards
      can tell the two apart. Set the floor <= 0 to disable it and rely
      solely on skip-if-unchanged.
    chat_tool: |
      `run_executive_research` (in orchestrator/research_tools.py).
      Inputs: optional `note` (focus hint). Returns JSON with
      `findings_count`, `tool_calls_count`, `ok_tool_calls`, full
      `findings` list (title, summary, severity_hint, suggested_audience,
      suggested_action, confidence, source_specialist, relevant_urls),
      `tool_calls` log, `narrative`, plus a `presentation_hint`. The
      Executive uses these to describe the run to the principal in
      chat — it does NOT re-route findings (the workflow already did).
    cost_shape: |
      Up to 7 research calls per run (one per specialist) with web_search,
      plus up to 3 synthesis iterations (Executive's tool-use loop — one
      to resolve recipients via lookup_person, one to route, one to wrap
      up). Each
      specialist's `effective_model()` is honored so a Council UI override
      applies. The cron's skip-if-unchanged guard means quiet days cost
      zero tokens.
    noise_calibration: |
      Hard floors keep volume actionable:
      - `PER_SPECIALIST_FINDING_CAP = 3` (down from 8 — 7 × 8 produced
        ~52 candidate findings per run, far more than the Executive
        could meaningfully route).
      - Specialist addendum requires NAMED-ENTITY GROUNDING: every
        finding must cite a primary competitor / active initiative /
        strategic priority / named vendor / tracked ticker BY NAME from
        the company context. 'Industry trend' findings are dropped.
      - Specialist addendum requires VERIFIABLE ACTIONABILITY: every
        `suggested_action` must be a step a specific human can complete
        in under 15 minutes. 'Monitor the situation' is dropped.
      - Low-confidence findings are filtered BEFORE synthesis
        (`workflows/executive_research.py`) — they never reach the
        Executive's tool-use loop.
      - Synthesis routing budget capped at `_MAX_ROUTING_TOOLS_PER_RUN = 5`
        successful OUTBOUND tool calls per run (DMs, alerts, watchlist adds,
        follow-ups, workflow suggestions); further outbound tool_use blocks
        short-circuit with an `over budget — skipped` summary so the model
        sees a tool_result acknowledgement on the next turn. Read-only
        context lookups (`_NON_ROUTING_TOOLS`: `lookup_person`,
        `list_people`, `ask_about_person`) are exempt — they are passed to
        `execute_tool_calls` as `free_tools`, never decrement the budget,
        and never terminate the loop, so the Executive can resolve a
        department head without spending the budget meant for the DM that
        lookup was for (the "looks up people but never routes" bug).
      - Synthesis system prompt defaults to IGNORE — surfacing requires
        a clear material reason, not a precautionary "might as well".
    invariants_inline:
      - Specialists surface findings; the Executive decides routing.
        Specialists never send messages themselves.
      - The synthesis loop's tool list excludes `run_executive_research`
        itself — no recursion.
      - Specialist failures are non-fatal (`asyncio.gather` with
        per-call try/except) — one model crash does not kill the run.
      - The cron does NOT insert an Alert when the workflow succeeds;
        the workflow's synthesis already routes findings via the right
        outbound tool. Double-insertion would duplicate briefing cards.
      - The persona's privacy invariant still binds the synthesis step —
        board / comp / legal findings stay per-Person, never broadcast.
      - Noise floors are locked in by unit tests —
        `PER_SPECIALIST_FINDING_CAP ≤ 3` and
        `_MAX_ROUTING_TOOLS_PER_RUN ≤ 5`. Loosening either reintroduces
        the round_2 noise floor.
      - Low-confidence findings (`confidence == "low"`) are dropped
        before synthesis and never become DMs, alerts, or briefing cards.

review:
  store: openexecutive.knowledge.review_store.ReviewStore (shares episodic_memory.db).
  default_state: |
    Shipped content is TRUSTED ON ARRIVAL. `sync_builtin_registrations` and
    `sync_external_registrations` register `approved` with a NULL
    `reviewed_at`, so a new instance starts with an EMPTY review queue.
    Before this, all 81 built-in docs registered `pending`, and a brand-new
    box greeted its first user with "81 items need review" — work nobody had
    a basis to do on day one, gating nothing.

    PROVENANCE IS AN EXPLICIT COLUMN FED BY A COMMITTED MANIFEST — never
    inferred, and never re-derived from the filesystem. Two mistakes were
    caught here in review, both of which silently approved a user's own
    unvetted document and labelled it "shipped" in the UI:
      1. Keying on (pending, reviewed_at NULL). A brand-new upload via
         `POST /knowledge/builtin` -> `ReviewStore.register()` has exactly
         that shape.
      2. Keying on "a .md file exists under knowledge/builtin/". That route
         writes the user's file into that SAME tree
         (`api/routes/knowledge._resolve_path`), so a directory scan re-flagged
         uploads as shipped on the next boot.
    So `review_items.trusted_default` (INTEGER, default 0; additive ALTER for
    older DBs) is set to 1 only for paths listed in
    `knowledge/shipped_manifest.py::SHIPPED_BUILTIN_FILES`, which
    `sync_builtin_registrations` iterates instead of rglobbing the tree.
    Regenerate that manifest when adding or removing a built-in doc;
    `test_shipped_manifest_matches_git` fails on drift. `register()` never
    sets the flag, so user content stays `trusted_default = 0` forever.

    Two states, read together:
      - trusted_default=1, approved, reviewed_at IS NULL -> shipped, unvetted
      - approved + reviewed_at set                       -> an SME signed off
    `count_trusted_defaults_by_domain()` counts the first kind and drives the
    "Curate N" affordance. The UI reads `trusted_default` off the API rather
    than inferring it.

    MIGRATION ORDER MATTERS. `ReviewStore.backfill_trusted_defaults()` must run
    AFTER both registration syncs, because it only touches rows they have
    flagged `trusted_default = 1`. Call sites: `api/main.py` lifespan and
    `clients/slots._ensure_schemas`. A `review_meta` marker row
    (`trusted_defaults_backfill_v1`) makes it fire exactly once, written under
    `BEGIN IMMEDIATE` with `INSERT OR IGNORE` so two workers booting together
    cannot raise a UNIQUE violation out of the lifespan. The marker lives in
    `review_meta` rather than `PRAGMA user_version` because
    `episodic_memory.db` is shared with episodic memory, alerts, people,
    talent and more.

    The migration's rule is NO SHIPPED DOC LOSES RETRIEVABILITY ON UPGRADE.
    Its only exclusion is `reviewed_at IS NULL` (which `set_status` always
    stamps, so every explicit approve/reject is skipped). Notes and
    annotations deliberately do NOT hold a row back: `retrieve`
    injects annotations by DOMAIN regardless of item status, so withholding an
    annotated doc would feed the Executive a correction to a document it can
    no longer see.
  effect_on_retrieval: |
    WITHHELD = `pending` OR `rejected`. `get_withheld_filenames(content_type)`
    is the single query the retrieval path uses; it replaced the old
    rejected-only lookups, which no longer exist.

    Both `retrieve` and `retrieve_failures` apply it, and so does
    `POST /knowledge/search` — the diagnostic panel documents itself as
    showing what RAG would surface, so it drops withheld rows too. It
    degrades to unfiltered if review state is unreadable (a read-only
    diagnostic should not 500, and must not create the DB file);
    `retrieve` is the enforcing gate and does NOT degrade. The failures
    path is the one that used to leak: failure case studies are registered
    for review but indexed into FAILURES_COLLECTION, and `retrieve_failures`
    consulted no review state at all, so rejecting a failure case study did
    nothing.

    The gate is now real. It could only be made real once shipped content
    defaulted to approved — enforcing it beforehand would have left a fresh
    instance with zero retrievable knowledge.

    `needs_revision` is deliberately NOT withheld. `touch_modified` flips an
    item there on ANY content edit, so withholding it would make editing a
    file in the knowledge UI silently delete it from retrieval. Approved
    items can still be promoted in priority.

    The filter keys on the `(domain, filename)` PAIR that Chroma metadata
    carries. Bare filename was both ambiguous and caller-choosable:
    `POST /knowledge/builtin` accepts any `(domain, filename)`, so uploading a
    file named after a shipped doc in a different domain silently withheld
    that shipped doc from every specialist. `get_priority_map` uses the same
    key for the same reason. The old design leaned on "all shipped basenames
    are unique", which only a test over the shipped tree ever checked and
    which nothing enforced at the write path.

    IDENTITY IS NAMESPACED. `build_item_id` is the single constructor, with
    three disjoint namespaces: `builtin:<domain>:<file>`,
    `failure:<domain>:<file>`, `external:<source_id>`. Failure case studies
    used to fold into `builtin:`, which is the namespace a user upload reaches
    — and since no file sits at `knowledge/builtin/<domain>/<file>` for a
    failure doc, `create_builtin_file`'s exists() guard never fired, so an
    upload INSERT-OR-IGNOREd onto the shipped row and inherited `approved` +
    `trusted_default = 1`. `_migrate_failure_namespace` (marker
    `failure_namespace_v1`) re-keys existing rows, carrying status,
    reviewed_at, notes and annotations across under `PRAGMA
    defer_foreign_keys`. `create_builtin_file` also refuses outright to write
    onto a `trusted_default = 1` row, so a future id-space change cannot
    silently re-open it.
  curation: |
    Opt-in, per domain. `POST /review/curate {domain, action: start|stop}`
    moves a domain's untouched trusted defaults to `pending` (and back).
    Both directions require `trusted_default = 1 AND reviewed_at IS NULL`, so
    neither a user's own upload nor an item an SME decided on is ever moved.

    `domain` is REQUIRED — there is no "curate everything" selector. While a
    domain is curated its items are withheld, so no single call may take the
    whole knowledge base away from the Executive. The UI confirms with the
    exact count before starting.
  bulk_approve: |
    `POST /review/bulk-approve` selects by `domain` (min_length=1 —
    the store reads a falsy domain as "no filter", so an empty string would
    widen a scoped call to every pending item), an explicit `item_ids` list
    (over BULK_MAX_IDS=500 raises rather than silently truncating), or
    `all_pending: true`. A call with no selector is a 400 —
    the same "a bulk call must always carry a selector" rule as
    `/alerts/bulk-ack`. Returns `{approved_count, item_ids}` and writes a
    `review_bulk_approve` audit event; `/review/curate` writes `review_curate`.
  reset_and_slots: |
    `reset_all_state` wipes `review_annotations` + `review_items` (child
    first) and re-registers the shipped docs — built-in and any ingested OER
    sources. It then re-registers, as `pending`, every `.md` under
    `knowledge/builtin/` the manifest does NOT claim: the reset does not
    delete user-authored files or their Chroma chunks, so without this a doc
    an SME had REJECTED came back retrievable with no review row at all —
    un-suppressed and invisible in the queue. Conservative on purpose, since
    a previously-approved upload returning for review is the safe direction,
    and deleting the operator's files would be worse. This means a reset no
    longer
    inherits the previous operator's approvals and rejections — a stale
    rejection would otherwise keep suppressing retrieval on the new box.
    `clients.slots._ensure_schemas` runs `sync_builtin_registrations` after
    `initialize_db`, so a newly activated client slot has its trusted
    defaults immediately instead of an empty table until the next restart.

workflows:
  contract: Structured input → ordered named steps → rendered Markdown artifact.
  artifact_browsing: |
    Every completed run's Markdown artifact (persisted via `complete_run`
    into `workflow_runs.artifact`) surfaces in the unified artifacts section (UI label: Documents)
    (`/artifacts`, see the `artifacts:` key) in addition to its own run
    detail page at `/jobs/runs/{run_id}` — so workflow outputs are
    discoverable without remembering which run produced them.
  registry: openexecutive.workflows.WORKFLOW_REGISTRY
  streaming: SSE — every step emits a WorkflowEvent (start/progress/complete) consumed by /workflows/{name}/runs.
  human_in_the_loop: |
    `wait_for_human` (openexecutive/workflows/wait_for_human.py) is a
    first-class step primitive that pauses a run: `save_checkpoint` moves
    the `workflow_runs` row to `status='awaiting_human'` and stores the
    serialized `WaitForHumanEvent` in `state_json`. (It does NOT write to
    scheduled_actions, and it is NOT the department authority gate — see
    the correction under `departments.authority_gate`.)

    DELIVERY — `workflows.gate_delivery.deliver_gate_question`, called by
    both checkpoint sites (api/routes/workflows.py and
    orchestrator/workflow_run_tools.py) BEFORE `save_checkpoint`, so
    state_json carries the routing fields. Two modes. Self-approval: the
    chat session's `origin_channel` is set (and is not `email` — an email
    turn's answer is no chat reply, so nothing would ever send the
    question) and its `caller_person_id` is the gate's person — nothing is sent (the question rides in the
    Executive's own reply) and the gate records `origin_session_id` plus
    the session's channel/ref. Out-of-band: delegate to
    `schedule_tools.handle_message_person` (preferred-channel selection,
    per-channel id validation, fall-through, alert fallback), and record
    the `channel` / `channel_ref` / `message_id` its success payload now
    returns. Delivery may not happen — the outbound guard can suppress it
    and an unreachable person falls back to an alert — in which case the
    routing fields stay EMPTY and the caller reports `delivery` as
    `suppressed` / `alerted`, never "waiting on them".

    MATCHING — each adapter calls `inbound_resolver.resolve_inbound_message`
    with every `session_id` the message belongs to (a Slack thread reply also
    offers its parent `slack:channel:{c}:{u}`, mirroring the history
    double-write — a gate raised on a mention records the channel session
    while the answer arrives under the thread's, and a single-id comparison
    made that gate permanently unanswerable). Tier 1 (explicit `in_reply_to`
    vs a stored `outbound_message_id`) rules out only the candidates that
    carry an outbound id — the ones it could have matched — and lets the rest
    continue; Slack passes `thread_ts` on every threaded message, so an
    unconditional refusal made tiers 2-3 unreachable there, and a global test
    let one delivered gate's id block an unrelated self-approval gate. Tier 2
    normalizes channel names (`slack_dm` ≡ `slack`) and treats an empty
    stored channel as a wildcard ONLY when `state_json` has no `delivery` key
    at all — that marks a checkpoint written before gate delivery existed. A
    row whose delivery was suppressed / alerted / failed also has no channel
    but DOES carry the key, and is not matchable: nobody was asked on any
    channel, so matching it would record an answer to a question that was
    never put. Tier 3 is one utility-fast disambiguation call at 0.85
    confidence. Two guards stop an open gate swallowing unrelated traffic: a
    gate with an `origin_session_id` matches only the conversations the
    adapter names, and the parser can answer `unrelated`, which declines to
    resolve so the message reaches the normal chat path. The parser receives
    the gate's own question (without it a bare "yes" can never be judged
    unrelated), and its fallback is flagged with `PARSE_FAILED_KEY` — a key
    the model has no reason to emit — rather than the old `note ==
    "parse_error"` string, which a human could produce and thereby have a
    genuine rejection discarded. The fallback guard applies to EVERY reply
    shape, not just approve_reject, and every shape can answer `unrelated` —
    without it an open free_text gate turned the person's next message into
    its answer verbatim, and a numeric gate swallowed any message containing
    a number. `ack_alert` is withheld from the unattended passes
    (`executive_reflection` and the `executive_research` synthesis): both
    render open alerts into their context, those headlines come from inbound
    mail and chat, and the server-side ack trust check keys on a session's
    `origin_channel`, which those passes do not set.
    `resumer.apply_resolution` then records the
    decision, marks the run `resolved`, and writes an audit row. A timeout
    instead applies the step's `on_timeout` policy (escalate /
    auto_proceed / fail). Either way the captured outcome surfaces in the
    Today dashboard for the founder to see.

    Every adapter replies with the one shared wording from
    `resumer.resolution_acknowledgement`, which names the decision (via the
    shared `DECISION_VERBS` map in wait_for_human.py) and then says what
    actually happens next, keyed on whether the run carries a
    `resume_state_json`: resuming now, stopping here because the answer was
    a reject/defer, or — for a pause-only gate — closed out with nothing
    further. The original "Got it — your response has been recorded."
    implied work was in flight when none was; saying "the workflow does not
    continue on its own" for a resumable gate would now be the same error
    in the other direction.

    RESUME — a paused run continues on its own. Nothing serializes a
    generator frame; that assumption is what deferred this for so long. The
    only state alive across a dynamic workflow's steps is its inputs
    (already in `workflow_runs.inputs`), a recomputable company-profile
    block, the completed steps' string outputs, and the loop cursor — so the
    engine hands the checkpoint a small JSON `WorkflowResumeState`
    (workflow_name, gate_step_id, gate_step_index, next_step_index,
    outputs), stored in the new `workflow_runs.resume_state_json` column,
    and `DynamicWorkflow.resume` replays its step loop from
    `next_step_index`. `run()` and `resume()` share one loop (`_run_steps`),
    so a gate reached on a resumed run raises an identical pause and a
    second gate needs no special handling.

    The payload rides on `WaitForHumanEvent.resume_state`, a field declared
    `exclude=True` so it can never leak into `state_json` — the resolver
    branches on which keys are PRESENT there, so shape stability is a
    property of the type rather than a rule each call site must remember. A
    gate with no payload is pause-only: the decision is recorded and the run
    stops, which is what every caller got before resume existed.

    EXECUTION — `resumer._process_resumable` claims a `resolved` run
    carrying a payload with one guarded UPDATE (`claim_run_for_resume`:
    resolved -> running, stamping `resumed_at`, incrementing
    `resume_attempts` and minting a `resume_claim` token), then drives
    `workflow.resume(...)` to a terminal row. It is reached two ways:
    immediately, via a task `apply_resolution` kicks off so a Slack approval
    starts in seconds, and from `_tick` every 60s as the durable backstop.
    Both share the claim, so a run executes exactly once even with two
    resumers against one database. The kicked task is created inside the
    inbound handler that recorded the answer, so it starts under
    `set_session(None)` and `audit.context.unscoped_audit_rows()`: it must
    not act as the approver, and it must not inherit the approver's audit
    scope — with the principal's scope every row of the run naming a contact
    would turn private, and whoever started the run would see them vanish
    after the approval. `_tick` runs the executor AFTER the
    timeout loop, which is what finally makes `on_timeout='auto_proceed'` do
    what its name says: `_handle_timeout` resolves the run and the same tick
    executes it.

    FENCING — the claim is not a lease. The stale sweep decides a worker is
    dead from a wall-clock guess (`_RESUME_STALE_AFTER`, 90 minutes, set
    beyond 12 specialist consults at the specialist timeout), so a slow but
    ALIVE worker can be declared dead and replaced. Every write the executor
    makes therefore carries the claim token — `finish_resumed_run` and a
    fenced `save_checkpoint` — and is refused once superseded. Without that,
    the replaced worker's late `complete_run` lands on top of its
    replacement's result, or its `save_checkpoint` at a later gate
    RESURRECTS an already-`done` run to `awaiting_human` and asks the
    approver a second time. `requeue_run_for_resume` clears the token, which
    is what breaks the old worker's write.

    RETRY BUDGET — `resume_attempts` bounds the requeue. It is reset by
    `save_checkpoint`, because reaching a new gate is new work rather than
    another attempt at the last one; counting gates against it would leave a
    three-gate workflow with no crash-recovery budget by its final gate,
    without a single failure. Exceeding the bound is TERMINAL, not a
    disappearance: an exhausted run is `running` with a payload, so it is in
    neither queue, and `list_exhausted_resuming_runs` exists so the resumer
    can end it instead of leaving it showing as in-progress forever.

    THE GATE FAILS CLOSED — continuing is an allowlist
    (`CONTINUE_DECISIONS` = approve, auto_proceed), not "anything that is not
    a stop word". `decision` is whatever a fast model extracted from
    free-form chat, and it drifts: under a denylist, "rejected", "Reject",
    "decline" and "no" all CONTINUE the run, so the approver declines and the
    deliverable is produced anyway. Reply shapes that ask a question rather
    than seek permission (`NON_APPROVAL_SHAPES`) always continue — the answer
    is the value, there is nothing to fail closed on. A stop ends the run at
    `error` with the human's note. Either way the decision becomes the gate
    step's own output via `dynamic._format_resolution`, so it appears as a
    section IN the artifact; that text is capped and blockquoted because it
    reaches the synthesis specialist as prompt context.

    A DEFINITION EDITED DURING THE PAUSE — `resume` re-validates the
    payload's version/engine/workflow name, that `steps[gate_step_index]` is
    still the same gate, AND a `steps_fingerprint` over the whole step list;
    the index to continue at is DERIVED (`gate_step_index + 1`), never read
    from the payload. Pinning only the gate is not enough: `upsert_definition`
    overwrites by name and any rostered chat user can call `save_workflow`,
    so someone could keep the gate identical and replace every step after it,
    and the approver's sign-off would be recorded against work they never
    saw — defeating the one thing an approval gate is for.

    THE TIMEOUT/REPLY RACE — `_tick` lists expired rows and then acts on
    them, so a reply can land in the gap. Both terminal branches of
    `_handle_timeout` check `mark_timed_out`'s guarded result first and bail
    if it returns False; the writes that follow have no status guard of their
    own, and continuing would strip the payload off (or overwrite) a run a
    human had just answered.

    NO BUILT-IN workflow yields the gate — `offer_approval` did, and it was
    removed with the talent vertical. (`exec_search_brief` survived that
    removal — it is an advisory CHRO brief with no gate and no pipeline
    dependency.) Only user-created dynamic workflows pause. Gates remain
    banned in cadence-enabled dynamic workflows (`validate_definition`): a
    cron fire has no interactive human to ask.

  dynamic_user_created: |
    Users create reusable workflows on the fly — from the executive chat, the
    conversational wizard at /jobs/new, or the step-by-step advanced editor —
    without shipping a Workflow subclass. /jobs opens on a "Start here" panel
    (components/jobs/StartHere.tsx) that leads to all three: "Start" hands the
    typed description to the wizard through sessionStorage
    (lib/workflowStarters.ts, stamped and honoured for 5 minutes) and the
    wizard sends it as the first message. A `/jobs/new?describe=` link only
    prefills the composer, so a crafted link can't send text the user never
    typed; it is also the fallback when storage is blocked, so then nothing
    is sent until the user presses Start. Below the panel: the user's custom
    workflows, four ready-made starter picks, and the full built-in list
    folded behind "Browse all" (`?browse=1`). The picks and the example
    chips follow the workspace mode (`starterPicksFor` /
    `workflowStarterChipsFor` in lib/workflowStarters.ts): a team gets
    investor_update, board_prep, mbr and competitive_teardown and a board
    pre-read chip; solo ("Just you", an owner-operator) gets mbr,
    pricing_review, churn_deep_dive and quarterly_plan, and chips for a
    Friday cash and pipeline check, customers who stopped buying and the
    competitor digest. tests/unit/test_jobs_starter_picks.py pins every
    pick to a WORKFLOW_REGISTRY entry that is not background and not
    principal-only in its mode. A dynamic
    workflow is a stored JSON definition (the `dynamic_workflows` table;
    `openexecutive.workflows.dynamic_store`) interpreted at runtime by ONE
    generic engine, `openexecutive.workflows.dynamic.DynamicWorkflow`, which
    implements the same Workflow ABC as the built-ins. `get_workflow` /
    `list_workflows` (workflows/__init__.py) fall through to the dynamic store
    after WORKFLOW_REGISTRY, so the HTTP run path, SSE streaming, run
    persistence, and the /jobs/[name] form renderer are unchanged. Built-ins
    win on a name collision; `WorkflowMeta.is_custom` flags dynamic ones.

    Definition model (`openexecutive.workflows.dynamic_models`): free-text
    `input_fields` plus an ordered `steps` list of three kinds — `specialist`
    (consult a specialist with a goal prompt + optional rag_query),
    `approval_gate` (a wait_for_human pause), and a terminal `synthesis` step
    that assembles the Markdown artifact. `validate_definition` enforces the
    invariants: exactly one terminal synthesis step, valid specialists,
    `{placeholder}` tokens that reference declared input fields, rostered
    approval/cadence people, and a parseable cadence.

    Authoring from chat (`openexecutive.orchestrator.workflow_authoring_tools`,
    wired into the executive tool list) uses a DRAFT → CONFIRM handshake:
    `draft_workflow` validates and returns a `confirm_token` + plan summary
    (no persistence); after the user approves, `save_workflow` re-validates
    and persists only if the token still matches the definition (a mismatch is
    rejected, so the saved workflow is exactly what the user saw). Both tool
    schemas are fixed, so the cached tool list stays stable. The step-by-step
    advanced editor drives the `/workflows/custom` CRUD endpoints directly.
    A definition with action (tool) steps saved from chat is stored
    is_active=False (applied after the token check), its cadence is not
    scheduled, and
    save_workflow returns status `saved_pending_review` + the /jobs/{name}
    link. The chat token is model-held, so it is not a human seeing the tools:
    the approval is **Turn on workflow** on the review card that /jobs/{name}
    shows for an inactive custom workflow (POST /workflows/custom/{name}/
    activate, which re-runs validate_definition_and_tools when turning on).
    Chat may keep revising a switched-off one, but never replaces a
    switched-on workflow with action steps, or one that reads or sends email
    as its creator, directly (an inbound email steering the Executive could
    otherwise stage new tools under a familiar name). save_workflow with
    overwrite=true leaves a CHANGE CARD instead (orchestrator.workflow_change,
    decision class app_action, hidden catalog action change_workflow that
    do_in_app never offers): server-written lines name every step added,
    removed or changed, tools by plain name, schedule and title. Only a
    verified speaker in a private conversation who is the owner or the
    workflow's creator can stage one, and only where the card shows (web
    chat, or a chat app channel_cards.shows_cards). The tap
    (api.routes.workflows.apply_chat_change) saves it only if the stored
    workflow still matches the card's base (else 409), re-validates tools,
    runs workflow_email.save_refusal for the tapper (signed web caller or a
    ChatTap), keeps is_active, and saves with save_if_unchanged. Chat reads a
    saved definition with list_workflows(name=...) (owner or creator, private
    conversation). The refusal is decided from
    a read, so the save itself is conditional on that row
    (dynamic_store.save_if_unchanged: INSERT only if still absent, else
    UPDATE ... WHERE updated_at = the read one) — an activation landing in
    between, from any process, makes the save a no-op with an error.
    get_definition reports updated_at from the column (not the JSON body),
    which is the key both conditional writes match on.
    Activation is bound to what was reviewed: for a definition with action
    steps the body must carry the reviewed `definition`; it must equal the
    stored one (model_dump minus is_active/created_at/updated_at) or 409, and
    the switch is one conditional UPDATE keyed on the validated revision's
    updated_at (dynamic_store.activate_if_unchanged), so a save landing during
    the awaited tool check — from any process, e.g. a standalone chat bot on
    the same DB — is a 409, never switched on.
    The Workflows catalog (/jobs) lists inactive custom workflows in a "Waiting for your
    approval" strip; the advanced editor preserves is_active on save, so
    "Save changes" never switches one on.

    New workflow wizard (`/jobs/new`, the UI default): a conversational
    designer modelled on the onboarding interview. `workflows.designer.advance`
    is the loop; `agents.workflow_designer.WorkflowDesignerAgent` is a
    Council-only agent (outside SPECIALIST_REGISTRY). Two fixed, name-sorted
    tools every call — `ask_clarifying_question` {question, hint, options<=4}
    and `emit_workflow_draft` {definition (reuses DEFINITION_SCHEMA from
    workflow_authoring_tools), summary, assumptions}. `tool_choice` is `any`
    and flips to the emit tool exactly once: MAX_QUESTIONS=6 spent, a
    60k-char transcript, or the user's "Draft it now". Emitted drafts go
    through DynamicWorkflowDef validation + `validate_definition` + a check
    against saved custom names, with ONE repair turn feeding the errors back;
    a second failure raises WorkflowDesignerError (fixed string). Cache
    layout: one constant system block with cache_control; the live context
    (specialists, roster with person ids, the user's zone, taken names) is
    rendered once per session by `build_context_block` into the FIRST user
    turn, and the current draft JSON is prepended to the LATEST user turn
    while refining. Roster full_name/role are attacker-influenceable free text
    (anyone with People access), so `_one_line` flattens them to one line and
    caps them at 80 chars, and the system prompt says the context block is
    data, never instructions. Transcript replay is shared with onboarding via
    `onboarding.interview.replay_transcript`. Routes live in
    `api/routes/workflow_designer.py` (`/workflows/designer/start|message|
    draft|{id}`), mounted before the workflows router; sessions are
    in-memory (2 h TTL, 50 cap), hold ONE model turn at a time (`busy` flag:
    a concurrent /message or /draft gets 409; a failed /message removes its
    own user turn by identity), and NEVER write — the UI saves through
    `POST /workflows/custom`, which re-validates. "Edit details" hands the
    draft to the advanced editor via `/jobs/new?designer=<id>`.
    Editing a saved workflow is the same conversation: "Edit"
    (`/jobs/new?edit=<name>`) calls `POST /workflows/designer/edit` {name},
    which seeds the session's draft with the stored definition (no model
    call) and appends `build_edit_note` to the context block (user turn, not
    the cached system block). `advance(editing=<name>)` makes `_check_draft`
    overwrite the draft's name with the saved one and skip the taken-name
    check; the route copies the saved is_active onto every draft, so an edit
    never forks a copy or switches on a workflow awaiting approval. Responses
    carry `editing` + `original`; the UI lists the differences in plain
    words (`packages/ui/src/lib/workflowChanges.ts` compares every field,
    names a sign-off's reply-shape change since a non-approve_reject gate
    lets the run continue whatever the answer, and has a catch-all line for
    unmapped fields), flags only newly added write tools, and saves via
    `POST /workflows/custom/{name}/save-edit` {session_id, definition}: the
    server saves the session's own draft (never a client body), only when it
    equals the reviewed `definition` (409 if a message landed since the card
    loaded — sessions are not bound to a caller), re-validates it,
    keeps the stored is_active, and writes with
    `save_if_unchanged(draft, session.original)` — 409 if the workflow
    changed since the session opened (e.g. switched off mid-edit), for a
    session about another workflow, or with nothing drafted. It is under
    `/workflows/custom` so write limits on that prefix cover it. The draft
    JSON in the latest user turn is marked as data, not instructions. The
    form editor is `/jobs/new?edit=<name>&mode=advanced`; "Edit details"
    from an edit conversation opens `?edit=<name>&designer=<id>`, takes the
    current is_active from the stored workflow, and saves with PUT.

    Step scripts (`run_script`, workflows/step_script.py): an action step is
    also offered `run_script` (unless WORKFLOW_STEP_SCRIPTS=false) so the
    agent can write one short Python script for repetitive work instead of a
    model turn per call. It runs in Monty (pydantic-monty, a sandboxed
    interpreter for model-written code) in a worker process per script,
    stepped from the event loop with AsyncMonty feed_start/resume: each call
    to an undefined function pauses the worker and is answered by
    action_step._StepCalls.call, the same path as a direct tool_use
    (allowlist — a name outside it is refused AND audited —, a budget: script
    calls spend _StepCalls.script_call's own, 10x max_tool_calls capped by
    WORKFLOW_SCRIPT_MAX_CALLS (default 500), not the 1-50 direct budget,
    TargetPolicy with held writes returning {"status": "held"}, one
    workflow_tool_call audit row per call), plus a `run_script` row. The
    step's tools are identifier-mapped functions, plus call_tool(name,
    arguments); OS calls get Monty's refusal; no files, network, env,
    subprocess or third-party imports. Because the script is driven in the
    step's own task, cancelling the run (or the wall clock) stops the worker
    and the in-flight call together, and each call's progress/held events
    reach the engine as they happen (run_script is an async generator). No
    threads. Limits: execution time (excludes waiting on tools), memory,
    recursion, a max_suspensions backstop above any step budget, wall clock,
    script size; printed output past its cap is dropped, not fatal.
    Each script yields ("stats", {calls, duration_ms}) before done; the
    run_script audit rows (chat kind: script, workflow tool: run_script)
    carry them, and AuditLogger.usage_summary adds them up as `scripts`
    (scripts, ok, calls, turns_avoided = sum(calls - 1), duration_ms,
    in_workflows) for the Token usage page. Actions taken collapses repeats. Results
    and errors list the calls the script made, so a model fixing a script
    that failed partway does not repeat writes that already ran. Scripts are
    never stored; definitions stay data, not code. The workflow designer's
    prompt keeps per-item work in ONE action step (items spelled out in its
    goal) and never lists run_script; validate_definition rejects a step that
    lists it, so the designer's repair turn removes it.

    Chat scripts may also call the Executive's own tools in
    step_script.CHAT_OWN_TOOLS (reads; create/ack alerts; open loops; goals;
    watch list; schedule_followup; message_person; upsert_person) when the
    turn is offered each (turn_handlers minus withheld_tools), via the
    turn's handler (Take the lead gated_handlers on a leading run), with the
    usual chip and a kind: skill, via: run_script audit row. Excluded:
    broadcasts, calendar, memory/skill edits, workflows, research, documents,
    Act as me. The cached persona gets the constant TOOL_BUILDING_ADDENDUM
    (mcp_enabled and CHAT_SCRIPTS): build a tool rather than say there is
    none, check list_saved_tools first, keep what recurs, and never say
    "script"/"code" to people. People see saved tools as "Custom tools"
    (Settings -> Advanced -> Custom tools, guide section custom_tools) and
    the usage summary as "Done in one go".
    A turn's chat scripts share CHAT_SCRIPT_MAX_CALLS (default 200) calls,
    counted in Executive._stream_agent_loop's script_counts, plus per-turn
    caps on own tools (step_script.CHAT_OWN_TOOL_CAPS: message_person 10,
    upsert_person 25, create_alert 50). A CancelledError mid-call writes a
    cancelled audit row before re-raising. TOOL_BUILDING_ADDENDUM is gated
    on cache_manager._chat_scripts_on (setting + step_script.available()).
    Worker slots: run_script acquires a per-event-loop asyncio.Semaphore of
    SCRIPT_MAX_WORKERS (default 2) inside the wall clock before starting
    AsyncMonty, released in a finally (also on aclosing/cancel). Measured:
    a worker is ~8 MB RSS, exists only while its script runs, and none are
    left after timeouts, memory-cap kills or cancellation.
    Workflow approval of kept tools: saved_tools.workflow_version (NULL
    until the owner turns it on; set_workflows(name, version) sets the version
    the owner named, which must exist, so a version saved while they were
    reviewing is never approved by accident; set_enabled(False) clears it).
    Workflow steps use get_for_workflows / list_for_workflows (that version,
    enabled only); chat uses the current version. A newer save never moves
    workflow_version; pruning keeps it. PUT /saved-tools/{name}
    {workflows: true} needs take_the_lead._provably_theirs (409 otherwise);
    turning off doesn't. Prompted by the automated review: a principal turn
    that read an injected email could keep an attacker-shaped tool that a
    workflow then ran unattended.
    Python jobs (workflows/python_job.py, run_python_job): Pyodide 314 in Deno,
    one process per job (asyncio.Semaphore(1)), deno run --no-prompt --quiet
    --no-remote --allow-read=<PYTHON_SANDBOX_DIR>,<worker>, env stripped to
    PATH/HOME/DENO_DIR. Spike: under plain Node a job read all env vars, host
    files and the network; Node --permission can't load Pyodide; Deno denied
    env, fs, writes, run and net (incl. 127.0.0.1 and 169.254.169.254).
    Job JSON on stdin {code, files b64, pyodide dir, wheels}; result on
    stdout. Inputs: Knowledge files by plain name (company/docs) and
    text_files; outputs kept 7 days in company/python_jobs/<uuid>/ and served
    by GET /python-jobs/{id}/{name} (principal only). Image: npm pyodide +
    deno, compiled wheels from cdn.jsdelivr.net/pyodide/v<ver>/full verified
    by lock sha256 (docker/pysandbox-fetch.mjs), pip-pinned pypdf/openpyxl,
    build smoke runs a job. Measured: ~2.2 s start, 4 s PDF split (214 MB),
    11 s pandas+matplotlib (446 MB); image +~130 MB.
    Security review fixes: memory capped by RLIMIT_DATA (PYTHON_JOB_MEMORY_MB,
    default 1536; 1 GB broke pandas) plus --max-old-space-size=256 and
    --wasm-max-mem-pages=12288; worker caps output at 20 files / 25 MB and
    the API's stdout read is capped, sizes checked before base64 decoding;
    withheld on unattended passes (UNATTENDED_WITHHELD_TOOLS); downloads are
    no-store; npm deps via package-lock + npm ci, pip wheels --require-hashes;
    links URL-encode the file name.
    Documents: python-docx, python-pptx, fpdf2 (2.8.8; 2.8.9 was a week old),
    XlsxWriter and defusedxml are pip-pinned with hashes; their compiled deps
    come from Pyodide (lxml, pillow, fonttools, typing-extensions), which
    loadPackagesFromImports can't infer for non-Pyodide packages, so the
    worker's NEEDS map loads them per import (find_imports). One job writing
    a docx, a pptx with a chart, a PDF table and an xlsxwriter chart: 7 s.
    Second review: Deno writes v8/dep-analysis caches to DENO_DIR regardless
    of job permissions and a job could feed it data: modules (330 MB in one
    job, never pruned) -> per-job tempfile.mkdtemp DENO_DIR removed after the
    job, --no-code-cache, _prune drops the old company/python_jobs/.deno.
    stdout past the cap now kills at once (gather used to wait on stderr EOF
    while Deno blocked on the full pipe); worker Deno.exit(0) after its result
    so a leftover Worker can't hold the slot. Resources: preexec sets
    oom_score_adj=1000 and nice 10 (2 GB shared-cpu machines: a ~900 MB worst
    job plus the API); kept results capped at 200 MB total, oldest first.
    Recheck: job code could undo the worker's Deno.exit or close stdout and
    keep running, so the API reads only the result line (one line of JSON)
    and kills the process then; the exit code no longer counts once a result
    parsed. _prune runs under a lock and treats a vanished folder as gone
    (concurrent prunes raised FileNotFoundError and lost the reply's links).
    Remote runner (PYTHON_JOB_RUNNER_URL + PYTHON_JOB_RUNNER_KEY): run_job
    POSTs {code, inputs, files b64, max_*, timeout_s, memory_mb} with the key
    as a bearer token and no redirects; the reply is read up to
    _MAX_STDOUT_BYTES and only result/error/printed (length-capped), files,
    skipped and usage {peak_mb, cpu_ms} are kept; HTTP errors, timeouts and
    unreadable replies become job errors. available() is true with a runner
    and no local sandbox. URL must be https, or http to localhost/.internal/
    .flycast, and needs the key (settings refuse a URL without one). Result
    files must be str -> valid base64 (b64decode validate=True) or the job
    errors, so a bad runner reply can't raise in the handler. The runner is
    trusted to isolate jobs.
    A non-200 reply whose JSON body has run_locally: true (and an optional
    reason, at most 300 chars; body read up to 4 KiB, _turned_away) makes
    run_job run the job in the local sandbox when _local_sandbox_ready(),
    else the job fails with the reason. Only an explicit true falls back: any
    other non-200 stays a job error, so a busy or broken runner never moves
    every job onto the machine.
    PYTHON_JOB_EXTRA_LIBRARIES (with a runner only; comma-separated package
    names, each with an optional "(import <module>)", at most 300
    chars; anything else is dropped with a warning, not fatal, since it may be
    pushed to machines that must boot) is appended to the tool description by
    python_job.offered_definition (cached per process, so the tool prefix
    stays stable) for chat, research and reflection toolkits alike; the description otherwise says only the listed libraries
    are installed, and the model refused jobs needing scipy and the like. The
    workflows group label says jobs work with or without files: "on files"
    alone made the model refuse jobs on data typed into the chat.
    Kept jobs, attachments, metering: run_python_job takes save_as +
    description (kept as saved_tools kind 'python', tools [], code as the
    script; only when the job worked) and tool + inputs to run one again
    (record_run with calls 0). Python tools are chat-only: _SELECT_WORKFLOW
    filters kind 'script', set_workflows raises, PUT /saved-tools 409s,
    run_script refuses them. attachment_files: POST /chat/upload binds the
    uploads as sent (workflows/turn_files.py ContextVar, safe names, '(2)' on
    repeats) for the whole SSE turn, so the model no longer retypes an
    attachment (~$0.30 per 100 KB of output tokens) and can split an attached
    PDF. inputs reach the code as a Python dict global. Each job logs a
    python_job audit row (ok, duration_ms, cpu_ms and peak_mb from
    /proc/<pid> just before the kill, bytes, attachments, saved_tool); the
    worker now reads its job as one stdin line and waits on stdin after its
    result so the API can measure it. GET /audit/usage python_jobs sums them
    plus the cache_event usage of the turns that ran a job.
    Fan-out nudge: after a round whose results hold a list of >= 5 items
    (step_script.lists_many: top level or up to two levels into a JSON
    object, not an error), with run_script offered and unused that round
    (chat: not withheld, not mail-touched), the constant FANOUT_HINT is added
    as a text block to that round's user message — once a turn in chat, once
    a step in workflows. The addendum and run_script description state the
    cost: every round re-reads the whole conversation.

    Chat scripts: the Executive's chat is offered the same `run_script` tool
    (step_script.CHAT_TOOL_DEFINITION, a constant so the cached tool prefix is
    stable) when the gateway runs, unless CHAT_SCRIPTS=false, and only on the
    principal's own turns: it is in content_trust.PRINCIPAL_ONLY_TOOLS (so no
    teammate's turn and no email turn is offered it, whatever its sender) and
    in schedule_tools.UNATTENDED_WITHHELD_TOOLS (so no scheduler trigger,
    reflection or research pass is), beside run_python_job in both. The
    handler's may_save / may_run_saved already refused to keep or re-run a
    saved tool on such a turn; neither stopped a fresh script, and a fresh
    script is the whole call budget in one tool_use. A workflow action step
    keeps its own scripts - that is the owner's definition, approved per step,
    and it never passes through either set. With no
    allowlist (tools=None), any MCP-shaped function name (server__tool) or
    call_tool(name, arguments) is a call by that exact name; the gateway
    decides what may run (its discovered set — search_tools results, kept for
    the gateway's process-wide session, not per conversation — its deny-list
    and recipient gates). Dunder or one-sided names never become calls. Each
    call is dispatched as a call_tool —
    through take_the_lead.gated_call_tool on an unattended leading run — and
    gets the same action chip and tool_invocation row (details.via =
    run_script; ok: false + FAILED when it raised) as it happens, plus one
    kind: script row with the source and result. Wall clock = half of
    CHAT_STREAM_TIMEOUT_S (30-600 s), enforced per await so it holds although
    the chat route drives the stream one task per step; contextlib.aclosing
    closes the script and its worker when a turn stops. Held results
    ({status: held | waiting_for_approval}) are marked in the returned calls
    list. Not offered on a turn private to the principal
    (in PRIVATE_TURN_WITHHELD_TOOLS; refused there if emitted anyway), and
    withheld whole by the Act as me lockdown (MAIL_TOUCHED_WITHHELD_TOOLS).

    Saved tools (workflows/saved_tools.py): run_script takes save_as +
    description with a new script; a script that SUCCEEDS is saved with the
    sorted set of tools it actually called (a failed one never is), and
    run_script(tool=<name>, inputs={...}) runs the saved script with
    `inputs` bound as a dict (exactly one of script/tool; save_as with tool
    is refused). Only the principal's own turns save (run_script_tool
    may_save): chat passes may_save when principal_only_withheld(session) is
    empty (principal speaking on a verified interactive surface, not email)
    and the run is attended; workflow steps pass False and their run_script
    schema has no save_as/description. A saved tool runs with the authority
    of whoever runs it, so its author must be at least as trusted as any
    runner (an inbound email or teammate could otherwise plant or re-version
    a tool the principal's turns and workflows then run). Running a saved
    tool is likewise limited (may_run_saved): workflow steps and the
    principal's own turns only; list_saved_tools is in
    content_trust.PRINCIPAL_ONLY_TOOLS (not offered, refused if emitted), so
    a stranger's email can't list the principal's automations or run one
    with chosen inputs. Descriptions are normalized to one line (Cc/Cf to
    spaces, whitespace collapsed); every save is audited saved_tool_changed
    with actor executive. Beyond that,
    saving is auto-approved by design: a saved tool runs through
    whatever context calls it (step: _StepCalls.call; chat: gateway
    call_tool and its gates), and a workflow step runs one only when
    saved.tools is a subset of step.tools (else an error naming
    missing_tools). Steps see usable saved tools in their run_script
    description (step_script.tool_definition(tools, saved)); chat gets the
    constant list_saved_tools tool (summaries, never scripts). Tables
    saved_tools / saved_tool_versions / saved_tool_runs in the episodic DB:
    a save with changed description, script or tools is a new version that
    becomes current; an identical save changes nothing; a turned-off tool
    stays off when the model saves a new version; runs keep the newest 200
    per tool; at most 200 tools. Owner-only routes /saved-tools (list,
    detail with script/versions/last 20 runs, PUT enabled, POST rollback;
    audited saved_tool_changed) back Settings -> Advanced -> Saved tools.
    SAVED_TOOLS_ENABLED=false stops saving and running everywhere.
    list_saved_tools is allowed under the Act as me lockdown (local read)
    and withheld on a turn private to the principal, like run_script.

    Email as the creator (delegation/workflow_email.py): two built-ins (plus
    oe__answer_email_as_me, delegation/workflow_reply.py, see handle_it),
    oe__draft_email_as_me (draft in the creator's mailbox, recorded as a
    chat draft) and oe__send_email_as_me (sent through
    reply_send.send_for_workflow, the third door). Written only as the
    workflow's owner; refused when someone else started the run by hand, the
    speaker is unrostered, an unattended Executive pass started the
    outermost run (chat_tools.started_by_a_pass), or another person's
    workflow is in the chain (chat_tools.running). Needs Act as me allowed + on + own mailbox
    connected, else the step is told to use the Executive's email. to/cc are
    write targets: the creator's own addresses and the addresses in the
    saved goal of a step listing an email-as-me tool (nowhere else in the
    definition; workflow_email.chosen_recipients, trusted by
    TargetPolicy.for_workflow only when the running definition matches the
    saved one) go unasked; the first email to any other address is held. Caps:
    DELEGATION_MAX_DRAFTS_PER_DAY for every email, plus
    DELEGATION_WORKFLOW_MAX_SENDS_PER_DAY (default 20) for sends, counted
    from delegation_drafts rows with source workflow_sent written before
    the send. A workflow with the send tool is created/changed/activated only
    by its creator per verified.caller_refusal (403 from POST/PUT
    /workflows/custom, save-edit, activate; save_refusal); chat's
    save_workflow only leaves a change card for one (workflow_change), saved
    on the creator's own verified tap. At send:
    is_enabled, handle_it.signing_ok, no client slot, draft unchanged
    (recipients exactly as written, from an own address, <=10, never the
    Executive's). Results and the run report carry to/subject, never the
    body; audit rows are private to the creator. The designer gets an
    "Email as the user" line (build_context_block(as_me=...)) and a line on
    whose account the gateway's mail and calendar tools use (the
    Executive's, EXEC_EMAIL_ADDRESS): a calendar step that names no calendar
    reads the Executive's calendar, so the user's needs oe__my_calendar or
    their address (build_context_block(user_email=...)). DEFINITION_SCHEMA
    says the same to chat.

    Reads as the creator (delegation/workflow_reads.py): oe__search_my_email,
    oe__read_my_email, oe__my_email_awaiting_reply and oe__my_calendar run
    chat's mail_read_tools handlers with the creator as the writer
    (mail_read_tools.AS_CREATOR; no conversation is marked private, the run
    is theirs). Read only when the run is the creator's (turn_owner ==
    creator), in the outermost workflow (chain length 1), not started by an
    unattended pass, with Act as me allowed + on + mailbox connected. A
    workflow that reads: every run is its creator's (scheduler creates the
    scheduled run with owner_person_id = creator, pins the viewer, and
    delivers the report and failure card to the creator; every path that
    runs it (scheduler, run route, chat run_workflow, resumer) wraps the run
    in private_run = rows_for_person(creator), so its audit rows and sends
    stay off the shared activity rail; the run route 403s
    anyone else; chat's run_workflow needs the turn's Act as me pin to be the
    creator and marks the turn touched_mail/read_mail first). Locked down for
    all steps (definition_refusal at save, run_rules at each step): tools
    only the reads, the email-as-me tools (sends unasked only to chosen
    recipients, so an address the mail named is held) and oe__ chat tools in
    MAIL_TOUCHED_ALLOWED_TOOLS; no run_script; approval gates and cadence
    only to the creator. Saved/changed/activated only by its verified
    creator (save_refusal covers reads too); chat never replaces one.

    Chat's tools in action steps (workflows/chat_tools.py): one list,
    `ACCESS`, labels every tool chat offers — use (a step may call it as
    oe__<name>), as_me (Act as me; chat-only for now), covered (the step
    already has its own path: gateway tools, run_script, specialist steps) or
    chat_only (it changes what the Executive knows or who is on the team, or
    acts on the person's screen). A unit test fails when a new chat tool has
    no label, so a new chat tool can't skip the decision. A "use" tool runs
    through the SAME chat handler, as an unattended chat turn would: an
    unattended Session bound as current_session, the workspace-mode filter
    (solo withholds department/broadcast tools), and, when a team member
    created the workflow, their department gate. Channels the instance has no
    token for are not offered. A saved workflow is the person's permission, so
    Take the lead's approval gates and the solo principal-only rules are not
    applied (no change for workflows that worked before). run_workflow refuses
    a workflow already in its own chain and nests at most 3 deep;
    run_workflow / run_executive_research get a 15-minute call timeout.
    oe__web_search is the model's own server search (appended after the sorted
    tools; paused turns are sent back as-is). Workflows have no tool
    handlers of their own: oe__message_person / oe__create_alert are the chat
    tools under the same names, and oe__read_file (LEGACY_NAMES) still
    resolves to read_document for saved workflows but isn't offered.

    Action steps (workflows that act): `ActionStepSpec` {goal, tools,
    max_tool_calls 1-50, default 20} in dynamic_models. `tools` is an allowlist
    of exact names — MCP gateway tools (`server__tool`) and built-ins (the
    chat's own tools as oe__<name>, below) — and the user's
    click on Create IS the approval (the review card lists every tool, flags
    ones that may change things, and names them in a "can use these without
    asking again" notice). Gateway meta-tools (search_tools / call_tool /
    load_mcp_server) are forbidden as step tools. `workflows/tool_catalog.py`
    parses extensible-mcp's Markdown `search_tools` output, resolves exact names
    (which doubles as the per-session discovery `call_tool` requires), and
    `validate_tools_available` runs on every save path (custom POST/PUT, chat
    draft/save, designer drafts). `workflows/action_step.py` runs the
    `workflow_actor` Council agent: constant cached system block, only the
    allowlisted tools (sorted), per-run goal/inputs/earlier results in the user
    turn; every tool_use re-checked against the allowlist; MCP calls go through
    `MCPGateway.call_tool` (deny-list + Gmail/Calendar/Drive recipient gates);
    budget enforced, then a tools-off (`tool_choice: none`) final turn; tool
    errors return as is_error; each call emits a `progress` WorkflowEvent and a
    `workflow_tool_call` audit row (tool + outcome, never arguments). Output =
    the agent's report + an "Actions taken" list. `oe__read_document` reads only
    under WORKFLOW_FILE_DIRS (or the company docs folder) (default workspace-mcp's attachment dir), resolving
    symlinks/`..` first. Action steps are allowed in cadence workflows. The
    designer gained a third constant tool, `search_available_tools`, answered
    inside the same `advance` call (≤4 per turn; tool_use/tool_result pairs are
    never stored in the transcript; found names are kept on the session as
    `discovered_tools` and replayed into later turns so forced drafts and
    repair turns can use them). Endpoints: GET /workflows/tools/search?q= and
    GET /workflows/tools/describe?names= (names regex-checked and deduped).
    Hardening from review: tools taking a url/uri/endpoint/webhook param are
    never labelled read-only (egress); chat draft_workflow/save_workflow save
    action-step workflows switched OFF until turned on from the review card
    (the review card is the approval, not a model-held token);
    run()/resume() pre-flight all action tools; running out of turns fails the
    step; resumes heartbeat their claim (persistence.touch_resume_claim, <=1/min)
    and stop when superseded, so a live run is never requeued and replayed.
    Targets are chosen at run time BY DESIGN: approval covers the tools, not
    which spreadsheet/doc/recipient/URL each call hits (tab per month, reply to
    the sender, doc per client). Bounds: the allowlist, the gateway recipient
    gates, the audit (workflow_tool_call rows of non-read-only tools carry a
    bounded `targets` digest — keys like *_id/to/url/path/spreadsheet; never
    content) and FIRST-WRITE CONFIRMATION:
    - action_step.TargetPolicy (one per run) checks every call whose tool is
      not labelled read-only; tool_catalog._read_only_label never labels a
      name carrying a write verb anywhere (find_and_replace_doc,
      check_and_merge_pr, get_or_create_folder …). resource_targets() walks
      arguments recursively; a resource key (snake/camel ids, to/cc/bcc,
      recipient, email, address, attendee, member, user, owner, parent,
      url/uri/href/link, path, channel, space, room, phone, host, bucket,
      table, spreadsheet, document, folder, calendar, file) marks its whole
      subtree, names included. Outside one, exact name/title/subject/
      file_name/display_name keys, message/thread/draft/label ids, range/sheet
      and user_google_email are skipped; any bare email/URL/+phone-shaped
      value is a target whatever its key, except under content keys (rows,
      values, data, body, content, text, html, markdown, description, notes,
      comment, summary, headline). Floats that are integers compare as ints.
      Too deep (>8), too many (>100) or over-long (>2000 chars) FAILS CLOSED.
      Key names are a heuristic: this is best-effort, layered on the tool
      allowlist, gateway recipient gates and the audit.
    - Trusted: values in workflow_approved_targets for this workflow (by
      normalized value — emails lowercased — not by tool), and ids a write in
      this run created: TOP-LEVEL id/link keys (id, *_id, *Id, *link, *url)
      of the JSON-object result of a tool whose name says it creates
      (tool_catalog.creates: create/insert/upload/add/copy/new/make/duplicate)
      and that takes no URL (tool_catalog.takes_url; an unknown schema counts
      as taking one) — never free text, nested records, or a reader's or
      updater's result (a page, an echoed title, a shared doc's links or a
      stranger in ccRecipients could plant one). Approvals are cleared when
      the workflow's action-tool set changes (dynamic_store upsert /
      save_if_unchanged), so a newly added tool never inherits them. Carried across pauses in
      WorkflowResumeState.run_created (both gate and held-writes pauses).
      Values in the workflow's own text are NOT trusted (anyone who can PUT
      the workflow could change them without review) — asked once.
    - The owner's question JSON-quotes each target (no injected lines) and
      always shows a URL's scheme+host in full, saying how much is hidden.
    - Anything else is HELD: not run, no budget spent, the model gets a
      "held for approval, don't retry" result, audited "held for approval";
      <= 10 per step, <= 16 KB args each, else refused; an identical repeat
      is held once. Every exit that won't settle them (step error or crash,
      resume refused for a changed definition / stale specialist / missing
      later tool) audits them as "dropped (reason)" and says in the error
      that N held writes did not run.
    - After the step, the engine yields WaitForHumanEvent to
      approved_targets.approver_for(name): the workflow's owner
      (dynamic_workflows.owner_person_id — set on insert only from the web
      caller on POST /workflows/custom or the chat session caller on
      save_workflow; never from a body/definition; kept by PUT, overwrite,
      activate), else the principal if the owner is unknown/archived.
      on_timeout=auto_proceed, 48 h. WorkflowResumeState gains
      kind="held_writes", held=[HeldCall(tool, arguments, targets)] and
      deliver_to_person_id; old payloads parse as kind="gate".
    - DynamicWorkflow._resume_held_writes (fingerprint + ActionStepSpec id
      checked like a gate): only decision "approve" runs the held calls, each
      re-checked against the LIVE step allowlist and resolve(); targets are
      remembered first. reject/auto_proceed/defer/unknown skip. Either way a
      "Held for approval" section is appended to the step output and the run
      continues at idx+1. No approver at all: held writes skipped and noted.
    - The principal can override from the web: POST
      /workflows/runs/{id}/decision (is_principal_or_self on
      awaiting_person_id; approve_reject gates only) -> apply_resolution. A
      chat reply only matches the person asked (inbound_resolver filters on
      awaiting_person_id).
    - Scheduler: _run_dynamic_workflow checkpoints a held_writes pause
      (checkpoint_gate) instead of raising, stamps deliver_to_person_id with
      the cadence recipient, marks the row done and re-chains; the resumer
      DMs the artifact after finish_resumed_run (and carries
      deliver_to_person_id onto any later pause). Every other gate still
      raises in the scheduler.
    - Known limit: a daily cadence can raise a second question about the
      same target while the first is unanswered; answering either remembers
      the target for later runs.
    Egress labelling walks the whole schema (nested/items/anyOf/$defs) and an
    unparsed schema is never "reads only". requeue_run_for_resume takes
    stale_before so a heartbeat between the sweep's SELECT and UPDATE wins.

    Catalog: `Workflow.background` / `WorkflowMeta.background` is True for
    the system-run built-ins (morning_brief, end_of_day_digest,
    weekly_review, executive_reflection, executive_research); /jobs files
    them under a "System" chip instead of the default view, and the alert
    review never suggests one for an alert (`alerts.review._workflow_matches`
    skips any workflow with the flag).

    Optional cadence: a definition may carry the cadence DSL +
    `cadence_person_id`. `workflows.dynamic_cadence` enqueues a
    `dynamic_workflow` scheduled action; the scheduler runs the workflow and
    DMs the artifact to that person, then re-chains. See the `scheduler:` key.
    A gate followed by more steps now resumes: the run pauses at
    awaiting_human and, once answered, the resumer executes the remaining
    steps and produces the artifact (see `human_in_the_loop` -> RESUME).
    Gates no longer have to sit immediately before synthesis. They remain
    forbidden in CADENCE-enabled definitions, though — a cron fire has no
    interactive human, so `validate_definition` rejects them there.
  chat_launch: |
    Any workflow — built-in or custom — is launchable from a chat turn, not
    only the /jobs UI. `openexecutive.orchestrator.workflow_run_tools` wires two
    tools into the Executive's main loop:
      - `list_workflows` (read): the launchable catalog via `list_workflows()` +
        `WorkflowMeta`, flattened to each workflow's name/title/section/
        estimated_minutes/input fields. Read-only → no action chip.
      - `run_workflow` (write): resolves built-ins AND active custom workflows
        via `get_workflow`, validates `inputs` against the workflow's
        input_model, persists the run (`create_run` → `complete_run`/`fail_run`),
        and streams `workflow.run(...)` to completion. It mirrors the HTTP
        route's WaitForHumanEvent handling — literally, now: both go through
        `workflows.gate.checkpoint_gate`, which delivers the question and
        checkpoints the run in one place so the two copies cannot drift.
        It returns a `GatePause`, reported as `status='awaiting_human'`
        with a `delivery` field (self / sent / suppressed / alerted /
        failed) and a `resumable` flag, rather than hanging. `_awaiting_hint`
        combines the two: an undelivered question is never reported as
        "waiting on them", and a pause-only gate is never described as
        continuing by itself. The nine runners that CANNOT pause
        (schedulers, evals, client rotation, onboarding, research tools)
        call `gate.ensure_workflow_event`, which raises on a gate instead
        of letting it be swallowed — the scheduler's dynamic-workflow
        branch used to ignore one and store `complete_run(run_id, "(no
        artifact)")`, a phantom success every cadence period.
    Guardrail: `_CHAT_LAUNCH_BLOCKLIST` excludes `executive_research` (it has the
    dedicated `run_executive_research` tool). PRINCIPAL-ONLY: a workflow's
    `principal_only_modes` (ClassVar on `Workflow`, empty by default) names
    the workspace modes in which only the principal on a verified surface
    (`people_tools.is_principal_on_verified_surface`, create_goal's rule) may
    launch it from chat — `weekly_review` in {solo, team} (the principal's
    decision log from every session with [decision N] ids, commitments and
    goals, and it re-grades goals) and `morning_brief` in {solo} (commitments
    and calendar). `workflow_run_tools._principal_only_refusal` checks at
    dispatch, before `create_run`, with the turn's effective mode; anyone
    else (email, Google Chat, unverified Telegram, a teammate, an unattended
    run, no session) gets a plain JSON error that does not name the rule,
    audited refused=true with workflow, mode and caller context. A check that
    raises refuses. Team `morning_brief` is launchable by anyone as before.
    Over HTTP the same modes decide who may START or TRIGGER such a run,
    with a web caller rule instead of the surface rule:
    `POST /workflows/{name}/runs` (the Jobs page) and `POST /evals/runs` (a
    workflow scenario runs `workflow.run` on live data) call
    `api.routes.workflows.refuse_principal_only_run`. It lets through only a
    caller whose x-caller-email is the principal's own, non-archived entry,
    or a request with no x-caller-email (the CLI, local login, a direct call
    behind the shared secret; the UI proxy stamps every other session's
    email), which counts as the principal and needs no roster read
    (`_caller_is_the_principal`). Unlike PUT /workspace
    (`chat._caller_is_principal_or_unclaimed`, unchanged), an install with no
    principal on the roster lets no signed-in caller in: that state follows
    archiving the old principal to re-run onboarding, or a roster filled in
    before anyone was flagged, and teammates can be signed in then. The
    chat gate refuses everyone in that state too. Anyone else gets a 403
    whose detail does not name the rule ("Only the principal can run this
    workflow." / "Only the principal can run the <id> eval."), before
    `create_run` or `create_eval_run`, audited like the chat refusal
    (tool_invocation, refused=true, workflow, mode, caller_person_id,
    surface jobs or evals, actor the caller's email). The mode is the stored
    one (`read_stored_mode`), or for an eval the scenario's workspace_mode
    first; a mode that cannot be read counts as principal-only
    (`workflows.base.principal_only_in`), and a roster that cannot be read
    refuses a caller with an email. The evals route hands `run_scenarios`
    the scenario list it checked (`scenarios=`), so a user scenario edited
    in between cannot swap in an unchecked workflow. Residual: the Jobs
    route checks the stored mode, then the workflow reads the mode again
    when it runs, so a team-to-solo switch in that instant (only the
    principal can make one) could let a teammate start the solo morning
    brief. The gate is about starting a run, not reading one: stored runs,
    the scheduled briefs and weekly reviews included, are read under the
    existing GET /workflows/runs and /workflows/runs/{run_id} rules (and
    stored eval results under /evals/runs), the same as the rest of the
    app's records such as /memories/decisions. Running a workflow
    from chat DELIVERS NOTHING — it renders the artifact into the conversation; the
    recurring principal briefs reach anyone only through the scheduler's
    `_deliver_to_principal`. The tool description previously claimed
    `morning_brief` and `end_of_day_digest` DM the principal when run and told
    the model to confirm first, which had it soliciting a confirmation on a
    false premise (#136); it now names `executive_reflection` as the one
    workflow that really does execute tool calls of its own. A successful
    `run_workflow` emits an `action_taken` chip (in `action_chips`) linking to
    `/jobs/runs/{run_id}`.
  grounding: |
    Deterministic grounding of what the unattended passes write
    (`openexecutive.briefing.grounding`). Why: the brief, the digest, the
    reflection and alert text went from the model straight to delivery, and
    a fabricated colleague, a wrong unit count and a wrong property manager
    all shipped that way — then the alert review affirmed them.
    - Sources: `sources_from_context` splits the rendered context into one
      source per line, labelled by its ALL-CAPS section header (a header
      also carries its bullet count); plus the company profile's prompt
      block lines and the department titles. Tool results join a reflection's
      sources as they arrive (`GroundingScope.guard`).
    - Names: a run of 2+ capitalised words (after trimming a STOP set —
      section headers, weekdays, months, imperative openers, product and
      org nouns), or one capitalised word in a person slot ("ask Marcus",
      "Marcus wrote", "Marcus's"). Grounded when one source line holds every
      token (no splicing a first name from one line with a surname from
      another), or a roster person containing it is mentioned in a source.
    - Figures: money, percentages, k/M/B numbers and bare numbers ≥ 11;
      never dates, times, years, durations, ids, list markers, Q3/FY26 or
      small counts. Grounded when a source number is within half the step
      the prose shows ($1.2M ↔ $1,234,567), or — for a percentage — two
      numbers on one source line give it.
    - Briefs (`ground_brief`, morning_brief + end_of_day_digest, after the
      quiet fallback): one repair call to the fast model with the list of
      ungrounded items; still-ungrounded lines are dropped, then headers
      left empty; an "_I left out N lines … under Left out of your brief on
      Home._" note is appended (all of it → the HELD_BACK_ALL line). Every
      held line is kept in the audit row's untruncated `full` payload (the
      4 KB `details` cap would cut a list), and `recent_held_back` reads the
      last day's back for `GET /today` `held_back` — principal only, set
      after the narrative inputs are taken so held lines never reach a
      prompt. Before this the note said "/today has the full list", and
      nothing there listed them. Each grounded figure then gets a server-chosen
      ` [n]` (the value-matching line with the most words in common with the
      figure's clause) and a `**Sources**` list at the end (`- [n] <section>
      — <snippet>`, snippets stripped of []()<>*_`| and cut to 90 chars, at
      most 9; links masked, @-mentions stripped — they quote inbound mail).
      Text with nothing to change comes back byte-identical. The
      morning brief now renders its context itself and passes it as
      `rendered_context`, so the check reads exactly what the model read. The
      fingerprint hashes inputs, so suppression is unaffected;
      record_delivered stores the grounded text. The /today header is not
      grounded (it has the cards beside it).
    - Reflection: outward tools refuse ungrounded prose with a JSON error
      naming the items; the "Flagged for the brief" section is filtered before
      the tool log is appended (brief_state._FLAGGED_RE now also stops at
      `---`), with a "_Grounding: held back N flags_" note after the log.
    - Modes: GROUNDING_CHECKS=enforce (default) | report (audit only) | off;
      GROUNDING_CITATIONS=true. Fail-open everywhere.
  notable_recent:
    - |
      engagement_value_report — a NEW PATTERN: the data-driven retrospective.
      Unlike form-driven workflows (investor_update, mbr) whose substance is
      typed by the user, this one READS its substance from the database —
      clients/engagement_activity.gather_engagement_activity pulls the
      period's decisions, initiatives, advice counts, delivered workflow
      artifacts (excluding itself), follow-through, and alerts handled via
      existence-guarded SQL. Works on the live DB (active client /
      single-company) or a parked slot's state.db opened read-only (no
      activation — cockpit mechanism). One board_comms call narrates the
      gathered facts (grounding: prompt forbids inventing anything not in
      the JSON facts; empty period skips the LLM entirely). V1 trigger is
      human-initiated (cockpit "Value report" link prefills /jobs runner,
      chat run_workflow, /jobs) because scheduled_actions swap with the
      client — renewal-timed auto-generation belongs to the overnight
      rotation phase.
    - "department_check_in — runs on department cadence; surfaces goals, blockers, asks. Phase A: the `goal_status` step now returns structured JSON `{verdicts:[{goal_id,status,rationale}], narrative}` and persists each verdict back to `department_goals.status` + the new `last_reviewed_at` column via `store.record_goal_review`. Emits a single `goal_status_review` audit row per run carrying the from→to transitions. See `departments.goal_review_persistence`."
    - inbound_resolver — matches human replies back to paused workflow runs.
    - crisis_comms — drafts incident response messaging.
    - churn_deep_dive — structured customer-loss analysis.
    - "morning_brief — Shift 3 recurring workflow. Fires once per day from the scheduler (default 08:00 in the user's zone; an explicit PRINCIPAL_BRIEF_MORNING_TIME env var is read as UTC). Targets the principal: utility_fast model renders a ≤200-word Markdown briefing. CHANGE-AWARE: the window is 'since the last DELIVERED morning brief' (`briefing.brief_state.since_for`, 24 h on a cold store, clamped to 7 d); activity comes from `_build_activity(20, since=…)`; proposals (action category only) split into NEW SINCE LAST BRIEF (enumerated, with why_now / next move) vs a one-line CARRIED OVER count (with the likely-stale count); a REWRITTEN block lists carried items the review rewrote in the window (`brief_state.rewritten_since`: verdict `changed`, still open — reported under 'what changed', never as done); a HANDLED OVERNIGHT block lists the alert review's completed moves (`brief_state.handled_since`, `changed` excluded). Section order: top call → what changed → handled overnight → needs you (new only) → waiting on → at risk. A fingerprint of the inputs (`build_brief_fingerprint`, date-free) is compared to the last delivered one: unchanged ⇒ the artifact is the one-liner 'Nothing new since yesterday's brief — N items still waiting on you.' and no model call (`PRINCIPAL_BRIEF_SUPPRESS_UNCHANGED`, bypass with `force_full=true` on a manual run). The workflow yields a `result` event `{brief_fingerprint, suppressed, since}`; only `_run_principal_brief` records the fingerprint, after a successful delivery (`brief_state.record_delivered`, stored in `briefing_narrative` under scope `brief:<kind>`). Delivery (`scheduler.runner._deliver_to_principal`, also used for the client-rotation digest): the principal's `preferred_channel` (slack / discord / telegram / email / any) maps to slack_dm / discord_dm / telegram / email and is tried first, then the other chat channels they have an id for in the order slack_dm → discord_dm → telegram. Email goes through the active MCP gateway when it runs the Google Workspace server (`runner.email_ready()`: another MCP server alone does not make email ready) (`google_workspace__send_gmail_message`, `user_google_email` = the Executive's own address, `to` = the principal's email, subject `<workflow title> — <local date>` in the user's zone, e.g. 'Morning Brief — Fri 25 Sep' (`_email_subject`; a UTC date put tomorrow's date on an evening digest west of UTC); body_format html, the Markdown rendered by `utils.markdown_email` (markdown-it-py: raw HTML off, so quoted outside text shows as text; images off, so opening the email loads nothing remote; javascript:/vbscript:/file:/data: links dropped); an in-band error counts as failed, `workflows.action_step.looks_like_error`). Email is tried first when the preference is `email`, and otherwise last, as the backup after every chat channel: delivery stops at the first channel that sends, so an owner linked by email at setup (`any`) with a working Slack still gets no email — only when every chat channel is missing or fails. Email is not a DM, so the per-Person outbound guard does not apply; the gateway's roster egress gate does. `_deliver_to_principal` returns a `PrincipalDelivery(ok, detail, reason, channel)`; reason is delivered | no_owner | no_channel | gateway_down | send_failed. `gateway_down` is email set up (the mail server in the MCP config, the principal has an address) but no active gateway: the Executive's fault, recorded with the supervisor's start failure (`mcp_gateway.gateway_problem`) instead of `no_channel`, which told the owner to connect what they had. A `send_failed` detail quotes each channel's own error (`email: invalid_grant …; slack_dm: channel_not_found`), stored with the outcome (`record_delivery_outcome(detail=…)`, JSON in the row's text, older bare-channel rows still read) and repeated by the notice and the Daily brief light (`brief_state.describe_problem`, whose fix says to reconnect when the detail shows a dead grant). Before planning, `_deliver_to_principal` / `deliver_to_person` run the lazy re-check `runner.ensure_email_ready` → `mcp_gateway.ensure_active_gateway`: with the gateway down and no attempt running, the supervisor (`orchestrator.gateway_boot.GatewaySupervisor`) tries a start now rather than waiting for its next backoff retry, so a gateway that failed at boot can still carry this brief; `_execute_action` resolves the gateway the same way instead of keeping the None boot handed the scheduler. The order comes from `runner.delivery_order` via `runner.principal_delivery_plan()` — public, because the Briefing notice and the Setup status light use them too. When no channel can deliver (e.g. a web-only principal, or email-only with no gateway) the brief is still generated and stored as a run with its artifact, exactly as before; it is not delivered (audited `delivery_failed`), so the window and fingerprint do not advance, and the next occurrence is chained. Every run's outcome is recorded (`brief_state.record_delivery_outcome`, scope `brief_delivery:<kind>`: the reason, and the channel that sent it — a channel name, never an address), including `not_written` when the workflow raised, emitted an error or produced no artifact (then nothing is sent), and `send_failed` when delivery itself raised. `last_delivery_outcome()` returns the latest of the two briefs and the (solo) weekly review (`brief_state.DELIVERY_KINDS`; `BRIEF_KINDS` stays the two daily briefs, whose send times the Setup page lists). `current_problem(outcome, has_owner, can_deliver)` says what still keeps it from the owner: send_failed and not_written stay reported until the next brief records a new outcome; having nowhere to send it is judged from now, so a fix clears it and a partial fix reports what is left (an owner added but still no channel reads no_channel). `GET /today/brief-delivery` (the Briefing's notice, owner only, null while the scheduler is off) and the Setup status 'Daily brief' light read it; brief names come from `scheduler.action_phrasing.KIND_LABEL` (`brief_state.brief_name`). SOLO: with effective_workspace_mode solo it uses STANDALONE_BRIEF_SOLO_SYSTEM (top call → what changed → handled overnight → needs you → due this week → goals at risk, named by area; no waiting-on or department sections) over the solo context render, which adds today_data['due_soon'] (open_loops.principal_due_soon: the principal's open loops overdue or due within 7 days) as a DUE THIS WEEK block, and the fingerprint carries the mode, drops the people-awaiting set and, when there are due items, carries them as (loop_id, state) pairs. TOP THREE TODAY (solo only, the DM brief only): `briefing.top_three.build_top_three` picks up to three in code — overdue then due-today commitments, off-track then at-risk goals (by area), commitments due later this week, then active initiatives stalest first — and renders them as a TOP THREE TODAY block the solo prompt turns into a 'Top three today' section right after the top call. When `runner.google_workspace_ready()` (gateway up and the Google Workspace server configured) and the principal has an email, ONE `google_workspace__get_events` call (asyncio.wait_for, 4 s) lists today's events (local midnight to midnight, sent as UTC) on the principal's calendar — `calendar_id` = their address, read as the Executive's account (`user_google_email` = EXEC_EMAIL_ADDRESS), or `primary` when that IS the principal's address; `parse_events` reads workspace-mcp's text listing or JSON and treats an error, a timeout or an unknown shape as NO calendar (never as a free day). With a calendar each item gets its own free block (an hour, never under 30 min) inside CALENDAR_BUSINESS_HOURS_START/_END, not before now, all-day events not blocking, plus a TODAY'S CALENDAR block (titles quoted as data); without one there are no slots and no calendar block. The calendar is read only when something was picked, and nothing here can fail the brief. The fingerprint adds the items' keys (`loop:N:state`, `goal:N:status`, `project:N` — no dates, no slot times) and only a coarse `calendar_hash` (busy blocks rounded to 15 min + the all-day count, no titles, no dates), each only when present, so an unchanged day still suppresses and a solo install with nothing picked keeps its old fingerprint. A day whose calendar read times out after one that did not (or the reverse) changes the fingerprint once — accepted. No slots on a non-business day (`calendar_tools.is_business_day`, shared with the booking caps), though the day's events are still listed. Only a date-only event is all day; a zero-length timed event is listed but blocks nothing; an event whose times cannot be read is dropped from the listing, the busy time and the all-day count, and a reply that lists events but none readable counts as no calendar (never a free day). Logs carry only the reply's length or the exception type — never reply text. OWN CALENDAR: with Act as me and Read my calendar on for the principal (and their mailbox opening as theirs), `read_todays_calendar` also reads their own calendar through their own sign-in (delegation.calendar.events_for, Gmail or Outlook, declined events dropped), concurrently with the Executive's read, and merges them (same title and times listed once; either read alone is enough). `build_top_three(include_own=private_ok)` adds it only on a run for the principal; `live_signals.refresh_calendar` (principal-private cache) always includes it."
    - "morning_brief (live world, since the principal-brief rework) — besides the board it reads `live_signals.gather_live_signals(since)`: inbound, stuck, the principal's chats, and today's calendar read fresh in BOTH modes (`refresh_calendar(max_age=0)`) unless the solo top three already rendered TODAY'S CALENDAR. It carries the latest executive_reflection run's 'Flagged for the brief' bullets finished inside the window (`brief_state.reflection_flags_since`, via `persistence.get_run` since list_runs omits the artifact) and drops rhythm runs from its activity (`_build_activity(exclude_workflows=RHYTHM_WORKFLOWS)`): their dated titles moved the fingerprint daily so suppression never fired. Team section order: top call → today → what changed (inbound first) → handled overnight → needs you → waiting on → at risk (the slipping goal or the department left out). Period is the local date. PRIVACY: private rows (the principal's contacts' alerts via `_build_today(include_private=True)`, private audit rows, drafts, chats, the calendar) are read only when `morning_brief.PRINCIPAL_DELIVERY` is set (the scheduler sets it around `_run_principal_brief`) or on the principal's own verified chat turn in a conversation only they can read (`is_principal_on_verified_surface` AND `delegation.settings.private_conversation`: web chat, Slack/Discord DM, private Telegram — never a shared channel, where the reply is posted for everyone). A run that used one reports `private_to_principal` on its result event; the scheduler, `run_workflow` and `POST /workflows/{name}/runs` then store `persistence.PRIVATE_RUN_ARTIFACT` via `stored_artifact` (private_used compares every key and count of the live read with the shared one), because /workflows/runs is readable by every signed-in user. The fingerprint adds `live_keys` (time-free: sender|subject|count, stuck lines, drafts count, conversation titles, calendar shape) and the reflection flags only when non-empty, so a caller passing neither keeps its old fingerprint. INFO log 'morning_brief: context since=… inbound=… stuck=… private_used=… suppressed=…'."
    - "end_of_day_digest — Shift 3 recurring workflow. Fires once per day from the scheduler (default 18:00 in the user's zone; an explicit PRINCIPAL_BRIEF_EOD_TIME is read as UTC). Same shape as morning_brief but framed as a recap since the last DELIVERED digest (`brief_state.since_for`, 24 h on a cold store): what OE did today (activity since), alerts it handled today (completed moves only; rewritten-but-open items render as a REWRITTEN block under still pending), what's still pending (NEW SINCE LAST BRIEF, action category only, carried-over as one line), what's at risk for tomorrow, one optional 'sleep on this' question. Same fingerprint / one-liner suppression and `force_full` as morning_brief, under scope `brief:principal_brief_eod`. SOLO: _EOD_DIGEST_SOLO_SYSTEM (what I did today → open decisions → goals at risk tomorrow by area → sleep on this) over a context with GOALS AT RISK BY AREA and no people-waiting block."
    - "weekly_review — the principal's weekly look back and ahead (background; inputs all defaulted; playbook `weekly-review`). Steps: goals (every area with goals graded concurrently by its own specialist with the check-in's verdict contract `_parse_verdicts` and write-back `department_check_in.persist_goal_verdicts` → `record_goal_review`, one `goal_status_review` audit row per area with actor `weekly_review`; no goals → skipped, no specialist → listed ungraded, specialist failure → shown as last recorded) → commitments (`open_loops.principal_due_soon`, overdue or due within 7 days) → projects (active initiatives with no update for 7+ days) → decisions (`episodic.decisions_since`, the last 7 days) → revisit (`episodic.decisions_awaiting_outcome`: at most 3 decisions older than 30 days with an empty or whitespace outcome, newest first, shown as [decision N]) → assemble. Every section always renders, with a one-line note when empty. Next week's top 3 comes from one fast-model call (constant `WEEKLY_TOP_THREE_SYSTEM`; the playbook and the review ride in the user turn) trimmed to at most three list items, or — on failure or an empty reply — the ranked pick `briefing.top_three` uses. Yields a `result` event (areas graded/ungraded, due count, quiet project ids, the week's and the revisit decision ids). Role-neutral wording; says area in solo and department in team. Scheduled weekly in solo only (`principal_weekly_review`, see the scheduler key). The artifact starts with `TITLE_PREFIX` + the period and ends with the `TOP_THREE_HEADING` section; `summarize_review(artifact)` reads those back as plain text ({period, top_three, excerpt}) for the solo Briefing's 'This week's review' card (GET /today/weekly-review, see the today key). Evals: `workflow_weekly_review_001`."
    - "executive_reflection — Shift 5 recurring workflow. Fires once per day ~30 minutes before the morning brief (default 07:30 in the user's zone; an explicit PRINCIPAL_REFLECTION_TIME is read as UTC). The first workflow OE runs ON ITSELF — not for a department, not for the principal, but for its own org-coordination judgment. Three steps: (1) gather /today + /today/activity + recent open alerts, (2) single LLM call with the full outbound toolkit (schedule_followup, send_*_dm, send_department_message, send_company_broadcast, suggest_workflow, create_alert, etc.) bounded to ≤4 iterations — the model decides per signal whether to act now, notify the right audience via the persona's 'Choosing Who to Tell' rule, raise it for the morning brief, or ignore, (3) emit a short Markdown summary with a structured tool-call log. MEMORY: the context carries a YESTERDAY'S STANDUP block (the previous done run's artifact, capped at 1500 chars) and the prompt forbids re-acting on or re-notifying about anything listed there unless it changed; open alerts render with `alert_id`, the review verdict, note and recommended move. Reflection never closes alerts (the alert review does, with evidence) — the prompt does not instruct `ack_alert`. The artifact is stored via complete_run but NOT DM'd — the morning brief surfaces what was decided via /today/activity. This operationalizes the 'When You Notice Something on Your Own' persona section (Shift 1). SOLO: the role-neutral solo prompt, no team tools, a YOUR PRINCIPAL line instead of the roster — see routing.reflection_then_decide."

artifacts:
  summary: |
    The Executive artifacts section (`/artifacts`, shown to users as "Documents") is a unified view over
    every deliverable the Executive produces, in any registered format
    (see `formats:`). It does NOT
    introduce a new table — it aggregates the two places artifacts already
    live, so the underlying rows stay canonical:
      1. `draft_artifact` documents — alerts with `source='artifact'`
         (see `artifact_tools:`), shown regardless of read/ack/dismiss
         status so a drafted memo is never lost once it leaves `/today`.
      2. completed workflow runs — `workflow_runs.artifact` where
         `status='done'` (see `workflows:`).
    Reads are unified; writes are limited to two reversible/irreversible
    lifecycle actions (archive/restore + delete) — see `lifecycle:`.
  formats: |
    `orchestrator/artifact_formats.py` — `ARTIFACT_FORMATS` registry, one
    `ArtifactFormat` per format (label, mime, extension, `build`, `display`,
    `text`, `render_file`). Everything is stored as TEXT in the owning row;
    no file is ever written to disk, so there is no file volume and
    archive / delete have nothing extra to clean up:
      - markdown — the Markdown (+ Sources footer); download .md.
      - html — rebuilt through an ALLOWLIST (`sanitize_html`, stdlib
        html.parser, so attribute entities are decoded before checking):
        document/table/list/media tags + inline SVG; no script/iframe/
        object/embed bodies; no meta/base/link/form controls; no on*
        handlers; <a href> only http(s)/mailto/#, non-fragment links forced
        to target=_blank; <img src> only data:image/*. A regex pass was
        bypassable (`re&#102;resh`) and let the frame self-navigate to an
        attacker URL. Download .html.
      - docx — the Markdown source; `markdown_to_docx` (python-docx) renders
        headings, lists, GFM tables, quotes, code and inline emphasis at
        download time.
      - xlsx — JSON `{"summary", "sheets": [{name, columns, rows}]}`;
        `sheets_to_xlsx` (openpyxl) renders at download time and writes
        every string cell as a literal string, NEVER a formula (cells can
        quote web/email text). Caps: 20 sheets, 5k rows/sheet, 200 cols,
        200k cells. Display = Markdown tables, 50 rows/sheet.
      - link — Markdown summary in `body`; URL + label in
        `alerts.artifact_url` / `artifact_link_label`; no download.
    Columns on `alerts` (additive migration): `artifact_format` (NOT NULL
    DEFAULT 'markdown', so legacy rows read as Markdown), `artifact_url`,
    `artifact_link_label`, `supersedes_id`. Workflow runs stay Markdown
    (the scheduler DMs and other readers consume that text) and gain
    formats only on the way out: `EXPORT_TARGETS` lets any Markdown
    artifact download as .docx. Document cap: 60k chars.
    `/today` `ProposalItem` carries `artifact_format` / `artifact_url`, and
    its `body` is the format's Markdown `display`, so the card and chat
    handoff never show raw HTML or sheet JSON.
  serving: |
    `openexecutive.api.routes.artifacts` (registered in api/main.py), a
    thin HTTP layer over `orchestrator/artifact_records.py` (shared with
    the `list_artifacts` / `get_artifact` tools).
    - GET /artifacts?archived=false — merges
      `alerts.store.list_artifact_alerts` +
      `workflows.persistence.list_artifact_runs`, sorts newest-first,
      returns summaries (no bodies; run previews are null since the list
      query omits the heavy artifact column). Each summary carries
      `format`, `format_label`, `downloads` (first = own file, then export
      targets; empty for links), `external_url`, `link_label`,
      `supersedes_id`. `archived` (default false) selects which slice:
      active-only or archived-only — a clean swap, never a superset.
    - GET /artifacts/{composite_id} — `body` is the sanitized HTML for
      html, the format's Markdown `display` otherwise, plus `rationale`
      (resolves archived artifacts too, so the gallery can still open one).
    - GET /artifacts/{composite_id}/download?as=<format> — the file, always
      `Content-Disposition: attachment`, `X-Content-Type-Options: nosniff`,
      `Content-Security-Policy: sandbox`, `Cache-Control: no-store` (the UI
      proxy keeps an upstream no-store instead of its default no-cache), so
      an HTML artifact never renders on the app origin. 404 for links or a
      target not in `downloads`.
    - POST /artifacts/{composite_id}/archive — reversible soft-hide.
    - POST /artifacts/{composite_id}/restore — un-archive.
    - DELETE /artifacts/{composite_id} — permanent hard-delete of the
      underlying alert / workflow-run row (`delete_alert` / `delete_run`),
      then drops its knowledge chunks (`unindex_artifact`).
  lifecycle: |
    Archive is a reversible soft-hide backed by a nullable `archived_at`
    column added to BOTH backing tables (`alerts.archived_at` and
    `workflow_runs.archived_at`; NULL = active, ISO timestamp = archived,
    via the idempotent PRAGMA + ALTER migration in each store). Archived
    artifacts drop out of the default list and surface only under
    `?archived=true`; restore clears the timestamp. Delete is permanent —
    it removes the canonical row, so a deleted draft/run is gone from
    `/today`, `/jobs`, and everywhere else, not just `/artifacts`.
    Store helpers: `set_alert_archived` / `set_run_archived`.
  addressing: |
    Composite id `"{kind}:{native_id}"` — `alert:<int>` or `run:<hex>`.
    The kind prefix is the dispatch key for EVERY per-artifact route
    (detail + archive/restore/delete); native id spaces are colon-free so
    the scheme is unambiguous and reversible (`_parse_composite_id`).
    Every per-artifact route 404s a non-artifact alert id (it must not
    become a general alert reader/mutator) or an incomplete run, and 400s
    a malformed id — enforced by the shared `artifact_records` guards
    (`MalformedArtifactId` → 400, `ArtifactNotFound` → 404).
  ui: |
    `/artifacts` gallery — a compact, sectioned (Drafts / Workflows) row
    list with an Active / Archived toggle and a kind filter
    (All / Drafts / Workflows). Each row has per-item actions: Archive
    (Active view) or Restore (Archived view) plus Delete; delete prompts a
    confirm, archive shows an Undo toast; non-Markdown rows show a format
    badge. `/artifacts/[id]` detail renders through
    `components/ArtifactViewer.tsx`: Markdown (ReactMarkdown + remarkGfm)
    for markdown / docx / xlsx previews; html in an `<iframe sandbox="allow-popups
    allow-popups-to-escape-sandbox">` (no scripts, no same-origin; popups
    only so a click on a sanitised target=_blank link opens a tab) whose srcDoc is prefixed with a CSP meta
    (`default-src 'none'`, inline styles and data: images only) so it can't
    fetch anything; link as an "Open {label} (host)" button + summary. It
    offers Copy, one Download per `downloads` entry (plain same-origin
    links to the proxy), "Revise in chat" (opens `/?new=1&draft=Revise
    artifact <id> …`), a "Replaces an earlier version" link when
    `supersedes_id` is set, and the same Archive/Restore + Delete actions
    plus the "Why this is worth your time" rationale. The workflow-run page
    adds "Download .docx" beside "Download .md".

user_guide:
  summary: |
    `/guide` is a plain-language overview of every user-facing feature —
    "what it is, what it does, how to use it" — for non-engineers. It is deliberately
    SEPARATE from the `/architecture` technical reference: Architecture
    explains how the system is built; the User Guide explains what each
    feature does for the user. Reached from a tile on the Settings hub
    (`ADVANCED_ITEMS` in `navConfig.ts`), not the day-to-day nav.
  module: |
    New top-level module `openexecutive/guide/`:
      - `sections.py` — `GUIDE_SECTIONS: list[GuideSection]` (id/title/sub),
        one entry per feature; `get_section`.
      - `prebuilt/<id>.json` — static, hand-authored content per section
        (same shape as architecture: section_id, title, markdown, mermaid,
        generated_at). The guide is intentionally diagram-free
        (mermaid: null).
      - `prebuilt.py` — thin `get_prebuilt`/`list_prebuilt` over the shared
        store.
  serving: |
    `openexecutive.api.routes.guide` (registered in api/main.py), mirrors
    the architecture routes:
      - GET /guide/sections — directory listing + availability (`fresh`).
      - GET /guide/sections/{id} — one section's authored content.
    Read-only file reads; NOTHING on this path calls an LLM.
  shared_loader: |
    Both `/architecture` and `/guide` load their JSON through one class —
    `openexecutive.utils.prebuilt_store.PrebuiltDocStore` — each pointed at
    its own `prebuilt/` directory. `architecture/prebuilt.py` and
    `guide/prebuilt.py` are thin shims over it; the path-traversal guard and
    required-key validation live in the store. The UI reuses the
    architecture `DynamicSection` component via a `basePath` prop
    ("architecture" default, "guide" for the guide).
  maintenance: |
    When a user-facing feature is added or materially changed, add/update
    the matching `guide/prebuilt/<id>.json` plus its registry entry in
    `guide/sections.py` and the mirror list in `app/guide/page.tsx` (IDs
    must match). Every section carries a `**How to use:**` walkthrough
    (where to click, which fields matter, what to say in chat) and, where
    it helps, an `**Example:**` — enforced by
    `tests/unit/test_guide_prebuilt.py`. Ask OE injects the page's section
    into the user turn, so the how-to steps also ground its answers. The
    `user_guide` architecture section documents this surface for engineers.

auth:
  ui_provider: |
    NextAuth.js with Google OAuth and/or one generic OpenID Connect
    provider (SSO: Keycloak, Okta, Entra ID, ...; packages/ui/src/lib/oidc.ts,
    on when AUTH_OIDC_ISSUER / _ID / _SECRET are all set and the issuer is
    https (http only for loopback: Auth.js trusts the token-endpoint ID token
    on TLS alone, without its signature), provider id `oidc`,
    endpoints from the issuer's discovery document), JWT session strategy
    (24h maxAge). Both feed the same email-keyed gate: an SSO sign-in adds no
    admission logic. Its email must be verified - the standard
    `email_verified` claim, or on an Entra issuer only Microsoft's `xms_edov`
    - unless the operator sets AUTH_OIDC_TRUST_UNVERIFIED_EMAIL=true (Setup
    status then shows amber), because access is granted by email alone and an
    unverified address at many providers is whatever the user typed. Google
    stays offered unless SSO is the only sign-in set up.
    Lives in packages/ui/src/auth.ts. Gate is enforced at two points:
      - `signIn` callback: strict initial check when a user first logs
        in. Denies on miss.
      - `authorized` callback: re-runs on every middleware-gated request.
        A user removed from the roster mid-session (or one whose JWT
        predates the roster) is bounced on their next request rather
        than coasting until JWT expiry. Fails open ONLY for a session
        that is not in ALLOWED_EMAILS and whose roster membership is
        currently unreadable; a definite miss (both lists readable,
        neither matched) still revokes. It returns the refusal itself
        (JSON 401 for /api/*, a redirect to /signin for pages), and
        middleware.ts exports `auth` UNWRAPPED — next-auth ignores an
        `authorized` false whenever a wrapper `auth((req) => …)` is
        passed, which is how this re-check went unenforced until the
        local-login change: removed users kept working until their
        JWT expired. /signin bounces a visitor onward only when
        `sessionStillAllowed` agrees, or a refused session would loop.
    Pages' security headers (packages/ui/src/middleware.ts, lib/csp.ts):
    every request but Next's static files and the favicon runs the
    middleware, /signin and Auth.js's routes included (they skip only the
    session check, SESSION_FREE_PATH in lib/middlewarePaths.ts). Every page
    gets Content-Security-Policy script-src 'self' 'nonce-…'
    'strict-dynamic' (+ 'unsafe-eval' on the dev server only), object-src
    'none', base-uri 'self', frame-ancestors 'self'; Auth.js's own HTML
    pages get frame-ancestors 'self' alone. The root layout awaits
    connection() so every page renders per request and carries its nonce.
    Local login (packages/ui/src/lib/localLogin.ts): `make dev` with
    neither Google nor SSO sign-in set up starts the UI with `-H 127.0.0.1` and
    OE_LOCAL_LOGIN=1 in one recipe line (the flag alone would hand
    the owner's seat to the network, so nothing else sets it). The recipe
    decides via scripts/devMode.mjs, which loads the env the way Next does
    (root .env exports plus packages/ui/.env*) and applies the app's own
    `localLoginEnabled`, so recipe and sign-in page cannot disagree;
    it also reports whether AUTH_SECRET is blank everywhere. The UI
    then offers a Credentials provider (`local-login`) instead of Google:
    an "Open" button with no password. Guards: the mode is compiled out
    of production builds (literal `process.env.NODE_ENV`, folded at build
    time), off whenever AUTH_GOOGLE_ID, AUTH_OIDC_ISSUER or OE_PUBLIC_DEPLOYMENT is set, and
    every sign-in and request must carry a loopback raw `Host` header —
    that stops DNS rebinding, since a browser cannot forge Host (it CAN
    set X-Forwarded-Host, which is why request.url is not used). The
    session has no email; the JWT carries `localLogin`, and it stops
    working the moment Google or SSO sign-in is set up. An AUTH_SECRET blank in
    every env file gets a throwaway per-run value from the Makefile, and
    trustHost is on in this mode without AUTH_TRUST_HOST (no OAuth redirect
    to steer; its checks read the raw Host). Docker (`make docker`)
    publishes port 3000 on all interfaces, so it never sets the flag — its
    ui service exports OE_LOCAL_LOGIN EMPTY, which (Next never lets a
    dotenv file override a set variable) also shadows any value in the
    bind-mounted packages/ui/.env*; `make dev` exports it empty outside the
    mode for the same reason; compose's api service shadows it empty too
    (from the root .env it would 403 the UI, which calls as Host api:8000).
    The API receives the same flag and then adds `_local_login_gate`
    (api/main.py), a 403 for (a) a raw Host that is not loopback, unless
    the path is a webhook that verifies its caller (Google Chat always;
    Telegram only with a TELEGRAM_WEBHOOK_SECRET Telegram can send, since
    without it the webhook accepts anyone's update), and (b) a write whose
    Sec-Fetch-Site
    is present and not same-origin/none. Without it the owner's browser
    could drive :8000 as the principal (usually no shared secret; no
    x-caller-email = principal): a DNS-rebinding page calls it
    same-origin, and a plain multipart form from any site or localhost
    port needs neither a cookie nor a preflight. The UI proxy, the CLI and
    webhook senders send no Sec-Fetch-Site. Both rules are mirrored in the
    UI (isLoopbackHost, OWN_PAGE_FETCH_SITES) with tests that read the
    Python literals and fail on drift. scripts/devMode.mjs resolves
    @next/env through `next` itself and needs Node 22.6+ (type stripping).
    Both callbacks share one helper (`checkEmailAllowed`). The allowlist
    is the UNION of two additive sources — neither overrides the other:
      1. ALLOWED_EMAILS: comma-separated env var on the UI, parsed once
         at module scope. Checked FIRST and a hit short-circuits, so the
         roster is never fetched for a configured operator: they sign in
         with the backend down, at no fetch latency. Revocable only by
         editing the env and restarting.
      2. Roster: GET /auth/allowed-emails returns every non-archived
         TEAM member with a non-null email — never a contact
         (`people.kind`), so adding a client to reach them by email does
         not let them sign in. Consulted only on an env miss, and purely
         additive.
    Roster fetch is cached for 5 minutes per Next.js server instance
    (ROSTER_TTL_MS in auth.ts) and concurrent misses coalesce onto one
    in-flight request — `authorized` runs per gated request, so without
    that a page load would fan out into N backend calls. A failed fetch
    returns null ("unknown") and is deliberately not cached, so the next
    caller retries instead of being pinned out for a TTL; a stale success
    is not served past its TTL.
    The old rule made the roster authoritative as soon as it held one
    email, which was issue #132: anything that wrote a Person row —
    including a fixture load, which wipes `people` and inserts its own
    addresses — silently evicted the operator from their own instance.
    Decision helpers are pure and live in packages/ui/src/lib/allowlist.ts
    (parseAllowedEmails / decideAllowed / resolveAllowed /
    createRosterLoader / describeDenial), unit-tested by
    packages/ui/scripts/allowlist.test.mjs; auth.ts keeps only the
    wiring, the audit calls and the NextAuth config. The decision's
    `source` — env | roster | no_match | env_only_roster_unavailable —
    is recorded in the audit-log `details`, and `decideSessionAction`
    maps a decision to the `authorized` outcome (allow /
    allow_roster_unknown / revoke).
  backend_gate: |
    BACKEND_SHARED_SECRET via x-api-key header gates every API route
    (see api.main._shared_secret_gate). The Next.js proxy at
    /app/api/backend/[...path] holds the secret and stamps it on
    every upstream request.
  per_user_identity: |
    The Next.js proxy also stamps `x-caller-email` from the verified
    NextAuth session (lowercased) on every upstream request. The
    inbound `x-caller-email` from the client is stripped before
    re-stamping so a client cannot spoof another user. Today the
    backend uses this header in /chat to resolve the caller to a
    Person row for Honcho's per-person memory; future routes
    (audit/today filters etc.) can read the same signal.
    A request WITHOUT the header resolves to the principal (the CLI's
    fallback), so the proxy sends none only for a local-login
    session, re-checked there (mode on, loopback Host); any other
    session without an email gets a 401 rather than that fallback.
    The proxy also 403s a write (not GET/HEAD) whose Sec-Fetch-Site is
    anything but same-origin/none (lib/crossSite.ts): the SameSite=Lax
    cookie stops other websites, not other pages on the same site, and a
    browser treats every localhost port as one site, so any local dev
    server could otherwise post a multipart form (chat upload, documents)
    with the user's cookie.
    Onboarding saves the owner's sign-in email on the principal's row
    (company_onboarding.people_and_contacts), so a Google-signed-in
    owner resolves to themselves from the first turn.
  caller_helper: |
    Routes read the caller only through api/caller.py (caller,
    caller_email, signed_in, actor, identity_key); a test fails on any
    other read of an x-caller-* header in the package. It answers a
    Caller(kind, email). kind "open" (no signing keys): the header as
    sent, and no header means the principal. "user" / "operator" /
    "service" come from the signed-caller gate: an operator names no
    one and runs as the principal (Caller.defaults_to_principal); a
    service never does, so _resolve_caller_person_id gives None,
    workflows' principal-only runs refuse it, and Act as me answers
    sign_in_required.
  signed_callers: |
    Optional. With CALLER_ASSERTION_PUBLIC_KEYS set on the API
    (kid:base64url raw Ed25519 public key, comma-separated for
    rotation), api.caller.caller_gate runs on every request after the
    shared-secret gate. The UI proxy signs x-caller-assertion with
    CALLER_ASSERTION_PRIVATE_KEY (lib/callerAssertion.ts): the value is
    v1.<base64url JSON claims>.<signature over "v1.<claims>">, and the
    claims are aud "openexecutive-api", iat, exp (the UI signs 30 s; the
    API accepts at most 120 s and 30 s of clock skew), jti, kid, kind
    user|operator, m (method), p (raw path + query as the API receives
    it) and sub (the email, lowercased; "" for the operator).
    Every jti is single-use (JtiLedger, in memory; the API runs as one
    process). It prunes expired ids and refuses when full of live ones.
    The signature is checked against each public key before the claims
    are parsed, so no unsigned byte reaches the JSON parser, and the
    claims must name the key that signed them. Local-login sessions sign
    as the operator. A service is never the principal, not even on an
    install with no owner yet: chat._caller_is_principal_or_unclaimed
    answers no for it, and the setup commit refuses it (403), since on a
    first setup it would choose the owner and their sign-in email.

    What the gate decides:
      - no caller header at all: Caller("service");
      - an x-caller-email with no assertion: 401 caller_assertion_required;
      - a bad, unknown-key, wrong-audience, wrong-method or wrong-path,
        expired, reused or duplicated assertion, or an x-caller-email that
        disagrees with it: 401 caller_assertion_invalid. The log carries
        the reason, the method and the path, never the token or email.
    The UI keeps stamping x-caller-email, so a UI with the key works
    against an API without it. Unreadable public keys stop create_app
    (RuntimeError), and so does a value that is set but lists no key
    (" , "): signing_on() reads "set" as on, so set must mean a key the
    gate checks; an unreadable private key makes the proxy answer
    500 to every call. Neither falls back to the header.

    Other consequences:
      - An MCP client holding only the shared secret is a service: /mcp
        refuses it the owner's records, the briefing and the roster, and
        ask_executive asks as no one (person_id None). A sign-in in front
        of /mcp that sends a signed assertion gets that person's answers
        (see mcp_server).
      - Setup's api_secret check warns when a shared secret is set
        without the keys.
      - scripts/make-caller-keys.py makes a pair, and
        scripts/mint-caller-assertion.py signs one request for curl.
      - Parity: packages/core/tests/unit/caller_assertion_vectors.json
        (the public RFC 8032 test key) is signed byte-identically by the
        script and by the UI (scripts/callerAssertion.test.mjs).
  host_origins: |
    Optional. OE_HOST_ORIGINS on the UI lists other apps' exact origins
    (https, or http under localhost; a bad entry refuses all, lib/
    hostOrigins.ts) that may frame the pages and call the host list
    (packages/ui/src/lib/host-list.json) from their own pages with the
    session cookie. They must be sibling hosts under the UI's registrable
    domain (SameSite=Lax). Why: a host app runs code Open Executive
    doesn't control (its administrators' scripts, installed apps), so
    what its origin can do is fixed here, not by the host.

    The host list: GETs of /auth/me (the email the call is made as, so a
    host's native screens can warn when this session is someone else's,
    as EmbeddedShell's UserHintWarning does in the frame; never
    /auth/allowed-emails), /today*, /decisions, /decisions/{id},
    /alerts/approvals/{id}, /sessions*, /watchlist*, /chat/voice,
    /chat/suggested-prompts; alerts ack/snooze/reopen/bulk-ack/review;
    POST /chat, /chat/stop, /chat/add, /chat/upload, /chat/transcribe;
    the watch list's describe/add/edit/delete/approve/decline. Never a
    card's approve/reject/cancel, prepare, Act as me, delegation,
    settings, People (tests/unit/test_host_list.py checks each entry is
    a real route and that rule).

    Enforcement (src/middleware.ts, app/api/backend/[...path]/route.ts):
      - Origin exactly a listed host + Sec-Fetch-Site same-site: only
        host-list calls, CORS for that origin with credentials; anything
        else naming a host origin 403 (with CORS). {name} is one plain
        segment (no . .. / \ ? # % or space).
      - Preflight answered before the session check; a listed call with
        no session is 401 with CORS, not the sign-in redirect.
      - The proxy drops Origin, Referer and Sec-Fetch-* of a host call
        (api/main.py _OWN_PAGE_FETCH_SITES would refuse its write), and
        sets the host surface: x-caller-surface: host and the optional
        signed claim "surface": "host" (after sub in key order; absent
        otherwise, so older assertions are byte-identical). With signed
        callers the API reads only the claim and 401s a header that
        disagrees (surface_mismatch) or comes without an assertion; in
        open mode any header value means host (narrows, never widens).
        api.caller.from_host answers it.
      - Everything else: lib/crossSite.ts as before.

    The host surface: chat sets Session.from_host per turn; it is a
    read_only_turn (MCP_CLIENT_WITHHELD_TOOLS, gateway reads only, no Act
    as me / recall_history / scripts / extensions), principal-only tools
    withheld, refusals say HOST_REFUSAL, never noted as the person's own
    words (history_chat.verified_speaker), and _stop_owner_key adds
    "|host" so it stops/adds to its own turns only. Each user line saves
    chat_messages.sender_surface ("host" or NULL); a conversation with any
    host line (session_store.host_wrote) holds EVERY later turn to the same
    rules, own page included, failing closed when unreadable: the line stays
    in the model's context and could plant an instruction for the person's
    next full-power turn. A host call into an existing conversation it
    never wrote in is a 409 (it would turn the person's own chat read-only).
    delegation.settings._offered refuses host turns. In a frame, chat sends
    (/chat, /chat/upload, /chat/add) ask like any change: the framed
    page's turn is the person's own; typing notices pass. A host turn
    teaches nothing: content_trust.principal_speaking and
    people_tools._is_verified_speaker_surface answer False for from_host,
    both post-turn blocks clear speaker_text and kept (no extraction, open
    loops, style, notes, review, Honcho), and attunement.style skips
    sender_surface rows. sessions.host_wrote makes the mark sticky across a
    rewind (Try again / Edit). Frame input also counts drop, paste and a
    Yes in the in-frame confirm; chat sends always ask in a frame, and the
    confirm shows the message. A host turn marks a new conversation as soon as its
    session row exists (session_store.mark_host_wrote), so an own-page turn
    running alongside is held too; briefing.live_signals leaves such
    conversations' titles (the host's words) out of the brief. The
    cross-chat readers of "the person's own words" skip host lines too:
    session_store.own_messages_since (a scheduled follow-up's "since"
    block, which can stand it down), own_conversation_since (the
    end-of-day digest; whole host-written conversations) and
    chat_topics.owner_only. A failed mark still holds the chat through the
    in-process chat._host_sessions set. Suggested starter prompts skip
    host-written chats' titles (fail closed); the Markdown export labels
    host lines "(from another app's page)".
    In any frame, card actions, chat messages, and any other change off the
    host list made within 10 s of a trusted click/key/drop/paste ask in
    FrameConfirm, inside the frame. A lured click on an invisible frame
    beats a plain dialog, so its Yes counts only under lib/seen.ts:
    IntersectionObserver v2 (trackVisibility) reported the panel whole,
    uncovered, untransformed and at full opacity for an unbroken 700 ms
    (pending reports read with takeRecords); the real pointer rested inside
    for 500 ms (reset on pointerleave and the frame's blur); the press began
    on Yes after that and a trusted click on Yes followed; and 250 ms later
    the same run of "seen" holds with the pointer inside. The panel wears
    .consent (the app's own colour tokens and a system font, never the
    host's). Without v2 (Firefox, Safari), or for keyboard and touch, it
    offers no Yes: a link to this app's own page, target _top (the card's
    /cards/<id>, else the asking page without embed); it never fails open.
    A No throws CardActionNotConfirmed.

    Pages (all, host origins set or not): Content-Security-Policy
    script-src 'self' 'nonce-…' 'strict-dynamic' (+ 'unsafe-eval' on the
    dev server only), object-src 'none', base-uri 'self', frame-ancestors
    'self' + host origins. The root layout awaits connection() so every
    page renders per request and gets its nonce.

    Embedded mode (lib/embed.ts, components/embed/): ?embed=1, a parent
    window, a listed origin and a valid oe-embed/v1 init (contract 1;
    colours, font pattern, bounded product name, email hint (display
    only: EmbeddedShell's UserHintWarning says so, with Sign out, when it
    isn't who is signed in here), native paths under the app's routes). AppShell then drops AppSidebar,
    TopBar, MobileBottomNav and AskOEPanel, keeping HubTabs,
    PausedBanner and the page. Messages ready/init/theme/route/open/
    badge, examples in lib/embed-examples.json shared with the host's
    tests. /signin in any frame shows no forms, only a link that opens it
    in a new tab (components/embed/FrameSignIn.tsx); the frame goes on
    once /api/auth/session has a user. In ANY frame card actions
    (decisions approve/reject/cancel, alerts approve, workflow decisions,
    roster requests), chat messages, and other changes off the host list
    after a click ask in FrameConfirm under lib/seen.ts's rule (fetch is
    checked against lib/cardActions.ts); each card has /cards/<id>, where a
    browser without IntersectionObserver v2 answers it.

    What remains (docs/auth.md): a host's scripts can read what the
    host list allows (briefing, conversations and replies, watch list)
    and start read-only chat turns as whoever has it open and is signed
    in here; they can't approve, send, change settings or People, or
    read/click into the frame.

integrations:
  chat_directory: |
    No raw chat ids: the person page, Add person and a department's
    Channels settings pick Slack, Discord and Telegram people and rooms by
    name (integrations/chat_directory.py; GET /chat-directory/people,
    /chat-directory/channels, /chat-directory/slack/lookup?email= in
    api/routes/chat_directory.py). The id is still what is saved, and the
    by-hand field stays under "Enter an ID by hand" (all there is for a
    provider with no bot).
      • Slack: conversations.list (public + private the bot is in;
        channels:read, groups:read, public only on missing_scope) and
        users.list (no bots, no deactivated; users:read, users:read.email
        for the profile email). users.lookupByEmail matches a person by
        work email after the cached list; the picker pre-selects it as
        "Found by email" with "Not them?".
      • Discord: REST API with the bot token. Text and announcement
        channels of the bot's servers (DISCORD_GUILD_IDS when set) and
        their members. Members need the Server Members privileged intent;
        a 401/403 reads as members_available=false with no options, not
        an error.
      • Telegram: no list API, so telegram_bot's webhook records each
        chat an update comes from (integrations/telegram_chats.py,
        table telegram_chats: chat_id PK, chat_type, title, username,
        first_seen_at, last_seen_at; newest 250 kept per kind, so new
        groups never push people out). Private chats are
        people, group/supergroup are rooms. A group that migrated to a
        supergroup or removed the bot is dropped.
      • TRUST: Telegram chats are recorded only when TELEGRAM_WEBHOOK_SECRET
        checked out; without it anyone could post an update putting a name
        of their choice next to a chat id. A row is a suggestion only and
        grants nothing; the roster still gates who is answered. Anyone can
        still pick their own Telegram name, so each person option's detail
        shows what they can't choose: the @username, when they first wrote,
        and who on the roster already has that chat ("already linked to X").
      • The routes are the principal's alone (chat._caller_is_principal_or_unclaimed,
        the same rule as changing the People list). Channels also open while
        no one is principal yet (first setup); people and the email lookup
        wait for a principal, since they name everyone in the company's
        Slack and Discord with their email. Anyone else gets 403 and the
        pickers fall back to the by-hand field.
      • Each provider/kind is cached in-process for 60 s, capped at 2,000
        items; a provider that fails reads as ok=false with no options.
        configured=false when the token is unset. Tokens go only in the
        Authorization header to slack.com / discord.com, never returned.
      • A department's Slack/Discord pickers pre-select the room named most
        like the department (lib/chatDirectory.closestOption in the UI);
        saved only when the person presses Save.
      • telegram_chats is per company: clients.slots._BLANK_WIPE_TABLES.
  chat_app_conversations: |
    A Telegram chat, a Slack or Discord DM and a person's @mentions in
    one channel are each one endless stream with a fixed base id
    (telegram:{chat}, slack:dm:{user}, slack:channel:{c}:{user},
    discord:dm:{user}, discord:channel:{c}:{user}). memory.conversations
    cuts it into conversations so the Chats page shows each one, titled,
    instead of one chat that never ends, and replayed history starts
    clean.
      • A message starts the next conversation when the stream has been
        quiet for two hours (CONVERSATION_GAP). The first keeps the bare
        base id; later ones are base~2, base~3 (memory.conversation_ids).
      • "/new", "new chat" or "new conversation" as the whole message
        starts one now; the reply names the conversation it ended. The
        empty row stays off GET /sessions until its first turn.
      • After a conversation's first exchange it is titled in the
        background (utils.session_title, else its first words).
      • Threads, email and web chats are never cut.
      • What the Executive sends into the stream on its own (a brief,
        the evening digest, a workflow report, a reminder; the
        scheduler's _send_on_plan) is saved into the current
        conversation as its message once sent (record_delivery; a held
        message when it goes out) and counts as activity, so the reply
        joins it with the message in view. Without this a reply like
        "can you fix it?" reached a turn with nothing before it.
        In a chat-app conversation get_recent_history puts a placeholder
        user turn before history that opens with an assistant message
        instead of dropping it (web chats still drop it).
      • What spans the stream compares base ids: inbound_resolver
        (an approval asked before a cut is answered after it) and the
        session-scoped decisions/advice in format_for_prompt.
      • Boot (and a client-slot restore) runs split_existing_streams
        once per DB (app_migrations): old history is cut by the same
        rule, each part titled from its first message, a read-mail lock
        carried to every part with mail_read_at unknown (fails closed).
      • An adapter outside the package registers its streams with
        conversation_ids.register_rolling and runs
        split_existing_streams(migration=<its own name>, only=<its base
        ids>) once, since the built-in sweep may have run before it
        registered. Boot runs the sweep off the event loop (to_thread).
  channel_access: |
    Channel access splits into INBOUND (does the message reach the
    Executive at all?) and OUTBOUND (can the Executive reply via the
    channel?).

    Inbound — divergent by channel today:
      • Email: NO roster gate on inbound. Every non-automated message
        flows to the Executive so triage can classify cold prospect
        signal, escalate, log, or propose. When the sender isn't on
        the People roster, the poller prepends a [POLICY] notice to
        the body the Executive sees explaining that outbound reply
        will be blocked. Audit ``integration_inbound`` row carries
        ``details.outcome="accepted_non_roster"`` for observability —
        the same row for one of the principal's contacts, who are private
        to the principal (see ``people.kind``). A sender is on the roster
        when ``people.identity.resolve_email_sender`` matches them (a
        primary address or alias, then the company-domain rule — see
        ``people.aliases`` / ``people.company_domains``). Non-roster mail
        that is not private to the principal and not machine-sent is ALSO
        held as a roster request (see ``people.roster_requests``) and
        acknowledged once; it is still triaged on this pass and replayed
        after the principal adds the sender.
      • Discord, Slack, Telegram: still roster-gated on inbound. A
        sender's channel ID must match a non-archived TEAM member's row
        (discord_user_id / slack_user_id / telegram_chat_id) — a
        contact's id counts as unknown. An unknown sender's message never
        reaches the Executive (``details.outcome="rejected_unknown_sender"``),
        but it is no longer silently dropped: a DM or mention (Slack,
        Discord) or a private chat on a verified webhook (Telegram) is
        held as a roster request, the sender gets the fixed
        acknowledgement privately, and the principal is asked who they
        are. Silent still: a contact (no chat access, and no request), a
        thread continuation the bot was not addressed in, a Telegram group,
        and any Telegram update without a valid TELEGRAM_WEBHOOK_SECRET.

    Outbound — roster-gated everywhere this matters:
      • Gmail send (``send_gmail_message`` — which also covers replies
        via thread_id in workspace-mcp 1.29.0 — and ``draft_gmail_message``)
        is gated at the MCP gateway
        (orchestrator.mcp_gateway._check_gmail_recipients). Every
        ``to``/``cc``/``bcc`` address must be in the ``RosterAllow``
        (a Person's primary or alias, case-insensitive; for a teammate,
        also their local part on a company domain) or be the exec's own
        address; misses get an ``integration_outbound_blocked`` audit row.
        The one exception is the roster-request acknowledgement: inside
        ``roster_ack_grant(to, subject, body)`` (a ContextVar set only by
        ``roster_intake.send_email_ack``) exactly one
        ``send_gmail_message`` with exactly those four keys
        (user_google_email, to, subject, body), a single plain ``to``
        equal to the granted one and the granted subject and body passes,
        audited private as ``integration_outbound`` kind roster_ack; the
        grant is then spent. Only a fixed
        set of argument keys passes (``_GMAIL_ALLOWED_ARG_KEYS``), so
        1.29.0's ``reply_all`` (To/Cc derived from the thread, never
        roster-checked) and ``forward_message_id`` /
        ``include_forwarded_attachments`` (forward any inbox message)
        are refused.
      • Outlook (Microsoft 365) send/reply/forward/draft/update and
        create-/update-calendar-event are gated by
        ``_check_m365_recipients`` on the same roster set; see
        ``mcp_gateway`` for the nested-shape walk.
      • ``send_telegram_message`` and ``send_discord_dm`` apply the
        same People-roster check pre-send.
      • Contacts (``people.kind``, private to the principal): a contact's
        address or chat id is reachable only when
        ``people_tools.contacts_reachable_now()`` —
        a turn the principal started on a verified surface (web chat,
        their own Slack / Discord, a verified private Telegram chat),
        or inside ``grant_contact_egress()`` (the decisions approve
        route when the approver resolves to the principal). An inbound
        email (even from the principal's address), a teammate's turn and
        unattended runs (scheduler, workflows — a kicked resume binds no
        session — alert review) reach the team only, and a contact is
        refused exactly like a stranger, so nothing reveals one exists.
        A turn about the principal's private mail
        (``Session.private_to_principal``) reaches the principal only.
        Applies to the Gmail / Calendar / Drive gates, calendar attendee
        resolution, ``message_person`` (which never falls back to a
        "Needs you" alert for a contact) and the raw DM tools with their
        person-id recovery.
      • ``send_slack_dm`` does not have a roster check today — a
        pre-existing gap not addressed by the email-inbound change.

    The old env-var allowlists (EMAIL_ALLOWED_SENDERS /
    TELEGRAM_ALLOWED_CHAT_IDS / DISCORD_ALLOWED_USER_IDS) have been
    removed; access is managed entirely via the /people UI.
  mcp_tool_timeout: |
    Every call through MCPGateway to the extensible-mcp child (call_tool,
    search_tools, load_mcp_server and the M365 gate lookups in
    _fetch_m365_json) goes through mcp_gateway._session_call, which bounds
    it with MCP_TOOL_TIMEOUT_S (120 s) and raises GatewayCallTimeout (a
    TimeoutError) past it. MCPGateway.call_tool turns that into an error
    payload ({"error": "... did not answer within N s. It may still have
    run ...", "timed_out": true}) and skips everything after the call: no
    outbound linkage, artifact row or grant-health reading for a call that
    may not have happened. Gate lookups read a timeout as a failed lookup
    (None), which the gates refuse on. Why: a hung workspace server held
    whatever awaited it for good: the serial email poller, a brief, a chat
    turn until its whole-turn deadline. The server is not told to cancel,
    so a send that timed out may still go: the roster acknowledgement
    (roster_intake.send_email_ack) raises AckUncertain on a timed_out
    payload and keeps its claim (roster_ack_uncertain row) so no second
    acknowledgement follows, and a turn cut off with MCP calls in flight
    writes a CANCELLED tool_invocation row for each (Executive agent loop).
  chat_stream_keepalive: |
    The /chat SSE body sends ": keepalive\n\n" (an SSE comment, skipped by
    every reader; the UI reads only data: lines) when CHAT_STREAM_KEEPALIVE_S
    (15 s, 0 = off) passes with the Executive's step still running.
    _next_stream_step waits min(remaining, keepalive) and returns idle with
    the step still in flight (pending); the loop yields the comment and
    passes pending back, so nothing restarts. Every other exit cancels the
    step, and the loop's finally cancels a pending one before the stream's
    aclose. The whole-turn deadline is unchanged. Why: browsers and proxies
    drop an idle stream well inside CHAT_STREAM_TIMEOUT_S.
  mail_sources: |
    Mail read from anywhere but the Executive's own mailbox goes through
    openexecutive.integrations.mail_sources, a vendor-neutral hook with
    nothing registered by default and no settings of its own. A deployment
    registers a MailSource (name, run loop, enabled check, replay of a held
    message) before the app starts; the lifespan starts every enabled one
    (start_mail_sources) and cancels it on shutdown. The source hands each
    message to handle_inbound as an InboundMail: the parsed message, the
    address it came to, a prove_sender check (DMARC, or SPF and DKIM
    aligned, as the source can tell), send_answer (how the turn's answer is
    mailed), an optional attachment reader, the payload a held message
    keeps, and a session id. handle_inbound runs the email poller's own
    rules (email_poller._handle_mail, shared with the mailbox): skip self
    and automated senders, hide roster / fact tokens, resolve the sender
    (team, contact, stranger), private-to-principal rows, the teammate's
    own rows only when proven, the untrusted-content wrapping, the
    principal's own proven mail, the forwarded-by-principal framing,
    co-present recipients, reply hydration and the turn deadline.
    What differs from the mailbox, because a source mails the answer
    itself rather than the model calling a send tool: a stranger is held
    for the principal silently (no acknowledgement, no turn) and comes back
    through the "email" replayer (mail_sources.replay_held_mail dispatches
    on the payload's mail_source key; the mailbox's held mail carries none
    and goes to email_poller.replay_held_email); a contact's mail, and mail
    claiming a teammate that nothing proves (private to the principal), is
    answered to the principal, never the sender; the answer carries the AI
    line (disclosure.with_mail_line) and an integration_outbound /
    integration_outbound_blocked row. Roster-request and fact
    confirmations are answered only from the mailbox they were sent from.
    Source names "google" and "microsoft" are reserved for the mailbox, and
    handle_inbound refuses a source that isn't registered (its held mail
    could never go back to it). While the Executive is paused
    (scheduler.pause) handle_inbound does nothing and returns PAUSED, so
    the source keeps the message. A stranger the roster queue won't take
    (declined lately, the daily cap) is logged "not held", never as held;
    a sender who is neither team nor contact by the time the turn runs gets
    no answer at all. A source's attachment text is scrubbed of roster /
    fact tokens, and its message ids never open anything in the mailbox
    (no allow_mail_ids).
  email_poller: |
    MCP poll loop in openexecutive.integrations.email_poller — runs
    as an asyncio task in the FastAPI lifespan, started by
    api.main._start_mcp_gateway once the gateway is up. It talks to the
    Executive's mailbox through the configured mail backend
    (integrations.workspace, EMAIL_PROVIDER: ``google`` = Gmail via
    workspace-mcp, ``microsoft`` = Outlook via ms-365-mcp-server — see
    ``workspace_providers`` below): provider.list_unread → provider.fetch
    → render_for_executive → Executive.chat → provider.mark_read. The
    backend never surfaces a Reply-To-style redirect header (Google strips
    them from the raw text; the Microsoft rendering has none), defending
    against redirect attacks; the poller filters auto-replies
    (mailer-daemon, noreply senders) and self-sent messages. Every backend
    renders the same Subject/From/To/Cc + ``--- BODY ---`` text the persona
    expects, followed by a ``--- REPLY ---`` block naming the exact reply
    tool and threading ids for THIS message (Gmail: send_gmail_message +
    thread_id; Outlook: reply-mail-message + messageId). That block rides
    in the user turn, which is what lets the cached persona say "use the
    reply tool in the REPLY block" instead of naming a vendor tool.
    Fail-soft: EMAIL_PROVIDER naming a server absent from mcp_servers.json
    logs one ERROR per cycle and skips, never crashes the loop. While the
    Executive is paused (scheduler.pause) each poll is skipped and the
    inbox left unread, so held mail is processed after resume. INBOUND
    is NOT roster-gated — see ``channel_access`` for the split. When
    the sender isn't on the People roster the poller prepends a
    [POLICY] notice to the message body the Executive sees, so the
    model picks a non-reply path (classify, log, alert, propose-add-
    to-roster) instead of wasting a turn discovering the outbound
    block. The outbound gate at ``mcp_gateway._check_gmail_recipients`` /
    ``_check_m365_recipients`` is the actual security boundary against
    auto-replying to spam.
    Deadlines: the loop is serial (one message at a time), so the
    Executive turn on each email runs under asyncio.timeout
    (EMAIL_TURN_TIMEOUT_S, 300 s). Past it the turn is cancelled
    (EmailTurnTimeout; a TimeoutError raised inside the turn is not
    mistaken for it), an integration_inbound row with outcome turn_timeout
    is written (private when the mail is), and the message is marked read
    and not run again, since the turn may already have replied. A message
    whose handling raises is retried on the next polls up to _MAX_ATTEMPTS
    (3) per run, then given up and marked read. Every gateway call it makes
    is bounded by MCP_TOOL_TIMEOUT_S (see mcp_tool_timeout).
    Mail from one of the principal's CONTACTS gets a contact [POLICY]
    notice instead (`_contact_notice`): it names them (name, role /
    company), says not to reply unless the principal asks, and asks for
    a summary for the principal and to tell nobody else; the turn stays
    unattributed (person_id None) and the gateway refuses mail to a
    contact on a poller turn anyway. This turn and the principal-forward
    turn below set `Session.private_to_principal`: they reach the
    principal only, raise private alerts, are not offered
    `schedule_tools.PRIVATE_TURN_WITHHELD_TOOLS` or any MCP tool outside
    `schedule_tools.PRIVATE_TURN_MCP_TOOLS`, and write only audit rows
    private to the principal — the poller's two inbound rows included
    (`_private_to_principal_mail`, the same rule), and every row written
    while the mail is handled, before the turn binds its session too
    (the `openexecutive.audit.private_rows` scope; see the audit.private_rows
    note). Each message is handled
    with no session bound (`schedule_tools.set_session(None)`), because
    `Executive.stream_chat` binds its session without unbinding it and the
    poller is one long-lived task: otherwise one message's private turn
    would still be current, and would mark, the next message's rows
    (see `people.kind`). Mail FORWARDED BY THE PRINCIPAL (the sender
    resolves to the principal and `_new_text_lines` reports a forward)
    is framed as `<forwarded_by_principal>`: summarise it, draft a reply
    the principal could send (text in the reply, never sent, never a
    Gmail draft), note any commitment or date, and offer to add the
    original sender as a contact (confirmed from the web app or the
    principal's Slack / Discord — an ordinary email turn cannot change the
    People list). The reply goes to the principal only;
    the From header is unauthenticated, so the framing grants nothing.

    Roster requests (see ``people.roster_requests``). Sender matching uses
    ``people.identity.resolve_email_sender`` everywhere the poller used
    ``find_person_by_email`` (aliases and the company-domain rule). Before
    any triage, ``roster_intake.try_email_roster_answer`` checks the mail
    for a roster-request token (``RR-…``): from the principal's PRIMARY
    address exactly (not an alias), carrying a pending request's token, not
    an automatic reply and not failing DMARC, it is the principal's answer — parsed with
    ``parse_decision(..., "roster_identity")``, applied, answered by a
    short email to the principal, marked read; no model turn. Anything else
    falls through (a refused token is audited privately). For NON-ROSTER
    mail that is not private to the principal (so never a contact's) and
    does not ``looks_automated`` (no-reply / notifications / billing-style
    local part, List-Id / List-Unsubscribe / Feedback-ID / X-Campaign,
    Auto-Submitted other than no, bulk/list/junk Precedence, DMARC fail),
    ``_hold_for_roster`` holds it (payload = message and thread id only;
    preview = subject + new text) and, only when Gmail authenticated the
    sender (``fact_confirmation.sender_authenticated``: a raw read showing
    Gmail's dmarc=pass for the From domain), sends the fixed
    acknowledgement via ``send_email_ack`` under the gateway's one-shot
    grant; an unauthenticated sender is held with no acknowledgement. The mail is
    STILL triaged on this pass, with a variant [POLICY] notice
    (``held_for_roster``) that opens with the same sentence as the
    non-roster one and adds: the sender was already told it is waiting,
    the principal was asked (a Today card), do not raise another alert or
    proposal just to add them, and the email comes back once they are
    added. ``replay_held_email`` (registered as the email replayer)
    re-fetches the message from Gmail after approval and handles it as
    new mail from a now-known sender.

    On an Outlook mailbox (EMAIL_PROVIDER=microsoft) the same flow runs on
    the provider's rendered text (`workspace.mail.render_message`, the
    Gmail layout), with three differences: no sender is ever
    authenticated (`fact_confirmation.read_raw` reads nothing for a
    non-Google backend, so `sender_authenticated` is False — no roster
    acknowledgement, no emailed fact confirmation, the principal's mail
    is never `email_authenticated`); attachments stay a list (the
    download is Gmail's); and the code's own emails to the principal
    (roster-request prompt and reply, fact confirmation, scheduled
    deliveries) go through `workspace.registry.send_from_executive`, the
    configured backend's send tool. The `--- REPLY ---` block naming the
    reply tool is appended after the untrusted-content block, never
    inside it.
    Peer memory records ``_email_memory_text(raw)`` as the sender's
    words, not the prompt (the poller's own trailing ``--- REPLY ---``
    block is dropped first — it is the LAST such line, a forged copy in
    the body having been quoted by workspace.mail._neutralize_markers):
    the subject, the body cut at the first quoted
    or forwarded message (Gmail's possibly-wrapped "On … wrote:",
    "-----Original Message-----", an Outlook From:/Sent: block, "--
    Forwarded message --", ">" lines) and the ``--- ATTACHMENTS ---``
    filenames — see ``honcho.sync_turn``. Only computed for a rostered
    sender (an unrostered one has no peer). The email text is sender-
    controlled, so attachment lines are split from the right and length-
    capped rather than matched with one regex: a pattern with adjacent
    ``\s+`` / ``.+?`` groups backtracked cubically on a long run of spaces
    (30 s at 4,000), stalling the whole API process from one inbound email.
    Like every other channel adapter, the poller calls
    ``Executive.chat`` on the standard path — it does NOT force
    ``committee_review=True``. Committee review is a per-request
    opt-in on ``/chat`` only; it was previously forced on for every
    inbound email (at least 5 model calls per message, ``medium`` Honcho
    prefetch) and removed because the revision pass never reaches
    Gmail anyway (outbound mail is sent from the draft's tool loop).
  workspace_providers: |
    openexecutive.integrations.workspace — the mailbox and calendar the
    Executive ITSELF runs on, behind two Protocols (MailProvider,
    CalendarProvider) with one module per backend (google.py, microsoft.py)
    and a registry keyed on settings (EMAIL_PROVIDER / CALENDAR_PROVIDER,
    Literal["google","microsoft"], default google, separate switches because
    Outlook mail + Google Calendar is legitimate). Layout mirrors
    openexecutive.providers. Why it exists: the Executive can DISCOVER any
    mail/calendar tool the gateway exposes, but three paths call a fixed
    backend with no model in the loop and used to spell Gmail tool names
    inline — the email poller (list/fetch/mark-read), alert email dispatch +
    the scheduler's email send-tool hint (alerts.dispatcher.dispatch_email,
    scheduler.runner), and the typed booking tools + the approval-time
    conflict check (orchestrator.calendar_tools._do_create_event /
    _do_delete_event, api.routes.decisions). Those now delegate; nothing else
    changed. The google backend is the old inline code moved verbatim (tests
    pin the argument dicts byte-for-byte). The microsoft backend: inbox
    polling via list-mail-folder-messages (mailFolderId=inbox, filter
    "isRead eq false" — never the all-folders /me/messages, which includes
    Junk/Deleted), get-mail-message with HTML→text (workspace/_html, a real
    HTMLParser) plus one list-mail-attachments call when hasAttachments, so
    the ATTACHMENTS section carries the same `N. name (mime, size KB)` lines
    workspace-mcp prints for Gmail (inline parts skipped; the sender-
    controlled name and MIME type are whitespace-collapsed / restricted to
    media-type characters and length-capped so they cannot forge or break a
    line; names go to peer memory via email_poller._attachment_name; on a
    failed listing only the download-bytes hint remains), mark read via
    update-mail-message
    {isRead:true}, send via
    send-mail's nested Graph shape (body.Message.toRecipients[].emailAddress),
    events via create-calendar-event with isOnlineMeeting +
    onlineMeetingProvider=teamsForBusiness and the Teams join link read from
    onlineMeeting.joinUrl (one re-read of the event if Graph returns before
    the meeting is attached), delete-calendar-event to cancel, and the
    advisory conflict check via get-calendar-view on the Executive's OWN
    calendar (delegated permissions cannot read attendees' free/busy — narrower
    than Google's query_freebusy, documented as such). The typed tools' video
    flag was renamed add_google_meet → add_video_link (Meet or Teams per
    CALENDAR_PROVIDER); calendar.wants_video_link still honours the old key
    for decision-ledger payloads written before the rename. INVARIANT: a
    provider never raises on a malformed backend response — [] / None /
    {"error": …} — so one bad poll cycle or booking never kills a loop.
    INVARIANT: the persona and the cached calendar tool definitions stay
    backend-neutral static text; the per-provider detail (which tool, which
    ids) rides in the user turn (REPLY block, scheduler hint). Startup logs
    both choices (registry.log_provider_status) and WARNS when a chosen
    backend's server is not in mcp_servers.json — fail-soft, never a boot
    failure, matching the calendar_booking_enabled precedent.
  slack: |
    openexecutive.integrations.slack_bot — async Bolt socket-mode
    adapter (``AsyncApp`` + ``AsyncSocketModeHandler``) embedded in the
    FastAPI lifespan (no separate process), started when both
    ``SLACK_BOT_TOKEN`` and ``SLACK_APP_TOKEN`` are set. The lifespan
    runs ``connect_async()`` as a background task and ``close_async()``
    on shutdown — ``connect_async()`` retries internally and never
    returns on a bad app token, so awaiting it would hang boot, and
    ``start_async()`` (sleep-forever) must never be used there.
    Handlers await on the application event loop, which is what keeps
    the uvicorn-bound MCP gateway, the shared AsyncAnthropic client and
    the SSE queues off a foreign loop. EVENTS OVER HTTP: with
    ``SLACK_SIGNING_SECRET`` set and no ``SLACK_APP_TOKEN`` (Socket Mode
    wins when both are set), the same Bolt app is built with the signing
    secret and an ``AsyncSlackRequestHandler``, and Slack posts events to
    ``POST /webhook/slack`` (integrations.slack_events, mounted at import so
    main.py never imports slack_bolt; it answers 503 until the lifespan
    sets the handler). The route itself checks the v0 signature (constant
    time, timestamp within 300 s, ASCII digits only, body capped at 1 MB)
    BEFORE handing the request to Bolt, because Bolt logs the whole body of
    a request that fails its own check (at INFO, which the process runs at)
    and raises on an unparseable body or timestamp: unsigned traffic would
    otherwise write anything into the log. A signed body Bolt can't parse is
    400. A signed request is then taken once: the route remembers the exact
    x-slack-signature of each request it hands to Bolt (an identical replay
    of any signed body inside the window carries the same one) and the
    event_id of an event_callback body (unchanged across Slack's re-signed
    retries), in a per-process in-memory set (TTL 660 s, twice the signature
    window plus slop; at most 10,000 keys, oldest dropped first), and answers
    a repeat 200 with an empty body without reaching Bolt, so Slack stops
    retrying. Keys are recorded before Bolt runs (concurrent copies are
    caught) and forgotten if Bolt raises or answers 5xx. Per process means
    one machine; a restart forgets the set.
    Bolt then verifies again, answers url_verification, and acks at once while
    the listener runs (Slack resends an event not acked within 3 s). The
    route is in _UNAUTHENTICATED_PATHS and passes the local-login Host
    gate as a self-verifying webhook. In BOTH modes a global middleware
    drops an event_callback whose event_id was already taken (bounded
    in-memory set) or that was delivered for another workspace than the
    bot token's (team_id / authorizations vs authorize_result.team_id).
    Responds to (a) ``@mention``
    events, (b) DMs, and
    (c) thread continuations: any non-mention message in a thread the
    bot has previously replied in is treated as a continuation and run
    through the shared ``response_gate`` (see `response_gate:` below).
    The bot's own user_id is resolved via ``auth_test()`` so it can
    detect its own past replies and avoid double-firing with
    ``app_mention``: at startup, and — if that failed — again from the
    channel ``message`` listener at most once a minute
    (``_resolve_bot_user_id``; a failure at boot used to disable thread
    continuations until a restart, #315). Setup status shows a listening
    Slack amber while it is unresolved (``bot_user_id()``). The thread is
    read with ``conversations_replies`` under a 5 s ``wait_for``; when
    that fails on a continuation, the thread's stored history
    (``slack:thread:{channel}:{thread_ts}``) decides whether the bot is
    in it — with history, a rostered sender gets an ephemeral "couldn't
    read this thread, @-mention me" and the drop is audited
    ``outcome=dropped_thread_unreadable``; without, it stays silent. Roster-gated per
    `channel_access`. An unknown sender's DM or @mention (not a thread
    continuation) goes to ``_hold_unknown_sender``: a contact gets nothing;
    otherwise name and profile email come from ``users_info`` (5 s
    timeout), the event is held with a fixed key set (``_HELD_EVENT_KEYS``:
    type, text, user, channel, channel_type, ts, thread_ts, files,
    subtype) as a roster request, and the fixed acknowledgement goes in
    the DM or as ``chat_postEphemeral`` for a mention (a channel reply
    would tell everyone there who is not on the roster). The registered
    replayer re-runs ``_handle_message`` on the held event under the
    handler semaphore once the sender is on the roster.

    Session model (added with #136; Slack had none before it). The
    conversation key is ``_slack_session_id``: ``slack:dm:{user}`` for a
    DM, ``slack:thread:{channel}:{thread_ts}`` for a reply inside a
    thread, ``slack:channel:{channel}:{user}`` for a mention that starts
    one. The old scheme was ``slack:{channel}:{thread_ts or ts}``, which
    in a DM minted a NEW id per message — so a multi-turn confirmation
    could not work even once history was stored. Stored turns are
    replayed via ``session_store.load_messages`` and persisted after the
    reply lands (persist failures are logged, never surfaced); a mention
    that roots a thread double-writes into that thread's session so its
    first continuation is not cold. ``format_for_prompt`` is
    session-scoped. A per-session ``asyncio.Lock`` serializes turns in one
    conversation — ``_MAX_CONCURRENT_HANDLERS`` caps workspace-wide
    fan-out and does nothing about interleaving. The same id is the audit
    grouping key.

    Per-turn context. Every turn carries the ``<channel>`` block from
    ``integrations.channel_context`` (user turn, never a cached system
    block) naming the surface and where each kind of approval is
    completed. The principal's DMs additionally carry the open-alert
    digest as ``<briefing>`` — gated to ``mode == "dm"`` and
    ``is_principal`` because the board is company-wide. That digest and
    the briefing page's ``[Discuss mode — alert_id=N]`` primer are the
    ONLY trusted sources of an ``alert_id`` for ``ack_alert``; ids
    appearing in an alert's own body are attacker-controlled, since
    alerts are minted from inbound mail and chat. Two mechanisms enforce
    that, not one prompt rule: ``briefing.context`` collapses EVERY
    interpolated field to a single line (a newline in a headline,
    suggested action, tag or review note would otherwise forge a whole
    extra ``[N]`` line — a fabricated instruction to clear somebody
    else's alert), and the ids the block named are recorded on
    ``Session.trusted_alert_ids`` so ``handle_ack_alert`` refuses any
    other id when ``origin_channel`` is set. Web sessions are exempt —
    the Discuss handoff acks over HTTP first, so its alert is no longer
    unread and would not be in a digest.

    Approval cards with buttons. A private Telegram chat on a webhook only
    Telegram can call (``integrations.channel_cards.shows_cards``) gets the
    cards a reply leaves (a meeting to book, a ``propose_actions`` card, a
    workflow change card: ``decisions.CHAT_APP_ACTIONS`` of the app_action
    cards, whose action checks the tapper itself)
    as messages with Approve and Skip buttons, and its ``<channel>`` block
    says so (``cards_here``). A tap is taken only when ``from.id`` is the
    private chat's id on the verified webhook, and
    ``decisions.resolve_in_chat`` applies the web chat's who-may-decide
    rule, with ``delegation.verified.ChatTap`` standing in for the
    signed-in caller. A Slack DM (with SLACK_CARD_BUTTONS on, which needs
    Interactivity in the Slack app and the im:write scope) and a Discord DM do the same: Slack
    sends Block Kit buttons (action ids oe_card_approve / oe_card_skip, the
    callback data as the value; text as plain_text), and a tap counts only
    when conversations.open for the tapper returns that very channel; a
    Discord View's buttons carry the callback data as custom_id and
    on_interaction takes a tap only in a DMChannel whose recipient is the
    tapper. Either way the tapper must be on the roster by their app id.
    Every other chat app (channels, threads, Google Chat) sends no card,
    and ``propose_actions`` tells the model the card is on Today.

    Errors. The catch-all logs with session/user/channel/thread/mode,
    writes an ``integration_inbound`` row with
    ``details.outcome="handler_error"`` under the inbound's session_id,
    and guards the apology send itself (an unguarded one escaped into
    Bolt). No interactivity endpoint and no Block Kit exist — Slack
    messages are text only, so no approval button can be offered there.
  discord: |
    openexecutive.integrations.discord_bot — discord.py gateway client
    embedded in the FastAPI lifespan (no separate process). Features:
    per-thread auto-titling after the first bot reply; session-scoped
    episodic context so threads have their own memory; author attribution
    so the Executive sees who in the thread said what. Auto-continues
    in bot-owned threads (without re-tag), with continuations gated by
    the shared ``response_gate`` (see `response_gate:` below).
    Roster-gated per `channel_access`. An unknown sender writing to the bot
    directly (a DM or a mention — not a thread it merely follows) goes to
    ``_hold_unknown_sender``: a contact gets nothing; otherwise the text
    and routing fields are held as a roster request and the fixed
    acknowledgement is sent in the DM, or by DM for a channel mention.
    ``/ask`` from an unknown user answers the interaction first with an
    EPHEMERAL ``ACK_TEXT`` (Discord's 3-second window) — replacing the old
    "ask the admin to add you" — then holds the prompt with no second
    acknowledgement. ``_replay_held`` re-runs ``_handle_message`` (DM, or
    the original channel) once the sender is on the roster.

    @mention routing: in DMs and inside existing threads, the bot
    replies in-place. In a plain text channel, the
    ``CLASSIFY_MENTION_CHANNEL`` path uses a lazy response router that
    decides AFTER the reply is generated whether to keep it inline
    (via ``message.reply``) or promote it to a brand-new bot-owned
    thread. The default mode is ``thread_unless_greeting``: promote
    every plain-channel @mention into a fresh thread EXCEPT when the
    user's incoming message is a bare casual hello ("hi", "good
    morning", "hey rufus"). Greeting detection is a curated frozenset
    match in ``_is_simple_greeting`` — deterministic, no LLM call,
    Unicode-aware so trailing emoji / ellipsis / emoticons don't block
    a match. Override via ``DISCORD_MENTION_REPLY_MODE``:
    ``always_thread`` (every @mention opens a thread — legacy);
    ``always_inline`` (never promote); ``auto`` (legacy length-only
    heuristic — promote when
    ``len(response) >= DISCORD_MENTION_THREAD_THRESHOLD_CHARS``,
    default 1500). On promotion the channel still sees a one-line
    ``↪ Replying in a thread`` pointer so users not following the
    thread know where the answer went. The four-way mode switch lives
    in ``_resolve_thread_promotion`` so it can be unit-tested without
    instantiating a Bot.

    Session model: plain-channel @mentions use a rolling per-(channel,
    user) session keyed ``discord:channel:{channel_id}:{user_id}`` so
    the bot remembers prior in-channel @mentions from the same person,
    analogous to how DMs roll per user. When the router promotes a
    reply to a new thread, the turn is **double-written** — once into
    the rolling channel session (so future channel @mentions remember
    it) and once into the new thread session
    ``discord:thread:{new_thread_id}`` (so future thread continuations
    have the original Q+A in context). The double-write is the
    deliberate trade-off that makes "ask in channel, follow up in
    thread, ask in channel again" feel coherent without any cross-
    session lookup table.
  response_gate: |
    openexecutive.integrations.response_gate — the shared
    "should the bot reply?" gate used by Slack and Discord for thread
    continuations only. DMs and explicit @mentions bypass the gate
    entirely. Calls the utility-fast model (Haiku, see `caching:`) with
    a rubric biased hard toward YES: reply NO only when the message is
    unambiguously addressed to a specific other named human, or carries
    no substantive content (bare acknowledgement, pure emoji). Returns
    ``GateDecision(allow, reason, raw)``; on NO the channel handler
    emits an ``integration_inbound`` audit row with
    ``details.outcome="skipped_gate"`` and ``details.skip_reason=...``
    so silent skips are investigable from /audit. Slack also adds an
    ``eyes`` reaction to the skipped message (``_react_skipped``,
    best-effort: needs the ``reactions:write`` scope), so a sender the
    gate misjudged can see it was read and @-mention the bot. Fail-open on any
    exception or timeout — a flaky Haiku call must never silence the
    bot. Single-human threads (only one distinct human across history
    plus current speaker) bypass the gate at the call site, since every
    message in a 1:1 is implicitly addressed to the bot. Discord-side
    can be disabled with ``DISCORD_THREAD_RESPONSE_GATE_ENABLED=false``;
    Slack has no equivalent kill-switch yet (the gate only fires once
    the bot has engaged in a thread, so accidental over-firing has a
    naturally small blast radius).
  telegram: |
    Webhook gating + per-chat conversation history. Roster-gated per
    `channel_access`. An unknown chat is held as a roster request only when
    the chat is PRIVATE and TELEGRAM_WEBHOOK_SECRET is set and valid
    (Telegram identifies the chat, not the sender, and an unverified
    webhook accepts anyone's forged update); a group or an unverified
    webhook stays silent. Contacts get nothing. The hold runs as a
    background task (the webhook stays fast): text with bot commands
    stripped (``_message_content``) plus attachment file ids, downloaded
    only on replay; the fixed acknowledgement is sent to that chat.
    ``_replay_held`` re-runs ``_process_and_reply`` once the chat is on the
    roster.
  google_chat: Webhook + service-account auth.
  setup_status: |
    GET /setup/status (api/routes/setup_status.py; checks in
    api/setup_checks.py) backs the UI's Settings → Setup status page:
    one light per part of the install, state ok | warn | error | off,
    with a plain-language summary and fix, an optional in-app link
    (/people, /onboard) and last_activity (latest integration_inbound
    audit ts for the channel's actor). Order = setup_checks.LABELS. The
    UI adds its own sign-in light (lib/setupStatus.ts signInCheck, from
    the UI's env) and sorts worst-first.
    LABELS is the whole row list and run_checks emits one row per key, so
    there is NO hide-when-fine mechanism: a condition that should show
    nothing when healthy cannot have its own row, it has to ride an
    existing one. That is why the pinned-Google-tools drift signal folds
    into check_gmail as a warn branch (see mcp.prime_pinned_tools) rather
    than adding a google_tools row, which would sit there as ok | off
    forever. A stand-in gateway in a test has no pinned_tools attribute
    at all, which is NOT the same as a real gateway whose probe has not
    finished (None) - check_gmail keys on a sentinel so the first case
    reads exactly as it did before the drift branch existed.
    Probes — at most one free read-only call per service, each bounded
    by PROBE_TIMEOUT_S (5 s), via one shared httpx client per run:
    Anthropic models.list(limit=1) through configured_async_client
    (max_retries=0; so a missing ANTHROPIC_WORKSPACE_ID on an org key
    surfaces as a 400/403); Slack POST auth.test (Bearer bot token);
    Telegram getMe then getWebhookInfo (empty url, a url whose path isn't
    …/webhook/telegram, or a last_error_date within 24 h = amber);
    Discord GET /users/@me only while the bot is not ready and its task
    hasn't died. Liveness from app.state, which the lifespan sets:
    slack_handler (client.is_connected()), discord_bot (is_ready() AND
    ws.open — discord.py keeps _ready set through a dropped connection
    while it reconnects; only close() clears it) + discord_bot_task (a
    finished task is red; LoginFailure / PrivilegedIntentsRequired map to
    their own fixes), mcp_gateway.
    Roster: a connected Slack/Discord/Telegram is amber while no
    non-archived Person has its id field, or when the latest inbound row
    is a "Rejected: …" from the last 24 h whose sender id (extracted from
    the summary) is still not on the roster — so the light clears as soon
    as the fix is made, and one stranger can't leave it amber for good.
    Message text from inbound summaries is never echoed. Local login without
    TELEGRAM_WEBHOOK_SECRET is red (the local-login gate refuses the
    webhook). Google Chat: numeric project number, one of the SA
    settings, and a readable SA key file (≤64 KiB JSON with
    client_email). Gmail: google_workspace in configured_server_names,
    gateway up, and the workspace-mcp credentials present in this
    process's env (GOOGLE_OAUTH_CLIENT_ID + _SECRET, or a
    GOOGLE_SERVICE_ACCOUNT_KEY_* with GWORKSPACE_AUTH_MODE=
    service_account) — that env is what the gateway forwards.
    Your own Gmail (your_gmail, Act as me): off with no owner email; else
    delegation.gmail.gmail_status under asyncio.wait_for(PROBE_TIMEOUT_S)
    — a token refresh and GET users/me/profile, only once the owner's
    credential file exists. connected is ok; no credential is off, or
    amber while Act as me is on; shared_mailbox is off while it is off; any
    other status is amber, or red while it is on; a timeout is amber.
    Secrets: no token in a response or log line — probes report a status
    code, a Slack error code matching [a-z_]{1,40}, or an exception class
    name; _fetch never logs a URL (Telegram's carries the token), and the
    Telegram token must match \d+:[A-Za-z0-9_-]{30,} before it is put in
    one. Daily brief (check_brief, id "brief", after the scheduler): off
    with the scheduler; amber with no owner (link /people) or nowhere to
    send it (runner.delivery_order empty — link /people/<owner id>); red
    when the latest brief's send failed or it couldn't be written
    (brief_state.current_problem); amber when the last brief got through
    on a later channel than the first one tried (that channel is broken:
    names it and points at its light); amber when nobody chose a time
    zone (no workspace zone and USER_TIMEZONE unset or UTC), saying the
    briefs run on UTC (link /settings); else ok, naming the first channel
    and each brief's next time in the user's zone. gather_snapshot reads
    the outcome, runner.email_ready(), runner.next_brief_runs() and the
    zone, so the check itself does no I/O.
    Sample values from .env.example (setup_checks.EXAMPLE_VALUES,
    RFC 2606 example domains for emails) are named as samples and never
    sent; test_setup_checks.py fails if .env.example ships a sample the
    set doesn't know, and scripts/setupStatus.test.mjs keeps the UI's
    example-domain set equal to the API's.
    Each check runs guarded: one that raises becomes a red "couldn't
    run" light (class name logged), not a 500. Runs are shared: a
    request within _REUSE_FOR_S (5 s) of the last run gets its answer,
    and concurrent requests await one shielded task — so "Check again"
    can't become a stream of calls to those services. Both live on
    app.state (setup_status_runs), not module globals, and a task from
    another event loop is never awaited. Same auth as
    every route (shared secret; local-login host gate).
    Comment-as-value: python-dotenv reads `KEY=   # note` as "# note"
    (it strips only a comment that follows a value). Settings maps such
    values to None for the Slack, Telegram, Discord and Google Chat
    credentials (config._unset_if_comment → _blank_or_comment), so a
    copied .env.example no longer switches Telegram and Google Chat on
    with their comments as tokens; the example's notes now sit on their
    own lines. TELEGRAM_WEBHOOK_SECRET is deliberately NOT covered: None
    would skip the webhook's header check. Instead a secret outside
    setWebhook's charset ([A-Za-z0-9_-]{1,256} — the only values Telegram
    can send back) is treated as proving nothing: the webhook answers 401
    to every update without comparing (a forger who guessed the junk text
    would otherwise match it, and a non-ASCII value would make
    hmac.compare_digest raise), people_tools and the local-login gate's
    _webhook_verifies_its_caller return False, and Setup status shows it
    red. One rule for all four: Settings.telegram_webhook_secret_valid.
  attachments: |
    openexecutive.integrations.attachments — cross-platform attachment
    handling for the web chat, Discord, and Telegram. Inbound images are
    extracted to Anthropic vision content blocks and forwarded to the
    Executive in the same turn as the text. Inbound documents
    (PDF/DOCX/XLSX/TXT/MD/CSV) have their text extracted and inlined into the
    user message AND are indexed into the ChromaDB
    ``inbound_attachments`` collection in a fire-and-forget background
    task. Per-file cap 20 MB; extracted text
    truncated to 40 000 chars. Web chat exposes this through
    ``POST /chat/upload`` (multipart) — capped at 5 files per turn.

    Indexed under ``source_name="attachment:<bare filename>"``, domain
    ``attachment``, metadata ``type=attachment``. The name is the chunk-id
    namespace and the retrieval citation, and an attachment's filename is
    chosen by whoever sent the message — unprefixed, an inbound
    ``strategy-2026.md`` would upsert over the curated company document of
    that name, so inbound content stays in its own namespace and its
    provenance is visible. (``Path(...).name`` strips directory components
    first.) The prefix does NOT separate senders from each other: ids are
    md5 of the prefixed name alone, so two senders' ``notes.md`` collide.
    Inert while nothing reads the collection, and the first thing to fix if
    that changes.

    Isolation is the COLLECTION. ``inbound_attachments`` is the one
    collection ``retriever.retrieve`` never queries at all, so an attachment
    cannot resurface as company knowledge in a later, unrelated turn. It is
    still inlined into the turn that carried it, which is where it is useful.
    The domain value is belt-and-braces behind that: ``attachment`` is in
    neither UPLOAD_DOMAINS nor DOMAIN_ALIASES, and deliberately not
    ``general``, which ``_with_general`` would fan out to every specialist.

    What this replaced, because the reasoning was wrong and should not come
    back: the rows lived in ``company_docs`` under domain ``company_docs``,
    on the premise that a domain outside the specialist set matched no
    filter. It matched every one — the mechanism is written up once under
    knowledge.general_catch_all. They came back under "From your company
    documents", top-ranked and indistinguishable from a curated upload.
    ``loader.migrate_attachments_out_of_company_docs`` moves the
    legacy rows across on boot (write-then-delete: the store holds the only
    copy). Wiped per company by ``store.delete_attachment_docs()`` on
    client-slot restore and fixture reset.

    Attachment processing is roster-gated on Discord (``_is_rostered`` in
    ``on_message``): it used to run before ``_handle_message``'s gate, so an
    unrostered sender's file was downloaded and indexed before their message
    was dropped. There is still no operator surface listing these rows —
    ``GET /documents`` is a filesystem listing and attachments are never
    written to docs/.

    Passing the staging tempfile path as the identity was the #113 bug on this
    path too: duplicate chunks on every re-send, and no filename any API call
    could delete.
  broadcast_tools: |
    openexecutive.orchestrator.broadcast_tools — two new tools exposed
    to the Executive alongside the existing per-Person DM tools:

      • send_department_message(department_slug, integration, text)
        — posts to a department's configured team room (Slack channel id,
        Discord channel id, or Telegram chat id), set via the
        Department.slack_channel_id / discord_channel_id /
        telegram_chat_id fields. Returns a structured error containing
        "no <integration> channel configured" when the dept has no
        configured channel for that integration, so the model can read
        the error and fall back to DMing the department head.

      • send_company_broadcast(integration, text) — posts to the
        company-wide default room sourced from
        SLACK_DEFAULT_CHANNEL_ID / DISCORD_DEFAULT_CHANNEL_ID /
        TELEGRAM_DEFAULT_CHAT_ID env vars. Errors with "company
        default <integration> channel not configured" when the env
        is unset; the persona's "Choosing Who to Tell" rule
        instructs OE to fall back to /today-only when this happens.

    These differ from the per-Person DM tools (send_slack_dm /
    send_discord_dm / send_telegram_message) in that they target
    rooms / channels, not specific people — the People-roster gate
    that protects DMs does not apply. They are the structural
    expression of OE's outbound-targeting judgment: OE picks among
    DM / dept channel / company broadcast by which tool it calls,
    with the persona's `## Choosing Who to Tell` section telling it
    when each is appropriate.

    Deployment note (Discord): `send_channel_message` posts via the
    Discord REST API at channels/{id}/messages, which requires the
    bot to be a member of the guild containing the channel (or, for
    threads, of the parent channel's guild). Channels the bot can
    not access return a structured error to the model — they do not
    surface as silent no-ops.
  alert_pipeline_routing: |
    Sub-commit 3c extends the alert dispatcher with two new
    `AlertChannel` values (department_channel, company_broadcast)
    and threads the triage decision's `department_slug` /
    `broadcast_integration` through to the per-channel dispatchers.
    The triage prompt (`prompts/triage_prompt.py`) carries the same
    "Choosing Who to Tell" rule as the Executive persona — single
    LLM call per alert produces both the severity and the audience.

    Broadcast channels bypass the per-user `channels_enabled`
    preference filter in `preferences.resolve_channels` —
    `channels_enabled` governs PERSONAL delivery (DM me, email me),
    not org-level routing the triage agent already decided on.
    Severity threshold and quiet hours still apply. Quiet hours are read
    in the user's zone (memory.workspace_settings.get_user_timezone) when
    `user_preferences.quiet_hours_tz` is "UTC" or empty, and in the stored
    zone otherwise (an unloadable one also falls back to the user's zone).
    "UTC" is the model default and the column DEFAULT, so every existing
    row carries it, and nothing in the app writes the column — a stored
    "UTC" is the default, never a choice.

    Privacy invariant (board / comp / legal / valuation / layoffs /
    severance stays DM-only) is encoded BOTH in the triage prompt
    (primary enforcement) AND in `dispatcher._violates_privacy_invariant`
    (defence-in-depth backstop). A model misroute that picks
    `department_channel` or `company_broadcast` for a sensitive-tag
    alert is refused at dispatch time with a logged error — the
    alert still persists, but the broadcast doesn't happen.

    Broadcast bodies are plain text (no `*foo*` markdown): Slack
    renders that as bold, Discord as italic, Telegram MarkdownV2
    requires escaping. Cross-platform plain text is the safest cut.
  mcp_gateway: |
    openexecutive.orchestrator.mcp_gateway.MCPGateway — proxies remote MCP
    servers as tools available to the Executive (Gmail, Calendar, Drive, …).
    The MCP is configured via company/mcp_servers.json (workspace-mcp at
    --tool-tier complete to expose the full Google Workspace tool surface).
    docker/workspace-mcp-launch.sh also reads WORKSPACE_MCP_TOOLS (default
    all, or comma-separated service names passed as --tools).

    Telling the model what is connected (F004, F009): configured_server_names()
    used to feed only the setup checks and the boot log, while the identity
    addendum named Gmail and Drive unconditionally, and search_tools (an
    uncached proxy; prior turns replay as plain text) was how the model found
    tool names — so it rediscovered them on most turns and, on an empty result,
    said it could not see Gmail. Now MCPGateway.start() records server_names,
    and block 0 carries a Connected Systems section built from them
    (prompts/connected_systems.render_connected_systems) with the Google tool
    names pinned by service (GOOGLE_TOOL_MANIFEST, checked against
    workspace-mcp 2.1.0 — re-check on a bump). extensible-mcp's
    DiscoveredToolsFilter runs only tools one of the session's searches
    returned and keeps them for the session's life, so the lifespan runs
    MCPGateway.prime_pinned_tools() once in the background when
    google_workspace is configured. It probes the SAME narrowed set the
    prompt advertises (connected_systems.pinned_google_tools, filtered by
    WORKSPACE_MCP_TOOLS and WORKSPACE_MCP_TOOL_TIER), so a service that was
    never imported is never probed and never warned about. A name neither
    can account for is logged once naming both causes - excluded by those
    two variables, or renamed by workspace-mcp since the pin - because the
    old text named only the rename and sent operators to the manifest for
    what was usually a service-list setting (exact-name searches; misses
    kept on the gateway as PinnedToolsProbe, not only logged: GET /health
    reports them as google_tools_missing and Setup status turns the Email
    (Gmail) row amber naming a few and counting the rest. The probe is ONE
    frozen value assigned once, so no reader has to reconcile two attributes:
    missing=() means it ran and found everything, missing=None means the probe
    itself failed, and the attribute still being None means it has not
    finished. Only () reads green anywhere, so a probe that died can never
    look healthy. prime_pinned_tools catches BaseException, not Exception,
    because anyio wraps a session failure in BaseExceptionGroup, which is not
    an Exception - the same reasoning as the gateway's startup guard in
    api.main; CancelledError still propagates, since that is shutdown
    cancelling the task and the probe genuinely has no answer. Settings are
    read once for the whole run and passed into each probe, because
    get_settings() builds a fresh Settings every call and this read the
    environment once per missing tool),
    and call_tool retries a PINNED name once after discovering it when
    the reply is extensible-mcp's "has not been discovered via search_tools"
    refusal — after every gate has passed the same arguments. Unpinned tools
    still need the model's own search; nothing here widens what a call may do
    (gates and PRIVATE_TURN_MCP_TOOLS unchanged).

    workspace-mcp hosting: that google_workspace server runs CO-LOCATED inside the
    API as a stdio child of the gateway — NOT a separate service. This fits the
    single-tenant model (one install = one company = one exec Google account), so
    the server is inherently one-per-install; co-locating means a new install needs
    only the API+UI apps. workspace-mcp is baked into the API image in its own
    venv (docker/Dockerfile: `uv pip install workspace-mcp==2.1.0` at /opt/
    workspace-mcp — it has the --tool-tier flag and a fastmcp that works
    with modern pydantic) and launched by
    docker/workspace-mcp-launch.sh, referenced as the `command` of the
    google_workspace entry in /data/company/mcp_servers.json. The launcher selects
    the auth mode from GWORKSPACE_AUTH_MODE (an env var, no rebuild to switch):
    `oauth` = single-user, refresh token persisted at /data/google_credentials on
    the API volume — seed it by copying a locally-obtained token onto the volume
    (the API serves NO Google OAuth callback); `service_account` = domain-wide
    delegation via GOOGLE_SERVICE_ACCOUNT_KEY_JSON/_KEY_FILE + USER_GOOGLE_EMAIL,
    no browser callback. INVARIANT: the Google secrets must be added to
    _FORWARDED_ENV_VARS so extensible-mcp can interpolate the $VAR placeholders in
    the child's env block from its own environment. No separate service, deploy
    credential, or deploy job. See docs/deployment.md.

    Microsoft 365 hosting (the Outlook twin of the block above): the
    microsoft_365 server is @softeria/ms-365-mcp-server, a Node package,
    pinned (0.154.2) and installed in a throwaway `node:20-bookworm-slim`
    build stage with `--omit=optional` (skips keytar, the native OS-keychain
    binding); only the node binary and the installed package are copied into
    the python API image (docker/Dockerfile; libstdc++6 added for the node
    binary; a /usr/local/bin/ms-365-mcp-server wrapper is written there). A
    build-time smoke runs the launcher's exact flag combo
    (`--preset mail,calendar --list-permissions`) so a bump that breaks a flag
    fails the build, not production. Launched by docker/ms365-mcp-launch.sh
    as the `command` of the microsoft_365 entry. Auth is MSAL device-code
    against the operator's OWN Entra app (MS365_MCP_CLIENT_ID is REQUIRED;
    the server's built-in Softeria client id is refused): the refresh token
    persists at MS365_MCP_CREDENTIALS_DIR=/data/ms365_credentials (0700,
    file-backed store because MS365_MCP_USE_KEYTAR=0), seeded once with
    `ms365-mcp-launch.sh --login` from inside the container (the server has a
    native device-code CLI, so unlike Google there is no mint script and no
    file to copy). MS365_MCP_EXPECTED_USERNAME pins the bound account.
    INVARIANT (launcher): extensible-mcp leaves an UNSET `$VAR` placeholder
    as the literal string "$VAR" in the child's env, so the launcher scrubs
    any MS365_MCP_* value starting with "$" back to unset before its checks —
    otherwise MSAL would be handed "$MS365_MCP_TENANT_ID" as an authority.
    INVARIANT: the MS365_MCP_* vars are in _FORWARDED_ENV_VARS
    (test_mcp_gateway guards that every `$VAR` in the example config's env
    blocks is forwarded).
    Tool surface: the launcher starts the server with an EXPLICIT allow-list
    (`--enabled-tools`, an anchored regex of ~28 Outlook mail + calendar tool
    names, DEFAULT_ENABLED_TOOLS in the launcher), NOT the upstream
    `mail,calendar` preset. Security review showed the preset also registers
    recipient-carrying tools the gate never saw — forward-calendar-event,
    create-/update-specific-calendar-event, create-/update-mail-rule (a
    persistent forwardTo/redirectTo of all future inbound mail),
    update-mailbox-settings (external auto-reply), calendar permission sharing,
    whole-calendar delete, download-bytes-to-file (writes to the container
    filesystem) — and an upstream bump could add more. With the allow-list the
    scopes requested at --login are exactly Mail.ReadWrite, Mail.Send,
    Calendars.ReadWrite (+ User.Read/offline_access); MailboxSettings.* is no
    longer requested. INVARIANT: every tool the allow-list admits is either
    roster-gated in mcp_gateway (_GATED_M365_*, the by-id lookups, the
    download-bytes target pin) or carries no recipient (test_ms365_launcher
    pins the exact set). The gate ALSO covers the excluded writers (mail
    rules, mailbox settings, specific-calendar, forward-calendar-event,
    calendar permissions) so an operator who widens the list via
    MS365_MCP_ENABLED_TOOLS / MS365_MCP_PRESET still gets the roster check;
    the example config denies mail-rule / mailbox-settings /
    calendar-permission tools as a third layer. Tool names are HYPHENATED
    Graph endpoint aliases (`microsoft_365__send-mail`), proxied verbatim by
    extensible-mcp; the underscore deny globs in mcp_servers.json therefore do
    not match them, and the example config carries hyphenated patterns
    (`*delete-mail*`, `*__logout`, `*__remove-account`,
    `*download-bytes-to-file*`). Deliberately NOT denied: delete-calendar-event,
    the only cancel path (Google parity with manage_event action=delete). The
    gate is keyed to the literal server name `microsoft_365`;
    registry.log_provider_status warns at startup about a look-alike server
    under another name (which would expose the same tools ungated).
    OneDrive tools (opt-in, MS365_MCP_ONEDRIVE=true; off by default because
    the server requests every scope of its tool list on each silent token
    refresh, so adding file scopes to a sign-in that never consented to them
    breaks mail and calendar too until --login is rerun): the allow-list
    then also admits the Google Drive-equivalent
    OneDrive surface — list-drives, get-drive-root-item, list-folder-files,
    get-drive-item, search-onedrive-files, upload-file-content,
    create-onedrive-folder, move-rename-onedrive-item, copy-drive-item,
    share-drive-item, create-drive-item-share-link,
    list-drive-item-permissions. delete-onedrive-file,
    delete-drive-item-permission and get-download-url stay out. The launcher
    adds `--extra-scopes "Files.Read.All"` (the tool scopes alone are
    Files.ReadWrite, the account's own drive; Files.Read.All reads folders
    shared WITH the Executive). Files.ReadWrite.All is deliberately not
    requested. Gates: share-drive-item and
    create-drive-item-share-link (_M365_DRIVE_SHARE_TOOLS) pass
    _check_drive_share (every email on the roster, no public / domain scope
    or flag) and _check_m365_drive_share: no `anonymous` / `organization` /
    `owner` value, no grantee named by objectId / alias / siteUser /
    application / device (nothing the roster can check), and a link's scope
    must be exactly `users` (no scope = the tenant default, often
    anonymous); a share body must be an object (a JSON-string body would hide
    its grantee keys); an invite must set requireSignIn true (Graph defaults
    to false, an open link on many tenants) and roles only read / write; a
    link's type only view / edit (embed is public). Those four pinned
    fields (scope, roles, type, requireSignIn) count only at the body's top
    level (or as a top-level argument the server merges into it); the same
    key deeper, e.g. inside a recipient, is a decoy and refused. Writes
    (_M365_DRIVE_WRITE_TOOLS: upload-file-content, create-onedrive-folder,
    move-rename-onedrive-item, copy-drive-item) must target the Executive's
    own drives, read through list-drives (/me/drives) at call time,
    fail-closed: every top-level drive-id spelling and every body driveId
    (a copy's destination) must be one of them; a parentReference may hold
    only driveId and id (no path / siteId / shareId the gate cannot pin),
    and a copy must name its destination driveId, so a planted instruction
    cannot write company files into a stranger's shared folder.
    Google has the same rule (_check_google_file_write): any google_workspace
    write (a name starting with a write verb) that names a file
    (document_id, spreadsheet_id, presentation_id, form_id, file_id) or a
    destination folder (folder_id, parent_folder_id, add_parents) runs only
    when get_drive_file_permissions names the Executive's own address as the
    owner, or the item is the company's own (_company_item, read from the
    lookup's last "ID: <id>" line on, since the name before it is anyone's):
    owned by someone on a company domain (people.identity.company_domains
    plus the Executive's own domain unless free mail) with its permission
    list visible, or on a shared drive whose every organizer is the
    company's; and every user and domain it is shared with is the
    company's, never a group (it can hold anyone) or "anyone with the link".
    The lookup must keep Drive's own shape after the id line (Type, Parents,
    Owners, Size in that order, one Owners line, one permission list right
    after its count with exactly that many entries, or the private line),
    else the item is not the company's. "root" needs no lookup, a
    copy's or PDF export's source is only read, the sharing tools keep their
    own gate, and an unreadable owner, a shared-drive item organized from
    outside, or two Owners lines (a file name can hold a line break) is
    refused. A rename or move the person tapped on a drive_files card
    (tapped_drive_call, update_drive_file with file_id / name / add_parents
    / remove_parents only) checks only the folder it goes to; refusals tell
    the model to put such a change on that card.
    search-onedrive-files' q is substituted into the request path unencoded
    (/drives/{d}/search(q='{q}')), so a quote / slash / dot-dot would walk
    the GET to any Graph path (mail MIME, inbox rules): q must be plain words
    (no ' " / \ ? # % ( ) &, no "..", no control characters, at most 200
    chars). A dot-only drive-id / driveItem-id is refused on every tool
    (`..` survives the server's percent-encoding). download-bytes is pinned to mail attachments AND
    `/drives/{id}/items/{id}/content` (optionally `?format=pdf`, Graph's PDF
    rendering), with the same dot-segment / encoded-slash refusal; a OneDrive
    result is rewritten from base64 to the file's text
    (_onedrive_content_as_text: drive_sync._extract on PDF / docx / xlsx /
    txt / md / csv, 20 MB, 200k chars; any other type gets a note pointing at
    the ?format=pdf target). search-onedrive-files, list-drives,
    get-drive-root-item, list-folder-files and get-drive-item are in
    PRIVATE_TURN_MCP_TOOLS beside the Google Drive reads, and download-bytes
    runs on a private or mail-touched turn only with a OneDrive content
    target (schedule_tools.is_onedrive_file_read; mail attachments stay out,
    as Gmail's do). Not yet in
    memory.drive_reads (Google only).
    OneDrive sync token: `ms365-mcp-launch.sh --access-token` (only argument
    allowed; after the placeholder scrub and cache-path defaults) execs
    docker/ms365-access-token.mjs, which loads the server's own AuthManager
    over the same encrypted cache and prints {access_token, expires_on} for
    scopes read from stdin. INVARIANT: the helper mints only Files.Read /
    Files.Read.All tokens (any other scope is refused), and prints only the
    token JSON on stdout; errors are one stderr line with the MSAL code.
    knowledge.onedrive_account runs it per sync tick and holds the token in
    memory; a reconnect-class error (invalid_grant, interaction_required,
    consent_required, no_account) is not retried within the tick.
    Account tools: ms-365-mcp-server registers login, logout, verify-login,
    list-accounts, select-account and remove-account whatever
    `--enabled-tools` says, so neither the launcher allow-list nor an
    operator-merged deny glob can be relied on. INVARIANT: MCPGateway.call_tool
    refuses login / logout / select-account / remove-account
    (_BLOCKED_M365_AUTH_TOOLS, matched via _normalize_tool_name, checked
    before any argument gate) with the standard _refuse error and an
    integration_outbound_blocked audit row, independent of operator config,
    and MCPGateway.search_tools drops them from search results
    (_drop_blocked_tools) so the model is never offered them. A chat turn
    therefore cannot sign the mailbox out, wipe the seeded token, switch the
    acting account or start a device-code sign-in for an account someone
    else controls; setup is only the launcher's `--login`. The read-only
    verify-login / list-accounts stay callable. The example config's deny
    globs remain as defense in depth.

    Acting-account pin: workspace-mcp takes the acting Google account per
    call (user_google_email). Nothing checked it, so a model-chosen address
    could open another mailbox the server holds a credential for, or under
    GWORKSPACE_AUTH_MODE=service_account (domain-wide delegation) possibly
    anyone's in the domain. MCPGateway.call_tool now runs
    _check_acting_account first for every google_workspace__* call: a
    present user_google_email that is not the exec address (case- and
    space-insensitive) is refused with an error tool_result and an
    integration_outbound_blocked audit row (field user_google_email). An
    absent value stays allowed. Someone's own mailbox is reached only
    through delegation.gmail (Act as me), never through the gateway.

    Pinned gateway: extensible-mcp is launched as `uvx --exclude-newer <cutoff>
    --from git+...@<commit>` (_EXTENSIBLE_MCP_LAUNCH_ARGS in
    orchestrator/mcp_gateway.py), and docker/Dockerfile pre-warms with the same
    arguments. The commit fixes extensible-mcp's code; the cutoff fixes its ~94
    transitive dependencies, which uvx otherwise re-resolves against PyPI on
    every networked start. INVARIANT: runtime and pre-warm args must match —
    tests/unit/test_extensible_mcp_pin.py enforces it. Unpinned, uvx resolved
    `main` on GitHub at every start: a push to extensible-mcp changed every
    running deployment on restart, an image rollback did not roll the gateway
    back, and a start without network failed. The no-network start holds only
    when the build-time pre-warm succeeded: it is `|| true`, so an image built
    during a GitHub outage fetches the commit at first start. uv itself is
    unpinned (`pip install uv`). The repo has no tags; bump the commit and
    cutoff together. Dependabot does not track git URLs.

    Cold-start embedding cache: extensible-mcp runs as a uvx subprocess and
    builds a tool-search vector index with fastembed, which loads
    Qdrant/all-MiniLM-L6-v2-onnx (fastembed remaps the name
    "sentence-transformers/all-MiniLM-L6-v2" to this ONNX repo). The MCP stdio
    client does NOT inherit the parent environment — with env=None the child gets
    only a fixed allowlist (HOME, PATH, …) — so MCPGateway.start() explicitly
    forwards _FORWARDED_ENV_VARS (FASTEMBED_CACHE_PATH, HF_HUB_OFFLINE, HF_HOME,
    TRANSFORMERS_OFFLINE) when present. The API image bakes this model under
    FASTEMBED_CACHE_PATH=/opt/fastembed-cache (docker/Dockerfile) and runs
    offline, so the ~90 MB model loads from disk instead of being re-fetched from
    the Hugging Face Hub on every cold start (which previously dominated boot).
    INVARIANT: anything the subprocess needs from the environment must be added
    to _FORWARDED_ENV_VARS — parent env is otherwise invisible to it.

    Enablement (config._resolve_mcp): MCP_ENABLED left unset is INFERRED from
    the presence of mcp_servers_config_path, so dropping an mcp_servers.json
    next to profile.yaml turns MCP on with no further configuration. An
    EXPLICIT setting wins in both directions — MCP_ENABLED=false keeps MCP off
    with the file still in place. This needs care: the validator used to test
    `not self.mcp_enabled`, which cannot distinguish "never set" from "set to
    false", so the file's presence silently overrode an operator who had asked
    for MCP to be off (#122; the trap is easy to fall into because
    docs/deployment.md lists /data/company/mcp_servers.json under persistent
    state, so shipping the file there is the expected setup). It now reads
    INVARIANT: probe the config path through config.mcp_config_file_present,
    never Path.exists/is_file directly. Those re-raise any OSError outside
    (ENOENT, ENOTDIR, EBADF, ELOOP), so an EACCES on a parent directory whose
    ownership does not match the container user propagates — and from inside
    this validator that is out of Settings() itself, which api/main.py calls at
    module level, making it an IMPORT-time crash rather than a degraded boot.
    The helper tests is_file, so a directory at the config path counts as
    absent too; it used to be enough to auto-enable MCP.
    The check reads
    model_fields_set — the field names the env/init actually supplied — and
    stores that on the private attr Settings._mcp_enabled_explicit, which the
    read-only Settings.mcp_auto_enabled property reads. Private attr, not a
    field: it is derived on every load, so an env var for it could only ever be
    discarded, and a field with an alias would advertise a knob that does not
    exist.
    INVARIANT: read model_fields_set BEFORE assigning mcp_enabled. Pydantic
    adds a field to that set on assignment too, so after the auto-enable the
    set no longer distinguishes the two cases; anything downstream that wants
    to know "was this explicit?" reads mcp_auto_enabled, never
    model_fields_set.

    Startup is BEST-EFFORT, in api.main._start_mcp_gateway (extracted from the
    lifespan so it is unit-testable). It never raises. Two checks run before
    the subprocess is spawned: MCP off is a no-op, and a config that defines no
    servers under mcpServers is logged at WARNING and skipped — gateway not
    started. That empty-config case is why the crash existed: extensible-mcp's
    load_config ends with ValueError("Config must define at least one server in
    'mcpServers'") and the child exits, so the only thing reaching us is anyio's
    "Attempted to exit cancel scope in a different task than it was entered in"
    from stdio_client unwinding a subprocess that had already gone — a
    traceback that names nothing about configuration. configured_server_names()
    (mcp_gateway) reads the names up front for that check and for the log; it
    returns [] for a missing, unreadable, oversized, non-object, or serverless
    config. INVARIANT: it NEVER raises, and its except is deliberately broad.
    It reads an operator-owned path during startup, where an exception is the
    crash loop rather than a bug report, and the narrow catch it started with
    had two holes: Path.is_file/exists re-raise any OSError outside (ENOENT,
    ENOTDIR, EBADF, ELOOP), so an EACCES on a parent directory whose ownership
    does not match the container user propagates — and with an explicit
    MCP_ENABLED=true this is the FIRST stat of the path, because _resolve_mcp
    short-circuits its own exists() check; and json.loads answers
    deeply-nested input with RecursionError, which is not a ValueError. It
    tests is_file() rather than exists() so a directory or a symlink to a FIFO
    at that path is never opened, and caps the read at _MAX_CONFIG_BYTES
    (1 MiB) so a symlink to something huge cannot stall the boot.
    A gateway that fails anyway is logged at ERROR via logger.exception with the
    config path, the server names, and whether the config file or an explicit
    MCP_ENABLED turned MCP on, then close()d; app.state.mcp_gateway stays None,
    set_active_gateway is NOT called, and the email poller (which rides on the
    gateway) is not started. The API then boots without MCP tools.
    INVARIANT: an MCP failure must never propagate out of the lifespan. It used
    to, which kills the container — under `restart: unless-stopped` that is a
    crash loop whose only outward symptom is a healthcheck that never passes
    (#122 hit 15 restarts). Losing the Gmail/Calendar/Drive surface and the
    email poller beats losing the whole API. Same degradation pattern as the
    Discord bot block in the lifespan.
    INVARIANT: catch BaseException there, not Exception, with a bare
    asyncio.CancelledError re-raised first. The #122 failure surfaced from
    anyio, and anyio wraps a task group's failures in BaseExceptionGroup as
    soon as one of them is a BaseException such as CancelledError.
    BaseExceptionGroup is NOT an Exception subclass, so `except Exception`
    lets through the exact shape the guard exists for. The re-raise keeps the
    lifespan's own cancellation (a bare CancelledError in our frame) meaning
    shut down rather than degrade.
    INVARIANT: the teardown after a failed start is itself contained and
    bounded (_close_mcp_gateway_quietly, _MCP_CLOSE_TIMEOUT_S=10s). It runs
    from inside the except block, so anything it raises replaces the
    actionable log with the crash that log prevents — the operator then reads
    the right message and the container dies anyway. MCPGateway.close's own
    contextlib.suppress(Exception) does not cover the BaseExceptionGroup case.
    INVARIANT: the start is bounded (_MCP_START_TIMEOUT_S=120s, generous
    because the child is `uvx --from git+…` and may clone extensible-mcp on a
    cold start). MCPGateway.start builds ClientSession with no
    read_timeout_seconds, so initialize() waits forever on a child that is
    ALIVE BUT SILENT — a slow or unreachable network on that clone, for
    instance. No try/except can see that: the lifespan simply never yields, so
    the healthcheck never passes, which is #122's symptom with none of its
    traceback. A DEAD child was always fine (BaseSession's receive loop fails
    every pending request with CONNECTION_CLOSED, so initialize() raises
    McpError); only the silent one needed a clock.

    Egress gating: MCPGateway.call_tool intercepts four tool families before
    delegating to the MCP subprocess. All four resolve the allow-list from the
    shared _roster_allow_set() helper, which returns a people.identity.RosterAllow
    (a set-like object: exact primaries and aliases, plus — for a teammate — any
    address on a company domain whose local part matches theirs, the rule
    inbound mail is matched by): every team member's addresses plus the exec
    address, and contacts' addresses only when people_tools.contacts_reachable_now()
    (the principal's own verified turn, or grant_contact_egress()); otherwise a
    contact's address is refused exactly like a stranger's, so the refusal never
    reveals a contact. A private turn (Session.private_to_principal) narrows it
    to the principal's address and the exec's:
    - Microsoft 365 (_GATED_M365_MAIL_TOOLS: send-mail, reply-/reply-all-/
      forward-mail-message, create-draft-email, create-reply-/reply-all-/
      forward-draft, update-mail-message, send-draft-message;
      _GATED_M365_CALENDAR_TOOLS: create-/update-calendar-event — matched via
      _normalize_tool_name, which lowercases and collapses "-"/"_" so a proxy
      rewrite of hyphens cannot un-gate a tool): Graph nests recipients
      (body.Message.toRecipients[].emailAddress.address, body.attendees[]…),
      so _check_m365_recipients walks EVERY string in the argument tree — keys
      and values, any depth — except the free-text keys in
      _M365_FREE_TEXT_KEYS (content, subject, comment, bodyPreview; NOT
      "body", which is also the request-body wrapper); every email-shaped
      token must be on the roster, any C0 control character is refused
      (header injection via a display name), any non-exempt string that
      contains "@" but is not pure ASCII is refused (_EMAIL_RE is ASCII-only,
      so an internationalized domain like evïl.example would otherwise yield
      no match and pass while Graph still delivers), and so is any non-exempt
      string with a quote or a stray "@" the regex does not account for (a
      quoted local part like "a@roster"@evil.example). Fail-closed on
      unforeseen keys
      (replyTo, internetMessageHeaders values…). The free-text exemption is
      safe only because the server's send shapes are JSON objects — a body
      string cannot address anyone; a raw-MIME send tool, should one appear,
      must be gated separately or denied. update-mail-message is gated because
      it can PATCH toRecipients onto a draft that send-draft-message later
      sends; all reads pass through. delete-calendar-event (Exchange mails
      every attendee the cancellation) reads the event and roster-checks its
      attendees (_check_m365_event_delete), except the typed
      cancel_calendar_event of that one event (calendar_cancel_grant). RSVP
      (accept / decline / tentatively-accept) and cancel-calendar-event are
      gated by an EVENT lookup (_check_m365_referenced_event →
      get-calendar-event, select organizer/attendees): their free-text
      comment is emailed by Exchange to the organizer (RSVP) or every
      attendee (cancel), none of whom is in the arguments — an attacker's
      invite could otherwise exfiltrate text through a decline comment.
      download-bytes (a generic authenticated Graph GET proxy in
      ms-365-mcp-server) is pinned by _check_m365_download_target to
      /me/messages/{id}/attachments/{id}/$value, the only shape the
      Executive needs, so the read side of the allow-list cannot be
      bypassed through it. The reply family is different: Graph's reply /
      reply-all / send-draft actions carry NO recipient in their arguments —
      the recipient is whoever the referenced messageId names — so the
      argument walk alone would let a reply to an unrostered sender through.
      For _M365_REPLY_BY_ID_TOOLS (reply-mail-message, reply-all-mail-message,
      create-reply-draft, create-reply-all-draft, send-draft-message) the gate
      first READS the referenced message through the server
      (_check_m365_referenced_message → get-mail-message, select
      from/replyTo/to/cc/bcc) and roster-checks the recipients Graph will
      derive: replyTo-else-from for a reply, plus the original to/cc for
      reply-all, the draft's own to/cc/bcc for send-draft. Reply-all checks
      the UNION of replyTo and from (plus to/cc), failing closed whichever of
      them Graph addresses. INVARIANT:
      fail-closed — a missing messageId, a lookup error/exception, a
      non-object result, or a message implying no addressable recipient all
      refuse the call.
      Sender pin (_check_m365_sender, every _GATED_M365_MAIL_TOOLS call,
      before the recipient walk): Graph lets a delegated caller set from /
      sender to any mailbox it holds Send As / Send on Behalf on, and replyTo
      steers every reply, while the roster walk would accept a rostered
      colleague's address there. Any key normalizing to from, sender or
      replyto (any depth, any spelling), or an internet-header pair named
      one of them, may carry only EXEC_EMAIL_ADDRESS (case-insensitive) in
      any string containing "@"; display names pass, leaving the field out
      sends as the signed-in mailbox. The Outlook twin of the Gmail
      acting-account pin (_check_acting_account).
      Move guard (_check_m365_move_destination): move-mail-message into the
      well-known folders deletedItems, junkEmail, recoverableItemsDeletions
      or recoverableItemsPurges (any destinationId, any depth,
      case-insensitive) is refused, so a move cannot be used as an ungated
      trash; a non-string destinationId is refused too. An opaque folder id
      is not resolved, so only the well-known names are caught. This is what makes the poller's [POLICY] promise ("the
      gateway will block a reply to an unrostered sender") true on Outlook.
      The rendered inbound text also defangs any `--- REPLY ---` /
      `--- BODY ---` / `--- ATTACHMENTS ---` line inside a body (quoted with
      "> ") so a message cannot forge the block the persona reads the reply
      tool from. After a successful send-mail (not reply/forward,
      which name the recipient only by message id) an outbound_context linkage
      is recorded per to/cc address (_record_m365_outbound_context), sharing
      _record_outbound_context_for with the Gmail path.
    - Gmail (_GATED_GMAIL_TOOLS): to/cc/bcc must be on the People roster
      or the exec address; unknown argument keys rejected. One exception,
      checked after the key checks and before the roster check:
      _roster_ack_admits passes exactly one send under roster_ack_grant (the
      fixed roster-request acknowledgement to one unknown sender: tool
      send_gmail_message, keys exactly user_google_email/to/subject/body, a
      single `to` equal to the grant with no , ; < > or newline, the granted
      subject and body), then marks the grant used; audited private as
      integration_outbound kind roster_ack.
    - Calendar (_GATED_CALENDAR_TOOLS = {google_workspace__manage_event}):
      attendees must be on the People roster; this is a hard backstop — the
      typed create_calendar_event tool enforces the same rule via person IDs
      before calling the gateway, but the gateway check ensures bypass-proof
      safety even for raw call_tool invocations. rsvp_comment is refused
      (Google mails it to the organizer, who may be off the roster), and a
      call that names no attendees — an update that keeps the event's
      existing, possibly off-roster guests — is sent with
      send_updates="none" (_pin_calendar_notifications), so nobody is emailed
      text the gate never saw. A delete is pinned the same way (Google mails
      the cancellation to a guest list the gate never saw), except the typed
      cancel_calendar_event of a meeting the Executive booked, which keeps
      its notice through calendar_cancel_grant for that event id only. Take
      the lead counts a connected tool whose action deletes
      (manage_event action=delete) as deleting.
    - Refused outright (_refuse, audited as integration_outbound_blocked):
      every Apps Script tool (_BLOCKED_APPS_SCRIPT_TOOLS plus the
      _is_apps_script_tool name pattern, scoped to the google_workspace
      namespace) — code running as the Executive's account outside these
      gates, and since workspace-mcp 1.29.0 schedulable to keep running
      (manage_script_trigger); and any argument that makes the server fetch a
      URL (_URL_FETCH_ARGS: create_drive_file.fileUrl, which also takes
      file://; update_drive_file and import_to_google_* file_url;
      _URL_FETCH_KEYS on every tool and inside every Gmail attachment entry)
      — workspace-mcp's SSRF guard blocks internal hosts only, so a public
      URL's query string carries data out before any recipient gate matters
      (a send to the Executive's own address always passes that gate).
      Attachments still go by path, content or artifact_id; Drive files by
      content / base64_content. Keys Google itself fetches are refused at any
      depth when the value has a URL scheme (_URL_SCHEME_RE, any scheme, not
      just "://"): any key ending in url / uri or image_source
      (_GOOGLE_FETCH_KEY_RE — insert_doc_image.image_source, Slides
      createImage url / imageUrl and a page background's
      stretchedPictureFill.contentUrl, Forms image.sourceUri, Docs image_uri)
      except the stored-as-text ones (_STORED_URL_KEYS: link_url,
      conference_uri, youtube_uri); a Drive file id has no scheme and passes.
      A value is a URL once the characters a URL parser strips are removed
      (_INVISIBLE_RE: C0 controls, zero-width and bidi format characters,
      BOM) and "//host" counts (_is_url). On every tool that can write cells
      (_CELL_WRITER_RE: sheet, table, conditional, drive_file, import_to —
      the Drive create / update / import tools turn CSV into a native
      Sheet), any string anywhere in the arguments holding a formula call
      Google evaluates by fetching (_FORMULA_FETCH_RE: IMPORTDATA, IMPORTXML,
      IMPORTHTML, IMPORTFEED, IMAGE) is refused — the URL is in the cell
      value, so no key-based check could see it, and a `values` argument may
      arrive JSON-encoded or a CSV cell mid-line; =SUM(...) passes. Every
      gate walks a string that encodes JSON as the value the server decodes
      (_parsed_json, in _iter_arg_strings and _nested_fetch_key), so a
      \u0049MPORTDATA escape or a JSON-string `requests` list is read as
      IMPORTDATA / as the list; one over _JSON_STRING_MAX on a cell-writing
      tool is refused rather than skipped. Text is also scanned with
      character references decoded and comments / CDATA markers removed
      (_formula_fetches), since a converter decodes markup before it sees
      "&#x49;MPORTDATA(" or "IMPORT<!---->DATA(". An upload that becomes a
      native Sheet (_becomes_sheet: import_to_google_sheets, update_drive_file
      — its target type is unknown here — or create_drive_file with a
      spreadsheet / CSV mime type) may only be text `content`: base64_content
      and a server-side file_path are refused for it, because an XLSX / ODS
      hides formulas behind zip members, XML encodings and character
      references that no scan here reads reliably (an earlier version
      unzipped and scanned; a review beat it four ways). A PNG to Drive or a
      DOCX to Docs is not a cell write and is untouched. Residual,
      unverified: whether Drive's HTML / Markdown import fetches an <img src>
      while converting `content` into a Doc (refusing image tags there would
      break a legitimate import, so it is left open and noted).
      Also refused on every tool: text
      Google mails to a person the roster never checked (_MAILED_TEXT_KEYS:
      rsvp_comment to the organizer, manage_out_of_office /
      manage_focus_time decline_message to whoever invites the Executive),
      and arguments that are not a JSON object (every gate reads a dict; a
      list or string would have skipped them all).
    - Key spelling: every gate reads a parameter through _arg / _arg_values
      (normalized: lowercase, alphanumerics only), and a refusal fires on any
      variant. workspace-mcp 1.29.0's CamelCaseArgumentsMiddleware renames an
      undeclared camelCase key to the declared snake_case parameter, so
      `Attendees`, `userGoogleEmail` or `rsvpComment` reached the tool as the
      real thing while an exact-key gate saw nothing; the 1.29.0 bump opened
      this against the acting-account and attendee gates until the fix. The
      notification pin drops every spelling of send_updates before writing
      the canonical one, so a `sendUpdates: "all"` cannot survive beside it.
    - Drive sharing (_GATED_DRIVE_TOOLS = {google_workspace__manage_drive_access,
      google_workspace__set_drive_file_permissions}, plus a defensive
      _is_drive_share_tool() name-pattern fallback that never matches a pure
      read): exposed only at the `complete` tier. _check_drive_share scans EVERY
      string (in both key and value position, any depth — so an email in an
      unknown field or as a dict key is still caught) — every email-like token
      must be on the roster, and any public/whole-domain scope is refused in both
      the string form (anyone / anyone_with_link / domain in _PUBLIC_SHARE_SCOPES)
      AND the typed-flag form (a boolean/int "make public" flag whose key
      exactly matches a normalized _PUBLIC_SHARE_KEYS name — covering Drive v3
      booleans and legacy v2 link names like withLink — via _has_public_share_flag,
      so {"public": true} can't slip past the string scan). Disabling link
      sharing (the safe direction) still passes. Residual: comment-notification tools
      (manage_document_comment etc.) can email a non-roster address and are NOT
      gated — a softer vector left open deliberately.

    A private turn may call only schedule_tools.PRIVATE_TURN_MCP_TOOLS, an
    exact allow-list: the Google Workspace reads the code already uses or
    documents (search_gmail_messages and get_gmail_message_content from the
    email poller; get_events, list_calendars and query_freebusy from the
    calendar surface below and the decisions route; the Drive, Docs and
    Sheets reads search_drive_files, get_drive_file_content,
    list_drive_items, search_docs, get_doc_content, list_docs_in_folder,
    list_spreadsheets, get_spreadsheet_info, read_sheet_values and
    list_sheet_tables, each marked read-only by workspace-mcp and run with a
    read-only scope) and the two gated Gmail tools
    (send_gmail_message, draft_gmail_message), which the Gmail gate narrows
    to the principal on such a turn. Not a server prefix: at the complete
    tier much of Google Workspace reaches people with no recipient check —
    a Google Chat message to a space, Docs / Sheets / Drive writes into
    files already shared with others, manage_event on a shared calendar
    (the calendar gate checks attendees and pins notifications only), the
    comment-notification tools above — and no
    other server has any check (a Slack or Notion server; the default
    `fetch` server, whose URL can carry the turn's content; a server loaded
    at runtime). So on such a turn the chat loop
    (Executive._stream_agent_loop) passes on only the allowed tools from
    search_tools (workflows.tool_catalog.filter_search_results; output it
    cannot parse reads as no match) and refuses a call_tool naming anything
    else: schedule_tools.private_turn_withholds, answered with
    private_turn_withheld_error and a tool_invocation audit row that is
    private to the principal (details.refused = "private_turn"). A missing
    or non-string name is refused too, and names match exactly, so a server
    loaded as google_workspace__x never passes. search_tools and call_tool
    stay offered and load_mcp_server stays withheld, so the offered list
    and its cached prefix do not change. Add a name to the allow-list only
    for a tool that reads, or whose every recipient the gateway checks.
    Residual: if the google_workspace server is not connected, a normal
    turn could load a server under that exact name.

    Calendar tool surface (a subset of the complete tier; all namespaced google_workspace__):
      manage_event    — create/update/delete/rsvp (action param)
      get_events      — list events in a time range
      list_calendars  — calendars the user can access
      query_freebusy  — free/busy check across calendars

    Typed Executive tools wrapping the calendar MCP:
      create_calendar_event  — propose (or auto-execute when promoted) a FUTURE
        meeting; enforces caps (horizon, business-hours, roster, principal-protect,
        max-events/day), writes a decision_instances ledger row, and routes
        through gate_action(scope=MEETING_SCHEDULING). On the PROPOSE path it also
        surfaces a companion briefing alert (source='decision_scheduling',
        external_id='decision:{id}', routed to the approver, tagged
        decision_instance:{id} / decision_class:meeting_scheduling) so the proposal
        is visible AND approvable directly in the briefing — there is no separate
        proposals page. The auto-execute path does NOT create an alert (nothing to
        approve). today.py parses the decision_instance:{id} tag onto
        ProposalItem.decision_instance_id so the card routes Approve/Reject to the
        /decisions endpoints.
      create_instant_meeting — book an impromptu meeting starting ~1 min from now
        and return the Google Meet link immediately. AUTO-EXECUTES (no approval
        step — the user asked to meet now) and SKIPS the horizon + business-hours/
        weekday caps; still enforces roster, principal-protect, max-attendees, and
        max-events/day, and records an `executed` ledger row for audit.
        Since nothing approves it, it (and cancel_calendar_event) runs only when
        someone on the team asked on a verified surface
        (calendar_tools._asked_on_a_verified_surface: the principal, or a
        rostered teammate never in an email-started turn); otherwise it refuses.
        Team mode's create_calendar_event that operations would auto-execute
        is proposed instead on such a turn.
      cancel_calendar_event  — cancel by decision_instance_id. Only a
        meeting_scheduling instance, and one whose payload is private (a
        meeting with the principal's contact) only when contacts are reachable
        (the principal's own verified turn); any other id reads exactly like a
        missing one, so the tool can neither reverse another class (a reply
        card) nor reveal that one exists. mark_reversed is also called with
        decision_class, so the ledger refuses the wrong class itself.

    Video links: every booking requests a video-meeting link by default —
    on Google via add_google_meet=true on the manage_event call (workspace-mcp
    builds the conferenceData createRequest; conferenceDataVersion=1; the URL
    is parsed back out of conferenceData.entryPoints[type=video].uri), on
    Microsoft via isOnlineMeeting + onlineMeetingProvider=teamsForBusiness (URL
    from onlineMeeting.joinUrl) — per CALENDAR_PROVIDER (see
    ``workspace_providers``). Either way it is surfaced in the tool result +
    persisted on the decision_instances final_payload as `meet_link`. The
    model can opt out per-event with add_video_link=false for an in-person
    meeting (gate: CALENDAR_MEET_LINKS_ENABLED, default true; the pre-rename
    add_google_meet key is still accepted). Instant meetings always attach a
    link. The typed tools' descriptions are static, backend-neutral text
    ("Google Meet or Microsoft Teams, per the configured calendar") so the
    cached tool block never depends on settings.

    Around-the-meeting participation: on any successful booking, a best-effort
    post-meeting follow-up is scheduled (CALENDAR_POST_MEETING_FOLLOWUP_ENABLED,
    default true). It inserts an `ad_hoc` scheduled_actions row (run_at = end +
    5 min, scope_key="meeting_followup:{event_id}") targeted at the first
    non-principal attendee reachable on a configured DM channel — resolved via
    schedule_tools.resolve_person_scheduled_dm — asking them for a recap
    (decisions + action items). The attendee's reply is ingested through the
    existing outbound→inbound DM context linkage; no Meet/Drive transcript
    integration is involved. Skipped silently when no attendee has a reachable
    DM channel. Failure to schedule never blocks the booking.
  own_gmail: |
    Act as me (delegation) connects a second, separate Gmail — the
    principal's own — read and drafted into by delegation.gmail.DelegateGmail
    over the Gmail REST API, never the MCP gateway. Credential: one file per
    person in DELEGATION_GOOGLE_CREDENTIALS_DIR (company/delegation_google/,
    /data/delegation_google in Docker), named from sha256 of the lowercased
    address, 0600 in a 0700 directory, minted by scripts/connect-own-gmail.py
    (loopback OAuth on the Executive's own Desktop client; scopes
    gmail.readonly + gmail.compose; the API serves no OAuth callback, as
    for the exec token). Never in WORKSPACE_MCP_CREDENTIALS_DIR:
    workspace-mcp picks a credential there by address, which would hand the
    model the mailbox. gmail_status re-checks on every use that the
    credential opens the mailbox on the person's People email, and refuses
    the exec address outright (shared_mailbox). Drafts are threaded
    (In-Reply-To, References, threadId) and stamped X-OE-Ghostwritten; no
    send method. email_poller.sender_new_text (the poller's quoted-reply
    stripper, made public) keeps only each sender's own words for the voice
    learner and the ghostwriter's thread.

  mcp_server: |
    openexecutive.mcp_server — Open Executive exposed AS an MCP server, the
    inverse of `mcp_gateway:` above (gateway = OE consumes remote MCP servers;
    server = external MCP clients consume OE). Built on FastMCP, Streamable-HTTP
    transport, mounted into the FastAPI app at `/mcp` (streamable_http_path="/"
    mounted under "/mcp" so the external endpoint is exactly `/mcp`; compliant
    clients follow the trailing-slash 307 to `/mcp/`).

    Lifespan INVARIANT: mounting a sub-app does NOT run its lifespan, so
    api/main.py wraps the serving phase in `mcp.session_manager.run()`. Without
    it every `/mcp` request 500s. The session manager is created lazily when
    create_app() calls mcp_server.mount() → streamable_http_app().

    Auth: `/mcp` is intentionally NOT in _UNAUTHENTICATED_PATHS — the existing
    shared-secret middleware gates it, so clients send `x-api-key:
    $BACKEND_SHARED_SECRET` like the UI. FastMCP's DNS-rebinding (Host-header)
    check is disabled (TransportSecuritySettings(enable_dns_rebinding_protection
    =False)): the endpoint authenticates with a header secret, not a cookie, so
    a browser rebinding attack cannot supply the key, and traffic arrives behind
    the deployment's TLS terminator. The shared secret is the real access control.

    WHO IS ASKING: every handler answers as the caller the API verified. The
    mounted app shares the outer request's scope state, so what caller_gate
    put on request.state reaches the handler: mcp_server._request() reads the
    Starlette request from FastMCP's request context (mcp.get_context(); a
    handler signature takes no Context, so the resource list is unchanged),
    and api_caller.caller(request) answers. The person comes from
    api.caller.person_id_for, the one rule chat._resolve_caller_person_id
    now delegates to: a signed-in email is that person (None off the
    roster); open mode with no x-caller-email, or an operator, is the
    principal; a service is no one. With no request (a direct in-process
    call) it is Caller("open"), or Caller("service") once signed callers are
    on. Rules per caller, mirroring the web app:
      - oe://memory/{decisions,initiatives,advice}, oe://today/activity: the
        principal alone (resolves to the principal, or defaults_to_principal);
        anyone else gets "Only the owner can read this." (CallerRefused,
        returned by FastMCP as the JSON-RPC error message).
      - oe://today/briefing: someone on the roster (or the principal by
        default), built as GET /today builds it: include_private for the
        principal only, viewer = viewer_for_person(caller), so a drafted
        artifact's card only for its owner. oe://people/roster: someone on
        the roster, the team only (never contacts), as GET /people gives it.
        A service or an unrostered caller gets "Only someone on the team can
        read this."
      - oe://company/profile, oe://departments/state, consult_specialist,
        search_knowledge, list_workflows (GET /workflows is public too):
        anyone who reached /mcp.
    A deployment that fronts /mcp with its own sign-in and stamps the signed
    caller (x-caller-assertion for POST /mcp/), as the UI proxy does, so gets
    per-person answers with the same rules as the web app.

    ASK_EXECUTIVE READS ONLY, UNLESS IT MAY ACT: it takes only `message` (the caller comes from
    the request, never an argument) and builds a Session with
    from_mcp_client=True and caller_person_id = the resolved person (NOBODY
    as documents_viewer when that is no one). On such a turn the chat loop
    (_stream_agent_loop) neither offers nor runs
    schedule_tools.MCP_CLIENT_WITHHELD_TOOLS = PRIVATE_TURN_WITHHELD_TOOLS |
    UNATTENDED_WITHHELD_TOOLS | the DMs (message_person, send_slack_dm,
    send_discord_dm, send_telegram_message), ack_alert, create_alert,
    leave_out_of_brief, close_open_loop, upsert_person, archive_person,
    set_department_head, remove_/tune_watchlist_entry, draft_workflow,
    propose_form_values — a fixed set dropped before the sort, so the variant
    keeps a stable cached tool prefix. What stays: the specialists and the
    list/lookup/read tools (a test pins the list). No Act as me
    (delegation.settings._offered answers False, and the loop adds no
    delegation tools), no recall_history, no extension tools. Gateway: only
    schedule_tools.MCP_CLIENT_MCP_TOOLS (PRIVATE_TURN_MCP_TOOLS without the
    Gmail/Outlook send and draft tools) — search_tools results are filtered
    to it, call_tool naming anything else and load_mcp_server are refused in
    the loop, and MCPGateway.call_tool refuses again on any path that reads
    current_session. A refused call returns a JSON error
    (mcp_client_withheld_error: the conversation comes from another AI app,
    so it can read and advise but can't send, post, book or change
    anything; tell the person to ask in Open Executive itself) and an audit
    row refused="mcp_client". The conversation itself is still recorded in
    memory, so ask_executive is annotated readOnlyHint=False,
    destructiveHint=False; the other three tools readOnlyHint=True. Every
    tool has an MCP title and annotations, and descriptions state what a
    tool does without steering a client between tools.

    MAY ACT (opt-in, per request): mcp_server.may_act() sets
    Session.mcp_client_may_act. With BACKEND_SHARED_SECRET configured it is
    true only when the request carries `x-mcp-client-actions: on` AND the
    API's shared-secret gate let it through (the gate sets
    request.state.shared_secret_ok after its x-api-key compare_digest; the
    mounted app shares request.state). With no secret, the header is ignored
    and the MCP_CLIENT_ACTIONS setting (default false) decides. Fails closed.
    On such a turn (schedule_tools.mcp_client_acting; read_only_turn is
    false, mcp_rules_turn still true):
      - The fixed withheld set is MCP_CLIENT_ACTING_WITHHELD_TOOLS =
        MCP_CLIENT_WITHHELD_TOOLS - MCP_CLIENT_RUNS_WHEN_ACTING, so a newly
        withheld tool stays withheld here until it is listed on purpose.
        Runs directly (each under its own owner-only / person checks): alerts
        (ack, create, leave_out_of_brief), open loops (close, assign),
        follow-ups (schedule, cancel, move), the watch list (add, remove,
        tune), goals and department goals, decision outcomes, remember/forget
        facts and the company profile. Still withheld: roster writes
        (upsert_person, archive_person, set_department_head: someone added
        on one call would be someone a card reaches on the next; a new
        contact goes on an add_contact card, which always waits), everything that reaches another
        person directly (DMs, calendar create/cancel/instant meeting,
        broadcasts, department messages), load_mcp_server, run_script,
        run_python_job, list_saved_tools, the workflow tools,
        run_executive_research, and the rest of the read-only set
        (propose_form_values, read_document, draft_artifact, mark_draft_sent,
        resolve_roster_request). Extension tools, recall_history and Act as
        me's mailbox tools are not offered; gateway calls stay
        MCP_CLIENT_MCP_TOOLS. A withheld call gets mcp_client_withheld_error
        (acting=True): do it in Open Executive itself.
      - people_tools._is_verified_speaker_surface counts the turn as
        verified for caller_person_id (the caller api.caller verified, as for
        the web chat), so the tools' own checks decide; a read-only MCP turn
        never counts. history_chat.verified_speaker still refuses every MCP
        turn, so no History note or conversation review is taken from an AI
        app's text. ask_executive renders the live board
        (briefing.context.render_and_trust) so ack_alert has its trusted set.
      - Outward actions go on an approval card: propose_actions
        (action_card_tools) is offered alone of Act as me's tools, its
        speaker the verified caller with Act as me on. The card follows the
        person's mode (action_cards.on_its_own_refusal follow_handle_it,
        kept on the card's payload so run_on_its_own re-checks the same
        rule): with Suggested actions not in training, it is carried out at
        once when Handle it for me is on at a setting covering people they
        know (every card recipient is on the roster as team or contact, and
        each roster entry is at least action_cards.SETTLED_AFTER, 7 days,
        old, so nobody added or planted lately is reached), no add_contact,
        an invite never booked as approved (the meeting gate decides), and
        the plain-code checks pass (Act as me on, signed callers or local
        login, nothing sensitive, no link or amount, a message no longer
        than the setting's replies and ON_ITS_OWN_MESSAGE_MAX, the daily
        cap), and the turn read no outside text (outside_content.read_outside)
        or mail. In training the training rule applies. Otherwise the card
        waits for the person's tap on the web, as any card.
      - Every audit row the turn writes carries details.via = the MCP
        client's clientInfo.name, or "an AI app" (audit.via_app; FastMCP runs
        stateless, so a tool call usually has no initialize of its own); the
        card's payload keeps via and its approved / handled / held rows
        repeat it.

    Surface — what's valuable beyond chat (OE already has six chat channels, so
    a chat-only server adds nothing): company-grounded context as READ-ONLY
    resources, and the specialist council as tools.
      Resources: oe://company/profile, oe://today/briefing, oe://today/activity,
        oe://people/roster, oe://departments/state, oe://memory/{decisions,
        initiatives,advice}. Pure reads of existing service functions
        (load_or_create_profile, today._build_today/_build_activity,
        people.list_people, departments.list_departments, episodic list_*); no
        LLM calls. The warm ChromaDB store is handed to handlers via
        mcp_server.set_store() from the lifespan (handlers take no Request
        argument; only the caller read goes through the request context).
      Tools: consult_specialist (flagship — orchestrator.router.route_to_specialist,
        stateless, the specialist enum is a Literal pinned to SPECIALIST_REGISTRY
        by a unit test), search_knowledge (knowledge.retriever.retrieve),
        list_workflows (workflows.list_workflows → Workflow.meta), and ask_executive
        (Executive.chat, non-streaming, as the verified caller, reading only
        unless the request may act — see ASK_EXECUTIVE READS ONLY and MAY
        ACT). No other tool here sends or mutates company state;
        ask_executive's conversation is recorded in memory.

    DEFERRED by design: workflow EXECUTION is not exposed — workflows are
    long-running async generators (minutes) that would exceed a single MCP
    tool-call's request/response window; only the catalog is listed. If added
    later, use a job-handle pattern (start_workflow → run_id, then poll) over the
    existing workflows run-persistence. MCP `prompts` are skipped — OE workflows
    are server-executed orchestrations, not message templates.

    Prompt-caching: unaffected. This path is parallel to chat; resources are
    pure reads and consult_specialist delegates to the same BaseAgent.analyze
    that reuses the existing cached system blocks.
  peer_memory: |
    The peer-keyed memory integration has its own top-level section
    (see `peer_memory:`). From the integrations perspective: each
    inbound channel adapter resolves the sender to a Person via
    find_person_by_{slack,discord,telegram,email}_id and threads
    person_id into Executive.chat(); the wrapper handles the rest
    (per-person sync, plus per-department mirror when a dept-bound
    specialist contributes to the turn).
  scheduler_bridge: |
    The scheduler runner (see `scheduler:` above) fires due nudges
    through the integration named on the scheduled_actions row's
    `channel` column (`telegram`, `slack_dm`, `email` via MCP, etc.),
    so a single runner can deliver messages across all integrations
    without per-channel dispatch logic. The principal briefs and the
    client-rotation digest use `_deliver_to_principal` instead: Slack /
    Discord / Telegram through the DM handlers, and email through the
    active MCP gateway's `google_workspace__send_gmail_message` (from the
    Executive's own mailbox to the principal's address, formatted as
    HTML) — first when the principal prefers email, otherwise as the backup
    after every chat channel — see `workflows` → morning_brief.
  outbound_reply_context: |
    Cross-session DM context linkage — fixes the failure where the
    principal tells OE "DM Alex about X" in one session, OE sends the
    DM, and then Alex's reply lands in a fresh per-person session
    (`discord:dm:{alex_id}`) with empty history, so OE has no idea what
    Alex is replying about.

    The block is context for the LLM turn, never the person's words:
    ``memory.honcho_client`` strips it (``inbound_hydration.strip_outbound_reply_context``)
    before ``sync_turn`` and ``sync_department_turn`` post the message and
    before the prefetch query is sent, otherwise Honcho's deriver attributes
    the Executive's own DM to the person who replied to it.

    Write side — when a direct-send tool (`send_discord_dm`,
    `send_telegram_message`, `send_slack_dm`, and therefore
    `message_person`, which delegates) runs WHILE a live conversation
    session is active (the `current_session` contextvar is set), it
    persists an `outbound_context` row: the recipient (channel +
    channel_ref), the full outbound text, the originating session id,
    and the platform message id (best-effort). Scheduler/cadence sends
    have no `current_session`, so they intentionally write no linkage.
    Email is covered too, but recorded one layer deeper: there is no
    `send_email` tool — the Executive emails via the raw MCP tool
    `google_workspace__send_gmail_message`, so the linkage is recorded
    in `orchestrator.mcp_gateway` right after a successful send (one row
    per `to`/`cc` recipient, keyed by the bare lowercased address, the
    Executive's own address skipped; a soft-error result records
    nothing). channel is `"email"`.

    Read side — a single shared helper,
    `integrations.inbound_hydration.hydrate_user_message`, is called by
    the Discord, Telegram, and Slack inbound handlers on the 1:1 DM
    path ONLY, and by the email poller (`integrations.email_poller`)
    keyed on the bare lowercased sender address, right before
    `Executive.chat`. It looks up the most-
    recent `open` linkage for (channel, sender) within a 72h window
    and, on a hit, prepends an `<outbound_reply_context>` block — the
    outbound text plus a short backstory excerpt loaded from the
    originating session — to the message handed to the model. The block
    goes in the USER turn (prompt-caching rule), and is injected into a
    copy only: the pristine reply text is what gets persisted to
    history, so the one-shot context never leaks into future turns.

    Lifecycle is one-shot: the linkage is consumed (status `open` →
    `consumed`, race-safe via `UPDATE … WHERE status='open'`) on the
    first matched reply, so a later unrelated DM from the same person
    is not re-hydrated with stale backstory. This is deterministic and
    independent of Honcho/peer_memory (which is per-person and disabled
    by default). Slack DMs are gated to `mode == "dm"` so a public-
    channel reply can't pull private outbound context into a shared
    thread; for email the per-recipient address match is the gate.
    Storage + helpers live in `memory.episodic` (`outbound_context`
    table; `insert_outbound_context` / `find_open_outbound_context` /
    `mark_outbound_context_consumed`); `_VALID_OUTBOUND_CHANNELS` is
    `{discord_dm, telegram, slack_dm, email}`.

evals:
  module: openexecutive.evals
  runner: openexecutive.evals.runner — parallel scenario execution with cancellable runs.
  judges: openexecutive.evals.judges — LLM-as-judge scoring against per-scenario rubrics.
  persistence: openexecutive.evals.persistence — run history, scenario CRUD, judgement records.
  api: /evals — scenario CRUD, run launch, run history, cancel.
  ui: UI-triggered runner with SSE streaming, parallel execution, scenario CRUD inline, stop button on active runs.
  scenarios_dir: openexecutive/evals/_scenarios — YAML scenarios bundled with the package so they ship in the Docker image.
  workspace_mode: |
    A chat, mcp or workflow scenario may set `workspace_mode: solo` (or
    `team`; anything else fails the scenario, and validate_scenario_yaml
    rejects it) to run as that mode without touching the install-wide
    setting — scenarios run concurrently on one Executive. Chat sets
    Session.workspace_mode; a workflow scenario runs with a Session carrying
    it bound as current_session (only when the key is set, so unkeyed
    workflow scenarios keep running with no session). The chat judge adds
    a role-neutral solo section (the asker may be an owner, an in-house
    executive or an independent — do not reward assuming which; helping
    them work with the people in their world is good, coordinating or
    messaging those people unasked, broadcasting, or offering to loop the
    asker in is a failure; the scenario's quality_criteria are listed) only
    for solo scenarios; every other judge prompt is unchanged. solo_001..003
    run against the solo_studio fixture (an owner): "who should I loop in"
    (the principal decides; affected clients are people they tell), a goal
    update (area, one goal, rationale) and a status question (no department
    / people-waiting sections). solo_004 is an in-house executive (a VP of
    Marketing at an ~800-person company preparing a budget case for their
    CFO and a hard conversation with a direct report): the boss and the
    report are people the principal works with, not a team to message, and
    no business owner is assumed. The standalone evals/run_evals.py passes
    the key through too.
  principal_role: |
    A scenario may set a `principal_role` mapping — the workspace settings'
    role keys (role_kind, role_title, reports_to, remit, measured_on) —
    to play a principal with that role. evals.scenarios.
    scenario_principal_role validates it like the API (unknown key, bad
    kind, over-long text, a block that sets nothing, or a scenario without
    workspace_mode solo raises; validate_scenario_yaml rejects it with a
    "`principal_role`:" message) and returns a PrincipalRole, which the
    chat runner puts on Session.principal_role and a workflow scenario on
    its bound session — never into the install-wide row, which concurrent
    scenarios would share. It reaches the Executive's org block and every
    specialist's <principal_role> tag exactly as a stored role does. The
    solo judge section then adds "THE ASKER'S ROLE" (the keys and values)
    so the judge knows the role the question may not repeat. solo_005: a
    Director of Operations at a 2,000-person logistics company (in_house,
    reporting to a VP) asks for help with a quarterly update — expect
    manager-facing framing against what they are measured on and no
    business-owner assumptions (runway, fundraising, investors, own
    pricing). evals/run_evals.py passes the block through too.
  principal_only: |
    A workflow scenario runs `workflow.run` directly on the install's live
    data, so an eval run is another way to trigger a workflow. POST
    /evals/runs refuses (403, audited, surface evals) a kind=workflow run
    when any of its scenarios names a workflow that is the principal's alone
    in the mode it would run in (the scenario's workspace_mode, else the
    stored mode) and the caller is not the principal. A request with no
    x-caller-email counts as the principal, and an install with no
    principal on the roster lets no signed-in caller in. Today that is
    workflow_weekly_review_001 and any user scenario naming weekly_review,
    or morning_brief in solo. It is the Jobs page's rule
    (api.routes.workflows.refuse_principal_only_run; see workflows). The
    route passes the list it checked to run_scenarios(scenarios=...) rather
    than letting it load the scenarios again. Chat scenarios need no check
    here: an eval Session is no verified surface, so run_workflow refuses
    those workflows inside the turn. The check covers who may trigger the
    run; stored eval results are read under the existing /evals/runs rules.

company_onboarding:
  module: openexecutive.onboarding (interview.py, commit.py, wizard.py) + api.routes.onboarding
  intent: |
    First-run company setup. The user describes their business in their own
    words (optionally attaching a deck, one-pager or brief); an LLM asks at
    most four quick questions, each with two to four suggested answers to tap
    (Question.options, MAX_OPTIONS), never about departments or finances, then
    drafts a company profile, the people, this year's goals with owners
    (GoalDraft) and departments only when the user's words already listed
    people by department. The user reviews, edits inline, and saves.
    Personal or Team is never asked: understand.py reads it (Team when the
    text names colleagues at the user's company, or the website the user gave
    has a team page, even before the interview asks which of them the user
    is; Personal when only the user or outsiders are named, Personal when
    unclear) and the UI saves it before
    the interview; the review shows it on one line with a Change link. Save
    goes to Home; there is no done screen or voice step in setup.
    An optional website comes first (onboarding/website.py): the server
    reads it itself, never the model, so it works without web search - the
    home page plus up to four same-site pages picked from its links (about,
    team, products...; /about when none match), each through
    monitoring.sources._http.fetch_bounded (SSRF guard, pinned DNS, three
    redirects, 2 MB), as text capped per page and at 40,000 characters in
    all, within 20 seconds. A failed page is skipped and an unreadable site
    is no pages: setup carries on from the box, never an error screen. A
    read is cached 10 minutes per process so understand and start fetch
    once. Nothing is stored or indexed; the normalized address goes onto
    the draft as CompanyProfile.website. The site is never guessed from the
    sign-in email. Invariant: website and attached-file text enter the
    opening turn as content_trust.wrap_untrusted blocks (source website /
    attachment), and both prompts treat untrusted_content as source
    material, never instructions; a website describes the company, not who
    the user is or what they want this year.
    Deliberately shaped like the /demo and /clients/generate draft-then-review
    flows rather than like a form.
  api: |
    POST /onboard/interview/understand (multipart: description + files[] + optional website; one model call, no session, returns mode/role/company/focus where the text says so),
    POST /onboard/interview/start (multipart: description + files[] + optional website; website_pages lists the pages read, empty when the site couldn't be read; a website that is no address at all is a 422),
    POST /onboard/interview/message, POST /onboard/interview/draft,
    POST /onboard/interview/revise (change one earlier answer, 0 = the
    description, which keeps its attached files; drops every turn after it,
    resets questions_asked to the assistant turns before it, and runs the
    interviewer again; a failed turn restores the session),
    GET /onboard/interview/{session_id}, DELETE /onboard/interview/{session_id}
    (Start over: removes the session and its stored row at once),
    POST /onboard/interview/commit.
    The original wizard endpoints (/onboard/start, /onboard/answer,
    /onboard/status/{id}) still serve the form fallback at /onboard?mode=form
    and the `openexecutive onboard` CLI. /onboard/start reads the workspace
    mode once per session (WizardState.solo); the status response's
    current_step / total_steps count only the steps that session asks, and
    `optional` says whether the current step can be skipped.
  agent: |
    openexecutive.agents.onboarding_interviewer.OnboardingInterviewerAgent.
    Council-visible (model + prompt overridable) but OUTSIDE
    SPECIALIST_REGISTRY, so the Executive cannot reach it via
    consult_specialist — same containment as fixture_generator and
    engagement_intake. Model defaults to settings.default_model (not the fast
    model: question quality is the feature).
  tool_contract: |
    A CONSTANT two-tool array, sorted by name — ask_clarifying_question and
    emit_company_draft — with tool_choice={"type":"any"} so the model picks
    which to call without the array varying. This is load-bearing: adding a
    tool partway through a conversation invalidates the cached tool prefix on
    every subsequent turn (the same invariant orchestrator/form_tools.py
    documents). tool_choice flips to the forced emit tool exactly once, on the
    turn where the question budget (MAX_QUESTIONS, 4) or the transcript
    ceiling (MAX_TRANSCRIPT_CHARS)
    is reached, or when the user clicks "draft it now". That single call misses
    the tools cache; one miss per setup session is the accepted price of a
    bounded interview. Do NOT "fix" it by making the tools conditional.
  caching: |
    The system block is the ONBOARDING_INTERVIEWER_SYSTEM constant, never
    f-stringed. When the user re-runs setup over an existing profile,
    profile.to_prompt_block() goes into the FIRST USER TURN, never the cached
    system block. This path does not touch prompts/cache_manager.py, so the
    "exactly 2 cache_control blocks" budget there is unaffected.
  validation: |
    Two stages, mirroring fixtures.generator: Pydantic model_validate, then
    interview.validate_draft for referential integrity — exactly one
    is_principal, unique person names, every department head_person_name
    matching a person (or empty), distinct department titles, and every goal
    named, within MAX_GOALS / MAX_GOAL_CHARS, its owner_name a drafted person
    (or empty) and its department_title a drafted department (or empty).
    The commit re-runs the same check on the body. A failure of
    either feeds the errors back as a follow-up user turn and retries ONCE
    with the emit tool forced.
  error_contract: |
    NO failure path echoes model or user input. A ValidationError's str()
    embeds the offending values, which here are the user's ARR, burn and
    runway. InterviewError / InterviewTimeout messages are fixed, input-free
    strings safe to return as an HTTP detail, and every log line carries an
    exception TYPE only. Note fixtures/generator.py interpolates the exception
    into its GenerationError — that is NOT the pattern to copy here.
    Route mapping: InterviewTimeout -> 504, InterviewError -> 502, oversized
    message -> 422 (checked in the route, not with Field(max_length=...),
    because FastAPI's 422 body echoes the rejected input).
  session_state: |
    In-memory OrderedDict in api/routes/onboarding.py, 2h TTL and a 50-session
    cap, swept on every handler and after each insert, PLUS a write-through
    copy in the episodic SQLite database (onboarding/interview_store.py, table
    onboarding_interviews: session_id, payload JSON, updated_at; same TTL and
    cap, enforced on every save). `_get_interview` reads the store when the
    process does not hold the id, so a deploy or restart mid-interview, or a
    second worker, no longer loses the interview. The row is deleted the
    moment the commit succeeds (the transcript is unedited free text with the
    company's financials; the profile is on disk) and when the TTL sweep
    evicts it; a store failure is a warning, never a failed turn. Every
    store call also sweeps expired and over-cap rows, PRAGMA secure_delete
    zeroes deleted pages, and a blank client slot wipes the table
    (clients/slots._BLANK_WIPE_TABLES). A session belongs to whoever
    started it (InterviewSession.owner_key = api_caller.identity_key):
    every read or turn by another caller is the same 404 an unknown id
    gets, since the id alone is no longer a capability once sessions
    outlive the process and a browser remembers its id. A held copy is
    replaced by a newer stored row (`load(newer_than=stored_at)`), so two
    workers never overwrite each other's turns. The browser keeps only the
    session id (localStorage `oe.onboard.session`, lib/firstRun.ts) plus
    the description typed before Continue (sessionStorage, cleared by
    "later" and by Continue), and
    GET /onboard/interview/{id} resumes at the same question or draft; a 404
    (saved, expired) clears the memory and starts fresh.
  write_once_commit: |
    The interview NEVER writes. POST /onboard/interview/commit is the single
    write, ordered so nothing observable changes until the atomic save
    succeeds: (1) validate profile + drafts, then the owner email
    (commit.check_owner_email), (2) reject an empty name,
    (3) profile.save_to_yaml (write-then-rename, O_EXCL, fsync), (4) mark the
    session saved, (5) seed people, then link the owner email to the
    principal (best-effort), (6) reconcile departments, then save the goals
    (commit.save_onboarding_goals: period "year", no department unless one
    drafted is named, owner the named person else explicitly the principal,
    skipping any worded like a goal already set for this year or
    ongoing, so a re-run adds none; their
    titles also become strategic_priorities.current_year in step 3's
    profile via derive_org_structure), (7) fire the post-onboarding research
    workflow. A failure at 1-3 leaves the session
    untouched, so the user edits the draft and retries. This replaces the
    deepcopy-snapshot rollback the wizard needs (process_answer mutates state
    before the build can fail). A second commit returns 409, preserving the
    research-fire dedup guarantee.
  departments_are_additive: |
    THE key difference from the fixture path. cli/fixture_loader._seed_departments
    DELETEs every department and goal before inserting — correct when swapping
    in a demo company, destructive here: a re-run of setup would drop the
    departments the workspace already has, with their goals and
    specialist_key wiring. An unmatched draft is created with the specialist
    its name maps to (specialist_key_for_area) unless another department
    already has that specialist. onboarding/commit.reconcile_onboarding_departments
    instead matches each drafted department onto an existing one by slug or
    case-insensitive title (`departments.store.match_department`, shared with
    the create_goal chat tool), UPDATEs matches in place (preserving charter scope
    and specialist_key), CREATEs only what is unmatched, and never deletes. An
    empty drafted mission or head leaves the existing value alone rather than
    clearing it.
  people_and_contacts: |
    Exactly one person is is_principal (the user) and gets AuthorityScope.WILDCARD;
    nobody else gets a scope. PersonDraft uses extra="ignore" so an email or
    chat handle the model emits despite the system prompt is dropped at the
    model boundary — OE never auto-imports contacts, matching the fixture and
    engagement-intake invariants. Channels, availability and scopes stay a
    deliberate action on /people.
    The one exception is the owner's OWN sign-in email, and it never comes
    from the model: OnboardCommitRequest.owner_email is a separate field the
    review screen pre-fills from the signed-in session and the user confirms
    (or changes, when setting up for someone else). On a re-run the field
    starts from the CURRENT owner's email, not the re-runner's login, and
    Save waits until both have loaded (the commit is once per session).
    check_owner_email lowercases it and 422s — with fixed, non-echoing
    messages — on a malformed address, one already held by a non-archived
    person other than the drafted principal (two rows sharing an email would
    resolve sign-in to the older one; when that holder is the current
    principal the message says so, since a renamed owner is a new row under
    the name-keyed upsert), one that differs from the drafted principal's
    existing email (setup only FILLS IN a missing email: replacing it would
    sign the owner out and hand their seat to whoever re-ran setup), or a
    roster it cannot read. link_owner_email then saves it on the principal's
    row after the people seed, re-checking that it replaces nothing. Before
    this, the signed-in owner
    matched no Person, so `x-caller-email` resolved to nobody and their chat
    list stayed empty until they found the People page. Optional with
    local login, whose email-less session already resolves to the
    principal. "The drafted principal's row" is matched BY ID against the
    same name-keyed dict save_onboarding_people builds (two rows can share
    a name; the upsert takes the last), and link_owner_email also refuses
    an email another active row holds.
    Owner changes: the seed demotes the old principal and grants WILDCARD
    to the drafted one, and any signed-in user can open /onboard, so the
    commit route calls commit.owner_change_blocked before any write: when a
    principal exists and the draft's principal maps to a different row (a
    renamed owner included), the caller — resolved from x-caller-email; no
    header means the principal — must be the principal, else 403. Keeping
    the 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. One case is adopted, not refused: the
    address is the caller's own sign-in (api_caller.caller_email), it is on
    the current principal's row, and that row carries another name (a
    hosted sign-up seeds the owner's row from the address when no name was
    given; or an old spelling). check_owner_email(caller_email=...) lets it
    through and `adopt_owner_row` renames that row to the drafted name
    right before save_onboarding_people, so the name-keyed upsert updates
    the owner's entry instead of adding a namesake and then failing the
    email check with "use the owner's name exactly as on the People page".
    Guarded: never for another caller, never onto a name already on the
    roster, no-op when the names already match. 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 from
    the reviewed people and department tables at commit time
    (onboarding.commit.derive_org_structure). The draft-review screen therefore
    omits the Org Structure section (ProfileSections `omit={["org"]}`) — leaving
    it editable would give the user two places to edit the same list.
  uploads: |
    api/intake_uploads.py holds the attachment helpers shared with
    POST /clients/generate (8 files, 25MB each, .pdf/.docx/.doc/.xlsx/.xlsm/
    .csv/.md/.txt, text extracted via knowledge.loader). Extracted text is
    appended to the opening user turn, labelled per file.
  scope_note: |
    Onboarding drafts the profile, people and departments — NOT memory,
    documents or scheduled actions. Seeded "past decisions" invented from a
    five-minute conversation would be fabricated history in a real company's
    episodic store; the fixture generator may invent because it is building
    fiction. This gap is a decision, not an oversight.
  ui: |
    /onboard — app/onboard/page.tsx phase machine (describe -> confirm ->
    conversation -> draft -> voice -> done), components/onboard/
    {OnboardDescribe,OnboardConversation,OnboardDraftReview,OnboardPeopleDraft,
    OnboardDepartmentsDraft,OnboardDone}.tsx. First run: the owner (the
    principal, per /people/me) is sent to /onboard from Home and from every
    AppShell page except /settings while /health says no profile exists
    (useFirstRunRedirect; rule shouldRedirectToOnboard in lib/firstRun.ts),
    unless they pressed "I'll do this later" (localStorage `oe.onboard.later`).
    The done screen shows what was saved and the two accounts as two
    separate things: the Executive's own mailbox (its Google or Microsoft
    account; the morning brief comes from it) and, optional, the owner's own
    mailbox for Act as me. Home's banner slot then shows the getting-started
    checklist (GettingStarted.tsx; rows from gettingStartedItems: profile,
    first question, the two mailboxes read from /setup/status checks `gmail`
    and `your_gmail`, and in team mode the roster) until every required row
    is done or it is hidden (`oe.gettingStarted.hidden`); it outranks the
    no-profile banner and the quiet-day note. The draft screen reuses
    the /company-profile section editors via
    components/company-profile/ProfileSections.tsx, extracted for this purpose:
    the sections already took onSave as an injected prop, so onboarding passes
    one that merges into local draft state instead of PATCHing. Plain JSON
    POSTs with a typing indicator, no SSE — a clarifying question is one
    sentence, and the draft turn is a forced tool call whose partial JSON
    cannot be usefully streamed.
  solo_mode: |
    First run opens on a free-text box (components/onboard/OnboardDescribe.tsx).
    POST /onboard/interview/understand (onboarding/understand.py, forced
    report_understanding tool, uncached system text) reads the description plus
    extracted attachments once and returns mode, role_kind, role_title,
    reports_to, company and focus, each null when the text does not say. The
    confirm screen shows them; Personal / Team is required, the role fields
    (components/workspace/RoleFields.tsx, shared with Settings) are editable.
    Continue writes PUT /workspace ({mode, timezone}; the mode alone if the
    server rejects the zone, then the role via lib/principalRole.ts
    roleUpdate), refreshes the WorkspaceProvider, then calls
    /onboard/interview/start with the same text, so the interview already sees
    the saved mode and role and asks only about what is missing
    (MAX_QUESTIONS = 5). A failed read keeps the text and falls back to the
    Personal / Team choice. "Skip, I'll answer questions instead" goes
    straight to the confirm screen empty. `?for=me|team` marks the choice as
    made so moving between the conversation and the form does not ask again.
    The voice step (VoicePicker) comes last, after the draft is saved. A
    re-run (GET /health says a profile is loaded) skips the describe and
    confirm screens; they are changed in Settings, and the flow follows them.
    The conversation's opening prompt and example follow the role kind (owner:
    the business; in_house: the organisation, function, remit and manager;
    independent: the practice and clients; none: role-neutral).
    Interview: when get_workspace().mode == "solo", advance() passes solo=True
    and the workspace's role_kind to _build_messages, which prepends
    interview.solo_hint(role_kind) to the FIRST user turn (before the re-run
    profile block) — one static constant per kind, never the principal's own
    text. Every variant keeps `people` to only the principal with
    is_principal true and `departments` empty. SOLO_ROLE_HINTS["owner"] asks
    about the offer, customers, pricing, cash and runway; ["in_house"] says
    the company is their employer (draft the profile for it), adds no
    manager, peers or team as people, avoids cash/runway/fundraising as if
    the business were theirs, and asks about the organisation, their function
    and remit, who they report to, team size (context, not a roster) and what
    they are measured on; ["independent"] asks about the practice, clients
    and pricing; no kind or "other" gets the role-neutral SOLO_HINT, which
    asks which kind of principal they are. All ask their top goals.
    The system block (ONBOARDING_INTERVIEWER_SYSTEM) and the tool array are
    unchanged, so both caches hold across modes. A principal-only draft with
    no departments already passes validate_draft.
    Review: in solo OnboardDraftReview hides the people and departments
    drafts and shows a "You" card (name and role — the drafted principal,
    else the first drafted person, else blank; the role falls back to the
    role step's title) beside the owner sign-in email
    field; the commit sends that one person as principal and an empty
    department list, so save_onboarding_people creates exactly one Person and
    reconcile_onboarding_departments adds nothing — the seeded defaults stay,
    as the areas /goals groups goals by. The workspace settings live in their
    own table, so the commit's profile rebuild cannot wipe them.
    Form wizard: WizardState(solo=...) skips SOLO_SKIPPED_FIELDS
    (headcount_and_founding — the required Team Size step —, team_members,
    fractional_executives); current_step stays an index into WIZARD_STEPS so
    a step keeps its identity, and position() / total_steps() drive the
    progress label. The CLI wizard does the same.

fixtures:
  module: openexecutive.api.routes.fixtures
  intent: |
    A demo / development affordance. Lets a fresh install snapshot its
    current company/department/people/memory state, swap in a curated
    fixture (Shark Tank, nonprofit, SMB, mid-market SaaS), then unload
    back to the snapshot. Lets the system be demoed end-to-end without
    polluting any real installation.
  api: /fixtures — list, status, snapshot, reset, unload, load, generate, create, delete.
  storage: |
    HYBRID. The four curated fixtures stay as git-tracked YAML under repo-root
    fixtures/companies/<name>/. User-generated fixtures live in the
    generated_fixtures SQLite table (module openexecutive.fixtures.store) in the
    same episodic_memory.db on the persistent data volume, so they survive
    redeploys (container disk is ephemeral). GET /fixtures merges both sources; every list
    item carries source: "curated" | "generated".
  generation: |
    POST /fixtures/generate {description} runs the Council-configurable
    fixture_generator agent (forced emit_fixture tool call — module
    openexecutive.fixtures.generator) to author a full bundle: profile, people,
    departments (+goals), seeded memory (decisions, initiatives, advice,
    briefing alerts), and 5-7 company docs. The agent resolves its model +
    system prompt via the Agent Council (effective_model / effective_system_prompt),
    so the model is selectable in the Council UI and routes through OpenRouter
    when OPENROUTER_ENABLED — like quality_judge / utility_fast. The draft is
    validated against the canonical Pydantic models with cross-file referential
    integrity (every department head + alert recipient must be in the roster;
    exactly one principal) but NOT persisted. POST /fixtures {bundle,
    scenario_description} re-validates and saves it. Safety invariant: generated
    people carry NO contact handles and NO scheduled_actions are generated, so a
    generated company is inert — it never emails/DMs or fires the scheduler.
  loading: |
    load_fixture_any() resolves a name to either the curated dir or, for a
    generated fixture, materializes the stored bundle into a temp directory and
    loads it through the identical _apply_state_from_source path (same
    auto-snapshot, active-fixture sentinel, and Honcho workspace behavior).
  delete: DELETE /fixtures/{name} soft-deletes a generated fixture; curated fixtures cannot be deleted.
  factory_reset: Wipes live state AND the auto-snapshot so the install returns to a true clean state.
  monitoring_state: |
    The external-monitoring tables (watchlist + external_signals) are NOT
    part of the snapshot round-trip — they're regenerated by the
    executive_research scan and external monitor. Load, unload, and reset
    all clear them (external_signals before watchlist, per the FK) so every
    fixture and the restored user state start with a clean watchlist instead
    of inheriting the previous company's monitors.
  packaging: Fixtures are copied into the API Docker image so demos work in deployed environments.
  solo_fixture: |
    fixtures/companies/solo_studio (Tallgrass Studio, a one-person design
    studio) is one example of a solo principal — an owner; solo principals
    can equally be executives inside larger organisations or independents.
    people.yaml holds only the principal (its owner, wildcard),
    departments.yaml four areas (strategy, finance, marketing, product)
    headed by the principal with one or two goals each and no cadences,
    workspace.yaml sets mode: solo and the owner's role (role_kind owner,
    title, remit, measured_on), and memory.json seeds decisions and
    initiatives with no scheduled actions. Its evals are the built-in
    solo_001..003 scenarios (solo_004 and solo_005, in-house executives,
    need no fixture).
  client_interplay: |
    Loading a fixture while a client slot is active first saves that client
    back to its slot and clears the active-client sentinel (leaving client
    mode for demo mode), so a demo can never destroy client work. unload is
    also the "exit client mode" path: it save-backs an active client before
    restoring _user_backup. reset clears the active-client sentinel but
    PRESERVES slot directories — deleting a client is its own deliberate
    DELETE /clients/{slug}, never a side effect.

clients:
  module: openexecutive.clients
  intent: |
    Named client-company slots — multi-client support for fractional
    executives. One OE instance serves several client companies, exactly one
    active at a time. A slot is an on-disk save file of the FULL company
    context; activating a slot saves the current client back to its slot and
    restores the target. Single-company installs never touch this: the
    /clients page shows only an intro until a slot is explicitly created, and
    no default behavior changes.
  api: |
    /clients — GET list (+active +fixture_active), POST create
    {display_name, slug?, source: current|blank|generated, bundle?,
    intake_description?}, POST /clients/generate (multipart: `description`
    form field + optional `files` attachments; grounded AI draft from intake
    notes and/or files — returns a reviewable bundle + suggested slug,
    persists nothing), POST /clients/save (checkpoint active slot without
    switching), POST /clients/{slug}/activate, DELETE /clients/{slug}
    (refuses the active slot).
  engagement_intake: |
    The engagement-setup path: POST /clients/generate runs the
    Council-configurable engagement_intake agent (module
    openexecutive.agents.engagement_intake — the grounded sibling of
    fixture_generator, same FixtureBundle schema / validation / repair-retry
    via fixtures.generator._generate_bundle, OUTSIDE SPECIALIST_REGISTRY).
    Grounding rules: extract-don't-invent (unstated numerics stay null),
    only people named in the intake material, docs are engagement working
    documents (intake brief, current-state, stakeholder map, open
    questions), memory seeds only stated decisions/initiatives, and NO
    contact handles even if present in the notes — contacts are added
    deliberately via /people later. The demo fixture generator is unchanged
    and remains the Company Simulator's fictional path.
    Intake material can be pasted text AND/OR file attachments
    (PDF/Word/Excel/CSV/Markdown/text; legacy .xls unsupported). The route
    extracts each file's text via knowledge.loader.extract_text_from_file
    (xlsx/csv added there), feeds a per-file-capped slice into the draft
    prompt, and appends the fuller text to the bundle's docs as
    `source_<name>.md`. Those flow into the seed slot like any generated doc
    and are indexed into company_docs on activation — i.e. attachments become
    retrievable company docs (extracted text, not the original binary).
  seed_slots: |
    source="generated" writes a SEED SLOT: profile.yaml + docs/ as normal
    slot artifacts, plus people.yaml / departments.yaml / memory.json (the
    same shapes curated fixtures use, via bundle_to_serialized +
    materialize_to_dir). No state.db; live state untouched; not activated.
    On first activation the blank-restore path applies the seed files with
    the fixture loader's seeders (people → memory → departments, so heads
    and assigned ids resolve by name); no default departments are added
    (brief/cadence bootstraps still run and pick up the seeded
    departments). After the first save-back
    writes state.db, the seed files remain as the engagement's birth record
    but are no longer consulted. meta.json records origin="generated" +
    the intake_description.
  slot_contents: |
    company/_client_slots/<slug>/ (gitignored — client data is never
    committable): state.db (VACUUM INTO copy of the shared episodic_memory.db
    — chat history, scheduled actions, departments, people, watchlist,
    audit/runs), profile.yaml, docs/ (all file
    types), skills/, mcp_servers.json (per-client external MCP tools, e.g.
    one client's Crayon credentials), meta.json (display name + timestamps).
  restore_mechanics: |
    DB restore goes through sqlite3's online backup API into the live
    connection's file (inode never changes, so handles held elsewhere stay
    valid); saves use VACUUM INTO for a transactionally-consistent copy.
    After a restore the idempotent schema initializers re-run (a slot saved
    before a schema-adding deploy lacks new tables), the ChromaDB
    company_docs collection + company-authored skills are re-indexed from
    the restored dirs, and recent_research artifacts are wiped (same rule as
    fixtures: per-company research never crosses companies). Activating a
    blank slot (no state.db yet) factory-wipes the per-client tables and
    re-seeds defaults (departments, principal briefs, cadences) so the new
    client's Today works without a process restart.
    Wipe lists must cover the DERIVED CACHES, not just authored state.
    briefing_narrative and person_insights were wiped by NO path, and because
    /today serves the cached narrative unconditionally (regenerating only in a
    BackgroundTask), whichever path swapped the company rendered the OUTGOING
    one's narrative under the incoming one. Do not assume person_insights'
    input_hash self-guards: that hash covers role, is_principal, status,
    awaiting/reply counters, overdue, on_leave_until, reachable_now,
    authority_scope, department_slugs, four hour-bucketed timestamps and the
    UTC day — all per-person signals, and NOT person, name or company
    identity. The key is a reused autoincrement person_id, so an outgoing
    principal and a freshly seeded incoming principal hash identically
    whenever those signals coincide. Ordinary steady state, not a collision.
    THREE paths swap live company state and each kept its own hand-written
    table list, which is why fixing one left the leak live in the other two.
    They now all consume `cli.fixture_loader.PER_CLIENT_CACHE_TABLES`:
    `clients.slots._BLANK_WIPE_TABLES` (switch into a blank/seed slot),
    `reset_all_state` (factory reset), and `_apply_state_from_source` (fixture
    load AND unload — the worst surface, since a demo is what gets
    screen-shared). The fixture-path wipe sits in `_apply_state_from_source`
    beside the unconditional watchlist wipe, NOT in `_seed_episodic_memory`:
    that seeder returns early when a fixture has no readable `memory.json`,
    and `load_fixture` only requires `profile.yaml`, so a wipe inside the
    seeder is skipped on exactly those loads while the company still swaps.
    Client→client switching into a slot that HAS state.db was already safe:
    the sqlite backup API truncates the destination to an exact copy.
    Add any new per-company cache table to that constant, once.
    Graded as NOT wiped: generated_fixtures (operator-level, see
    _GLOBAL_TABLES) and architecture_sections (repo-derived, keyed by a hash of
    the facts file). Still UNGRADED, deliberately deferred: dynamic_workflows
    and eval_scenarios. These ARE client-scoped — the non-blank path already
    swaps them with the whole DB — and on the blank path the outgoing client's
    workflow definitions stay registered AND active (`list_definitions(
    active_only=True)`), runnable against the incoming client's data, with full
    bodies exposed via /workflows. They are not in the wipe list because they
    are authored, not derived, and `snapshot_user_state` (the first-activation
    branch, when no client is active) captures only profile/docs/memory.json/
    people/departments — so wiping them there would irrecoverably delete the
    operator's own work. The fix is to capture them in that snapshot FIRST,
    then wipe. Both tables were observed empty on all known installs as of
    2026-09 — an observation at a point in time, not an invariant to rely on.
  invariants:
    - At most one slot is active; the .active_client sentinel records it
      (allowlist-validated on read, same defence as the fixture sentinel).
    - Only the active client is live — its scheduled actions fire, its docs
      are indexed. Parked clients sleep. (The single-instance scheduler
      constraint is unchanged; multi-workspace concurrency is explicitly a
      later phase.)
    - Slot ops share the fixture switcher's destructive-op lock
      (_FIXTURE_OP_LOCK) — fixture loads, snapshots, resets, and slot
      switches serialize against each other. The Notion sync tick
      coordinates with the same lock without queueing on it — it skips the
      tick when the lock is held, fetches from Notion unlocked, then takes
      the lock only for its short local write phase, aborting (no writes)
      if the active client changed while it was fetching. In-process only —
      a CLI run is a separate process the lock cannot see (known
      limitation).
    - A fixture and a client are never active simultaneously - slot ops
      refuse (409) while a fixture is loaded.
    - generated_fixtures is operator-level (the demo library), not client
      data — preserved verbatim across slot restores.
    - executive_control (the operator pause switch, scheduler.pause) is
      operator-level too and preserved the same way — activating a client
      never un-pauses (or re-pauses) the Executive.
    - workspace_settings (solo/team mode + the user's time zone,
      memory.workspace_settings) is per company, NOT operator-level - a
      saved slot carries its row in state.db and a blank slot's wipe
      (_BLANK_WIPE_TABLES) returns it to the defaults before the briefs and
      cadences are re-seeded.
    - Act as me's tables (delegation.schema.TABLES - delegation_settings,
      delegation_voice, delegation_voice_history, delegation_drafts,
      delegation_inbox_watch, delegation_inbox_messages) are per company
      too - in _BLANK_WIPE_TABLES and reset_all_state - so a blank client
      starts with it off, no writing profile and no inbox watcher. The
      watcher never scans while a slot is active. The per-person Gmail
      credential is a file outside the slot, re-checked against the live
      roster on every use, and no verbatim exemplars are learned while a
      slot is active.
    - First activation with no active client auto-snapshots the user's
      original company to _user_backup (same restore point the fixture
      switcher uses; POST /fixtures/unload brings it back).
  honcho: |
    Each client gets a STABLE Honcho workspace override
    (openexec-client-<slug>, no uuid) so per-person peer memory persists
    across park/reactivate. The fixture loader's teardown paths and the
    startup reconcile recognise the openexec-client- prefix and never delete
    or clear these the way they do sacrificial per-fixture demo workspaces.
  caveats: |
    mcp_servers.json is read by the MCP gateway at process startup, so a
    client switch that changes it takes effect on the next API restart (the
    activate response carries mcp_config_changed and the UI surfaces it).
    Scheduled actions restored from a parked slot whose run_at passed while
    parked are claimed on the next tick after activation — authority gates
    still apply, but expect the active client's overdue follow-ups to fire
    shortly after a switch.
  ui: /clients page (Settings → advanced tools). Create from current company or blank, activate (auto-saves the previous client), save-now checkpoint, delete with confirm, per-slot engagement-details editor, and the practice cockpit board (2+ slots only).
  engagement_metadata: |
    Practice-level fields on meta.json (PATCH /clients/{slug}, allowlist
    ENGAGEMENT_META_FIELDS in clients/slots.py): role, status
    (active|paused|winding_down|completed), engagement_start, renewal_date,
    retainer (display only — billing stays external), hours_per_week,
    primary_contact, notes. Editable for active AND parked slots because
    meta.json is deliberately OUTSIDE the swapped client state. Invariant:
    renewal awareness lives here, never as scheduled_actions — those swap
    with the client and would vanish when parked.
  rotation: |
    Overnight client rotation (cockpit v2 — module
    openexecutive.clients.rotation, scheduled kind client_rotation). OFF by
    default (CLIENT_ROTATION_ENABLED; time via CLIENT_ROTATION_TIME, HH:MM
    UTC, default 03:30). At the window: activate each parked slot in turn
    (skipping completed engagements and never-activated slots), generate
    that client's morning_brief as a workflow artifact (NEVER delivered
    from the parked context), run its external monitor scan when monitors
    are enabled, save back, and ALWAYS restore the original active client
    in a finally. Per-client failures are recorded and skipped. After
    restore, a cross-client digest composed from the fresh cockpit is
    delivered once via the original client's principal path. Safety rails:
    (1) a .rotation_in_progress marker in the slots root is the single
    source of truth — the scheduler loop PAUSES CLAIMING while it exists
    (otherwise the next tick would fire the just-activated client's overdue
    outbound backlog at 3am), and the /clients UI shows a banner from the
    same flag; stale markers are cleared at scheduler boot. (2) the
    rotation row swaps with the client like all scheduled_actions, so it is
    idempotently re-seeded at boot AND after every slot activation.
    Documented residual race: actions claimed in the same tick as the
    rotation row run concurrently with the first switch — same exposure as
    a human switching mid-action, rare at a 03:30 window.
  value_report: |
    The engagement_value_report workflow (see workflows.notable_recent) is
    the renewal artifact: what the executive did for THIS client over a
    period, generated from the engagement's own record. Cockpit cards with
    state carry a "Value report" link that deep-links the /jobs runner with
    the client_slug prefilled (base64url prefill param). Parked clients are
    read from their slot without activation.
  cockpit: |
    Cross-client practice board (module openexecutive.clients.cockpit, GET
    /clients/cockpit). Per-slot rollup cards: the ACTIVE client is counted
    from the live DB; PARKED clients are counted by opening their slot's
    state.db read-only IN PLACE (sqlite file:...?mode=ro URI — no
    activation, no lock, cannot block or be blocked by a switch). Counts:
    pending + overdue scheduled actions, awaiting replies, unread alerts,
    plus engagement metadata and
    days_to_renewal. Honesty contract: parked data is as fresh as the
    slot's saved_at (stamped on every card); a broken slot degrades to one
    error-flagged card, never a failed board. Every table query is
    existence-guarded (slots saved before schema-adding deploys). /today
    gains an additive practice_clients section (parked clients only,
    format_practice_for_today) gated on 2+ slots — single-company installs
    see nothing anywhere. Deliberately NOT doing periodic autosave: the
    active card is always live-fresh; parked staleness is inherent until
    the v2 overnight-rotation phase.

delegation:
  module: openexecutive.delegation
  intent: |
    Act as me — the one place the Executive writes AS a person instead of as
    itself. Everywhere else it has its own Google account and bots and signs
    as itself. Here, only when the person asks — or, with the second switch
    (Draft replies to my inbox), for mail in their inbox that needs them —
    it writes an email in their voice and saves it as a DRAFT in their own
    Gmail for them to review and send. The only thing it ever sends is one of
    those inbox drafts, exactly as it is in Gmail, when the person taps Send
    on its card (delegation.send), or a draft chat wrote as them when they
    tap Send under it in the chat (delegation.send_chat_draft); no tool
    sends. The principal may turn
    it on, and each team member once the owner lets them. Off by default; off changes nothing —
    prompts, tool lists and prompt caches are byte-identical to an install
    without it.
  who: |
    delegation.settings.can_delegate(person) is the single rule: a
    non-archived team member (never a contact) who is the principal, or any
    other one once team_members_enabled(): the install allows it
    (DELEGATION_TEAM_MEMBERS, default off — it offers the owner the switch)
    AND the owner turned on "Let team members use it" (PUT /delegation/team,
    principal only; one row in delegation_team, absent = off). Off again
    takes it away from every team member from their next message; their
    inbox watchers stop at the next check (act_as_me_off), and their own
    switches, drafts and cards are kept. The ghostwriter's prompt is a
    constant outside the Council, so the /agents and /personas edit routes
    (no principal check) can't change how anyone's draft is written. A
    person turns it on for themselves (PUT /delegation); nobody turns it on
    for anyone else. delegation_settings holds one row per
    person; missing, unreadable or 0 is off (is_enabled never raises).
  turn_pin: |
    pin_turn_delegation(session, speaker_text) runs at the start of every
    chat turn (stream_chat and the committee path, beside
    pin_turn_workspace_mode) and pins a TurnDelegation on
    Session.turn_delegation — enabled, offered, touched_mail, drafts,
    speaker_text, person_id — read fresh every turn, so switching it off
    applies from the next message. offered requires ALL of: can_delegate and
    enabled for the speaker; the speaker verified on this surface —
    is_principal_on_verified_surface(session) for the principal,
    teammate_on_verified_surface(session) naming that same person for a team
    member (web chat signed in, own Slack or Discord, verified Telegram;
    never an email turn); on the web,
    Session.web_caller_signed_in (the request carried x-caller-email) or
    local login (utils.deployment.is_local_login, the same function api.main
    uses) — a request with no caller header is not a sign-in and never gets
    it, while the header itself is trusted from whoever holds
    BACKEND_SHARED_SECRET (the UI proxy), as on every principal-only route; a
    conversation private to the speaker (the web chat, a Slack or Discord DM
    by session id slack:dm: / discord:dm:, a verified private Telegram chat)
    and never a shared channel or thread, where the draft's preview and the
    matching threads would be posted for everyone and other people's
    messages sit in the model's context; and a turn that is neither
    unattended nor private_to_principal (the email poller), so inbound text
    never reaches it. The pin is also set in a ContextVar for the turn's
    task (turn_delegation prefers it when it names the same session), so two
    turns running at once on one session each read their own. The Gmail connection is
    NOT part of the offer (the handler checks it per call), so the cached
    tool prefix never flips when a token lapses. speaker_text is pinned
    because the turn's message joins the session history only after the
    turn, and a draft's address typed this turn needs no check — outside any
    tag block an adapter added (settings.typed_addresses drops the
    <outbound_reply_context> backstory hydrated into a DM, and counts none
    at all when the message carries an attachment — an "[Attached: …]"
    document label or a "(Attached …" / "(Skipped …" / "(Could not …" note,
    matched anywhere: none has an end mark, and a filename is chosen by
    whoever sent the file).
    Session.delegation_override (evals and tests only) replaces the speaker,
    the setting and the mailbox with a fake; the surface checks are skipped
    and the tool is offered only when a fake mailbox is supplied.
  tool: |
    ghostwrite_email (orchestrator.delegation_tools), input {intent,
    thread_id?, find?, to?, reply_all?}. Own registry DELEGATION_TOOLS /
    DELEGATION_TOOL_HANDLERS, NEVER _ALL_SKILL_TOOLS (reflection, research,
    workflows and tests enumerate that list). _stream_agent_loop adds it to
    the pool before the sort and builds a per-turn handler map only when the
    pin says offered; otherwise a call is an unknown tool. The handler
    re-checks the pin and (without an override) the verified surface, then
    the caps — 5 drafts per turn, and DELEGATION_MAX_DRAFTS_PER_DAY (default
    50, at most 1000) per person per UTC day, shared with the inbox watcher
    (delegation.caps.reserve/release). The day is counted from
    delegation_drafts (delegation.drafts: one row of ids per saved draft —
    person_id, source chat|inbox, thread_id, draft_id, message_id,
    sent_message_id, created_at, gone_at; never an address, subject or text), with an
    in-process count as a floor in case a row was lost, refusing when they
    cannot be counted. The handler records its row (source chat) after the
    draft is saved, best effort.
    Each slot is reserved synchronously before the first await and handed
    back when nothing was drafted: _stream_agent_loop gathers a round's tool
    calls, so a check-then-count-later cap let every parallel call through.
    Then it sets touched_mail BEFORE the first mailbox read and runs
    gmail_status. A search with several matches returns status choose with
    candidates (subject, sender, date; no text) and drafts nothing.
    Recipients are decided in code: a reply goes to the last inbound From,
    never Reply-To (flag reply_to_ignored), with cc only on reply_all (minus
    the writer and the sender; beyond 10 trimmed and flagged cc_trimmed);
    References from gmail.references_header — whole ids only, the parent
    last, the oldest after the root dropped to fit one header; a new email
    or a forward may go to any well-formed address (_new_recipients): it is
    only a draft in their own mailbox, and they see who it is to before
    they send it. An address neither on the roster (contacts only when
    contacts_reachable_now) nor typed in speaker_text comes back in
    not_in_people with check_address, and the persona names it for them to
    check. Result {status drafted, draft_id, gmail_link, to, cc,
    subject, preview, flags, open_questions, note}; the link is built from a
    fixed https://mail.google.com/ prefix and the note marks the preview as
    data. action_chips gives it a chip only for status drafted.
  read_before: |
    my_email_read_before (orchestrator.mail_read_tools) lists the threads
    read_my_email opened for the same person before, in any conversation, so
    a later one reopens the email with read_my_email instead of asking them
    to search again (where, never what). delegation.mail_reads keeps one row per (person_id,
    mailbox, thread_id) in delegation_mail_read: subject and first sender as
    one line each (160 chars), the mailbox address and read_at; never text,
    attachments or recipients. Listed only for the speaker and the mailbox
    open now, newest first, optional words matched against subject and
    sender; rows older than RETENTION (30 days) are never listed and are
    pruned on the next write, MAX_ROWS (200) per person, and PUT /delegation
    with enabled false deletes the person's rows. It runs through _run like
    the other reads (a search slot, _open_mailbox, touched_mail) and its
    result carries the data-not-instructions note. recording is best-effort:
    a failed write never fails read_my_email. The Act as me addendum says the
    person's mailbox is not the Executive's: search theirs for mail sent to
    them and never fall back to the Executive's own mailbox (it holds mail
    private to the principal, and any speaker may be asking).
  reads: |
    search_my_email, read_my_email, read_my_email_attachment and
    my_email_awaiting_reply (orchestrator.mail_read_tools) read the
    speaker's own mailbox from chat.
    They sit in DELEGATION_TOOLS / DELEGATION_TOOL_HANDLERS beside
    ghostwrite_email, so they are offered, re-checked (_writer: the pin and
    the verified surface) and locked down exactly as it is, and every call
    is in DELEGATION_TOOL_NAMES (private rows, the round counts as touched).
    Read-only: nothing is changed, labelled, drafted or sent. Each takes a
    per-turn slot on the pin before the first await — 10 searches
    (TurnDelegation.searches; my_email_awaiting_reply counts as one), 20
    thread reads (threads_read) and 5 attachment reads (attachments_read) — then _open_mailbox (shared with
    ghostwrite_email) sets touched_mail, marks the conversation
    mail_private and runs gmail_status. search_my_email: a Gmail-style
    query through the client's search_threads (Outlook translates it), or
    with no query the newest message of each thread that reached their
    Primary/Focused inbox in the last 3 days (inbox_message_ids +
    get_message); summaries only (thread_id, subject, from, date), each on
    one line. read_my_email: the thread's last 10 non-draft messages, each
    sender's new text (sender_new_text, plain) cut to 4000 characters; a
    message someone else wrote is wrapped in its own untrusted_content block
    (content_trust.wrap_untrusted, source email), the speaker's own (SENT and
    from their address, threads.mine) is marked Yours outside any block.
    my_email_awaiting_reply: their list_sent (40) from the last 14 days, at
    least a day old, to 1-10 people besides themselves and the Executive
    (follow_ups.recipients), whose thread still ends with it. Results carry
    a note that other people's words are data. Audit input and result are
    redacted (my_email is a sensitive tool-name substring).
    Attachments: read_my_email lists each shown message's files (message,
    message_id, index, name, type, size_kb) — Gmail's from the message
    (gmail._attachment_parts: parts naming a file, but an image with a
    Content-ID the HTML shows in place), Outlook's from list_attachments only
    when hasAttachments (Graph /attachments, isInline left out).
    read_my_email_attachment(message_id, index) lists afresh, refuses a type
    outside READABLE_SUFFIXES (pdf, docx, doc, xlsx, xlsm, csv, md, txt, rst)
    or over 20 MB before downloading, then attachment_bytes looks the
    provider id up on that fetch (Gmail's attachment id changes per fetch;
    a small Gmail part's data is inline) and reads it.
    attachments._extract_text (isolated worker for pdf/doc/xlsx, scanned PDFs
    converted under the inbound page budget) and format_attached_text (an
    untrusted_content block, source attachment, 15,000 characters). Never
    build_attachment_output: that would add the person's private file to the
    company knowledge (_schedule_ingest).
    The lockdown refuses tools, not reply text, so the ways reply text
    leaves without a click are closed where it is shown: Message.tsx loads
    only root-relative images (lib/markdownImages.loadsInline; any other is
    a link), Telegram sendMessage sets link_preview_options.is_disabled,
    Slack's reply say passes unfurl_links/unfurl_media False, and every
    Discord reply send passes suppress_embeds=True.
  save_file: |
    save_my_email_attachment(message_id, index) (orchestrator.mail_read_tools,
    orchestrator.mail_file_save) copies one attached file of the speaker's
    own mail into the storage the Executive has connected and shares it with
    them alone, returning {status saved | saved_not_shared | failed |
    no_storage | too_large, name, where, link}. Only when they asked in their
    own words this turn: own_words of speaker_text must hold one of
    _SAVE_WORDS (save, saved, upload, onedrive, or drive after to/in/into/on/my/your/google), checked before
    the slot (TurnDelegation.files_saved, SAVES_PER_TURN 10) and before the
    mailbox is opened; else status not_asked. Bytes via
    mailbox.attachment_bytes, never the model; any type, MAX_ATTACHMENT_BYTES
    (20 MB) checked on the listing and on the bytes; clean_name strips
    path/reserved/control characters and keeps the extension. Storage
    (storage_for): EMAIL_PROVIDER's server when the gateway has it and it
    doesn't need a reconnect, else the other; neither, or an eval mailbox
    (ScenarioMailbox.saves_to_storage False): status no_storage, the model
    offers to forward instead. Folder: always made by the save
    (create_drive_folder / create-onedrive-folder "From your email"), never
    found by search or listing (a folder anyone made with that name could
    already be shared with them), its id kept in delegation_saved_folder
    (provider, account, folder_id, drive_id, created_at, current). When the
    remembered folder is gone or refuses the file, forget_folder marks it not
    current (the row stays, still protected) and a new one is made. Google:
    create_drive_file (base64_content, content_mime_type, base64_sha256; never
    fileUrl); manage_drive_access grant, share_type user, role reader,
    send_notification false, share_with the speaker's address. Microsoft:
    list-drives (personal or business drive), upload-file-content to
    "<folder>:/<free name>:" (an upload overwrites, so a name any recorded
    copy has, saved_files.names, becomes "name (2).ext"; the folder is never
    listed), share-drive-item with one email recipient, roles [read],
    requireSignIn true, sendInvitation false. One save at a time per event
    loop. Lockdown: in MAIL_TOUCHED_ALLOWED_TOOLS; its calls pass the
    mail-read refusal in MCPGateway.call_tool only as the exact objects held
    in code_built_call (identity, one of the seven _CODE_BUILT_TOOLS:
    create_drive_folder, create_drive_file, manage_drive_access, list-drives,
    create-onedrive-folder, upload-file-content, share-drive-item), so a model
    call on that turn is still refused; every other gate (acting account, URL
    fetch, sheet formulas, _check_drive_share / _check_m365_drive_share roster
    check, _check_m365_drive_write own drives) still runs. Not in
    PRIVATE_TURN_WITHHELD_TOOLS: it is never offered on a private-to-principal
    turn (Act as me isn't), and a later turn of a mail-private conversation
    may use it. Privacy (delegation.saved_files, table
    delegation_saved_files: person_id, provider, file_id, name, saved_at;
    recorded before the share; first owner kept): on every Google Workspace /
    Microsoft 365 call the gateway reads protected(viewer_person_id())
    (viewer = the pinned speaker when Act as me was offered, else None = all
    files hidden; the DB opened read-only, a missing DB or table = none). It
    refuses a call whose arguments name a file not the viewer's, and
    _hide_saved_files drops JSON list entries, then lines, naming one and
    masks any left. Folders, on every turn and for every speaker including
    the owner: a model call whose arguments name any recorded folder id, or
    (Microsoft) an item path through the folder name ("root:/From your
    email/x.pdf:", matched case- and space-insensitively after URL
    decoding; "<folder id>:/x.pdf:" is caught by the id), is refused, and
    _hide_saved_folders drops entries and lines naming a folder id and masks
    any left; only code-built calls skip both. Record failure after the
    upload: saved_files.quarantine hides the copy's id from every turn for
    the life of the process, nothing is shared, status failed, logged at
    error. A lookup failure refuses tools matching _FILE_TOOL_RE (drive,
    folder, file, download_bytes, doc, sheet, slide, presentation) and leaves
    mail and calendar unfiltered. Limits: ids are matched as text (a title
    without its id still shows), a copy someone makes is a new file, the
    quarantine does not survive a restart, sharing a whole drive root is not
    covered, and anyone signed in to the Executive's account outside the app
    sees everything. Rows are not deleted when Act as me is turned off.
    Persona: the DELEGATION_ADDENDUM tells the model to use it once per file
    when asked to save or upload a file and to give them the link.
    Eval: delegation_014.
  calendar: |
    Read my calendar (delegation.calendar, table delegation_calendar, one
    row per person, absent/unreadable = off). On the Act as me sign-in:
    Google calendar.events, Microsoft Calendars.ReadWrite, added by
    connect-own-gmail.py / connect-own-outlook.py --calendar; the only
    write is answering a meeting invite (see invites). A sign-in minted
    earlier with calendar.readonly / Calendars.Read keeps reading
    (CALENDAR_READ_SCOPES, CALENDAR_SCOPES) and its invite cards say to
    connect again (calendar_write_granted False). Optional
    scopes: the token refresh still requires only the mail ones; the
    clients keep the scope string the refresh returns (_GRANTED) and
    list_events raises CalendarNotGranted (a GmailError, not an auth error)
    before calling when it is missing, or on a 403. An Outlook refresh asks
    for Calendars.ReadWrite (or Calendars.Read for an older file) only when
    the credential file's scopes list it (_refresh_scope); a mail-only one
    never asks, so its refresh can't fail on it. PUT /delegation/calendar
    {enabled}: on needs Act as me on, gmail_status connected and a one-hour
    list_events that works (409 act_as_me_off / calendar_not_granted, 503
    calendar_error); off always works; Act as me off turns it off;
    delegation_calendar_changed audit, private. GET /delegation carries
    calendar {enabled, connect_command (provider's command + --calendar)}.
    my_calendar (mail_read_tools, in MAIL_READ_TOOLS so DELEGATION_TOOLS,
    MAILBOX_TOOL_NAMES, the lockdown allow-list and the my_calendar
    redaction substring): refuses calendar_off before anything opens, then a
    searches slot, _open_mailbox (touched_mail, read_mail), events from
    start (default today) for 1-31 days in get_user_timezone, singleEvents /
    calendarView, cancelled and working-location left out, one-line fields,
    data-not-instructions note. Nothing kept. The Act as me addendum names
    it and says reading the calendar counts as reading their mail.
  invites: |
    Meeting invites (delegation.invites), only with Read my calendar on
    (watching = calendar.enabled); off, an invite is skipped "automatic" as
    before. In inbox._consider, a message with calendar_invite goes to
    invites.skip_reason (the watcher's rules less the reply-writing ones:
    a calendar service's Sender header is not "automatic", no recipient
    cap, no you_replied/draft_exists) then invites.consider. No model call.
    Sender: inbox.relation_of + handling_relation; a stranger or an
    unverified known sender is skipped invite_stranger / invite_unverified.
    Event: mailbox find_invite (Gmail: the invite's iCalendar UID from its
    text/calendar part, gmail.ics_invite, or its attached .ics, then
    events.list?iCalUID= on the primary calendar; Outlook: GET
    /messages/{id}?$expand=microsoft.graph.eventMessage/event, only
    meetingMessageType meetingRequest). Skipped with reasons
    invite_not_found, invite_not_organizer (organizer != From),
    invite_answered, invite_past, invite_calendar_not_granted. A calendar
    GmailError (not auth / rate limit) is retried later without backing off
    the mail scan. Clashes (invites.clashes): calendar.events_for over the
    meeting's window, other events' start/end only (never titles), the
    meeting itself and declined / all-day events left out; None when
    unreadable (clash_checked False). Card: delegation_invite decision,
    approver_only, never an alert, payload private + event_id, title, start,
    end, clashes, can_answer (calendar_write_granted is not False),
    connect_command when it can't; idempotency key
    delegation_invite:<person>:<message_id> via invites.create_once, which
    also fixes reply cards: an open card under the key is that card, a
    settled one gets a new card under key:<uuid>. Ledger outcome
    invite_card, then accepted / declined / dismissed / expired. GET
    /delegation/invites lists them (no calendar call). Approve =
    invites.answer: caller_refusal (403 not_yours / 409
    caller_signing_required), Act as me + Read my calendar on, live (start
    ahead, under CARD_TTL 7 days), gmail_status connected,
    claim_for_execution, mailbox.answer_invite(event_id, accept) — Gmail GET
    event, set the self attendee's responseStatus, PATCH attendees with
    sendUpdates=all; Outlook POST /events/{id}/accept|decline
    {sendResponse: true}. CalendarWriteNotGranted -> release, can_answer
    False on the card, 409 calendar_write_needed; GmailNotFound -> failed,
    409 gone; other GmailError -> release, 502 calendar_error (answering is
    idempotent). Reject answers nothing. On its own (invites.refusal, plain
    code): Handle it for me on; relation in KNOWN_RELATIONS; Replies in
    training -> training.allowed_inviter (key
    act_as_me|person:<id>|invite_from|<address>, setting replies), else
    Take the lead as you or the dial's level; signing_ok; clash None ->
    calendar_unread, any clash -> clash; can_answer; not sensitive(title);
    lead rules; handle_it.count_refusal (daily limit, once a day per
    thread). Then gate auto_execute, claim, answer_invite(accept=True),
    finish executed, record_handled; any failure releases and hands the
    card back. Never declines on its own. handle_it.handled includes them
    (source invite, summary "Accepted <first>'s <title>, <when>"), so GET
    /delegation/handled and Today's sent_as_you show them. Audit, private:
    delegation_invite_carded / _answered / _handled / _dismissed.
  forward_and_remind: |
    ghostwrite_email takes forward (a thread id) with to: a draft forwarding
    the thread's latest non-draft message, intent the note above it (the
    ghostwriter writes the note only), recipients by _new_recipients
    (any address; not_in_people names ones to check), subject "Fwd: ...". DraftSpec.forward
    (gmail.ForwardOf: message id, header block, the sender's own words).
    Gmail: build_raw quotes the header and text under the note and attaches
    DraftSpec.attachments; create_draft fills them from the original
    (attachment_bytes), at most FORWARD_MAX_FILES 10 and FORWARD_MAX_BYTES
    20 MB, counting the rest in CreatedDraft.skipped_attachments (flag
    attachments_left_off). Outlook: POST /messages/{id}/createForward with
    the note as comment and only recipients and the ghostwritten property
    in message; the body is never patched.
    drive_files (a new email or a reply, never a forward; the principal
    only): up to 15 Google Drive file ids (drive_attach.MAX_FILES). orchestrator.drive_attach sizes
    each with a code-built google_workspace__get_drive_file_permissions and
    downloads it with a code-built google_workspace__get_drive_file_download_url
    (both in mcp_gateway._CODE_BUILT_TOOLS) as the Executive's account. The
    saved copy comes only from one anchored "Saved to" line whose file name
    ends in workspace-mcp's uuid (the Drive name echoed above it is chosen by
    whoever shared the file), is read only inside the tool download folders,
    deleted, and its bytes go in DraftSpec.attachments under the forward
    caps, named from the saved name. Nothing of the file reaches the model,
    so it is no outside read; after an outside read the result asks the
    model to name each file. Someone else's saved_files entry or a save
    folder is refused before and after the downloads (fail closed); a failed
    fetch makes no draft. Outlook uploads each file to the new draft (fileAttachment, at
    most OUTLOOK_ATTACHMENT_MAX_BYTES 3 MB, larger left off and counted)
    and deletes the draft if an upload fails.
    remind_me(text, when) (orchestrator.reminder_tools) is in
    DELEGATION_TOOLS but not MAILBOX_TOOL_NAMES: it opens no mailbox and
    never sets touched_mail/read_mail. delegation.reminders.clean_text makes
    the text one line, replaces anything a chat app could link (a URL of
    any scheme, an address, a domain-like word, host:port, IPv4) with
    [link], caps 300; when
    is read in the workspace timezone (a date alone is 9:00), at least a
    minute ahead and within a year. Caps: TurnDelegation.reminders 5 a turn,
    MAX_PENDING 25 waiting; refused when delivery_order finds no channel.
    Stored in delegation_reminders (person_id, text, due_at, created_at,
    claimed_at, sent_at, cancelled_at), never scheduled_actions. The
    scheduler hook _maybe_send_reminders -> reminders.maybe_send (once a
    minute) -> send_due claims each due row (claimed_at compare-and-set),
    drops it when over two days late, and sends "Reminder you set on <date>:
    <text>" through
    deliver_to_person to the setter alone, private audit rows
    (delegation_reminder_set / _sent). In MAIL_TOUCHED_ALLOWED_TOOLS: it
    reaches only the speaker, as fixed text, and nothing runs at fire time.
    due_at is stored in UTC so _due's string comparison is in time order.
    A due reminder whose person is outside their availability (quiet hours,
    leave; OUTBOUND_RESPECT_QUIET_HOURS) is left unclaimed (_held) and goes
    when it ends; the guard would otherwise suppress it after the claim.
    The Slack and Discord DMs it may ride turn link previews off
    (unfurl_links/unfurl_media False; Discord flags SUPPRESS_EMBEDS). A
    forward's subject never goes into the composer's intent.
  approval_cards: |
    orchestrator.action_card_tools.propose_actions (in DELEGATION_TOOLS and
    MAIL_TOUCHED_ALLOWED_TOOLS; not a MAILBOX_TOOL_NAMES tool) leaves the
    speaker a card of up to 5 actions: invite (create_calendar_event input,
    roster attendees), message (message_person: person_id + text as sent),
    add_contact (principal's cards only), drive_files (rename and/or move up
    to 25 Google Drive files, principal's cards only, always waits for the
    tap, runs through MCPGateway.tapped_drive_change). delegation.action_cards.check
    validates each (roster, not archived, contacts only on the principal's
    card, not themselves, times ahead) at propose and again at approve. A card
    is a delegation_actions decision, approver = speaker, approver_only (404 to
    everyone else, the principal too), never an alert; same actions still
    waiting dedupe to one card. Caps: TurnDelegation.action_cards 3 a turn,
    OPEN_CARDS_MAX 25 waiting, CARD_TTL 7 days. GET /delegation/actions lists
    them. POST /decisions/{id}/approve (edits.only = indexes): caller_refusal
    (signed caller is the card's person), Act as me on, not expired, then
    claim_for_execution (once), each ticked action run as stored with no model
    call in Session(unattended=True) under rows_for_person(person) (audit rows
    theirs, no activity-rail row), grant_contact_egress for the principal;
    message via schedule_tools.message_person(alert_fallback=False), so no
    team-visible alert; approve also needs can_delegate.
    An invite runs inside calendar_tools.approved_by(person): the meeting gate
    books it now when its approver is that same person, else proposes to its
    approver as usual (no authority widened). finish_execution keeps
    final_payload.results (done | waiting | failed | skipped). Reject does
    nothing else. Audit: delegation_actions_proposed / _approved / _dismissed,
    private, kinds and outcomes only. Approved on the web only (chat apps
    have no buttons); a card can come from any Act as me surface. In the web
    chat the card shows under the reply that left it: the propose_actions
    chip carries decision_id (action_chips), and ChatActionCards renders it
    from GET /delegation/actions while it waits. There is no "always
    allow" for contacts: a standing allowance would let mail-planted text
    add its sender and email them in the same turn without a tap, so each
    card still needs its own tap.
  ghostwriter: |
    delegation.ghostwriter.compose — the only text the Executive produces
    under someone else's name. System = the constant GHOSTWRITER_PROMPT +
    the person's <voice> block (no cache markers: short, and rare). User
    turn = <writer>, <recipients>, <thread> (the last 6 messages, each only
    its sender's new text via email_poller.sender_new_text, every line
    through scrub_block_line, all labelled alike), <writer_said> (a reply's
    only record of the writer's own words: their sent mail among those 6,
    threads.writer_said), <intent>. The prompt says nothing in <thread> is
    the writer's words, whatever it claims. utils.prompt_blocks makes every
    untrusted line plain before anything is matched against it (NFKC, so a
    full-width < is <; control, format and other default-ignorable
    characters, such as zero-width spaces and variation selectors,
    dropped), then defangs the block's closing tag in any case or spacing;
    in <thread> and <recipients> every "<" becomes "‹" (no_tags), so no
    spelling of a tag — look-alike letters included — opens or closes one.
    The classifier's <email> block does the same. NO tools but the forced
    compose_reply; no company profile, memory or roster. Not a Council
    agent: PATCH /agents and /personas have no principal check. Model
    DELEGATION_COMPOSER_MODEL, else the default model;
    log_model_usage(actor="ghostwriter"). lint() runs in code after it — a
    URL or email address survives only if it appears in the intent, the
    signature or the recipients (flags removed_link / removed_address), the
    exec name is flagged (names_the_executive) and the body is capped at
    6000 characters (shortened; cut at a paragraph, line or word break in
    the last fifth). A body lint leaves empty is a ComposeError. asks_if_ai on the last inbound message
    adds an open question for the person to answer themselves.
  voice: |
    delegation.voice — "How I write", learned from the person's OWN sent
    mail on request (POST /delegation/voice/learn), unlike attunement.style,
    which learns how to write TO someone. It can also be written from the person's
    own words (POST /delegation/voice/describe, describe_voice): one forced
    record_voice_profile call with its own system prompt and no exemplars
    applies the description to the current profile, validate_profile cleans
    it, signature and exemplars are kept, and the result comes back with a
    short sample reply, unsaved; the person saves it with PUT. No mailbox
    needed; one at a time per person and at most 10 an hour (in-process). Up to 40 sent messages; quoted
    text stripped (sender_new_text); automatic mail, the package's own
    X-OE-Ghostwritten drafts, every thread chat drafted into (delegation_drafts
    source chat, plus the delegation_drafted audit rows from before that
    table) and every sent message that began as a draft for them
    (delegation_drafts.sent_message_id — the inbox watcher drafts into too
    many threads to skip them whole) skipped; at least 5 samples; at most once per
    10 minutes; one pass at a time per person (in_progress); never over a
    locked profile, and a lock or edit made while it runs wins (the learned
    profile is dropped: locked / changed). One forced-tool call
    (record_voice_profile), then validate_profile in code — greetings per
    audience (team / contact / other) and a sign-off (short, at most two
    lines; no links, handles, amounts or markup; a literal backslash-n is a
    line break, read after NFKC, and a value with more such lines than fit
    keeps its first ones — which also repairs a profile stored before that
    rule, since stored rows are re-validated as they are read; a typed value
    with too many lines is a 422 naming the rule), length and formality
    from fixed lists, up
    to 8 habits and 6 avoid rules through attunement.style's deny-list plus
    a writing-topic check and a roster-name check, and up to 3 exemplars
    (each verbatim from a sample, emails and phones masked, none while a
    client slot is active). The signature comes from Gmail sendAs, never
    the model, through gmail.html_to_text: a <br> always ends a line and a
    block tag (div, p, li, tr, table, lists, headings, blockquote…),
    opening or closing, ends one only when it has text — Gmail puts a
    signature's first line straight in the outer <div> and each later line
    in its own <div>, so closing tags alone glued the first two lines.
    POST /delegation/voice/signature reads it again without a relearn (a
    relearn would replace the person's edits, and a locked profile can't
    relearn): nothing else changes and the lock is kept. Tables
    delegation_voice and delegation_voice_history (every change kept).
  gmail_client: |
    delegation.gmail.DelegateGmail — direct Gmail REST (httpx), never
    registered with the MCP gateway. Methods profile_email, search_threads
    (metadata only), list_message_ids, get_thread, get_message, list_sent,
    send_as_signature, send_as_addresses, create_draft, get_draft (None on
    a 404) and delete_draft (False on a 404); on the calendar list_events,
    calendar_granted, calendar_write_granted, find_invite (reads) and
    answer_invite (the person's own attendee answer on one event,
    sendUpdates=all; delegation.invites only); and ONE send method, send_draft:
    an existing draft by its id — POST drafts/send with the body {"id": ...}
    and nothing else, never messages.send — called only by
    delegation.reply_send (unit tests pin the method set, the one endpoint,
    the body and the call site). A GmailError carries maybe_done when the
    request may have been carried out anyway (a timeout after connecting, a
    5xx, an unreadable 2xx). A parsed message also carries received_at
    (internalDate), bcc, bulk, delivery_report, calendar_invite and
    sender_authenticated; a 429 or a rate-limit 403 raises GmailRateLimited
    and a 404 GmailNotFound, both GmailErrors.
    gmail_status answers connected, not_configured, needs_reconnect
    (invalid_grant, a 401/403 or a missing scope; tokens of an app in
    Testing mode expire after 7 days — a 403 whose reason is a rate limit,
    and any 429, is a GmailError to retry instead), mismatch, no_email, shared_mailbox
    (the person's address is the exec address; refused before asking
    Google) or error. Credentials per person, see integrations.own_gmail.
    html_to_text (HTML-only bodies and the sendAs signature) runs on mail
    anyone can send, on the event loop, so every step is one forward pass:
    the <br> and block patterns end at the next "<" as well as ">", tags
    (utils.html_tags.strip_tags, shared with page_watch) and script / style
    elements are cut by scanning forward, and a decimal
    character reference past Unicode's range becomes U+FFFD before
    html.unescape (which raises past 4,300 digits). A unit test times
    crafted input.
    Callers never name Gmail's query syntax: they use inbox_message_ids
    (the Primary inbox since a time, not from the person) and
    has_written_to (any sent mail to an address), so either client fits.
  outlook_client: |
    delegation.outlook.DelegateOutlook — the Outlook twin: direct Microsoft
    Graph REST (httpx), never registered with the MCP gateway and never the
    Microsoft 365 MCP server the Executive's own Outlook uses. Same public
    methods, return types and errors as DelegateGmail (a unit test compares
    the method sets), so every caller is unchanged; gmail.gmail_for picks it
    when the person's credential file says "provider": "microsoft"
    (gmail.credential_provider). One file per person either way: a person
    has one mailbox for Act as me, and each loader ignores the other kind.
    Why one file: everything that stores or checks a person's sign-in
    already names one path per person.
    scripts/connect-own-outlook.py mints it: device-code sign-in on the
    Executive's own Entra app (MS365_MCP_CLIENT_ID, MS365_MCP_TENANT_ID,
    default common), delegated User.Read, Mail.ReadWrite, Mail.Send and
    offline_access, /me checked against --email, and "account": personal
    when the id token's tid is the consumer tenant (refreshed at
    consumers). The tenant is validated against a fixed pattern before it
    is put in the token URL. Microsoft rotates the refresh token on use: the
    new one is written back atomically (0600), keeping every other key, and
    only when the file still holds the old one (a reconnect meanwhile wins).
    The mailbox's address (profile_email, the primary of
    send_as_addresses) is the directory's /me mail, else
    userPrincipalName — never an address read from mail, because Sent
    Items is the owner's to fill and the People check binds the file to a
    person (a review found a Sent Items fallback let one mailbox claim
    another person's address). A personal account signing in with a
    non-Outlook address is matched by that sign-in address.
    Graph differences, all absorbed in the client: Prefer
    IdType="ImmutableId" and text bodies on every call (a sent draft keeps
    its id); a thread is conversationId; a draft's message id is
    "<id>.<changeKey>" (draft_version), because callers detect an edit by a
    changed message id and Outlook keeps a draft's id when it is edited;
    labels are mapped — DRAFT, SENT only for mail in their Sent Items folder
    (parentFolderId, so a From set to their address by someone else never
    counts), INBOX, and CATEGORY_UPDATES for Focused Inbox "other"; a draft
    with no From reads as from the mailbox; the ghostwritten mark is a
    named extended property; sender_authenticated only from the topmost
    Authentication-Results (Exchange writes it above anything the sender
    added) holding exactly one dmarc verdict, a pass for From's domain
    plus exactly one compauth= clause, which only Exchange Online
    Protection writes (exchange_authenticated) — so mail that reached the
    mailbox without EOP's stamp is never verified by a header its sender
    wrote. delete_draft sends If-Match with the draft's etag: with
    immutable ids a draft sent between the read and the DELETE keeps its
    id, and Graph then answers 412 and the sent message is left alone. Replies use createReply on the message they
    answer (by internetMessageId, else the newest), then PATCH the text and
    recipients; a failed PATCH deletes the half-made draft. delete_draft
    refuses anything that isn't a draft. send_draft is POST
    /messages/{id}/send with an empty body, called only by reply_send.
    search_threads turns a Gmail-style find into KQL: words, from:, to:,
    cc:, subject: and newer_than: kept, other operators dropped, quotes
    removed. Graph has no signature API: send_as_signature is "", the voice
    learner keeps the stored signature, and POST
    /delegation/voice/signature is a 409 signature_unavailable. Links:
    gmail.mailbox_link opens the draft itself in Outlook on the web
    (outlook.office.com/mail, or outlook.live.com/mail/0 for a personal
    account); MAILBOX_LINK_PREFIXES is what the chat chip and the reply
    cards (ui lib/replyCards.ts, a test compares them) will link to.
  privacy: |
    From the moment ghostwrite_email sets touched_mail,
    people_tools.audit_row_private_to_principal answers True, so every row
    the turn writes after it is private to the principal; the chat_turn
    reply (it carries the preview), the committee rows and both
    tool_invocation rows also pass private explicitly, and anything the turn
    starts afterwards runs under private_rows(touched_mail). The turn teaches
    no memory: episodic extraction, the open-loop pass, the working-style
    pass and the Honcho peer and department syncs are all skipped, because
    its reply quotes a draft built from other people's mail (the extractor's
    summaries are free text, so quote-gating alone would not keep it out). "ghostwrite" is in redaction._SENSITIVE_SUBSTRINGS,
    so the tool rows carry no input or result text. The four delegation_*
    events are always private and metadata-only (see audit.event_types).
    The inbox watcher is private the same way: every row a scan or a card
    action writes is private (rows_for_person), and it starts no chat turn,
    alert, scheduled action or workflow run and teaches no memory.
    For a team member, private means THEIRS ALONE, the principal included:
    audit rows carry private_to_person (people_tools.audit_row_owner — the
    id passed, the rows_for_person scope, or the speaker of a touched turn;
    never the principal's own id, so the principal's rows are unchanged) and
    every audit read leaves them out unless it asks for that person
    (owned_by); GET /audit/logs/{id} is a 404 for them to everyone; only
    usage_summary counts them. Their reply cards are approver_only. Before
    the first mailbox read ghostwrite_email marks the session mail_private
    (session_store.mark_mail_private, creating a channel adapter's row early
    with its owner, binding one to an ownerless row and refusing to read if
    that fails or the conversation is someone else's), after which only the
    session's owner may open it (chat._session_access) and working-style
    learning skips it. Every later turn in it starts touched_mail
    (settings.pin_turn_delegation reads the flag, failing closed): the
    turn's rows are the owner's, and so are the web chat's rows before it
    (the inbound chat_turn and the knowledge_retrieval row); no memory pass
    runs, even when the answer comes from history
    alone; anyone else speaking there is not offered Act as me. A channel
    adapter's own pre-turn rows (integration_inbound, and the retrieval
    Discord and Telegram run first) are written as before. The inbox
    classifier weighs a team member's sender by the team and their own sent mail, never the principal's contacts. The
    owner sees counts only: drafts and sends in 30 days, inbox on or off.
  lockdown: |
    Once a turn has read the principal's own mail — from the round that
    calls ghostwrite_email or a mailbox read (search_my_email,
    read_my_email, read_my_email_attachment, my_email_awaiting_reply,
    save_my_email_attachment, which stays allowed: see save_file) or
    recall_history, since a round's tools run together — only a door to the
    open internet or to everyone stays shut until the turn ends
    (delegation.lockdown, MAIL_TOUCHED_WITHHELD_TOOLS): outside fetches
    (read_document, load_mcp_server, add/tune_watchlist_entry,
    run_executive_research, any call_tool outside PRIVATE_TURN_MCP_TOOLS),
    scripts and library jobs (run_script, run_python_job), workflows
    (suggest_workflow, run_workflow, save_workflow: they run later,
    unattended, and may fetch or script), posts to everyone
    (send_department_message, send_company_broadcast, create_alert) and
    changes to who is on the roster or holds authority (archive_person,
    set_department_head, resolve_roster_request), and text that steers
    later turns (schedule_followup, whose intent runs unattended as a
    prompt when due; create_goal, update_department_goal and
    record_decision_outcome, shown to every later turn). The
    risk is prompt injection: anyone can put text in the inbox, and a URL
    could carry what the mail said anywhere. Everything else runs, because
    it is fenced on its own: DMs and message_person reach only the roster
    (_guard_outbound), calendar invites name attendees by person id, the
    Executive's Gmail / Outlook send through call_tool checks every
    recipient against _roster_allow_set, remember_fact and update_company_profile keep only the
    speaker's own words, and a workflow drafted in chat is saved only once
    a person confirms it.
    upsert_person runs only for a contact the speaker named this turn
    (lockdown.speaker_named_contact: kind contact, only name, role, email,
    leave and response fields; a word of the name in their own words, in
    a message that asks to add, save or change someone; a new contact's
    address one they typed or one that sent the mail this turn read
    under the contact's name (TurnDelegation.mail_senders, noted by
    mail_read_tools; lockdown._sent_by), never one the
    mail's text only mentions; on an
    update the stored name too, and a changed address must be one they
    typed), because the roster is what every send check trusts. Any other
    refused upsert_person gets lockdown.CONTACT_REFUSAL, which points the
    model at an add_contact approval card instead of asking them to type
    the address. What an
    email itself asks for (a meeting, a message, a new contact) is still
    never done on its say-so: the persona sends it to propose_actions.
    Every tool the Executive can be offered is in exactly one of
    MAIL_TOUCHED_ALLOWED_TOOLS / MAIL_TOUCHED_WITHHELD_TOOLS (a test fails
    on an unclassified one) and an unclassified name is withheld. The
    dispatch guard in executive._stream_agent_loop refuses at dispatch with
    a private tool_invocation row (details.refused "mail_touched") and an
    error telling the model to offer it in the next message; the offered
    list is unchanged, so the cached prefix is the same all turn. The
    handlers that reach outside or post to everyone check again
    (lockdown.outside_reach_refusal: research, read_document, the
    watchlist, workflows, broadcasts, MCPGateway.call_tool and
    load_mcp_server). Drive reads are not remembered on such a turn
    (drive_reads.may_remember). The server-side web_search stays, as on a
    turn private to the principal. The lockdown is per turn
    (TurnDelegation.read_mail, set only by the tools that read the mailbox
    or notes): the next message starts afresh, in a mail_private
    conversation too, which stays private (touched_mail) but is not locked
    at all. History keeps only the speaker's words and the Executive's
    final replies, never a tool's result, and the next message is the
    person asking again after reading that reply. (Until 2026-10 a later
    turn held the same tools for some 20 to 30 messages while the reading
    turn was in view, lockdown.carried_withholds; it was dropped as too
    restrictive: a refused contact add or link in a long chat app
    conversation stayed refused even after the person confirmed.
    sessions.mail_read_at is still stored by mark_mail_private.) The process
    log names a refused call_tool's inner tool only when it is shaped like
    a tool name (executive._loggable_tool, [a-z0-9_]{1,64}), else
    "call_tool:<unlisted>": that name is the model's own text, which mail
    could steer, and the log is not private (the audit row keeps it). The
    same goes for a turn private to the principal.
  reply_answers: |
    delegation.answers — "Decide before sending" with taps. The ghostwriter's
    compose_reply tool returns each open question as {question, choices
    (2-4 short answers the writer might pick, never facts), about (time,
    document, other)}; ghostwriter.parse_questions also takes plain strings,
    so a model answering in the old shape still gives its questions.
    ComposedDraft keeps open_questions as strings (chat, Handle it, the
    evals and every reader use them unchanged) plus question_choices in the
    same order. On a card (inbox.compose_reply, follow_ups) answers.suggest
    fills two kinds in code: a time question, with Read my calendar on and
    the scan's mailbox client, gets up to 3 free half hours, one a day over
    the next 5 working days from tomorrow (calendar.events_for, then
    briefing.top_three.free_gaps in the workspace zone and business hours;
    all-day and declined events don't block), source "I checked your
    calendar: these are free."; only times are used, never an event's
    title, and no model sees them. A document question whose words match a
    company document's name (knowledge.loader.list_company_docs) gets
    'I'll send "<name>" separately', source 'Found "<name>" in your
    documents.' Attaching is not offered: a card's draft is plain text
    (card_drafts keeps no files and update_draft_text refuses a draft with
    files), so a choice never says a file is attached. The card payload
    stores question_choices beside open_questions; cards made before it
    have none and show plain questions. Answers are saved by POST
    /delegation/replies/{id}/answer (see the delegation API notes);
    answered_questions keeps {index: answer}. Send in the UI waits until
    every question with choices is answered, unless the words were changed
    by hand (questions_settled); the server doesn't add a send rule.
  inbox_watcher: |
    delegation.inbox — the second switch, "Draft replies to my inbox"
    (delegation_inbox_watch: person_id, enabled, watch_since, last_poll_at,
    status, backoff_until, failures, updated_at, updated_by; absent is off).
    Turning it on needs Act as me on and gmail_status connected, and sets
    watch_since to now every time, so mail from before is never drafted
    for; turning Act as me off turns it off too. Off means no Gmail call and
    no row, with one exception: a send the person started that Gmail never
    confirmed is still followed through (inbox.settle_sends, on the same
    interval, throttled in memory by _LAST_SETTLE). It runs from a throttled
    scheduler-tick hook
    (runner._maybe_scan_inbox → inbox.maybe_scan, after the pause, profile
    and rotation gates), not a scheduled_actions row (those are on
    /scheduled for everyone and anyone may cancel them): every
    DELEGATION_INBOX_POLL_MINUTES (default 5) per person, one scan task at a
    time and one scan per person (inbox._SCANNING), never while a client
    slot is active; POST /delegation/inbox/check runs the same scan. A scan
    runs entirely under private_rows(True) and logs counts and codes only.
    It first settles open cards (reconcile; one card's error never stops the
    rest), stops with backlog_full at 25 open cards (counting the drafts it
    makes), then lists in:inbox -in:chats -from:me minus the promotions,
    social, updates and forums tabs after watch_since — up to 100 ids — and
    takes the newest message of each thread that still needs a look,
    passing over settled messages and threads with an open card before the
    10-thread cap, so a burst of mail or a pause never hides older threads
    for good. It never marks mail read or changes a label.
    delegation_inbox_messages is its durable cursor (id, person_id,
    message_id, thread_id, received_at, sender_key — sha256[:16] of the
    address, never the address — relation, outcome, reason, classified,
    attempts, draft_id, decision_id, flags, created_at, updated_at;
    UNIQUE(person_id, message_id)); outcome is processing, retry, skipped,
    not_needed, deferred, failed, drafted, sent, dismissed, closed or
    expired. retry is a message left for a later scan, which claims it
    again: a failure that may pass — the classifier giving no verdict, the
    writer failing, Gmail refusing the draft (the scan then backs off), a
    card that couldn't be made (its draft is deleted first, so no draft is
    left without a card) or any other error with one message (which never
    stops the rest) — is final (failed) after MAX_ATTEMPTS (3); a daily
    limit reached while it was being read is not counted. Skipped with a reason (skip_reason, in code): before_watch,
    stale (over 3 days), no_sender, from_you (the person or a send-as
    address), from_executive, ours (X-OE-Ghostwritten), automatic
    (Auto-Submitted, Precedence bulk/junk/list/auto_reply, X-Autoreply, a
    bounce, a calendar invite or a no-reply sender), mailing_list, category,
    not_addressed (not in To or Cc), too_many_recipients (over 10),
    you_replied (the person wrote last) and draft_exists. Not recorded, so
    a later scan looks again: a message under 10 minutes old (mail the
    person answers at once never gets a card), one in a thread whose card
    is open, and one a daily limit holds back. A thread gone between the
    listing and the read is recorded skipped (thread_gone). Order per
    message: claim the row → classify → reserve the shared daily slot →
    write → create_draft (from the send-as address the mail went to, when
    that was an alias rather than the primary) and store its id → create
    the card (idempotency key delegation_reply:{person}:{message}) →
    drafted. Limits:
    5 drafts a scan; DELEGATION_INBOX_MAX_DRAFTS_PER_DAY (default 20)
    within the shared DELEGATION_MAX_DRAFTS_PER_DAY; 200 classifications, 2
    drafts per sender (1 for a stranger) and 10 stranger drafts a day. A
    lapsed sign-in sets the status and is looked at again every 30 minutes;
    a rate limit, an error reaching Gmail or a crash backs off from 5
    minutes, doubling to 2 hours. Neither turns the switch off; the card
    shows the status.
  inbox_classifier: |
    delegation.inbox_classifier — one forced-tool call (classify_email →
    needs_reply, kind, confidence) on DELEGATION_CLASSIFIER_MODEL, else
    ROUTING_MODEL, logged as inbox_classifier usage. The system prompt is a
    short constant (uncached); the user turn is a few one-lined header
    lines — From, the sender's relation (and "address not verified"), the
    recipient count, the subject — and the sender's own new words
    (sender_new_text, at most 3000 characters), every line scrubbed, inside
    one <email> block marked as data, after the person's own last email in
    the thread (their_last_words: only mail their own mailbox sent, SENT
    label, at most 1500 characters) in a <their_last_email> block, so a reply
    to their own ask reads as one. Real miss it fixes: they asked a contact
    for a call, the contact wrote back "my week is open, I'll circle back
    with times", and with only the new words it was filed fyi. Now a reply
    that says when someone is free without settling a time is scheduling.
    No other tools, context or memory.
    Code decides: a draft only when needs_reply, kind is question, request,
    scheduling, introduction or follow_up, and confidence clears 0.6 (team
    or contact), 0.7 (someone the person has written to, found by a Gmail
    in:sent to: search) or 0.85 (a stranger, or an unknown relation). A
    sender whose From address Gmail couldn't authenticate
    (fact_confirmation.headers_authenticated) is handled as a stranger
    whatever the roster says (inbox.handling_relation): the bar, the holding
    reply and the stranger limits; the card still shows who they claim to
    be (payload relation) beside handled_as.
    fyi, thanks, pitch, notification, newsletter, phishing and other never
    get one, and any failure or malformed answer means none.
    A group email (anyone else in To or Cc besides the sender and the
    Executive) is drafted for only when the person is in To and the email
    asks them themselves. The classifier lists the names the email greets or
    asks by name (asked_names) and code matches them against the person's
    name (inbox_classifier.names_them, whole name parts only, so "Alexis"
    never counts for "Alex" and a nickname misses), so mail that greets someone else is
    never theirs even when the model's overall asked_of_them says it is (a
    real miss: "Good morning, <colleague>, could you sign ..." to the person
    and that colleague). Only when it names nobody does asked_of_them decide,
    false for the group at large. The classifier is told the person's
    name, To or Cc, and how many others; a Cc-only person never gets a
    draft. Recorded not_needed / asks_someone_else.
  inbox_drafting: |
    delegation.inbox.compose_reply — ghostwriter.compose and the person's
    voice block unchanged, with a constant intent in place of a person's.
    Which words are the writer's is never written inside the thread text,
    where a sender's name, date or body could imitate any marker with a
    look-alike: threads.thread_text (shared with chat) labels every message
    alike and quotes body lines that read like its "[n] From:" headers, and
    threads.writer_said lists the writer's own words apart — only mail their
    mailbox sent (SENT, from their address) — as the <writer_said> block
    after </thread>, which nothing inside the thread can close; the other
    blocks' tags are defanged in thread text too
    (ghostwriter._defang_blocks). The intents:
    INBOX_REPLY_INTENT (acknowledge; say again only what <writer_said>
    already says, never anything in <thread>; no yes or no, date, time,
    price, fact or promise of its own; "I'll get back to you"; every ask it
    can't answer from their words goes in open_questions), or
    INBOX_HOLDING_INTENT for a stranger (a short thank-you-I'll-get-back
    holding reply, answering nothing). lint still strips any link or
    address that is not the person's own. The reply goes to the sender and, on
    a group email, Cc to everyone else it went to (threads.plan_reply with
    reply_all on, minus the person's own addresses and the Executive; a
    stranger's holding reply has reply_all off; Reply-To ignored; draft_to
    lists everyone and Send checks it); the card is
    flagged others_on_thread when anyone else was addressed, and then
    offers Reply to: the sender only, or everyone (reply_others, the list
    fixed when the card was written; PUT /delegation/replies/{id}/recipients
    {everyone}, card_drafts.set_recipients, rewrites draft_to, draft_spec and
    the mailbox draft's To/Cc, never an address from the request; a stranger's
    card starts on the sender only),
    executive_on_thread when the Executive was, and sender_unverified when
    Gmail's SPF/DKIM/DMARC results don't vouch for the From address
    (fact_confirmation.headers_authenticated). A sincere "are you an AI?"
    becomes an open question for the person.
  reply_cards: |
    A drafted reply waits on a card: a delegation_reply decision
    (DecisionClassSpec approver_only — its person's alone, a team member's
    hidden from the principal too — no alert: alerts feed chat turns,
    which would put other people's mail into memory; its payload also
    carries private: true). The payload holds ids (message, thread, draft
    and the draft's message id), the sender's name and address, relation,
    whether the sender was verified, the subject, received_at, they_wrote
    (the sender's new words, at most 2000 characters), the draft's to,
    subject and body, open_questions, flags, kind and confidence.
    GET /delegation/replies lists the caller's open cards from the database
    alone (delegation.replies.cards: no Gmail call, so Today never waits on
    Google) with a Gmail link built from the fixed prefix. Approving one
    sends its draft (see send). Dismiss is
    POST /decisions/{id}/reject; its after_reject (replies.dismiss) deletes
    the draft only when it is unedited — its message id still the one
    saved (Gmail gives an edited draft a new one) — and records the outcome
    (deleted, kept_edited, already_gone, not_connected, gmail_error) even
    when Gmail fails. Each scan first reconciles the open cards: expired
    after 7 days (the draft stays in Gmail), sent_in_gmail (the draft gone
    and the person's message after it; the draft row's sent_message_id is
    set), draft_deleted, you_replied, thread_gone — each a compare-and-set
    close_externally with the reason. A newer message from someone else
    brings the card up to date (answers.catch_up): one composer-model call
    rewrites the draft with it as <news> (data, never the person's facts; a
    decision only they can make comes back as a new question with choices,
    at most MAX_NEW_QUESTIONS), saved by card_drafts.redraft (edit's card
    checks without a caller), and the message plus the Executive's one-line
    note join the payload's conversation; caught_up_at then moves where
    later_messages (and Send's second yes) count from. Past MAX_CATCH_UPS
    news on one card, or a failed rewrite, it only adds the flag
    thread_moved_on. A card being sent right now
    (inbox.SENDING, this process) is left alone; one left executing by an
    unconfirmed send is settled (see send).
  send_chat_draft: |
    delegation.reply_send.send_chat_draft, reached only from POST
    /delegation/drafts/{row}/send (an AST test pins it). ghostwrite_email
    returns its delegation_drafts row id (draft_row); the chat chip carries
    it with the draft as saved (to, cc, subject, the first 800 characters)
    and the web chat shows an "Email as you" card with Send. The person's
    own tap is the permission, like a card's Send, so it needs no daily send
    cap. At send time: the row is the caller's own and source chat (else
    404 draft_not_found); verified.caller_refusal (409
    caller_signing_required on a server without signed sign-ins); Act as me
    on (Draft replies to my inbox not needed); no client slot; mailbox
    connected; the draft still there (draft_gone marks the row gone) and
    its message id the one recorded when chat wrote it (draft_changed: an
    edited draft is sent from the mailbox, never from here); recipients
    1-10, never the Executive's address, from a send-as address; for a
    reply, the person's own SENT message in the thread since closes it
    (you_replied) and a newer message from someone else needs a second yes
    (409 confirm, then thread_moved_on true). Then drafts.claim_send sets
    gone_at where it is NULL and sent_message_id is NULL (compare-and-set:
    a double tap sends once), one more get_draft must show the same
    version, and send_draft. Nothing went → release_send; maybe_done →
    claim kept, never resent. Records sent_message_id, a private
    delegation_chat_draft_sent row, and a history note when Always in the
    loop is on. may_do's chat_drafts row reads "Drafts, sent on your tap".
  send: |
    delegation.reply_send.send_approved_reply — the approve hook of
    delegation_reply, the only caller of DelegateGmail.send_draft, reached
    only from POST /decisions/{id}/approve (a principal-only class; an AST
    test pins both call sites). It runs under private_rows(True) and checks
    again at send time: the caller is the card's person and the API knows it
    — signed callers on and a user assertion for their email (or an
    operator under local login), or local login (the API answers loopback
    only); anything else is 409 caller_signing_required, because with only
    the shared secret whoever holds it could send as the owner — and the
    resolver is that person; Act as me and the inbox switch are on and no
    client slot is active; gmail_status is connected; the draft exists in
    the same thread and the person hasn't replied there since (draft_gone /
    you_replied close the card); its recipients (To, Cc and Bcc) are 1-10,
    never the Executive's address, and it is From one of their send-as
    addresses. Recipients that differ from the card's, or a newer message
    from someone else, need a second yes: a 409 confirm {reasons
    recipients_changed / thread_moved_on, recipients}, answered by approving
    again with edits {recipients: the list shown, thread_moved_on: true}.
    Then inbox.SENDING, claim_for_execution (proposed → executing,
    compare-and-set: a double tap sends once), one more get_draft — the draft
    must still be the version every check above read (its message id),
    since drafts.send sends whatever the draft is when Gmail gets the
    request; a changed one is refused (409 draft_changed) and handed back —
    then send_draft, and finish_execution — approved_with_edit when the draft's message id
    changed (edited in Gmail), with sent_message_id as external_event_id —
    the ledger outcome sent, delegation_drafts.sent_message_id and a private
    delegation_reply_sent row. A refusal that proves nothing went (a 4xx,
    auth, a rate limit, a 404) hands the card back (release_claim); a
    maybe_done failure leaves it executing and answers 502
    send_unconfirmed. The reconciler then asks Gmail
    (inbox._settle_unconfirmed_send): the person's message in the thread
    means it was sent (finished, confirmed_later), whether or not the draft
    has gone yet. Anything else waits for a second scan that sees the same
    (the first adds the ledger flag unconfirmed_seen; Gmail can take a
    moment to settle a send and show it): the draft still there and nothing
    sent means it was not sent (back to proposed, flagged send_failed —
    Gmail deletes a draft it sends); gone with nothing sent, it was
    deleted. Nothing is ever
    retried on its own. Send is the person's act, so it works while the
    Executive is paused.
  handle_it: |
    Handle it for me (delegation.handle_it): a third switch under Act as me,
    one row per person in delegation_handle_it (person_id PK, enabled,
    mode, levels (legacy), updated_at, updated_by; absent = off). One
    setting, mode careful | balanced (default) | bold (handle_it.RULES):
    careful = known senders only, <= 400 chars, confidence >= 0.9;
    balanced = known senders, <= 1200, >= 0.8; bold = strangers too,
    <= 2000, >= 0.8, links/amounts allowed at >= 0.9. Known = team, contact
    or correspondent. schema._add_handle_it_mode adds the column to an older
    table (reply_known not handle -> turned off, since it sent nothing on its own before; else reply_stranger handle -> bold, else balanced). Set only by PUT /delegation/handle-it from a
    caller delegation.verified.caller_refusal accepts (the rule Send uses:
    403 not_yours, 409 caller_signing_required on shared secret alone);
    enabling needs Act as me and the inbox watcher on (409 act_as_me_off /
    inbox_off); the inbox watcher going off turns it off.
    After compose, inbox._consider asks handle_it.refusal (plain code, any
    exception = refusal "uncountable"); None makes the card gate_mode
    auto_execute, else propose with handle_it_reason. Refusal codes, in
    order: level (off, or a stranger below bold), signing_off (signing_on or local login needed),
    sender_unverified, kind (question/request/scheduling/introduction/
    follow_up), unsure (below the mode's min_confidence), recipients (subset of the
    email's From/To/Cc less own and Executive addresses, sender included,
    at most MAX_RECIPIENTS), sensitive (SENSITIVE words in subject, the
    sender's new words, reply subject or body), amount, link (both allowed
    on bold at details_confidence 0.9), long (over the mode's max_body_chars), flagged (any flag but others_on_thread / executive_on_thread),
    thread_recent (one auto-send per thread per day, delegation_handled),
    in_a_row (last own message in the thread was an auto-send),
    daily_limit (DELEGATION_HANDLE_IT_MAX_SENDS_PER_DAY, default 20).
    Only when it passes, a last look (delegation.injection_check.held_back:
    one tool-less classifier-model call reading the sender's new words as
    plain text in an <email> block, up to 20,000 chars) asks whether they
    carry instructions for an assistant (ignore rules, forward/quote other
    mail, reveal what it knows, reply elsewhere, a passage addressed to the
    assistant; styling is gone, so hidden text is judged by its words); true, a failed call or a malformed answer
    holds the reply (handle_it_reason suspicious). It only ever holds back.
    A workflow step reaches the same path with oe__answer_email_as_me
    (delegation.workflow_reply -> inbox.answer_thread: the newest message of
    the named thread, not from the person, through _consider with only the
    STALE bound; the step names the thread, never the words or recipients;
    counted, claimed and carded as the watcher's own; refuses when a scan is
    running or the backlog is full). It counts as a send for save rules
    (workflow_email.sends) and may run in a workflow that reads mail.
    The watcher then calls reply_send.send_on_its_own — the second door
    into _send, pinned by an AST test to delegation/inbox.py (the third,
    send_for_workflow, is pinned to delegation/workflow_email.py) — which runs
    every send-time check with no caller and adds: gate_mode auto_execute,
    the switch on and the mode still allowing that sender (follows_up for
    a follow-up card), signing_ok, and the draft
    unedited since saved (draft_changed otherwise: the person took it
    over). A refusal hands the card back (decision_ledger.hand_back:
    auto_execute -> propose, compare-and-set, with handle_it_reason), and
    GET /delegation/replies carries waited_because (REASONS text). Finishes
    as executed (no resolver), outcome sent reason handled,
    a delegation_handled row (person_id, thread_id, decision_id,
    sent_message_id, sent_at) and a private delegation_reply_handled audit
    row; no History note (notes come from the person's own words). Any
    refusal or error leaves the card; the reconciler settles an
    unconfirmed auto-send as executed too. Runs inside the scan, so the
    pause gate stops it. GET /delegation/handled lists the caller's last 7
    days (theirs alone); Settings → Act as me shows the switch, the
    Careful / Balanced / Bold choice, sent_today and that list.
    Follow-ups as you (delegation.follow_ups): while on, inbox._scan calls
    follow_ups.look at most hourly (LOOK_EVERY): own sent mail 3-10 days
    old (AFTER / WITHIN) asking something ("?" in their new words), to
    1-MAX_RECIPIENTS people besides the Executive, still last in its
    thread, never followed up before (its delegation_inbox_messages row);
    at most PER_LOOK 2 a look, within the drafts cap. Ghostwriter
    FOLLOW_UP_INTENT, draft to exactly the original To/Cc.
    handle_it.follow_up_refusal: follow_up_level (Rules.follow_up_to:
    careful none, balanced team+contact, bold + correspondent),
    signing_off, recipients (must equal the original), sensitive, amount,
    link, long (> FOLLOW_UP_MAX_CHARS 600), flagged, then count_refusal.
    Card payload source follow_up (from_email = first recipient); the
    reconciler closes it "answered" and deletes its unedited draft when
    anyone else writes in the thread.
    In training is per Act as me setting, not a dial step (owner's ask,
    2026-10-09): delegation.training, one delegation_training row per
    (person_id, setting), settings replies | follow_ups | actions | drafts,
    PUT /delegation/training (putting replies/follow_ups in or actions out
    is narrowing and needs no signed caller; anything else does). Every
    allowance is a take_the_lead_allowed row, feature act_as_me, person_id
    set, key act_as_me|person:<id>|<action>|<who>: reply|<address>,
    follow_up|<sorted addresses>, message|person:<id>,
    invite|people:<sorted ids, self left out>, style|<address> (a kept
    example); training.setting_of(key) labels the one learned list. Theirs
    alone, capped per person (ALLOWED_MAX), never in learned_note.
    Replies in training: every reply waits (handle_it_reason training)
    unless its sender was allowed with Send and the "on its own next time"
    tick (POST /decisions/{id}/approve edits.allow; the tick replaced the
    separate Send + allow / Approve + allow buttons, 2026-10); an allowed sender's reply goes on
    its own only while Handle it is enabled, under the dial's Rules with
    the stranger check skipped, every other refusal check, and again at
    send time (removed since: handle_it_off). Follow-ups in training: the
    same with follow_up_training and follow_up_refusal skipping the
    relation check for exactly the allowed recipients. Take the lead as
    you lifts nothing while either is in training (turned off when they go
    in; PUT /delegation/take-the-lead answers 409 in_training). Suggested
    actions in training: Approve with the tick (edits.allow) on a
    delegation_actions card allows each message/invite that ran (never
    add_contact); propose_actions then carries out a card whose every
    action is allowed at once (action_cards.on_its_own_refusal: training
    on, Act as me on, signing_ok, not sensitive, no link or amount, message
    <= 1200 chars, at most ON_ITS_OWN_PER_DAY 10 actions a day, under one
    lock; run_on_its_own claims it, gate_mode auto_execute, status
    executed; a refusal there hand_back()s it to an ordinary card). An
    invite run on its own skips calendar_tools.approved_by, so the meeting
    gate decides (security review: a mail-chosen time must not be booked
    unasked).
    Guardrail (accepted tradeoff, review of PR 408): propose_actions runs
    on turns that read untrusted mail, so a message carried out on its own
    has model-written text nobody reads first. The allowance covers who
    and what kind, never the words; the sensitive/link/amount/length
    checks and the daily cap are what bound it, and only allowed roster
    people can receive it.
    Suggested actions On (training.ACTIONS_ON, row actions_on in
    delegation_training, PUT /delegation/training {actions_on}; In training
    wins when both are set and the route clears one when the other is set
    true): a card is carried out with no allow under the same checks plus
    _known_people_refusal (no add_contact, every recipient settled on the
    roster for SETTLED_AFTER 7 days, as for cards from another AI app).
    Nothing is learned under On. Handle it for me's web picker is Off / In
    training / On: In training sets replies and follow_ups together, and the
    dial's steps show under On only, because handle_it.refusal skips the
    level check while Replies is in training (only enabled matters).
    Drafts in training: on Send (ticked or not) with edits.example and a
    draft edited in the mailbox, the sent text is kept as style|<address>;
    training.example_for (style key first, then an older reply-key example)
    feeds the ghostwriter's <writer_example> (style only, untrusted block)
    for inbox replies, follow-ups and chat drafts to that one person. An
    old dial row on mode training moves to balanced + replies and
    follow_ups in training
    (schema._move_training_off_the_dial).
  prompt: |
    DELEGATION_ADDENDUM (prompts/executive_persona.py, a constant naming
    nobody) follows the unchanged identity addendum in block 0 while
    block0_delegation_on(session) — the install-level setting, or an eval
    session's override. See caching.block_order.persona_and_knowledge and
    caching.delegation_tool_prefix.
  api: |
    /delegation — GET, PUT {enabled}; /delegation/voice — GET, PUT (edit,
    lock), DELETE (reset); POST /delegation/voice/learn (409 in_progress /
    locked / too_soon / not_enough_mail / no_profile / changed); POST
    /delegation/voice/signature (the Gmail sendAs signature again; 409 with
    the Gmail codes, 502 gmail_error); POST /delegation/voice/describe
    {description} (an unsaved profile + sample_reply; 409 empty / too_long /
    in_progress / too_many / no_profile). The
    caller's OWN delegation only. 403 not_available_yet for a caller can_delegate
    refuses (the Settings card hides); 403 sign_in_required with no
    x-caller-email unless local login; turning it on needs gmail_status
    connected (409 gmail_not_connected / gmail_needs_reconnect /
    gmail_mismatch / no_email / shared_mailbox / gmail_error). Every change
    writes a private audit row. PUT /delegation/inbox {enabled?,
    mailbox_drafts?} (mailbox_drafts: also save each reply in their Drafts,
    off by default, so a reply lives on its card alone until Send makes the
    draft from it: delegation.card_drafts; 409
    act_as_me_off or the Gmail codes; the same DelegationOut back, whose
    inbox field is {enabled, status, message, watch_since, last_poll_at,
    checking}); POST /delegation/inbox/check (202 with the inbox state; 409
    inbox_off / in_progress); GET /delegation/replies ({cards: [...]}, see
    reply_cards; each card says in_mailbox and mailbox); PUT
    /delegation/replies/{id}/text {text} changes a reply's words on its card
    and, when it is in their Drafts, there too, only while that draft is still
    the version the card last saw (409 draft_changed / draft_not_plain /
    caller_signing_required, 422 empty / too_long); it sends nothing, and a
    change by hand sets questions_settled. PUT
    /delegation/replies/{id}/recipients {everyone} sends it to the sender
    only or to everyone the email went to (409 no_choice when nobody else
    was on it), with the same checks. POST
    /delegation/replies/{id}/change {text} (answers.change) rewrites it the
    way the person said, through the same rewrite as <change>, and adds
    their words and the Executive's note to the card's conversation (shown
    by ReplyCardOut.conversation). POST
    /delegation/replies/{id}/answer {answers: [{question_index,
    answer_text}]} (delegation.answers) answers what the reply left open:
    one composer-model call (REWRITE_PROMPT + the person's voice block, no
    tools, the draft and answers tag-scrubbed in the user turn) rewrites
    the body, signature and AI line kept out and put back, then
    ghostwriter.lint (links and addresses in neither the draft nor the
    answers removed, flags added to the card) and card_drafts.edit's own
    checks and mailbox update (rewrite= hook, held in _EDITING across the
    model call). It stores answered_questions {index: answer}, returns the
    card with changed_sentences (new sentences, found in code), 422
    no_such_question / empty / too_long, 429 too_many past
    ANSWERS_PER_HOUR (30) per person, 502 rewrite_failed; it sends nothing.
    Cards carry questions [{text, choices, source, answer}] (from
    open_questions + question_choices; a card made before choices shows
    none) and questions_settled. Why choices: tapping an answer beats
    rewriting the draft by hand on a phone. Send is POST /decisions/{id}/approve (edits carry the
    second yes; 409 confirm / caller_signing_required / draft_gone /
    you_replied / inbox_off / client_slot / the Gmail codes, 429
    rate_limited, 502 gmail_error / send_unconfirmed); Dismiss is POST
    /decisions/{id}/reject. PUT /delegation/handle-it {enabled?, mode?}
    (422 bad_mode) and GET /delegation/handled ({replies: [...]}, each with
    source), see handle_it; DelegationOut.handle_it is {enabled, mode,
    available, sent_today}; reply cards carry source ("follow_up" or "").
  may_do: |
    What it does for you (delegation.may_do, GET /what-it-may-do) is
    read-only: with the viewer's settings right now, one row per thing that
    can go out without asking, written as one sentence of what it does, its
    outcome (goes, waits, always_waits, drafts, off) and the setting that
    decides it. It sits beside every Delegate tab (DelegatePage ->
    WhatItDoesPanel: a right-hand column on a wide screen, a bottom sheet on
    a narrow one), grouped by outcome, and reloads on DELEGATION_CHANGED,
    which every delegation setter in lib/api.ts fires after a save, marking
    changed rows for ten seconds. /delegate and /delegate/what-it-may-do
    open Act as me. It reads the same settings the gates read, so it cannot say
    something they don't do: As you from settings.is_enabled,
    inbox.get_watch, handle_it.get / RULES / leading, training.get /
    learned and the person's rules; As the Executive (principal only) from
    take_the_lead.get, Lead.asks_first, the company's rules and the
    meeting_scheduling class mode; Departments from the registry. Invariant:
    a meeting Take the lead thinks of always waits, because both meeting
    gates need someone on a verified surface in the turn; Always asks first
    -> Meetings asked for in chat (meeting_scheduling's class mode: on is
    propose, off is auto_execute) covers only meetings someone asks for in
    chat (and in a team workspace also needs Operations on auto_execute). Department levels
    never hold Take the lead's own actions; Always asks first and the
    company's rules do. It writes nothing and reads no mail. 403 for a
    contact, anyone not on People, or no caller outside local login.
  reach: |
    How far it goes as you (ReachCard, PUT /delegation/reach {step}) is one
    dial over the Act as me switches: off, when_asked (Write drafts as me),
    inbox (Draft replies to my inbox), careful / balanced / bold (Handle it
    for me and its mode) and everything (Take the lead as you, owner only).
    reach_of derives the step from the stored switches; nothing new is
    stored, so every gate reads exactly what it read before. Down turns the
    switches above the step off, highest first, so no switch is ever on
    above one that's off; a lower sending mode is set directly and needs no
    signed sign-in. Up calls each switch's own route in order, so the
    mailbox, signed sign-ins, owner-only and not-in-training checks all
    still apply, and the first refusal stops at a whole step. Training is
    never changed by the dial. The UI shows it as two pickers
    (ReachCard.tsx): What it writes as you (WritesCard: off / when_asked /
    inbox, any sending step reads as inbox) on Delegate -> Act as me, and
    What it sends on its own (SendsCard: off saved as inbox, then the
    sending steps, with In training and Your rules at everything) on
    Delegate -> Handle it for me, which opens only at inbox and says so
    otherwise. Moving Act as me below inbox says Handle it for me stops
    too. What it does for you links act_as_me rows to the first and handle_it
    rows to the second.
  surfaces: |
    Settings → Act as me (ActAsMeCard): the Gmail status with the connect
    command and Check again, the Write drafts as me switch, the Draft
    replies to my inbox switch with its status line, when it last checked
    and Check now (the card polls GET /delegation while a check runs), and
    How I write
    (length and tone, a greeting input per audience, the sign-off and the
    habit / never lists in textareas that grow to fit, the signature with
    Refresh from Gmail and Don't add my signature — or Add my Gmail
    signature — and each exemplar quoted, with Remove examples).
    Settings → Your Executive (app/settings/executive; /settings/on-its-own
    redirects there): the pause. Take the lead (Delegate → Take the lead)
    lists Always asks first even while it is off, ending in Meetings asked
    for in chat (the meeting_scheduling class mode, moved from Workspace).
    Handle it for me (Delegate → Handle it for me) is What it sends on its
    own (rules at Everything), then What it sent (sent today, the week's
    list), Who it's allowed to handle (its learned items) and, under
    Advanced, the AI line on replies it sends. Setup
    status light your_gmail (amber while the inbox watcher is erroring,
    rate-limited or has 25 cards waiting); the API protection light says
    Send needs signed callers. The chat chip "Drafted an email as you
    to … — in your Gmail Drafts" opens the draft (target=_blank,
    rel=noopener noreferrer). Today: Replies waiting (RepliesWaiting, top
    of the left column, hidden unless GET /delegation/replies answers with
    cards) — each card shows the sender with their relation and whether the
    address was verified, the subject, They wrote (plain text), the draft,
    Decide before sending (open_questions) and the warnings, with Send
    (an inline confirm naming the recipients, and a second one when they or
    the thread changed), Edit in Gmail and Dismiss. Evals: a scenario's
    delegation block runs the
    turn against evals.mailbox.ScenarioMailbox and hands the saved drafts to
    the judge (delegation_001-003); type: inbox scenarios (an inbox block:
    person, relation, expect draft|no_draft, thread) run the watcher's two
    model calls on the thread's newest inbound message
    (inbox.reply_for) — whether it drafts must match, and a draft goes to
    judge_inbox (delegation_inbox_001-007; 007 checks the watcher's draft
    never claims anything was sent).
  config: |
    DELEGATION_GOOGLE_CREDENTIALS_DIR (Gmail and Outlook files alike;
    connect-own-outlook.py reads MS365_MCP_CLIENT_ID / _TENANT_ID only when
    it runs; no client secret is ever written into a person's file), DELEGATION_COMPOSER_MODEL,
    DELEGATION_MAX_DRAFTS_PER_DAY (1-1000, default 50),
    DELEGATION_INBOX_POLL_MINUTES (default 5),
    DELEGATION_INBOX_MAX_DRAFTS_PER_DAY (default 20, within the shared
    limit), DELEGATION_CLASSIFIER_MODEL (default ROUTING_MODEL),
    DELEGATION_HANDLE_IT_MAX_SENDS_PER_DAY (1-500, default 20).
  take_the_lead: |
    Take the lead (orchestrator.take_the_lead): the Executive acts on its
    own behind one gate. Two switches, off by default, rows in
    take_the_lead keyed by scope. "executive" (principal only, PUT
    /take-the-lead): unattended_toolkit and the chat loop's unattended path
    keep solo's booking / run_workflow / unrestricted message_person and
    wrap every acting tool (ACTING_TOOLS, and every MCP tool except a name
    that plainly reads and says nothing about acting: mcp_tool_acts fails
    closed) in the gate; UNATTENDED_WITHHELD_TOOLS stay
    withheld and every guard inside a handler still applies, so department
    approval levels hold. The reflection pass also gets the MCP gateway's
    search_tools and call_tool (executive_reflection._with_lead_tools;
    call_tool behind the gate, load_mcp_server left out) so it can find
    and use whatever the deployment has connected, with a user-turn note
    telling it to act (_LEAD_NOTE, never the cached system prompt) and
    room for it: 10 iterations, 4000 tokens, tool results up to 4000
    characters (execute_tool_calls result_chars). New mail or chat
    (a turn with origin_channel) wakes the reflection early: one
    take_the_lead_wake action 5 minutes out, none while one waits, at most
    every 30 minutes; the pause holds it. "person:<id>" (owner only for
    now, PUT /delegation/take-the-lead): the Handle it for me dial's top
    step; handle_it.refusal drops the mode limits (strangers, confidence,
    amounts, length up to 4000) for the added rules (lead_rule) and
    keeps everything else Handle it always keeps; a reply with a link
    still waits on a card (refusal link), since a link sent as the owner
    is the shape a phish takes (owner's choice).
    The gate (take_the_lead.check, plain code): six kinds, each with an Ask
    first switch (the decision ledger's mode for take_the_lead_action:<kind>,
    propose by default), all on to start: money, contracts, people_decisions,
    delete_share, someone_new (not on the roster or contacts), big_send
    (broadcast, department message, more than 5 people). Added rules
    (take_the_lead_rules, scope company or person:<id>; kinds person,
    domain, words, amount) always hold; unreadable rules hold the action.
    Recipients are the addresses in the input plus, for tools that name a
    person by id (message_person, assign_open_loop, the Slack / Telegram /
    Discord DMs), that person's addresses and name (_targets); an id the
    People list doesn't have counts as someone new. A name rule matches
    whole words. A direct message (message_person or a Slack / Telegram /
    Discord DM) whose only recipient is the principal skips the gate and is
    sent (_only_to_principal): the principal is who it would wait for, so a
    card would only ask them to approve a message to themselves. Anything
    that reaches or acts on anyone else is checked; an unreadable roster is
    not the principal.
    Structured only: no model reads a rule. A held action is a
    take_the_lead_action decision (principal_and_approver: only the
    principal and its approver see or resolve it) with a Today card,
    routed to the first non-principal teammate holding one of its People
    approval ranges (take_the_lead.approval_ranges, plain code, closest
    first: money spend_lt_2k / spend_lt_10k / spend_gt_10k by its largest
    amount, a higher range approving a lower one, no amount = gt_10k, or
    customer_credit for credit and terms; contracts vendor_onboarding then
    legal_sign for vendors, else legal_sign; hiring hiring_signoff; anything
    else about the board or investors board_comms; deletes and shares none;
    Personal mode too), else the authority gate's _route_proposal fallback to
    the principal. An action that reaches anyone off the team (a contact,
    someone unknown) always goes to the principal (_team_only): only their
    approval opens contact egress, and contacts are theirs alone. Approve
    claims the row and runs the exact call once (carry_out); reject drops it.
    take_the_lead_log feeds Recent activity (kind took_the_lead, named not
    quoted); /today/activity adds the caller's own Handle it sends
    (sent_as_you). No separate What I did list.
    In training (the executive row's training column; Settings shows Off /
    In training / On): an action check() lets through still waits as a
    training hold (Hit kind "training", always the principal's, alert tag
    take_the_lead:training) unless take_the_lead_allowed has its allowance
    key: action + who, <feature>|message|person:<id> for any direct message
    channel, |book|people:<ids> for exactly those attendees, |assign|,
    |workflow|<id>, |department|<slug>, |mcp|<tool>|<file name>|<argument names> (none
    for a connected tool with no file name or that reaches people: to/cc,
    recipient keys, an argument named for sharing, links or access, any
    address in it; a new argument is a different action); someone off the People list gives
    no key (keeps asking). edits.input is the principal's alone (403). The card's payload carries
    allow {key, label} and fields (editable_fields: message text; a
    meeting's title, start, end, description; a task and due date).
    /decisions/{id}/approve edits.input applies only those fields
    (apply_edits, EditError → 422) and finishes approved_with_edit;
    edits.allow on a training card (only) needs the principal on a provable
    request (403) and stores the allowance with the changed fields as its
    example (the wording fields only: text, title, description, task).
    Owner's choice: an edit with "Do it like this next time" both
    keeps the example and allows at once. learned_note() (training flag +
    the examples, the principal's own edited text only) is appended to the
    reflection and research user turns. suggestions(): training cards
    approved unchanged SUGGEST_AFTER (3) times in 30 days and not allowed;
    POST /take-the-lead/learned allows only a current suggestion, DELETE
    removes one (tightening, no proof needed; the row keeps removed_at so
    only approvals after it count toward suggesting it again). Leaving training while on is
    loosening (provable owner). The allowed list is shared across features
    (feature column, owner's choice: one list, a switch per feature); Act as
    me is the second (feature act_as_me, per person, a training switch per
    setting: see delegation).
  state: |
    delegation_settings, delegation_voice, delegation_voice_history,
    delegation_drafts, delegation_inbox_watch, delegation_inbox_messages,
    delegation_handle_it, delegation_handled, delegation_reminders,
    delegation_mail_read, delegation_training, delegation_saved_files and
    delegation_saved_folder (delegation.schema.TABLES) in the episodic DB (created by
    memory.episodic.initialize_db via delegation.schema.ensure_schema); per
    company — in clients.slots._BLANK_WIPE_TABLES and
    cli.fixture_loader.reset_all_state. A reply card is a decision_instances
    row (see trust_ledger).
  later_phases: |
    Each is its own change behind its own switch, off by default: more
    kinds under Handle it for me (meetings, handing to a teammate,
    the Executive's own ideas); stand in on positions the person approved.

diagram_style:
  required_classdefs: [entry, compute, storage, cache, external, hot]
  rules:
    - Always use classDef-compatible role tags on each node so the shared dark-theme palette applies.
    - Use 4-space indents; quote labels that contain colons or parentheses.
    - For flowcharts, prefer top-down layout for stacks; left-right for horizontal flows.
    - For sequence diagrams, never include classDef (Mermaid rejects it on sequence).

for_executives:
  audience: |
    Senior reader who is not the engineer — a founder, board member,
    head of department, or executive being walked through Open
    Executive for the first time. They have a 30-minute coffee with
    the team and want to understand the shape of the thing, not the
    plumbing.
  tone: |
    Outcomes first, internals last. Plain language. Short paragraphs.
    No mention of Pydantic, ChromaDB, MCP, FastAPI, Anthropic, prompt
    caching, cache_control, JSON schemas, asyncio, SQLite, classDef,
    or any class/function name. If a sentence would only make sense to
    a backend engineer, rewrite it so a non-engineer would nod along.
    The four "Without the Jargon" sections are the FIRST thing a
    friendly executive sees — earn the click into the deeper sections
    by being readable, not exhaustive.
  elevator_pitch: |
    Open Executive is a virtual executive backed by a small council of
    specialist agents (strategy, finance, product, operations, legal,
    HR, marketing, board communications). It joins your team's day —
    acting on its own where it's been given authority, proposing for
    approval where it hasn't, and escalating in real time on the
    things only the principal should see. The internals are visible
    and editable; nothing happens in a black box.
  three_modes:
    act:
      label: Act on its own (auto_execute)
      meaning: |
        For routine, recoverable work — daily engineering hygiene,
        meeting nudges, doc sweeps — Open Executive just does it and
        shows you what it did. The kind of work you wouldn't want to
        approve case-by-case.
      example: |
        Engineering pings the team each morning with open PRs older
        than 48 hours and any deploy failures in the last day. No
        approval; the digest just lands.
    propose:
      label: Propose for approval (propose_only)
      meaning: |
        For decisions that need a human signature — bringing on a new
        vendor, hiring a contractor, releasing a customer-facing
        feature — Open Executive drafts the work, parks it in the
        right person's queue, and does NOT send anything until they
        approve.
      example: |
        Finance drafts the month's vendor spend ($1,800 across three
        tools), routes it to whoever holds the "approve money under
        $10k" tag, and waits. No payment moves until they say yes.
    escalate:
      label: Escalate to a human (escalate)
      meaning: |
        For work too sensitive or time-critical for the routine queue —
        legal, a board-level event, a key customer upset — Open Executive
        drafts the response and puts it in front of the right person
        straight away, flagged urgent, even outside their working hours.
        Nothing is sent until they approve; approving sends it right away.
        (It used to send first and alert at the same time, which is not
        what "escalate to a human" promises.)
      example: |
        A customer's lawyer emails about a contract dispute. Legal is set
        to escalate, so Open Executive drafts the holding reply and the
        general counsel sees an urgent card within minutes — but the reply
        only goes out when they approve it.
  proactive_examples: |
    What Open Executive does when you're not in a chat with it:
      - Sends a morning brief (state of departments, what needs your
        attention) once a day on your preferred channel.
      - Sends an end-of-day digest (what landed, what's outstanding)
        each evening.
      - Runs check-ins with each department on its cadence (weekly,
        monthly) and posts the result to the team.
      - Nudges people on commitments that have gone quiet — if you
        promised someone you'd reply by Friday and haven't, it'll
        remind you.
      - Watches for inbound signal across email / Slack / Discord /
        Telegram and routes anything material to the right specialist
        before you ever see it.
  who_approves_what: |
    Approval routing is by TAG, not by job title. Each person carries
    one or more tags that describe what they're cleared to approve:
      - "approve money under $10k" — bookkeeper / ops finance
      - "approve money under $2k" — anyone with a corporate card
      - "sign off on hires" — the principal or HR head
      - "onboard a new vendor" — whoever owns that domain
      - "speak for the board" — the board comms owner
      - "extend customer credit" — the head of sales / customer success
      - "anyone, anything" — the principal (the wildcard)
    When a proposal needs approval, Open Executive looks for someone
    who carries the matching tag and routes the proposal to them. If
    nobody matches, it falls back to the principal. The principal is
    always the final stop.
  see_also:
    nojargon_what_it_is: For the wiring underneath, see `overview` and `agents`.
    nojargon_authority: For the implementation, see `org` (departments + people + authority gate).
    nojargon_proactive: For the runner and cadence DSL, see `scheduler` and `today`.
    nojargon_org: For the data model and routing rules, see `org` and `schemas`.

trust_ledger: |
  Per-class reliability record that powers the first-climb autonomy loop
  (FIRST_CLIMB_MEETINGS.md).  All tables live in the main episodic SQLite DB
  (packages/core/company/episodic.db).

  Tables:
    decision_instances  — one row per gated action proposal/execution.
      Columns: id, decision_class, created_at, department,
               originating_session_id, proposed_payload_json,
               idempotency_key (UNIQUE partial index), gate_mode,
               approver_person_id, confidence, status, resolved_at,
               resolver_person_id, final_payload_json, external_event_id,
               reversal_reason, severity.
      Status lifecycle: proposed → approved_unchanged | approved_with_edit |
        rejected | auto_no_response | failed | reversed (from approved/executed)
        executed → reversed | failed  (auto-execute path, Build 3)
        proposed → executing → approved_unchanged | approved_with_edit | failed,
          or back to proposed (release_claim: nothing was done)
        proposed → executing → executed: an auto_execute row acted on its
          own with no resolver (delegation.handle_it replies)
        proposed | executing → closed_externally (settled outside the app;
          the reason code goes in reversal_reason)
      All status transitions are compare-and-set — no silent overwrites.
      "executing" is for an approval with an outside effect that must happen
      once (sending an email): claim_for_execution claims the row BEFORE
      acting, so of two taps only one acts; a failure that leaves it unclear
      whether the effect happened stays executing for a reconciler, never
      retried. get_live_by_idem counts executing as open.

    decision_class_state — one row per class; holds the promoted/propose mode.
      Columns: decision_class (PK), mode (propose|auto_execute), updated_at,
               last_eval_json, breaker_tripped_at.
      Default-absent = propose (fail-safe; missing row ≠ promoted).

  CRUD + reliability reader: openexecutive.memory.decision_ledger
    create_decision_instance / get_decision_instance / mark_resolved /
    mark_reversed / mark_executed / claim_for_execution / finish_execution /
    release_claim / close_externally / record_high_severity_miss /
    list_instances / get_class_mode / set_class_mode /
    aggregate_reliability → ReliabilityCard

  API: openexecutive.api.routes.decisions
    What approve / reject / cancel do is per class: DECISION_CLASSES maps a
    class name to a DecisionClassSpec(name, principal_only, alert_source,
    approve, after_reject, cancel). Meeting booking is the spec for
    meeting_scheduling (approve books the event, cancel deletes it).
    delegation_reply is the inbox watcher's reply card (see
    delegation.reply_cards): principal_only, no alert; approve sends its
    draft (delegation.send: claim_for_execution before the send,
    finish_execution after, an unconfirmed send left executing for the
    reconciler), and after_reject deletes the draft when unedited. An
    instance of a class with no spec gets 409 on every action, never
    carried out as another class. A principal_only class is hidden from
    everyone else like a private payload (left out of GET /decisions, a 404
    on the rest). A reject that loses its compare-and-set is a 409; the
    class's after_reject runs after it, best effort. A class with no cancel
    answers 409 to /cancel.
    GET  /decisions              — list instances (filterable by class, status)
    GET  /decisions/{id}         — single instance detail
    POST /decisions/{id}/approve — approve proposal; creates calendar event via MCP
    POST /decisions/{id}/reject  — reject proposal
    POST /decisions/{id}/cancel  — cancel an approved/executed event
    GET  /decisions/classes/meeting_scheduling — {decision_class, mode}
                                   where mode is propose | auto_execute
    PUT  /decisions/classes/meeting_scheduling — body {mode}; same shape
                                   back. Principal only
                                   (chat._caller_is_principal_or_unclaimed,
                                   403 otherwise), 422 on any other mode;
                                   auto_execute is a 409 while no
                                   non-archived principal exists (the
                                   route is open to anyone then), propose
                                   stays allowed;
                                   a change writes a
                                   decision_class_mode_changed audit row
    GET  /audit/reliability      — ReliabilityCard for a class+window. The
                                   principal's alone (403 otherwise): it
                                   counts private decisions too
    Who may resolve: the principal, or the person the decision went to for
    approval (approver_person_id). Anyone else gets 403 on approve, reject
    and cancel (decisions._resolver). One nobody was asked about
    (approver_person_id NULL), or one private to the principal, is the
    principal's alone. The resolver's Person id is recorded in
    resolver_person_id. reset_all_state wipes decision_instances and
    decision_class_state, as the client-slot wipe already did.

  Briefing bridge: a proposed booking is surfaced as a companion briefing alert
    (calendar_tools._propose_via_decision_alert; source='decision_scheduling',
    external_id='decision:{id}', routed to the approver). approve/reject/cancel
    clear that alert (set_status_by_external → 'ack'/'dismissed') so it leaves the
    briefing once resolved. The dedicated /proposals UI page was removed —
    proposals are reviewed in the briefing. The endpoints (including /cancel and
    /audit/reliability) are retained for API/audit use even though no UI page
    consumes the reliability card or cancel-from-UI anymore.

  Invariants:
    1. Code caps (horizon, business-hours, roster, principal, max-events/day)
       enforced in create_calendar_event handler regardless of class mode.
    2. Class mode default-absent = propose (fail-safe).
    3. Circuit breaker (Build 3) wins over evaluator on same-tick conflict.
    4. Status transitions only via compare-and-set (rowcount check).
    5. Idempotency key UNIQUE partial index prevents duplicate proposals.

  Current class: meeting_scheduling (calendar booking).
  AuthorityScope.MEETING_SCHEDULING added to people/models.py.
  Department: operations (default; changeable per org structure).

  Solo mode: create_calendar_event gates on the class mode, with no
  gate_action("operations", …) call, so it works with no operations
  department (calendar_tools._solo_meeting_gate). auto_execute books now
  ONLY when the turn was started by the principal on a verified surface
  (people_tools.is_principal_on_verified_surface — the roster-write rule:
  web chat, their own Slack/Discord, private Telegram with a valid webhook
  secret; fails closed); an inbound email, a contact's turn or an
  unattended run gets a proposal to the principal instead, so injected
  text cannot book a meeting. A proposal goes to a non-principal team
  member holding the Meetings range (meeting_scheduling, on People), else
  the principal; a booking with a contact on it stays the principal's
  (private). Team is
  unchanged (department gate AND class mode).