Skip to content

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

feat(briefing): email briefs as a backup and show when one isn't sent (#226)

Rufus71a75c818f7b
diff --git a/packages/core/openexecutive/api/routes/today.py b/packages/core/openexecutive/api/routes/today.py
index dc3b3abb..729fcf41 100644
--- a/packages/core/openexecutive/api/routes/today.py
+++ b/packages/core/openexecutive/api/routes/today.py
@@ -1480,6 +1480,64 @@ def get_today_activity_daily(
return _build_daily_activity(days)
+class BriefDeliveryNotice(BaseModel):
+ """The latest brief that didn't reach the owner, for the notice above the
+ Briefing."""
+
+ brief: str # "morning brief" or "end-of-day digest"
+ at: str # when it ran (ISO)
+ problem: str
+ fix: str
+ # Whether it was written, so it can still be read on the Artifacts page.
+ readable: bool
+
+
+def _brief_delivery_notice() -> BriefDeliveryNotice | None:
+ from openexecutive.briefing.brief_state import (
+ DELIVERY_PROBLEMS,
+ brief_name,
+ current_problem,
+ last_delivery_outcome,
+ )
+ from openexecutive.config import get_settings
+ from openexecutive.scheduler.runner import principal_delivery_plan
+
+ # With the scheduler off no brief is coming; the Setup status page says so.
+ if not get_settings().scheduler_enabled:
+ return None
+ last = last_delivery_outcome()
+ if last is None:
+ return None
+ principal, plan = principal_delivery_plan()
+ reason = current_problem(last, has_owner=principal is not None, can_deliver=bool(plan))
+ if reason is None:
+ return None
+ problem, fix = DELIVERY_PROBLEMS[reason]
+ return BriefDeliveryNotice(
+ brief=brief_name(last.kind),
+ at=last.at.isoformat(),
+ problem=problem,
+ fix=fix,
+ readable=last.reason != "not_written",
+ )
+
+
+ "/today/brief-delivery",
+ response_model=BriefDeliveryNotice | None,
+ tags=["today"],
+)
+async def get_brief_delivery(request: Request) -> BriefDeliveryNotice | None:
+ """The latest morning brief or end-of-day digest that didn't reach the
+ owner and still has a problem to fix, or null. Only the owner is told:
+ anyone else gets null, since it is about the owner's channels."""
+ from openexecutive.api.routes.chat import _caller_is_principal_or_unclaimed
+
+ if not await asyncio.to_thread(_caller_is_principal_or_unclaimed, request):
+ return None
+ return await asyncio.to_thread(_brief_delivery_notice)
+
+
@router.get(
"/morning-brief",
response_model=TodayResponse,
diff --git a/packages/core/openexecutive/api/setup_checks.py b/packages/core/openexecutive/api/setup_checks.py
index 7f4a33f0..aac9d032 100644
--- a/packages/core/openexecutive/api/setup_checks.py
+++ b/packages/core/openexecutive/api/setup_checks.py
@@ -22,7 +22,7 @@ import logging
import os
import re
from collections.abc import Awaitable, Callable, Sequence
-from dataclasses import dataclass
+from dataclasses import dataclass, field
from datetime import UTC, datetime
from pathlib import Path
from typing import TYPE_CHECKING, Any, Literal
@@ -34,6 +34,7 @@ from pydantic import BaseModel
if TYPE_CHECKING:
from openexecutive.audit import AuditEvent
+ from openexecutive.briefing.brief_state import DeliveryOutcome
from openexecutive.config import Settings
from openexecutive.people.models import Person
@@ -105,6 +106,7 @@ LABELS: dict[str, str] = {
"telegram": "Telegram",
"google_chat": "Google Chat",
"scheduler": "Daily schedule",
+ "brief": "Daily brief",
"memory": "Long-term memory (Honcho)",
}
@@ -144,6 +146,13 @@ class Snapshot:
discord_bot_task: asyncio.Task[None] | None = None
slack_handler: Any = None
mcp_gateway: Any = None
+ # The daily brief: its latest run, whether email can carry it, when each
+ # brief next goes out, and the zone the user chose for those times (None:
+ # nobody chose one, so UTC).
+ brief_delivery: DeliveryOutcome | None = None
+ brief_email_ready: bool = False
+ brief_next_runs: dict[str, datetime] = field(default_factory=dict)
+ brief_zone: str | None = None
def _clip(text: str) -> str:
@@ -864,6 +873,81 @@ def check_scheduler(snap: Snapshot) -> SetupCheck:
return _result("scheduler", "ok", "Running.")
+# Delivery channel (scheduler.runner.delivery_order) → its light on this page.
+_DELIVERY_CHANNEL_CHECKS: dict[str, str] = {
+ "email": "gmail",
+ "slack_dm": "slack",
+ "discord_dm": "discord",
+ "telegram": "telegram",
+}
+
+
+def check_brief(snap: Snapshot) -> SetupCheck:
+ """When the morning brief and end-of-day digest go out, and where."""
+ from zoneinfo import ZoneInfo
+
+ from openexecutive.briefing.brief_state import (
+ BRIEF_KINDS,
+ CHANNEL_NAMES,
+ DELIVERY_PROBLEMS,
+ brief_name,
+ channel_phrase,
+ current_problem,
+ )
+ from openexecutive.scheduler.runner import delivery_order
+
+ if not snap.settings.scheduler_enabled:
+ return _result("brief", "off", "Off, because the scheduler is turned off.")
+ principal = snap.principal
+ if principal is None:
+ problem, fix = DELIVERY_PROBLEMS["no_owner"]
+ return _result("brief", "warn", f"Not sent: {problem}.", fix, link="/people")
+ plan = delivery_order(principal, email_ready=snap.brief_email_ready)
+ if not plan:
+ problem, fix = DELIVERY_PROBLEMS["no_channel"]
+ return _result(
+ "brief",
+ "warn",
+ f"Kept in the app only: {problem}.",
+ fix,
+ link=f"/people/{principal.id}",
+ )
+ last = snap.brief_delivery
+ reason = current_problem(last, has_owner=True, can_deliver=True)
+ if last is not None and reason is not None:
+ problem, fix = DELIVERY_PROBLEMS[reason]
+ return _result(
+ "brief", "error", f"Your last {brief_name(last.kind)} wasn't sent: {problem}.", fix
+ )
+ if last is not None and last.channel and last.channel != plan[0]:
+ # It got through, but not on the first channel it tried: that one is
+ # broken, and every brief is going by the backup.
+ first = CHANNEL_NAMES[plan[0]]
+ return _result(
+ "brief",
+ "warn",
+ f"Your last {brief_name(last.kind)} went {channel_phrase(last.channel)}, "
+ f"because {first} didn't work.",
+ f'See the "{LABELS[_DELIVERY_CHANNEL_CHECKS[plan[0]]]}" light on this page.',
+ )
+ zone = ZoneInfo(snap.brief_zone or "UTC")
+ times = [
+ f"the {brief_name(kind)} at {snap.brief_next_runs[kind].astimezone(zone):%H:%M}"
+ for kind in BRIEF_KINDS
+ if kind in snap.brief_next_runs
+ ]
+ when = f": {' and '.join(times)}" if times else ""
+ if snap.brief_zone is None:
+ return _result(
+ "brief",
+ "warn",
+ f"Sent to you {channel_phrase(plan[0])}{when}, in UTC because no time zone is set.",
+ "Set your time zone in Settings.",
+ link="/settings",
+ )
+ return _result("brief", "ok", f"Sent to you {channel_phrase(plan[0])}{when} ({snap.brief_zone}).")
+
+
async def check_memory(snap: Snapshot) -> SetupCheck:
from openexecutive.api.routes.health import honcho_health
@@ -906,11 +990,19 @@ def _latest_inbound() -> dict[str, AuditEvent | None]:
def gather_snapshot(settings: Settings, *, local_login: bool, app_state: Any) -> Snapshot:
"""Read everything the checks need. Blocking (SQLite): run it off the loop."""
+ from openexecutive.briefing.brief_state import last_delivery_outcome
+ from openexecutive.memory.workspace_settings import get_user_timezone, get_workspace
from openexecutive.people.store import find_principal_person, list_people
+ from openexecutive.scheduler.runner import email_ready, next_brief_runs
+ now = datetime.now(UTC)
+ zone_chosen = (
+ get_workspace().timezone is not None
+ or settings.user_timezone.strip() not in ("", "UTC")
+ )
return Snapshot(
settings=settings,
- now=datetime.now(UTC),
+ now=now,
local_login=local_login,
people=list_people(),
principal=find_principal_person(),
@@ -919,6 +1011,10 @@ def gather_snapshot(settings: Settings, *, local_login: bool, app_state: Any) ->
discord_bot_task=getattr(app_state, "discord_bot_task", None),
slack_handler=getattr(app_state, "slack_handler", None),
mcp_gateway=getattr(app_state, "mcp_gateway", None),
+ brief_delivery=last_delivery_outcome(),
+ brief_email_ready=email_ready(),
+ brief_next_runs=next_brief_runs(now),
+ brief_zone=get_user_timezone().key if zone_chosen else None,
)
@@ -941,6 +1037,7 @@ def _check_runners(
"telegram": lambda: check_telegram(snap, http),
"google_chat": off_loop(check_google_chat),
"scheduler": off_loop(check_scheduler),
+ "brief": off_loop(check_brief),
"memory": lambda: check_memory(snap),
}
diff --git a/packages/core/openexecutive/architecture/architecture-facts.yaml b/packages/core/openexecutive/architecture/architecture-facts.yaml
index 19707b53..c188021a 100644
--- a/packages/core/openexecutive/architecture/architecture-facts.yaml
+++ b/packages/core/openexecutive/architecture/architecture-facts.yaml
@@ -4176,7 +4176,7 @@ workflows:
- 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 (`google_workspace__send_gmail_message`, `user_google_email` = the Executive's own address, `to` = the principal's email, subject `<workflow title> — <date>`; an in-band error counts as failed, `workflows.action_step.looks_like_error`) and is used only when the preference is `email` (tried first) or `any` with no chat channel (tried last) — an owner linked by email at setup has `any` and keeps their chat delivery without extra emails. Email is not a DM, so the per-Person outbound guard does not apply; the gateway's roster egress gate does. 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."
+ - "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 | send_failed. 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. `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`)."
- "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`."
- "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)."
@@ -4695,7 +4695,19 @@ integrations:
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. Sample values from .env.example (setup_checks.EXAMPLE_VALUES,
+ 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
@@ -5127,9 +5139,9 @@ integrations:
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) when the principal
- prefers email, or prefers "any" and has no chat channel — see
- `workflows` → morning_brief.
+ 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
diff --git a/packages/core/openexecutive/architecture/prebuilt/api.json b/packages/core/openexecutive/architecture/prebuilt/api.json
index 844c08ce..a4e19555 100644
--- a/packages/core/openexecutive/architecture/prebuilt/api.json
+++ b/packages/core/openexecutive/architecture/prebuilt/api.json
@@ -1,7 +1,7 @@
{
"section_id": "api",
"title": "API Reference",
- "markdown": "The FastAPI surface lives in `openexecutive.api.main`, which mounts one router per topic. A shared-secret middleware gates every request via an `x-api-key` header, except `/health` and the `/webhook/*` callbacks (which carry their own verification). With local login (`OE_LOCAL_LOGIN=1`, which only `make dev` sets, and only while Google sign-in is not set up) a second middleware answers 403 to any request whose raw `Host` is not `localhost`, `127.0.0.1` or `[::1]` (except a webhook that verifies its caller: Google Chat always, Telegram only with a `TELEGRAM_WEBHOOK_SECRET` Telegram can send), and to any write whose `Sec-Fetch-Site` is present and not `same-origin`/`none`. The UI signs that owner in with no password and this API usually has no secret, so without it a web page in the owner's browser could drive the API as the principal — by DNS-rebinding its own hostname to 127.0.0.1, or by posting a plain form from another site or localhost port. CORS is restricted to configured UI origins. The gate is off when `BACKEND_SHARED_SECRET` is unset — intended for local development only — so any internet-reachable deployment sets `OE_PUBLIC_DEPLOYMENT`, and `create_app()` then refuses to boot without the secret rather than serving an unauthenticated API.\n\nEndpoints grouped by router:\n\n| Router | Key endpoints | Purpose |\n|---|---|---|\n| `chat` | `POST /chat`, `POST /chat/stop` | SSE stream of a live Executive turn. The request body optionally carries `page_context` (route, page title, guide section id, and a form descriptor with current values) — sent only by the Ask OE side panel so the Executive can explain the current page or propose form values. When the Executive calls its `propose_form_values` tool, the stream emits a `form_patch` event (`{type, form_id, fields, rationale, iteration}`) that the panel applies into the on-screen form as highlighted suggestions; the user reviews and saves through the form's normal submit path. Each round of tool calls also emits an `activity` event (`{type, label, tool, iteration}`) naming what is running — progress only, forwarded verbatim and never persisted with the message, unlike an `action_taken` chip. A `session_id` in the body must be a chat the caller may use (the same ownership rule as `sessions`). If it isn't, the turn runs in a fresh chat instead, so nothing is written into someone else's session and the reply looks the same as for an unknown id. An unknown namespaced id (`slack:…`, `telegram:…` and so on) is ignored and a fresh chat is started, because those ids belong to the channel adapters and claiming one first would make the caller its owner. The client mints a `client_turn_id` and sends it with the turn; `POST /chat/stop` takes that id and halts the turn mid-flight, so the button is live from the moment Send is pressed rather than only once the first SSE byte arrives. A stopped turn emits a `stopped` event and then the usual `done` over the same still-open stream — never an `error` — and whatever streamed so far is persisted and flagged. The endpoint returns 404 both for an unknown id and for another caller's turn, so it cannot be used to probe which turns are live. An optional `memory_text` (1–2000 chars) is what peer memory records as the caller's words instead of `message` — the briefing handoffs send it because their seed quotes the Executive's own card; `POST /chat/upload` derives it from the typed text and filenames. Since it never reaches the transcript, the `chat_turn` audit row keeps it beside `message`. After the reply — a stopped or timed-out one too, before the `stopped` / `error` / `done` frames — a turn that looked at anything sends one `sources` event, `{type, session_id, sources: [{kind, title, url}], unavailable: [area]}`: `kind` is `company`, `knowledge`, `notion`, `research`, `document` or `web`, `url` is only ever an http(s) link or, for an earlier document, `/artifacts/<id>`, at most 12 sources (6 from the web, pages the reply cites first), and `unavailable` names parts of the analysis (\"finance\") whose specialist failed or said nothing every time it was asked. It is persisted with the reply as `chat_messages.sources`. |\n| `sessions` | `GET /sessions`, `GET /sessions/{id}`, `GET /sessions/{id}/messages`, `DELETE /sessions/{id}`, `POST /sessions/{id}/messages/{message_id}/feedback`, `GET /sessions/{id}/followup` | List, read and delete saved chat sessions (assistant messages carry their row `id` and any `feedback`). The list is scoped to the caller. Every per-session route checks ownership, because session ids are guessable (`slack:dm:<user id>`, `telegram:<chat id>`): only the session's owner or the principal gets through, and a legacy row with no owner is the principal's alone. Anyone else gets the same 404 as for an unknown id, so the routes can't be used to find out which chats exist. The one other way in is having started the chat in this process (matched by Person id or verified email, so it survives the caller being added to the roster), which is how a caller the roster can't resolve keeps using their own chat. That record is in memory, so after a restart such an ownerless chat is refused for reads. The principal can continue someone else's ownerless chat without becoming its owner. Deleting a session also drops its in-memory copy, so a later turn naming that id starts fresh. The feedback route records 👍/👎 (`{\"feedback\": \"up\"|\"down\"|null}`) on one assistant reply; only the session's own caller or the principal may rate it. The rater is stored (`feedback_by_person_id`), and a 👎 on a reply to the rater's own message triggers a working-style pass for them (paced; see attunement). The chat stream's `done` event carries `message_id` for the persisted reply. The followup route returns `{\"suggestion\": string|null}` — one suggested next user message, written by the utility-fast model from the last few turns, that the chat composer shows as its greyed placeholder (Tab / → or the inline chip fills it in without sending). It is null unless the session ends on a persisted assistant reply, and null (uncached) when the model fails. Same ownership check as feedback; successful suggestions are cached in-process per (session, reply id). Messages from `GET /sessions/{id}/messages` carry each assistant reply's saved `sources` (the same shape as the chat stream's `sources` event, without `type`), so a reloaded chat shows them again. |\n| `today` | `GET /today`, `GET /today/activity`, `GET /today/activity/daily` | Morning-brief aggregation, recent-action rail, and Pulse heartbeat heatmap (per-day activity counts). |\n| `people` | `GET\\|POST\\|PATCH /people`, `POST /people/{id}/archive`, `GET /people/{id}/open-loops`, `POST /open-loops/{loop_id}/close`, `GET /people/{id}/outreach`, `GET\\|PUT\\|DELETE /people/{id}/attunement` | Roster CRUD and scope lookups. Archiving a person closes their open loops. The open-loop routes list what a person owes (soonest due first) and close one (`reason`: done / not_needed / cancelled) — both the principal's or the owner's only (403 otherwise, via `people.store.is_principal_or_self`). `/outreach` returns, per kind of proactive outreach over 30 days, `sent` / `replied` / `acted` / `ignored` / `pending` (voided DMs are excluded) — same access rule, checked before the person lookup so it can't probe which ids exist. `/attunement` reads, replaces (`rules`: up to 4 strings, or omitted to only set `locked`) or resets the person's working-style rules — same access rule, 404 for an archived person; `PUT` rejects a rule that is not purely about style with 422. Archiving a person also drops their working style. |\n| `departments` | `GET\\|POST\\|PATCH\\|DELETE /departments`, `.../goals` | Department state and per-department goals. `PATCH /departments/{slug}` also takes `watched_entities` (≤50 names, `[]` clears) — the entities the research watch policy may add watches for and route to this department. A `cadences` spec that does not parse is rejected with a 422 (empty means no cadence). |\n| `agents` | `GET /agents`, `GET /agents/models`, `GET /agents/models/options`, `PATCH /agents/{id}`, `POST /agents/{id}/test` | Specialist metadata and Council overrides. `/agents/models` is the flat model allowlist the PATCH validator uses; `/agents/models/options` returns the same ids in the same order, each tagged with `provider`, `provider_label`, `route` (`direct` / `openrouter` / `local`) and a display `label`, for the Council's Provider → Model picker. |\n| `personas` | `GET\\|PUT\\|POST\\|DELETE /personas` | Executive persona definitions. |\n| `alerts` | `POST /alerts/{id}/ack`, `POST /alerts/bulk-ack`, `POST /alerts/{id}/reopen`, `POST /alerts/review` | Groom the briefing queue. `ack` (`read`/`ack`/`dismissed`, optional `mute_topic`) also teaches a watch-sourced alert's watch (`trust_score`); `bulk-ack` takes explicit `alert_ids` and/or `older_than_days` + `category` (exempt sources skipped); `reopen` is the Undo for a `resolved` / `expired` / `dismissed` alert (never `ack` or an artifact / decision row; back to `unread` with every review stamp cleared and its TTL anchor refreshed, so it is live again even if older than its TTL); `review` runs the Executive's relevance review on demand (ignores the interval; still honours `ALERT_REVIEW_ENABLED`, the per-pass caps, the single-flight lock and per-alert idempotency) and returns the move counts. `bulk-ack` caps ids at 500, needs `older_than_days >= 1`, and applies watch feedback per row; `mute_topic` must be one of the alert's tags or a scoped `external:` / `department:` pattern. Alerts still surface only through the briefing (`/today` reads the live view) — there is no list, prefs, mutes, or live-stream endpoint. |\n| `artifacts` | `GET /artifacts`, `GET /artifacts/{id}`, `GET /artifacts/{id}/download?as=`, `POST /artifacts/{id}/archive`, `POST /artifacts/{id}/restore`, `DELETE /artifacts/{id}` | Browsable deliverables in any format — Markdown, HTML, Word, Excel, or a link into a connected app — with `format`, `downloads`, `external_url` and `supersedes_id` on every summary. `download` renders the file (Word/Excel built at request time from the stored text; any Markdown artifact, workflow output included, can export `?as=docx`) and is always an attachment with `nosniff` and a sandbox CSP. |\n| `decisions` | `GET /decisions`, `POST /decisions/{id}/{approve,reject,cancel}`, `GET /audit/reliability` | Approval-gated decision instances (e.g. calendar bookings). A proposed booking is surfaced on the briefing as a companion alert; approve/reject/cancel here also clear that alert. Reviewed in the briefing — there is no separate proposals page. |\n| `audit` | `GET /audit/logs`, `GET /audit/logs/{id}`, `GET /audit/sessions/{id}`, `GET /audit/usage`, `POST /audit/log` | Durable audit trail of side effects. `/audit/sessions/{id}` adds a per-session token cost summary; `/audit/usage` aggregates token usage and OpenRouter cost across all sessions (totals, by day, by model, and by source — the part of the system that made the calls — including server-side web-search counts). |\n| `architecture` | `GET /architecture/sections`, `.../sections/{id}` | This documentation surface. |\n| `guide` | `GET /guide/sections`, `.../sections/{id}` | Plain-language user-guide content surface — mirrors `architecture` (static, version-controlled files; no LLM on the serving path). |\n| `health` | `GET /health`, `GET /health/honcho` | Liveness probes (unauthenticated). |\n| `setup_status` | `GET /setup/status` | Settings → Setup status: one light per part of the install — AI model, company setup, owner, the Executive's address, API protection, Gmail, Slack, Discord, Telegram, Google Chat, the scheduler and Honcho — as `{checked_at, checks: [{id, label, state, summary, fix, link, last_activity}]}`, where `state` is `ok`, `warn`, `error` or `off` (optional and not set up), `fix` says what to do in plain language, `link` is an in-app page that helps (`/people`, `/onboard`) and `last_activity` is the channel's latest `integration_inbound` audit time. It tests live, with at most one free read-only call per service, each bounded to 5 s: Anthropic `models.list` (so an organisation key missing `ANTHROPIC_WORKSPACE_ID` shows up), Slack `auth.test`, Telegram `getMe` and `getWebhookInfo`, and Discord `users/@me` only while the bot is still connecting. It also reads the listeners the lifespan leaves on `app.state` (Slack's socket, the Discord bot and its task, the MCP gateway), the scheduler heartbeat and the pause switch. Sample values copied from `.env.example` are named as such without being sent anywhere. No token reaches a response or a log line: probes report a status code, a service's short error code or an exception's class name. Requests within 5 s of a run get that run's answer and concurrent requests share one run (kept per app on `app.state`), so the button can't become a stream of calls to those services. Gated like every other route; the UI adds a sign-in light of its own, from its own settings. |\n| `documents` | `POST\\|GET\\|DELETE /documents`, `GET /documents/{filename}` | Upload, list, view extracted text, and delete indexed company docs. Upload is keyed on the filename, so re-uploading a document replaces its chunks rather than duplicating them, and `DELETE` removes the rows as well as the file. `domain` must be one of the nine specialist domains (including `sales`) or `general`; anything else is a 400 rather than a 200 that indexes where no specialist can retrieve. |\n| `executive` | `GET /executive/status`, `POST /executive/pause`, `POST /executive/resume` | Operator pause switch for all autonomous work (scheduler, Gmail poller, workflow resumer); inbound chat and DMs stay live. Status returns `{paused, paused_at, paused_by, reason, held_actions, can_resume}` — `held_actions` counts due `pending` rows that fire on resume. `pause` takes an optional `reason` (≤200 chars) and is idempotent (re-pausing keeps the original start and reason); `paused_by` is the UI proxy's `x-caller-email`, else `api`. Behind the shared-secret middleware — not `SCHEDULED_ADMIN_TOKEN`, which the UI cannot send. Any caller may pause; `resume` is principal-only (`is_principal_or_self`, 403 otherwise; open while no principal is rostered; a header-less caller resolves to the principal as in `chat`), and status carries `can_resume` for the viewer so the UI hides Resume from everyone else. |\n| `workspace` | `GET /workspace`, `PUT /workspace` | Solo/team mode and the user's time zone (`memory.workspace_settings`). Both return `{mode, timezone, effective_timezone}` — `timezone` is what the user set (null when unset), `effective_timezone` the zone in effect (`timezone`, else `USER_TIMEZONE`, else UTC). `PUT` is a partial update: only the fields sent change; `mode` is `solo` or `team` (not null), `timezone` an IANA zone, or null/blank to clear it; an unknown zone, a bad mode or an unknown field is a 422. Switching to solo cancels every pending department check-in, switching to team re-schedules them, and a new zone re-times the pending briefs and reflection; each change writes a `workspace_settings_changed` audit row. `PUT` is the principal's alone (`is_principal_or_self`, 403 otherwise; a header-less caller resolves to the principal as in `chat`) and open while no principal is rostered, so first-run setup can pick a mode. Both work before onboarding — unlike `company-profile`, nothing here needs a profile. |\n| `scheduled` | `GET\\|DELETE` scheduled actions (`?status=…&order=asc\\|desc`) | Pending and fired scheduled actions; `order` flips the `run_at` sort (asc=soonest-first for the upcoming queue, desc=most-recent-first for terminal-status history). `DELETE /scheduled/{id}` cancels a `pending` row (409 otherwise). Like pause it only stops work, so any signed-in user may — the UI proxy's `x-caller-email` is trusted when the request also carries the `BACKEND_SHARED_SECRET` `x-api-key` — as may a matching `X-Admin-Token` (`SCHEDULED_ADMIN_TOKEN`) or a loopback caller with no token set; otherwise 401 (token set) or 503. Audited as `scheduled_action_cancelled`. |\n| `watchlist` | `GET\\|POST\\|PATCH\\|DELETE /watchlist`, `POST /watchlist/{slug}/approve`, `POST /watchlist/{slug}/decline` | External-monitoring watchlist + signals. Rows carry `origin` (`manual` \\| `executive` \\| `research` \\| `research_proposed`); `approve` turns a research suggestion (`research_proposed`, `dry_run`) into a live watch, `decline` `{reason: not_relevant \\| too_noisy \\| wrong_source}` removes it and records the decline (or, for `too_noisy`, keeps it live at a high floor), both 409 unless the row is a pending suggestion; `DELETE ?reason=` on a research-origin row records the decline too. |\n| `workflows` | `GET /workflows`, `POST /workflows/{name}/runs`, `GET\\|POST\\|PUT\\|DELETE /workflows/custom`, `GET\\|DELETE /workflows/custom/{name}/targets`, `POST /workflows/runs/{run_id}/decision`, `GET /workflows/tools/search?q=`, `GET /workflows/tools/describe?names=` | Workflow catalog, run management, and user-created (dynamic) workflow CRUD. Custom definitions come back with a server-managed `owner_person_id` (the creator — the web caller on `POST`, set on insert only; a client-sent value is ignored), who is asked to approve a workflow's first write to a new target. `GET /workflows/custom/{name}/targets` lists the targets its tool steps may write to without asking and `DELETE …/targets?value=` forgets one. `POST /workflows/runs/{run_id}/decision` with `{decision: \"approve\"|\"reject\"}` answers a run awaiting a yes/no sign-off from the web app — 403 unless the caller is the person it waits on or the principal, 409 if it isn't awaiting or needs a written reply — through the same `apply_resolution` a chat reply uses. Custom create/update also rejects (422) any action-step tool that does not resolve, and so does `POST /workflows/custom/{name}/activate` when turning a workflow **on** — that click is the approval for a tool workflow chat saved switched off (turning off is never checked). Turning on a workflow with action steps requires the body `{is_active: true, definition}` carrying the definition the user reviewed; if the stored one differs (ignoring `is_active` and timestamps) it returns 409, and the switch itself is a compare-and-set on the validated revision (`dynamic_store.activate_if_unchanged`, keyed on `updated_at`), so a save that lands while the tool check awaits the gateway — even from another process — is a 409 too, so only what was shown gets switched on. `GET /workflows/custom` lists inactive definitions too; `GET /workflows/{name}` 404s for them. The two `tools` endpoints return `{tools: [{name, description, read_only, source}]}` for the advanced editor's tool picker and the review card; `read_only` is true only when the name says it reads (a label, not a control). The run stream adds a `progress` event (`step_id`, `summary`) while an action step uses tools. Each catalog entry (`WorkflowMeta`) carries `is_custom` and `background` (true for the system-run built-ins the UI files under “System”). The run endpoint streams SSE; its `awaiting_human` event carries `delivery` (`self` \\| `sent` \\| `suppressed` \\| `alerted` \\| `failed`) alongside `person_id` / `question` / `awaiting_until`, because the outbound guard or an unreachable approver means the question may never have been asked — a client must not render “waiting on them” for those. A paused run ends the stream with neither `done` nor `error`, so that `awaiting_human` frame carries `terminal: true` to say so explicitly, plus `resumable` — whether the run continues by itself once answered or stops at the gate. `GET /workflows/runs/{run_id}` returns the run row with the resume payload replaced by a small `resume_progress` summary (`gate_step_id`, `completed_step_ids`, or `null`): the payload holds every completed step's full text, and the run-detail page polls this endpoint while a run is unfinished. |\n| `knowledge` | `/knowledge/builtin`, `/external`, `/search` | MBA knowledge base and external sources. `/search` is the introspection parallel of `retriever.retrieve` and mirrors its filters — including the `general` catch-all on the company collection — so the panel cannot report a specialist seeing nothing that it does retrieve in chat. It accepts `general` in `domain_filter` for the same reason. `/search` applies the same review gate as `retrieve()` — withheld (pending or rejected) built-in, external and failure rows are dropped, so the panel never advertises knowledge the Executive cannot use; it degrades to unfiltered rather than failing if review state is unreadable. `POST /knowledge/builtin` refuses a name already held by shipped content, and `POST|DELETE /knowledge/failures` now register and deregister for review — without that a user-authored failure case study had no review row, so no SME decision could block it. |\n| `skills` | `/skills`, `/skills/search`, `/skills/{name}/restore` | Skill registry (the UI's **Playbooks**) CRUD and search. `PUT` on a built-in saves a company customization that shadows it; `DELETE` returns `{name, outcome}` — `deleted`, `reverted` (customization removed, built-in back) or `hidden` (built-in hidden for this company); `restore` un-hides; `GET /skills?include_hidden=true` lists hidden built-ins. List and detail carry `used_by` — `[{name, title, is_custom}]` of the workflows that follow the playbook (switched-off custom ones included) (`WorkflowMeta.playbooks` is the other direction). |\n| `skill_drafts` | `/skill-drafts`, `/skill-drafts/{name}`, `/skill-drafts/{name}/approve` | Review queue for playbook changes the Executive proposed from chat. `GET` lists drafts (`action` create / update / delete, the proposed fields, an `id` version token, `current` — the playbook in effect now — and `followers`, the workflows that follow the name); `approve` (body `{id}`) applies exactly the reviewed version through the ordinary skills operations — 409 and the draft is kept if it was replaced since, on a conflict, or if its playbook vanished; `DELETE ?id=` discards that version only. |\n| `evals` | `/evals/scenarios`, `/evals/runs` | Eval scenarios and run results. |\n| `memories` | `/memories/{decisions,initiatives,advice}`, `GET /memories/people`, `GET /memories/people/{person_id}/conclusions` | Episodic-memory record management, plus the read-only peer-memory overview the Pulse People tab reads (`{status: ok|disabled|error, people: [...], conclusion_total}`; `?recent=` 1–50, default 5) and one person's full conclusion list, paged newest first (`{status, person_id, items, page, size, total, has_more}`; `?page=` ≥1, `?size=` 1–100, default 50; 404 when the person has no peer). |\n| `review` | `/review/items`, `/review/stats`, `/review/trusted-defaults`, `POST /review/curate`, `POST /review/bulk-approve` | Knowledge review queue and annotations. Shipped knowledge registers as a trusted default (`approved` with a NULL `reviewed_at`), so the queue starts empty; `curate` (`{domain, action: start|stop}`, domain required) opts one domain in or out, and `trusted-defaults` returns domain → unreviewed count. `bulk-approve` takes a non-empty `domain`, `item_ids` (max 500) or `all_pending: true`, and 400s with no selector; it returns `{approved_count, item_ids}`. |\n| `onboarding` | `/onboard/interview/start`, `/onboard/interview/message`, `/onboard/interview/draft`, `/onboard/interview/{id}`, `/onboard/interview/commit` | Conversational company setup. The `onboarding_interviewer` agent asks clarifying questions, then emits a draft profile + people + departments. **Nothing is persisted until `POST /onboard/interview/commit`** — the interview itself never writes. `start` is multipart (description + optional deck/one-pager uploads). `commit` answers 403 when the draft would make a different person the owner and the caller is not the current owner (setup demotes the old principal, and any signed-in user can open it). It also takes an optional `owner_email` — the principal's sign-in email, which the review screen pre-fills from the signed-in user — checked before anything is written (422 if it is malformed, already another person's, or would replace the principal's existing email — setup only fills in a missing one) and saved on the principal's People row, so the owner's chats resolve to them from the first turn. |\n| `workflow_designer` | `POST /workflows/designer/start`, `POST /workflows/designer/message`, `POST /workflows/designer/draft`, `GET /workflows/designer/{session_id}` | The conversational New workflow wizard. The `workflow_designer` agent asks clarifying questions (`phase: \"question\"`, with `hint` and up to four suggested `options`), then returns `phase: \"draft\"` with `draft.definition` (exactly the body `POST /workflows/custom` takes), `summary`, and `assumptions`; every response carries the `transcript`. **Nothing is persisted here** — sessions are in memory, and the UI saves through `POST /workflows/custom`. Errors are fixed strings (422 over the 8,000-char message cap or the transcript cap, 404 for an expired session, 409 while another turn on the same session is still running, 502/504 for model failure or timeout). Mounted ahead of the `workflows` router. |\n| `onboarding` (fallback) | `/onboard/start`, `/onboard/answer`, `/onboard/status/{id}` | The original 12-step form wizard, kept as a fallback (UI at `/onboard?mode=form`) and used by the `openexecutive onboard` CLI. `/onboard/start` reads the workspace mode once for the session: solo skips the Team Size, Team Members and Fractional Executives steps. Each status response's `current_step` / `total_steps` count only the steps that session asks, and `optional` says whether the current step can be skipped. |\n| `company-profile` | `GET\\|PATCH /company-profile` | Structured company profile. |\n| `auth` | `GET /auth/allowed-emails` | Non-archived people with an email, offered to the UI's sign-in gate. The gate takes the **union** of this roster and its own `ALLOWED_EMAILS` env list, so env entries always work (and are checked first, short-circuiting the fetch) and roster entries are additive — a roster change can never revoke a configured operator. With local login (`make dev` with Google sign-in not set up — the UI then listens on 127.0.0.1 only) the UI signs in without an email, sends no `x-caller-email`, and the backend resolves the caller to the principal, as it does for the CLI. |\n| `fixtures` | `/fixtures`, `/fixtures/{name}/load` | Demo-company fixture load/reset/snapshot. |\n| `clients` | `/clients`, `/clients/generate`, `/clients/cockpit`, `/clients/save`, `/clients/{slug}/activate` | Client-company slots — multi-client mode for fractional use; create from current/blank/AI-generated intake draft (pasted notes and/or file attachments, multipart on `/clients/generate`), save-back switching, engagement metadata (PATCH), cross-client cockpit, delete. See the Client Companies section. |\n| webhooks | `POST /webhook/telegram`, `POST /webhook/google-chat` | Inbound integration callbacks (self-verified). |\n| MCP server | `POST\\|GET /mcp` | Open Executive exposed as an MCP server (Streamable-HTTP). Not a router — a mounted FastMCP sub-app. Same shared-secret gate (`x-api-key`); exposes company context as resources and the specialist council as tools. See the MCP Server section. |",
+ "markdown": "The FastAPI surface lives in `openexecutive.api.main`, which mounts one router per topic. A shared-secret middleware gates every request via an `x-api-key` header, except `/health` and the `/webhook/*` callbacks (which carry their own verification). With local login (`OE_LOCAL_LOGIN=1`, which only `make dev` sets, and only while Google sign-in is not set up) a second middleware answers 403 to any request whose raw `Host` is not `localhost`, `127.0.0.1` or `[::1]` (except a webhook that verifies its caller: Google Chat always, Telegram only with a `TELEGRAM_WEBHOOK_SECRET` Telegram can send), and to any write whose `Sec-Fetch-Site` is present and not `same-origin`/`none`. The UI signs that owner in with no password and this API usually has no secret, so without it a web page in the owner's browser could drive the API as the principal — by DNS-rebinding its own hostname to 127.0.0.1, or by posting a plain form from another site or localhost port. CORS is restricted to configured UI origins. The gate is off when `BACKEND_SHARED_SECRET` is unset — intended for local development only — so any internet-reachable deployment sets `OE_PUBLIC_DEPLOYMENT`, and `create_app()` then refuses to boot without the secret rather than serving an unauthenticated API.\n\nEndpoints grouped by router:\n\n| Router | Key endpoints | Purpose |\n|---|---|---|\n| `chat` | `POST /chat`, `POST /chat/stop` | SSE stream of a live Executive turn. The request body optionally carries `page_context` (route, page title, guide section id, and a form descriptor with current values) — sent only by the Ask OE side panel so the Executive can explain the current page or propose form values. When the Executive calls its `propose_form_values` tool, the stream emits a `form_patch` event (`{type, form_id, fields, rationale, iteration}`) that the panel applies into the on-screen form as highlighted suggestions; the user reviews and saves through the form's normal submit path. Each round of tool calls also emits an `activity` event (`{type, label, tool, iteration}`) naming what is running — progress only, forwarded verbatim and never persisted with the message, unlike an `action_taken` chip. A `session_id` in the body must be a chat the caller may use (the same ownership rule as `sessions`). If it isn't, the turn runs in a fresh chat instead, so nothing is written into someone else's session and the reply looks the same as for an unknown id. An unknown namespaced id (`slack:…`, `telegram:…` and so on) is ignored and a fresh chat is started, because those ids belong to the channel adapters and claiming one first would make the caller its owner. The client mints a `client_turn_id` and sends it with the turn; `POST /chat/stop` takes that id and halts the turn mid-flight, so the button is live from the moment Send is pressed rather than only once the first SSE byte arrives. A stopped turn emits a `stopped` event and then the usual `done` over the same still-open stream — never an `error` — and whatever streamed so far is persisted and flagged. The endpoint returns 404 both for an unknown id and for another caller's turn, so it cannot be used to probe which turns are live. An optional `memory_text` (1–2000 chars) is what peer memory records as the caller's words instead of `message` — the briefing handoffs send it because their seed quotes the Executive's own card; `POST /chat/upload` derives it from the typed text and filenames. Since it never reaches the transcript, the `chat_turn` audit row keeps it beside `message`. After the reply — a stopped or timed-out one too, before the `stopped` / `error` / `done` frames — a turn that looked at anything sends one `sources` event, `{type, session_id, sources: [{kind, title, url}], unavailable: [area]}`: `kind` is `company`, `knowledge`, `notion`, `research`, `document` or `web`, `url` is only ever an http(s) link or, for an earlier document, `/artifacts/<id>`, at most 12 sources (6 from the web, pages the reply cites first), and `unavailable` names parts of the analysis (\"finance\") whose specialist failed or said nothing every time it was asked. It is persisted with the reply as `chat_messages.sources`. |\n| `sessions` | `GET /sessions`, `GET /sessions/{id}`, `GET /sessions/{id}/messages`, `DELETE /sessions/{id}`, `POST /sessions/{id}/messages/{message_id}/feedback`, `GET /sessions/{id}/followup` | List, read and delete saved chat sessions (assistant messages carry their row `id` and any `feedback`). The list is scoped to the caller. Every per-session route checks ownership, because session ids are guessable (`slack:dm:<user id>`, `telegram:<chat id>`): only the session's owner or the principal gets through, and a legacy row with no owner is the principal's alone. Anyone else gets the same 404 as for an unknown id, so the routes can't be used to find out which chats exist. The one other way in is having started the chat in this process (matched by Person id or verified email, so it survives the caller being added to the roster), which is how a caller the roster can't resolve keeps using their own chat. That record is in memory, so after a restart such an ownerless chat is refused for reads. The principal can continue someone else's ownerless chat without becoming its owner. Deleting a session also drops its in-memory copy, so a later turn naming that id starts fresh. The feedback route records 👍/👎 (`{\"feedback\": \"up\"|\"down\"|null}`) on one assistant reply; only the session's own caller or the principal may rate it. The rater is stored (`feedback_by_person_id`), and a 👎 on a reply to the rater's own message triggers a working-style pass for them (paced; see attunement). The chat stream's `done` event carries `message_id` for the persisted reply. The followup route returns `{\"suggestion\": string|null}` — one suggested next user message, written by the utility-fast model from the last few turns, that the chat composer shows as its greyed placeholder (Tab / → or the inline chip fills it in without sending). It is null unless the session ends on a persisted assistant reply, and null (uncached) when the model fails. Same ownership check as feedback; successful suggestions are cached in-process per (session, reply id). Messages from `GET /sessions/{id}/messages` carry each assistant reply's saved `sources` (the same shape as the chat stream's `sources` event, without `type`), so a reloaded chat shows them again. |\n| `today` | `GET /today`, `GET /today/activity`, `GET /today/activity/daily`, `GET /today/brief-delivery` | Morning-brief aggregation, recent-action rail, and Pulse heartbeat heatmap (per-day activity counts). `brief-delivery` returns the latest morning brief or end-of-day digest that didn't reach the owner, as `{brief, at, problem, fix, readable}` in plain language (`readable` is false when it couldn't be written, so there is nothing to read), or null — null while briefs go out, once the cause is fixed, while the scheduler is off, and for anyone but the owner (`chat._caller_is_principal_or_unclaimed`); it carries no address or channel id. |\n| `people` | `GET\\|POST\\|PATCH /people`, `POST /people/{id}/archive`, `GET /people/{id}/open-loops`, `POST /open-loops/{loop_id}/close`, `GET /people/{id}/outreach`, `GET\\|PUT\\|DELETE /people/{id}/attunement` | Roster CRUD and scope lookups. Archiving a person closes their open loops. The open-loop routes list what a person owes (soonest due first) and close one (`reason`: done / not_needed / cancelled) — both the principal's or the owner's only (403 otherwise, via `people.store.is_principal_or_self`). `/outreach` returns, per kind of proactive outreach over 30 days, `sent` / `replied` / `acted` / `ignored` / `pending` (voided DMs are excluded) — same access rule, checked before the person lookup so it can't probe which ids exist. `/attunement` reads, replaces (`rules`: up to 4 strings, or omitted to only set `locked`) or resets the person's working-style rules — same access rule, 404 for an archived person; `PUT` rejects a rule that is not purely about style with 422. Archiving a person also drops their working style. |\n| `departments` | `GET\\|POST\\|PATCH\\|DELETE /departments`, `.../goals` | Department state and per-department goals. `PATCH /departments/{slug}` also takes `watched_entities` (≤50 names, `[]` clears) — the entities the research watch policy may add watches for and route to this department. A `cadences` spec that does not parse is rejected with a 422 (empty means no cadence). |\n| `agents` | `GET /agents`, `GET /agents/models`, `GET /agents/models/options`, `PATCH /agents/{id}`, `POST /agents/{id}/test` | Specialist metadata and Council overrides. `/agents/models` is the flat model allowlist the PATCH validator uses; `/agents/models/options` returns the same ids in the same order, each tagged with `provider`, `provider_label`, `route` (`direct` / `openrouter` / `local`) and a display `label`, for the Council's Provider → Model picker. |\n| `personas` | `GET\\|PUT\\|POST\\|DELETE /personas` | Executive persona definitions. |\n| `alerts` | `POST /alerts/{id}/ack`, `POST /alerts/bulk-ack`, `POST /alerts/{id}/reopen`, `POST /alerts/review` | Groom the briefing queue. `ack` (`read`/`ack`/`dismissed`, optional `mute_topic`) also teaches a watch-sourced alert's watch (`trust_score`); `bulk-ack` takes explicit `alert_ids` and/or `older_than_days` + `category` (exempt sources skipped); `reopen` is the Undo for a `resolved` / `expired` / `dismissed` alert (never `ack` or an artifact / decision row; back to `unread` with every review stamp cleared and its TTL anchor refreshed, so it is live again even if older than its TTL); `review` runs the Executive's relevance review on demand (ignores the interval; still honours `ALERT_REVIEW_ENABLED`, the per-pass caps, the single-flight lock and per-alert idempotency) and returns the move counts. `bulk-ack` caps ids at 500, needs `older_than_days >= 1`, and applies watch feedback per row; `mute_topic` must be one of the alert's tags or a scoped `external:` / `department:` pattern. Alerts still surface only through the briefing (`/today` reads the live view) — there is no list, prefs, mutes, or live-stream endpoint. |\n| `artifacts` | `GET /artifacts`, `GET /artifacts/{id}`, `GET /artifacts/{id}/download?as=`, `POST /artifacts/{id}/archive`, `POST /artifacts/{id}/restore`, `DELETE /artifacts/{id}` | Browsable deliverables in any format — Markdown, HTML, Word, Excel, or a link into a connected app — with `format`, `downloads`, `external_url` and `supersedes_id` on every summary. `download` renders the file (Word/Excel built at request time from the stored text; any Markdown artifact, workflow output included, can export `?as=docx`) and is always an attachment with `nosniff` and a sandbox CSP. |\n| `decisions` | `GET /decisions`, `POST /decisions/{id}/{approve,reject,cancel}`, `GET /audit/reliability` | Approval-gated decision instances (e.g. calendar bookings). A proposed booking is surfaced on the briefing as a companion alert; approve/reject/cancel here also clear that alert. Reviewed in the briefing — there is no separate proposals page. |\n| `audit` | `GET /audit/logs`, `GET /audit/logs/{id}`, `GET /audit/sessions/{id}`, `GET /audit/usage`, `POST /audit/log` | Durable audit trail of side effects. `/audit/sessions/{id}` adds a per-session token cost summary; `/audit/usage` aggregates token usage and OpenRouter cost across all sessions (totals, by day, by model, and by source — the part of the system that made the calls — including server-side web-search counts). |\n| `architecture` | `GET /architecture/sections`, `.../sections/{id}` | This documentation surface. |\n| `guide` | `GET /guide/sections`, `.../sections/{id}` | Plain-language user-guide content surface — mirrors `architecture` (static, version-controlled files; no LLM on the serving path). |\n| `health` | `GET /health`, `GET /health/honcho` | Liveness probes (unauthenticated). |\n| `setup_status` | `GET /setup/status` | Settings → Setup status: one light per part of the install — AI model, company setup, owner, the Executive's address, API protection, Gmail, Slack, Discord, Telegram, Google Chat, the scheduler, the daily brief (when and where it goes) and Honcho — as `{checked_at, checks: [{id, label, state, summary, fix, link, last_activity}]}`, where `state` is `ok`, `warn`, `error` or `off` (optional and not set up), `fix` says what to do in plain language, `link` is an in-app page that helps (`/people`, `/onboard`) and `last_activity` is the channel's latest `integration_inbound` audit time. It tests live, with at most one free read-only call per service, each bounded to 5 s: Anthropic `models.list` (so an organisation key missing `ANTHROPIC_WORKSPACE_ID` shows up), Slack `auth.test`, Telegram `getMe` and `getWebhookInfo`, and Discord `users/@me` only while the bot is still connecting. It also reads the listeners the lifespan leaves on `app.state` (Slack's socket, the Discord bot and its task, the MCP gateway), the scheduler heartbeat and the pause switch. Sample values copied from `.env.example` are named as such without being sent anywhere. No token reaches a response or a log line: probes report a status code, a service's short error code or an exception's class name. Requests within 5 s of a run get that run's answer and concurrent requests share one run (kept per app on `app.state`), so the button can't become a stream of calls to those services. Gated like every other route; the UI adds a sign-in light of its own, from its own settings. |\n| `documents` | `POST\\|GET\\|DELETE /documents`, `GET /documents/{filename}` | Upload, list, view extracted text, and delete indexed company docs. Upload is keyed on the filename, so re-uploading a document replaces its chunks rather than duplicating them, and `DELETE` removes the rows as well as the file. `domain` must be one of the nine specialist domains (including `sales`) or `general`; anything else is a 400 rather than a 200 that indexes where no specialist can retrieve. |\n| `executive` | `GET /executive/status`, `POST /executive/pause`, `POST /executive/resume` | Operator pause switch for all autonomous work (scheduler, Gmail poller, workflow resumer); inbound chat and DMs stay live. Status returns `{paused, paused_at, paused_by, reason, held_actions, can_resume}` — `held_actions` counts due `pending` rows that fire on resume. `pause` takes an optional `reason` (≤200 chars) and is idempotent (re-pausing keeps the original start and reason); `paused_by` is the UI proxy's `x-caller-email`, else `api`. Behind the shared-secret middleware — not `SCHEDULED_ADMIN_TOKEN`, which the UI cannot send. Any caller may pause; `resume` is principal-only (`is_principal_or_self`, 403 otherwise; open while no principal is rostered; a header-less caller resolves to the principal as in `chat`), and status carries `can_resume` for the viewer so the UI hides Resume from everyone else. |\n| `workspace` | `GET /workspace`, `PUT /workspace` | Solo/team mode and the user's time zone (`memory.workspace_settings`). Both return `{mode, timezone, effective_timezone}` — `timezone` is what the user set (null when unset), `effective_timezone` the zone in effect (`timezone`, else `USER_TIMEZONE`, else UTC). `PUT` is a partial update: only the fields sent change; `mode` is `solo` or `team` (not null), `timezone` an IANA zone, or null/blank to clear it; an unknown zone, a bad mode or an unknown field is a 422. Switching to solo cancels every pending department check-in, switching to team re-schedules them, and a new zone re-times the pending briefs and reflection; each change writes a `workspace_settings_changed` audit row. `PUT` is the principal's alone (`is_principal_or_self`, 403 otherwise; a header-less caller resolves to the principal as in `chat`) and open while no principal is rostered, so first-run setup can pick a mode. Both work before onboarding — unlike `company-profile`, nothing here needs a profile. |\n| `scheduled` | `GET\\|DELETE` scheduled actions (`?status=…&order=asc\\|desc`) | Pending and fired scheduled actions; `order` flips the `run_at` sort (asc=soonest-first for the upcoming queue, desc=most-recent-first for terminal-status history). `DELETE /scheduled/{id}` cancels a `pending` row (409 otherwise). Like pause it only stops work, so any signed-in user may — the UI proxy's `x-caller-email` is trusted when the request also carries the `BACKEND_SHARED_SECRET` `x-api-key` — as may a matching `X-Admin-Token` (`SCHEDULED_ADMIN_TOKEN`) or a loopback caller with no token set; otherwise 401 (token set) or 503. Audited as `scheduled_action_cancelled`. |\n| `watchlist` | `GET\\|POST\\|PATCH\\|DELETE /watchlist`, `POST /watchlist/{slug}/approve`, `POST /watchlist/{slug}/decline` | External-monitoring watchlist + signals. Rows carry `origin` (`manual` \\| `executive` \\| `research` \\| `research_proposed`); `approve` turns a research suggestion (`research_proposed`, `dry_run`) into a live watch, `decline` `{reason: not_relevant \\| too_noisy \\| wrong_source}` removes it and records the decline (or, for `too_noisy`, keeps it live at a high floor), both 409 unless the row is a pending suggestion; `DELETE ?reason=` on a research-origin row records the decline too. |\n| `workflows` | `GET /workflows`, `POST /workflows/{name}/runs`, `GET\\|POST\\|PUT\\|DELETE /workflows/custom`, `GET\\|DELETE /workflows/custom/{name}/targets`, `POST /workflows/runs/{run_id}/decision`, `GET /workflows/tools/search?q=`, `GET /workflows/tools/describe?names=` | Workflow catalog, run management, and user-created (dynamic) workflow CRUD. Custom definitions come back with a server-managed `owner_person_id` (the creator — the web caller on `POST`, set on insert only; a client-sent value is ignored), who is asked to approve a workflow's first write to a new target. `GET /workflows/custom/{name}/targets` lists the targets its tool steps may write to without asking and `DELETE …/targets?value=` forgets one. `POST /workflows/runs/{run_id}/decision` with `{decision: \"approve\"|\"reject\"}` answers a run awaiting a yes/no sign-off from the web app — 403 unless the caller is the person it waits on or the principal, 409 if it isn't awaiting or needs a written reply — through the same `apply_resolution` a chat reply uses. Custom create/update also rejects (422) any action-step tool that does not resolve, and so does `POST /workflows/custom/{name}/activate` when turning a workflow **on** — that click is the approval for a tool workflow chat saved switched off (turning off is never checked). Turning on a workflow with action steps requires the body `{is_active: true, definition}` carrying the definition the user reviewed; if the stored one differs (ignoring `is_active` and timestamps) it returns 409, and the switch itself is a compare-and-set on the validated revision (`dynamic_store.activate_if_unchanged`, keyed on `updated_at`), so a save that lands while the tool check awaits the gateway — even from another process — is a 409 too, so only what was shown gets switched on. `GET /workflows/custom` lists inactive definitions too; `GET /workflows/{name}` 404s for them. The two `tools` endpoints return `{tools: [{name, description, read_only, source}]}` for the advanced editor's tool picker and the review card; `read_only` is true only when the name says it reads (a label, not a control). The run stream adds a `progress` event (`step_id`, `summary`) while an action step uses tools. Each catalog entry (`WorkflowMeta`) carries `is_custom` and `background` (true for the system-run built-ins the UI files under “System”). The run endpoint streams SSE; its `awaiting_human` event carries `delivery` (`self` \\| `sent` \\| `suppressed` \\| `alerted` \\| `failed`) alongside `person_id` / `question` / `awaiting_until`, because the outbound guard or an unreachable approver means the question may never have been asked — a client must not render “waiting on them” for those. A paused run ends the stream with neither `done` nor `error`, so that `awaiting_human` frame carries `terminal: true` to say so explicitly, plus `resumable` — whether the run continues by itself once answered or stops at the gate. `GET /workflows/runs/{run_id}` returns the run row with the resume payload replaced by a small `resume_progress` summary (`gate_step_id`, `completed_step_ids`, or `null`): the payload holds every completed step's full text, and the run-detail page polls this endpoint while a run is unfinished. |\n| `knowledge` | `/knowledge/builtin`, `/external`, `/search` | MBA knowledge base and external sources. `/search` is the introspection parallel of `retriever.retrieve` and mirrors its filters — including the `general` catch-all on the company collection — so the panel cannot report a specialist seeing nothing that it does retrieve in chat. It accepts `general` in `domain_filter` for the same reason. `/search` applies the same review gate as `retrieve()` — withheld (pending or rejected) built-in, external and failure rows are dropped, so the panel never advertises knowledge the Executive cannot use; it degrades to unfiltered rather than failing if review state is unreadable. `POST /knowledge/builtin` refuses a name already held by shipped content, and `POST|DELETE /knowledge/failures` now register and deregister for review — without that a user-authored failure case study had no review row, so no SME decision could block it. |\n| `skills` | `/skills`, `/skills/search`, `/skills/{name}/restore` | Skill registry (the UI's **Playbooks**) CRUD and search. `PUT` on a built-in saves a company customization that shadows it; `DELETE` returns `{name, outcome}` — `deleted`, `reverted` (customization removed, built-in back) or `hidden` (built-in hidden for this company); `restore` un-hides; `GET /skills?include_hidden=true` lists hidden built-ins. List and detail carry `used_by` — `[{name, title, is_custom}]` of the workflows that follow the playbook (switched-off custom ones included) (`WorkflowMeta.playbooks` is the other direction). |\n| `skill_drafts` | `/skill-drafts`, `/skill-drafts/{name}`, `/skill-drafts/{name}/approve` | Review queue for playbook changes the Executive proposed from chat. `GET` lists drafts (`action` create / update / delete, the proposed fields, an `id` version token, `current` — the playbook in effect now — and `followers`, the workflows that follow the name); `approve` (body `{id}`) applies exactly the reviewed version through the ordinary skills operations — 409 and the draft is kept if it was replaced since, on a conflict, or if its playbook vanished; `DELETE ?id=` discards that version only. |\n| `evals` | `/evals/scenarios`, `/evals/runs` | Eval scenarios and run results. |\n| `memories` | `/memories/{decisions,initiatives,advice}`, `GET /memories/people`, `GET /memories/people/{person_id}/conclusions` | Episodic-memory record management, plus the read-only peer-memory overview the Pulse People tab reads (`{status: ok|disabled|error, people: [...], conclusion_total}`; `?recent=` 1–50, default 5) and one person's full conclusion list, paged newest first (`{status, person_id, items, page, size, total, has_more}`; `?page=` ≥1, `?size=` 1–100, default 50; 404 when the person has no peer). |\n| `review` | `/review/items`, `/review/stats`, `/review/trusted-defaults`, `POST /review/curate`, `POST /review/bulk-approve` | Knowledge review queue and annotations. Shipped knowledge registers as a trusted default (`approved` with a NULL `reviewed_at`), so the queue starts empty; `curate` (`{domain, action: start|stop}`, domain required) opts one domain in or out, and `trusted-defaults` returns domain → unreviewed count. `bulk-approve` takes a non-empty `domain`, `item_ids` (max 500) or `all_pending: true`, and 400s with no selector; it returns `{approved_count, item_ids}`. |\n| `onboarding` | `/onboard/interview/start`, `/onboard/interview/message`, `/onboard/interview/draft`, `/onboard/interview/{id}`, `/onboard/interview/commit` | Conversational company setup. The `onboarding_interviewer` agent asks clarifying questions, then emits a draft profile + people + departments. **Nothing is persisted until `POST /onboard/interview/commit`** — the interview itself never writes. `start` is multipart (description + optional deck/one-pager uploads). `commit` answers 403 when the draft would make a different person the owner and the caller is not the current owner (setup demotes the old principal, and any signed-in user can open it). It also takes an optional `owner_email` — the principal's sign-in email, which the review screen pre-fills from the signed-in user — checked before anything is written (422 if it is malformed, already another person's, or would replace the principal's existing email — setup only fills in a missing one) and saved on the principal's People row, so the owner's chats resolve to them from the first turn. |\n| `workflow_designer` | `POST /workflows/designer/start`, `POST /workflows/designer/message`, `POST /workflows/designer/draft`, `GET /workflows/designer/{session_id}` | The conversational New workflow wizard. The `workflow_designer` agent asks clarifying questions (`phase: \"question\"`, with `hint` and up to four suggested `options`), then returns `phase: \"draft\"` with `draft.definition` (exactly the body `POST /workflows/custom` takes), `summary`, and `assumptions`; every response carries the `transcript`. **Nothing is persisted here** — sessions are in memory, and the UI saves through `POST /workflows/custom`. Errors are fixed strings (422 over the 8,000-char message cap or the transcript cap, 404 for an expired session, 409 while another turn on the same session is still running, 502/504 for model failure or timeout). Mounted ahead of the `workflows` router. |\n| `onboarding` (fallback) | `/onboard/start`, `/onboard/answer`, `/onboard/status/{id}` | The original 12-step form wizard, kept as a fallback (UI at `/onboard?mode=form`) and used by the `openexecutive onboard` CLI. `/onboard/start` reads the workspace mode once for the session: solo skips the Team Size, Team Members and Fractional Executives steps. Each status response's `current_step` / `total_steps` count only the steps that session asks, and `optional` says whether the current step can be skipped. |\n| `company-profile` | `GET\\|PATCH /company-profile` | Structured company profile. |\n| `auth` | `GET /auth/allowed-emails` | Non-archived people with an email, offered to the UI's sign-in gate. The gate takes the **union** of this roster and its own `ALLOWED_EMAILS` env list, so env entries always work (and are checked first, short-circuiting the fetch) and roster entries are additive — a roster change can never revoke a configured operator. With local login (`make dev` with Google sign-in not set up — the UI then listens on 127.0.0.1 only) the UI signs in without an email, sends no `x-caller-email`, and the backend resolves the caller to the principal, as it does for the CLI. |\n| `fixtures` | `/fixtures`, `/fixtures/{name}/load` | Demo-company fixture load/reset/snapshot. |\n| `clients` | `/clients`, `/clients/generate`, `/clients/cockpit`, `/clients/save`, `/clients/{slug}/activate` | Client-company slots — multi-client mode for fractional use; create from current/blank/AI-generated intake draft (pasted notes and/or file attachments, multipart on `/clients/generate`), save-back switching, engagement metadata (PATCH), cross-client cockpit, delete. See the Client Companies section. |\n| webhooks | `POST /webhook/telegram`, `POST /webhook/google-chat` | Inbound integration callbacks (self-verified). |\n| MCP server | `POST\\|GET /mcp` | Open Executive exposed as an MCP server (Streamable-HTTP). Not a router — a mounted FastMCP sub-app. Same shared-secret gate (`x-api-key`); exposes company context as resources and the specialist council as tools. See the MCP Server section. |",
"mermaid": null,
- "generated_at": "2026-09-25T14:20:57.450005+00:00"
+ "generated_at": "2026-09-25T15:23:57.766111+00:00"
}
diff --git a/packages/core/openexecutive/architecture/prebuilt/integrations.json b/packages/core/openexecutive/architecture/prebuilt/integrations.json
index 4a0f9751..95edf61d 100644
--- a/packages/core/openexecutive/architecture/prebuilt/integrations.json
+++ b/packages/core/openexecutive/architecture/prebuilt/integrations.json
@@ -1,7 +1,7 @@
{
"section_id": "integrations",
"title": "Integrations",
- "markdown": "External channels connect callers to the Executive. Each inbound adapter resolves the sender to a Person via `find_person_by_{slack,discord,telegram,email}_id` and threads `person_id` into `Executive.chat()`.\n\n### Inbound channels\n\n- **Slack** (`integrations.slack_bot`) — async Bolt socket-mode (`AsyncApp` + `AsyncSocketModeHandler`) embedded in the lifespan; responds to `@mention`s, DMs, and thread continuations, with per-conversation session memory (see **Conversation state** below). Text only: there is no interactivity endpoint and no Block Kit, so nothing Slack sends carries a button.\n- **Discord** (`integrations.discord_bot`) — discord.py gateway embedded in the lifespan; per-thread auto-titling, session-scoped memory, author attribution, configurable `@mention` thread promotion.\n- **Telegram** — webhook gating + per-chat history.\n- **Google Chat** — webhook + service-account auth. It resolves no approval gates and has no roster gate (the webhook authenticates Google, not the sender), and it never populates the session's trusted alert ids, so `ack_alert`'s trust check — which now runs on every session rather than only those declaring an `origin_channel` — refuses there by default, and its `<channel>` block says plainly that a sign-off cannot be answered from it.\n- **Email** (`integrations.email_poller`) — Gmail poll loop over the Google Workspace MCP (it starts only once the MCP gateway is up); strips Reply-To, filters auto-replies. While the Executive is paused (`scheduler.pause`) it skips each poll and leaves the inbox unread, so held mail is processed on the first poll after resume; the chat adapters above are not paused. The Executive sees the whole message; peer memory records only `_email_memory_text` — the subject, the sender's new text (cut at the first quoted or forwarded message) and the attachment filenames — parsed without backtracking-prone regexes, since the text is sender-controlled, and only for a rostered sender, the only kind with a peer to record into. Outbound, the principal briefs and the client-rotation digest are emailed through the same gateway (`google_workspace__send_gmail_message`, from the Executive's own mailbox to the principal's address, subject `<brief title> — <date>`) when the principal prefers email, or prefers `any` and has no Slack, Discord or Telegram id; an in-band error from the tool counts as a failed send and the next channel is tried. An emailed brief is not a DM, so the per-Person outbound guard below does not apply — the gateway's roster egress gate does.\n\nSlack, Discord, and Telegram are roster-gated on inbound: an unrostered sender's message is silently dropped (`details.outcome=\"rejected_unknown_sender\"`). Email is not inbound-gated — non-roster mail flows through with a `[POLICY]` notice so triage can classify it. Slack/Discord thread continuations pass the shared `integrations.response_gate` (utility-fast model, biased toward replying).\n\n### Checking a channel is set up\n\nSettings → Setup status (`GET /setup/status`, `api/setup_checks.py`) gives each channel a light and a plain-language fix. It tests the credentials with one free read-only call — Slack `auth.test`; Telegram `getMe`, then `getWebhookInfo` (is a webhook registered, is it this app's `/webhook/telegram`, did a delivery fail in the past day); Discord `users/@me`, only while the bot is still connecting — and reads what the lifespan left on `app.state`: the Slack socket's `is_connected()`, the Discord bot's `is_ready()` together with its gateway socket being open (discord.py stays ready while it reconnects after a drop), or the exception its task stopped with (`LoginFailure`, `PrivilegedIntentsRequired`), and the MCP gateway. Because inbound is roster-gated, a connected Slack, Discord or Telegram is amber while nobody on the roster has its id (`slack_user_id`, `discord_user_id`, `telegram_chat_id`), or when its latest `integration_inbound` row is a `Rejected: …` from the past day whose sender still isn't on the roster — the page shows the sender's id, never message text. Local login with no `TELEGRAM_WEBHOOK_SECRET` is red for Telegram, since the local-login gate turns its webhook away. Google Chat and Gmail are checked from configuration: a numeric project number and a readable service-account key; the OAuth client (or service-account key) the workspace-mcp child signs in with.\n\nA channel setting written `KEY= # note` in a `.env` file arrives as the note's text, because python-dotenv strips only a comment that follows a value. `Settings` reads such a value as unset for the Slack, Telegram, Discord and Google Chat credentials, so the line no longer switches a channel on with its own comment as the token. `TELEGRAM_WEBHOOK_SECRET` is the exception, because read as unset a junk secret would turn the webhook's check off. It is kept instead, and since Telegram can only ever send 1–256 of `A-Z a-z 0-9 _ -` (what `setWebhook` accepts), a secret outside that set — a leftover comment, a pasted `<value from Step 2>` — could only be matched by someone who guessed it: while it is set the webhook refuses every update, neither the local-login gate nor the roster tools count it as proof (`Settings.telegram_webhook_secret_valid`), and Setup status shows it red (`.env.example` shipped four such lines; the notes now sit on their own lines).\n\n### Conversation state\n\nEvery adapter keys a deterministic `session_id` off the conversation surface and replays that session's stored turns into `Session.conversation_history`, so a follow-up (\"yes, go ahead\") lands with the question still in context. Slack's ids are `slack:dm:{user}`, `slack:thread:{channel}:{thread_ts}`, and `slack:channel:{channel}:{user}` for a mention that starts a thread; because the bot's reply roots a Slack thread at that message's `ts`, the turn is double-written to that thread's session too, so the first continuation inside it is not cold. A reply inside a thread THAT PERSON ROOTED also offers the parent `slack:channel:{channel}:{user}` id when matching an approval gate, since a gate raised on the mention recorded that session while the answer arrives under the thread's. The root-author check is load-bearing: widening on \"threaded and not a DM\" alone offered one person's channel session inside any thread in that channel, so a remark they made to a colleague could resolve their open gate and post the run's title into that colleague's thread. Discord has the same shape — its auto-thread router promotes a mention reply into a bot-owned thread — and the same alias. An @-mention inside a DM is handled once, by the DM path: Slack fires both events, and taking both forked the conversation across two session ids. The same id is the audit grouping key and the scope passed to `format_for_prompt`. A per-session `asyncio.Lock` serializes turns within one conversation — the inflight semaphore caps fan-out across the workspace, which does nothing to stop two messages in the same thread from both reading history before either writes it. Persistence happens after the reply is sent and its failure is logged, never surfaced: the user already has their answer.\n\nThis was absent on Slack until #136. Every message built a fresh `Session` and minted a per-*message* id (`thread_ts` falls back to the message's own `ts`, so a DM never repeated one), which meant a multi-turn confirmation could not work: the Executive asked whether to send a briefing to Slack, the user said yes, and the next turn had no record of the question.\n\n### What the model is told about the channel\n\nChat adapters pass a `<channel>` block (`integrations.channel_context`) in the **user turn** — never a cached system block. It names the surface, states that the person cannot see the app's cards or buttons, and draws the line the assistant kept crossing: briefing proposals and alerts are actioned on the briefing page; a proposal that books something can only be approved there; a workflow sign-off the Executive is explicitly waiting on *can* be answered in the conversation. The principal's DMs on Slack, Discord and Telegram also receive the open-alert digest (`briefing.context.format_open_alerts_for_prompt`) as the `<briefing>` block, gated to DMs because the board is company-wide and a shared channel must not pull it in. That digest is the ONLY trusted source of an `alert_id` for `ack_alert`. The briefing page's `[Discuss mode — alert_id=N]` primer is a pointer to which item is under discussion, not authority on its own: the server accepts that id only if it is also on the live board it derived itself. An id appearing anywhere else, including inside an alert's own body, is not trusted: alerts are minted from inbound email and chat, so their bodies are attacker-controlled. Two mechanisms enforce that rather than one prompt rule. Every field the digest interpolates is collapsed to a single line, because a newline in an attacker-written headline, suggested action, tag or review note would otherwise forge a whole extra `[N]` line — a fabricated instruction to clear somebody else's alert. And the live board the server derived is recorded on the session, so `ack_alert` refuses any id outside it — on EVERY session, web included; the web previously had no check at all. The recorded set is the whole live board (the cap `/today` renders as cards), not just the rows the digest printed, so a card past the digest's 30-row render cap is still ackable rather than sending the principal back to the page. Be precise about what this buys: it stops an id that is invented, closed, snoozed or expired, including one quoted out of an attacker-written alert body. It does NOT stop the model being argued into acking the wrong LIVE card — one alert's body can still make a case about another id that is genuinely open. Scoping trust to the single item under discussion would need the primer id carried server-side, which it is not.\n\n### Handler failures\n\nAn adapter's catch-all replies \"I encountered an error processing your request.\" On Slack that used to be the whole story — one uncorrelated log line, no audit row, and an unguarded error-send that could itself escape into Bolt. It now logs with the session, sender, channel, thread and mode, and writes an `integration_inbound` row with `details.outcome=\"handler_error\"`, joining the inbound row under the same `session_id`. Upstream, a single crashing tool handler no longer takes the turn down at all: the orchestrator's tool gathers use `return_exceptions=True`, hand the model an error `tool_result`, and audit it with `ok=false` (cancellation is re-raised, not swallowed).\n\n### Attachments\n\n`integrations.attachments` handles web chat, Discord, and Telegram. Images become Anthropic vision blocks; documents (PDF/DOCX/TXT/MD/CSV) are inlined into the turn that carried them and indexed into the ChromaDB `inbound_attachments` collection. 20 MB/file cap; web chat uses `POST /chat/upload`.\n\nIndexed chunks are keyed on `attachment:<bare filename>` and tagged `type=attachment`. An attachment's name is chosen by whoever sent the message and the name is the chunk-id namespace, so without the prefix an inbound `strategy-2026.md` would upsert over the curated company document of that name. The prefix separates inbound content from curated uploads and keeps provenance visible; it does not separate senders from one another.\n\nIsolation is the **collection**: `retriever.retrieve` never queries `inbound_attachments` at all, so an attachment cannot resurface as company knowledge in a later, unrelated turn. Attachment processing is roster-gated on Discord too — it previously ran before the gate, so an unrostered sender's file was downloaded and indexed before their message was dropped. These rows still have no operator surface: they are never written to `company/docs/`, so `GET /documents` does not list them.\n\nThis replaced a domain-based scheme that did not work. The chunks lived in `company_docs` under a domain outside the specialist set, on the premise that an unrecognised domain matched no filter. It matched every one — `ChromaDBStore.query` attaches a `where` clause only when a domain filter is present, and an Executive-level retrieval passes none — so attachments came back under “From your company documents”, top-ranked and indistinguishable from a curated upload. Legacy rows are migrated across on boot.\n\n### MCP gateway & outbound\n\nMCP runs in **both directions**. As a *client*, `orchestrator.mcp_gateway.MCPGateway` proxies MCP servers (Gmail, Calendar, Drive — whatever `mcp_servers.json` configures) as Executive tools, with egress gating on Gmail recipients, Calendar attendees, and Drive share grantees against the roster (and a refusal of public / whole-domain Drive sharing). The Google Workspace server (`workspace-mcp`) behind those Gmail/Calendar/Drive tools runs **co-located inside the API** as a stdio child of the gateway — fitting the single-tenant model (one install = one company = one exec Google account), so there's no separate service to operate. It's baked into the API image and launched by `docker/workspace-mcp-launch.sh`, which selects single-user OAuth (token persisted at `/data/google_credentials`) or service-account domain-wide delegation from `GWORKSPACE_AUTH_MODE`. The gateway forwards the Google secrets to the child via `_FORWARDED_ENV_VARS`. As a *server*, `openexecutive.mcp_server` exposes OE's own company context and specialist council to external MCP clients at `/mcp` — the inverse direction; see the dedicated **MCP Server** section. The gateway launches extensible-mcp as a `uvx` subprocess whose fastembed tool-search index uses an embedding model baked into the API image and loaded offline, so it no longer re-downloads that model from the Hugging Face Hub on every cold start. extensible-mcp is pinned twice over: to a commit, which fixes its own code, and with `--exclude-newer`, which fixes the resolution of its dependencies — without the cutoff uvx re-resolves them against PyPI on every networked start, so a new release of any of them would reach running deployments on restart. Both live in `_EXTENSIBLE_MCP_LAUNCH_ARGS` in `orchestrator/mcp_gateway.py`, the Dockerfile's pre-warm uses the same arguments (a unit test enforces the match), so an image whose pre-warm succeeded starts the gateway with no network. The pre-warm is best-effort (`|| true`): an image built while GitHub was unreachable fetches the pinned commit on its first start instead. Updating the gateway is a deliberate bump of the commit and cutoff; `uv` itself is not pinned. Because the MCP stdio client does not inherit the parent environment, `MCPGateway.start()` explicitly forwards the embedding-cache/offline env vars (`FASTEMBED_CACHE_PATH`, `HF_HUB_OFFLINE`, …) into the child.\n\n**Emailing an artifact.** A Gmail send or draft may carry `attachments=[{\"artifact_id\": \"alert:12\", \"as\"?: \"docx\"}]`. `call_tool` runs the recipient gate first; only if it passes does `_expand_artifact_attachments` replace each such entry with the rendered file (`content` base64 + `filename` + `mime_type`, workspace-mcp's own attachment shape), produced by `artifact_records.render_artifact_file` — the same renderer as `/artifacts/{id}/download`. Only artifact rows resolve (never an arbitrary alert), links have no file, and an entry mixing `artifact_id` with other keys is refused. A stringified or single-object `attachments` is normalised first, so an artifact entry can never reach workspace-mcp unexpanded (it would silently drop it). At most 5 distinct artifacts per email (repeats are dropped) and 15 MB rendered in total; rendering runs off the event loop via `asyncio.to_thread`. A refusal writes `artifact_attachment_refused`; a successful send writes `artifact_attached` — both carry the recipients. Other attachment entries pass through unchanged.\n\n**Enablement, and why it degrades instead of dying.** `MCP_ENABLED` left unset is inferred from the presence of `mcp_servers_config_path` — dropping an `mcp_servers.json` next to `profile.yaml` turns MCP on with no further configuration. An **explicit** setting always wins in both directions: `MCP_ENABLED=false` keeps MCP off with the file still in place. It did not: `_resolve_mcp` tested `not self.mcp_enabled`, which cannot tell \"never set\" from \"set to false\", so the file's presence silently overrode the operator. The file is probed through `config.mcp_config_file_present`, never `Path.exists` directly — that re-raises an EACCES on a parent directory, and from inside a validator that comes out of `Settings()` itself, which `api/main.py` calls at module level. The check now reads `model_fields_set` (the fields the env actually supplied) and stores that on a private attr behind the read-only `mcp_auto_enabled` property, because the validator's own assignment joins that set and would otherwise make every auto-enable look explicit downstream.\n\nStartup is **best-effort**, in `main._start_mcp_gateway`. Two checks come before the subprocess: MCP off is a no-op, and a config defining no servers under `mcpServers` is logged and skipped — extensible-mcp's own loader raises on that and exits, and because the child is already gone the only thing that surfaces is anyio's \"Attempted to exit cancel scope in a different task\" from `stdio_client` unwinding, a traceback naming nothing about configuration. The start is also bounded (120s, generous because that child may still clone extensible-mcp on a cold start if the image's pre-warm failed): `ClientSession` carries no `read_timeout_seconds`, so `initialize()` waits forever on a child that is *alive but silent*, and an unbounded wait is a lifespan that never yields — the same healthcheck-never-passes symptom, which no `except` can see. A gateway that fails anyway is logged at ERROR with the config path, the servers it named, and whether the config file or an explicit `MCP_ENABLED` turned MCP on, then torn down under its own timeout; the API boots **without MCP tools and without the email poller** rather than refusing to boot. The guard catches `BaseException`, not `Exception`, re-raising a bare `CancelledError` first: the original failure came from anyio, which wraps a task group's failures in `BaseExceptionGroup` as soon as one is a `BaseException` — and that group is not an `Exception`, so `except Exception` would miss the very shape this contains. The teardown is contained too, since it runs from inside that `except` and would otherwise replace the actionable log with the crash it prevents. `configured_server_names` never raises either, and deliberately catches broadly: it reads an operator-owned path during startup, where an exception is the crash loop rather than a bug report — `Path.is_file` re-raises an EACCES on a parent directory, and `json.loads` answers deeply-nested input with `RecursionError`, which is not a `ValueError`. It tests `is_file()` so a directory or a symlink to a FIFO is never opened, and caps the read at 1 MiB. That exception used to propagate out of the lifespan and kill the container — under `restart: unless-stopped`, a crash loop whose only outward symptom was a healthcheck that never passed. Outbound tools: per-Person DMs (`send_slack_dm`, `send_discord_dm`, `send_telegram_message`) plus room-targeted `send_department_message` and `send_company_broadcast`. The per-Person DMs are additionally rate-limited and de-duplicated by the outbound anti-spam guard (below).\n\n### Outbound anti-spam guard\n\nEvery per-Person DM passes a deterministic guard (`orchestrator.outbound_guard.check_outbound_allowed`) after the roster gate and recipient-id recovery but before the network send — the single chokepoint **all** proactive DM paths reach (ad-hoc chat sends, the scheduler's followup/nudge dispatch, principal-brief delivery, the reflection turn, and research-finding routing). On a violation it returns a human-readable reason and the handler **suppresses** the send (`{\"status\":\"suppressed\",\"reason\":…}`), writes a `tool_invocation` audit row with `suppressed=true`, and writes **no** `done` activity row — so a blocked attempt never counts toward its own rate cap, and the Executive can read the reason and hold or `schedule_followup` for the recipient's next window. Three controls: **content dedup** (a near-identical message — whitespace/case-normalized, first 160 chars — already sent to the same recipient within `OUTBOUND_DEDUP_WINDOW_MINUTES`, default 360); a **per-recipient rate cap** (`OUTBOUND_MAX_PER_RECIPIENT_PER_WINDOW`, default 5, over `OUTBOUND_RATE_WINDOW_MINUTES`, default 60); and **quiet hours / availability** (`OUTBOUND_RESPECT_QUIET_HOURS`, default on — refuse while the recipient is on leave or outside their `people.channel` availability windows, surfacing the next open window). Delivery history is read from the existing `status='done'` `scheduled_actions` rows (`episodic.recent_sends_for_channel_ref`), so there is no new table. The guard is **fail-open**: any internal lookup error returns \"allow\", so it can never turn a working send into a crash or a silently-dropped message. Principal briefs and the internal heartbeat kinds use the `__internal__` channel and never reach these handlers, so they are unaffected.\n\n### Calendar & Google Meet\n\nThe Executive books meetings through two typed tools over the Calendar MCP. `create_calendar_event` schedules a **future** meeting (propose→approve by default, or auto-execute once that decision class is promoted) and may be used proactively when a stalled goal warrants a sync. `create_instant_meeting` spins up an **impromptu call starting now**, auto-executing without the approval step and skipping the business-hours/horizon caps, so the Executive can hand back a join link immediately. Both attach a **Google Meet** link by default (`add_google_meet`; opt out for in-person), parsed from the created event's `conferenceData` and surfaced to the caller plus persisted on the decision ledger. Either way the caps that matter still hold — roster membership, principal-protection, max attendees, and a daily booking ceiling.\n\n**Around-the-meeting participation.** The Executive doesn't join the call as a live voice; instead, on every successful booking it schedules a best-effort post-meeting follow-up (~5 min after the end) that DMs a human attendee asking for a quick recap — key decisions and action items. The reply flows back through the same cross-session DM context linkage described below, so the Executive can act on it (summarize, follow up) in a later turn. No meeting-transcript or Drive integration is required.\n\n### Cross-session DM context\n\nWhen the principal says \"DM Alex about X\" in one session, OE sends the DM and — if a live conversation is active — records an `outbound_context` linkage row (recipient, full outbound text, originating session id). Email is covered too but recorded one layer deeper — there is no `send_email` tool, so the linkage is written in `orchestrator.mcp_gateway` after a successful `google_workspace__send_gmail_message`, one row per `to`/`cc` recipient keyed by the bare lowercased address (OE's own address skipped). When Alex later replies on the 1:1 DM path — or by email — the shared helper `integrations.inbound_hydration.hydrate_user_message` (called by the Discord, Telegram, and Slack handlers, and by the email poller keyed on the sender address) looks up the most-recent `open` linkage for that sender within 72h and prepends an `<outbound_reply_context>` block — the outbound text plus a backstory excerpt from the originating session — to the message handed to `Executive.chat()`. So OE knows what the reply is about instead of starting from an empty per-person session. The block is context for the LLM turn only: peer memory strips it before recording what the person said (`strip_outbound_reply_context`, applied in `sync_turn`, `sync_department_turn` and to the prefetch query), so the Executive's own DM is never attributed to the person who replied to it. The block lands in the user turn (caching rule) and is injected into a copy only — the pristine reply is persisted to history. The linkage is one-shot (consumed on first matched reply, race-safe) so an unrelated later DM isn't re-hydrated. This is deterministic and independent of the per-person `peer_memory` (Honcho) layer.\n\nEvery adapter that persists a turn (Slack, Discord, Telegram, and the web route) records the message's **resolved sender** on `chat_messages.sender_person_id` — the rostered Person the adapter matched, or NULL for an unrostered sender — independently of the session owner, which falls back to the principal on Discord and Telegram so those threads stay visible. Attunement's open loops and feedback rely on this so an outsider's words are never read as someone on the roster's.",
+ "markdown": "External channels connect callers to the Executive. Each inbound adapter resolves the sender to a Person via `find_person_by_{slack,discord,telegram,email}_id` and threads `person_id` into `Executive.chat()`.\n\n### Inbound channels\n\n- **Slack** (`integrations.slack_bot`) — async Bolt socket-mode (`AsyncApp` + `AsyncSocketModeHandler`) embedded in the lifespan; responds to `@mention`s, DMs, and thread continuations, with per-conversation session memory (see **Conversation state** below). Text only: there is no interactivity endpoint and no Block Kit, so nothing Slack sends carries a button.\n- **Discord** (`integrations.discord_bot`) — discord.py gateway embedded in the lifespan; per-thread auto-titling, session-scoped memory, author attribution, configurable `@mention` thread promotion.\n- **Telegram** — webhook gating + per-chat history.\n- **Google Chat** — webhook + service-account auth. It resolves no approval gates and has no roster gate (the webhook authenticates Google, not the sender), and it never populates the session's trusted alert ids, so `ack_alert`'s trust check — which now runs on every session rather than only those declaring an `origin_channel` — refuses there by default, and its `<channel>` block says plainly that a sign-off cannot be answered from it.\n- **Email** (`integrations.email_poller`) — Gmail poll loop over the Google Workspace MCP (it starts only once the MCP gateway is up); strips Reply-To, filters auto-replies. While the Executive is paused (`scheduler.pause`) it skips each poll and leaves the inbox unread, so held mail is processed on the first poll after resume; the chat adapters above are not paused. The Executive sees the whole message; peer memory records only `_email_memory_text` — the subject, the sender's new text (cut at the first quoted or forwarded message) and the attachment filenames — parsed without backtracking-prone regexes, since the text is sender-controlled, and only for a rostered sender, the only kind with a peer to record into. Outbound, the principal briefs and the client-rotation digest are emailed through the same gateway (`google_workspace__send_gmail_message`, from the Executive's own mailbox to the principal's address, subject `<brief title> — <date>`, the date in the user's zone) as formatted HTML — rendered from the brief's Markdown with raw HTML and images off, so text quoted from outside shows as text and opening the email loads nothing remote. Email is first when the principal prefers it, and otherwise the backup after every chat channel, tried only when Slack, Discord and Telegram are missing or fail; an in-band error from the tool counts as a failed send and the next channel is tried. An emailed brief is not a DM, so the per-Person outbound guard below does not apply — the gateway's roster egress gate does.\n\nSlack, Discord, and Telegram are roster-gated on inbound: an unrostered sender's message is silently dropped (`details.outcome=\"rejected_unknown_sender\"`). Email is not inbound-gated — non-roster mail flows through with a `[POLICY]` notice so triage can classify it. Slack/Discord thread continuations pass the shared `integrations.response_gate` (utility-fast model, biased toward replying).\n\n### Checking a channel is set up\n\nSettings → Setup status (`GET /setup/status`, `api/setup_checks.py`) gives each channel a light and a plain-language fix. It tests the credentials with one free read-only call — Slack `auth.test`; Telegram `getMe`, then `getWebhookInfo` (is a webhook registered, is it this app's `/webhook/telegram`, did a delivery fail in the past day); Discord `users/@me`, only while the bot is still connecting — and reads what the lifespan left on `app.state`: the Slack socket's `is_connected()`, the Discord bot's `is_ready()` together with its gateway socket being open (discord.py stays ready while it reconnects after a drop), or the exception its task stopped with (`LoginFailure`, `PrivilegedIntentsRequired`), and the MCP gateway. Because inbound is roster-gated, a connected Slack, Discord or Telegram is amber while nobody on the roster has its id (`slack_user_id`, `discord_user_id`, `telegram_chat_id`), or when its latest `integration_inbound` row is a `Rejected: …` from the past day whose sender still isn't on the roster — the page shows the sender's id, never message text. Local login with no `TELEGRAM_WEBHOOK_SECRET` is red for Telegram, since the local-login gate turns its webhook away. Google Chat and Gmail are checked from configuration: a numeric project number and a readable service-account key; the OAuth client (or service-account key) the workspace-mcp child signs in with.\n\nA channel setting written `KEY= # note` in a `.env` file arrives as the note's text, because python-dotenv strips only a comment that follows a value. `Settings` reads such a value as unset for the Slack, Telegram, Discord and Google Chat credentials, so the line no longer switches a channel on with its own comment as the token. `TELEGRAM_WEBHOOK_SECRET` is the exception, because read as unset a junk secret would turn the webhook's check off. It is kept instead, and since Telegram can only ever send 1–256 of `A-Z a-z 0-9 _ -` (what `setWebhook` accepts), a secret outside that set — a leftover comment, a pasted `<value from Step 2>` — could only be matched by someone who guessed it: while it is set the webhook refuses every update, neither the local-login gate nor the roster tools count it as proof (`Settings.telegram_webhook_secret_valid`), and Setup status shows it red (`.env.example` shipped four such lines; the notes now sit on their own lines).\n\n### Conversation state\n\nEvery adapter keys a deterministic `session_id` off the conversation surface and replays that session's stored turns into `Session.conversation_history`, so a follow-up (\"yes, go ahead\") lands with the question still in context. Slack's ids are `slack:dm:{user}`, `slack:thread:{channel}:{thread_ts}`, and `slack:channel:{channel}:{user}` for a mention that starts a thread; because the bot's reply roots a Slack thread at that message's `ts`, the turn is double-written to that thread's session too, so the first continuation inside it is not cold. A reply inside a thread THAT PERSON ROOTED also offers the parent `slack:channel:{channel}:{user}` id when matching an approval gate, since a gate raised on the mention recorded that session while the answer arrives under the thread's. The root-author check is load-bearing: widening on \"threaded and not a DM\" alone offered one person's channel session inside any thread in that channel, so a remark they made to a colleague could resolve their open gate and post the run's title into that colleague's thread. Discord has the same shape — its auto-thread router promotes a mention reply into a bot-owned thread — and the same alias. An @-mention inside a DM is handled once, by the DM path: Slack fires both events, and taking both forked the conversation across two session ids. The same id is the audit grouping key and the scope passed to `format_for_prompt`. A per-session `asyncio.Lock` serializes turns within one conversation — the inflight semaphore caps fan-out across the workspace, which does nothing to stop two messages in the same thread from both reading history before either writes it. Persistence happens after the reply is sent and its failure is logged, never surfaced: the user already has their answer.\n\nThis was absent on Slack until #136. Every message built a fresh `Session` and minted a per-*message* id (`thread_ts` falls back to the message's own `ts`, so a DM never repeated one), which meant a multi-turn confirmation could not work: the Executive asked whether to send a briefing to Slack, the user said yes, and the next turn had no record of the question.\n\n### What the model is told about the channel\n\nChat adapters pass a `<channel>` block (`integrations.channel_context`) in the **user turn** — never a cached system block. It names the surface, states that the person cannot see the app's cards or buttons, and draws the line the assistant kept crossing: briefing proposals and alerts are actioned on the briefing page; a proposal that books something can only be approved there; a workflow sign-off the Executive is explicitly waiting on *can* be answered in the conversation. The principal's DMs on Slack, Discord and Telegram also receive the open-alert digest (`briefing.context.format_open_alerts_for_prompt`) as the `<briefing>` block, gated to DMs because the board is company-wide and a shared channel must not pull it in. That digest is the ONLY trusted source of an `alert_id` for `ack_alert`. The briefing page's `[Discuss mode — alert_id=N]` primer is a pointer to which item is under discussion, not authority on its own: the server accepts that id only if it is also on the live board it derived itself. An id appearing anywhere else, including inside an alert's own body, is not trusted: alerts are minted from inbound email and chat, so their bodies are attacker-controlled. Two mechanisms enforce that rather than one prompt rule. Every field the digest interpolates is collapsed to a single line, because a newline in an attacker-written headline, suggested action, tag or review note would otherwise forge a whole extra `[N]` line — a fabricated instruction to clear somebody else's alert. And the live board the server derived is recorded on the session, so `ack_alert` refuses any id outside it — on EVERY session, web included; the web previously had no check at all. The recorded set is the whole live board (the cap `/today` renders as cards), not just the rows the digest printed, so a card past the digest's 30-row render cap is still ackable rather than sending the principal back to the page. Be precise about what this buys: it stops an id that is invented, closed, snoozed or expired, including one quoted out of an attacker-written alert body. It does NOT stop the model being argued into acking the wrong LIVE card — one alert's body can still make a case about another id that is genuinely open. Scoping trust to the single item under discussion would need the primer id carried server-side, which it is not.\n\n### Handler failures\n\nAn adapter's catch-all replies \"I encountered an error processing your request.\" On Slack that used to be the whole story — one uncorrelated log line, no audit row, and an unguarded error-send that could itself escape into Bolt. It now logs with the session, sender, channel, thread and mode, and writes an `integration_inbound` row with `details.outcome=\"handler_error\"`, joining the inbound row under the same `session_id`. Upstream, a single crashing tool handler no longer takes the turn down at all: the orchestrator's tool gathers use `return_exceptions=True`, hand the model an error `tool_result`, and audit it with `ok=false` (cancellation is re-raised, not swallowed).\n\n### Attachments\n\n`integrations.attachments` handles web chat, Discord, and Telegram. Images become Anthropic vision blocks; documents (PDF/DOCX/TXT/MD/CSV) are inlined into the turn that carried them and indexed into the ChromaDB `inbound_attachments` collection. 20 MB/file cap; web chat uses `POST /chat/upload`.\n\nIndexed chunks are keyed on `attachment:<bare filename>` and tagged `type=attachment`. An attachment's name is chosen by whoever sent the message and the name is the chunk-id namespace, so without the prefix an inbound `strategy-2026.md` would upsert over the curated company document of that name. The prefix separates inbound content from curated uploads and keeps provenance visible; it does not separate senders from one another.\n\nIsolation is the **collection**: `retriever.retrieve` never queries `inbound_attachments` at all, so an attachment cannot resurface as company knowledge in a later, unrelated turn. Attachment processing is roster-gated on Discord too — it previously ran before the gate, so an unrostered sender's file was downloaded and indexed before their message was dropped. These rows still have no operator surface: they are never written to `company/docs/`, so `GET /documents` does not list them.\n\nThis replaced a domain-based scheme that did not work. The chunks lived in `company_docs` under a domain outside the specialist set, on the premise that an unrecognised domain matched no filter. It matched every one — `ChromaDBStore.query` attaches a `where` clause only when a domain filter is present, and an Executive-level retrieval passes none — so attachments came back under “From your company documents”, top-ranked and indistinguishable from a curated upload. Legacy rows are migrated across on boot.\n\n### MCP gateway & outbound\n\nMCP runs in **both directions**. As a *client*, `orchestrator.mcp_gateway.MCPGateway` proxies MCP servers (Gmail, Calendar, Drive — whatever `mcp_servers.json` configures) as Executive tools, with egress gating on Gmail recipients, Calendar attendees, and Drive share grantees against the roster (and a refusal of public / whole-domain Drive sharing). The Google Workspace server (`workspace-mcp`) behind those Gmail/Calendar/Drive tools runs **co-located inside the API** as a stdio child of the gateway — fitting the single-tenant model (one install = one company = one exec Google account), so there's no separate service to operate. It's baked into the API image and launched by `docker/workspace-mcp-launch.sh`, which selects single-user OAuth (token persisted at `/data/google_credentials`) or service-account domain-wide delegation from `GWORKSPACE_AUTH_MODE`. The gateway forwards the Google secrets to the child via `_FORWARDED_ENV_VARS`. As a *server*, `openexecutive.mcp_server` exposes OE's own company context and specialist council to external MCP clients at `/mcp` — the inverse direction; see the dedicated **MCP Server** section. The gateway launches extensible-mcp as a `uvx` subprocess whose fastembed tool-search index uses an embedding model baked into the API image and loaded offline, so it no longer re-downloads that model from the Hugging Face Hub on every cold start. extensible-mcp is pinned twice over: to a commit, which fixes its own code, and with `--exclude-newer`, which fixes the resolution of its dependencies — without the cutoff uvx re-resolves them against PyPI on every networked start, so a new release of any of them would reach running deployments on restart. Both live in `_EXTENSIBLE_MCP_LAUNCH_ARGS` in `orchestrator/mcp_gateway.py`, the Dockerfile's pre-warm uses the same arguments (a unit test enforces the match), so an image whose pre-warm succeeded starts the gateway with no network. The pre-warm is best-effort (`|| true`): an image built while GitHub was unreachable fetches the pinned commit on its first start instead. Updating the gateway is a deliberate bump of the commit and cutoff; `uv` itself is not pinned. Because the MCP stdio client does not inherit the parent environment, `MCPGateway.start()` explicitly forwards the embedding-cache/offline env vars (`FASTEMBED_CACHE_PATH`, `HF_HUB_OFFLINE`, …) into the child.\n\n**Emailing an artifact.** A Gmail send or draft may carry `attachments=[{\"artifact_id\": \"alert:12\", \"as\"?: \"docx\"}]`. `call_tool` runs the recipient gate first; only if it passes does `_expand_artifact_attachments` replace each such entry with the rendered file (`content` base64 + `filename` + `mime_type`, workspace-mcp's own attachment shape), produced by `artifact_records.render_artifact_file` — the same renderer as `/artifacts/{id}/download`. Only artifact rows resolve (never an arbitrary alert), links have no file, and an entry mixing `artifact_id` with other keys is refused. A stringified or single-object `attachments` is normalised first, so an artifact entry can never reach workspace-mcp unexpanded (it would silently drop it). At most 5 distinct artifacts per email (repeats are dropped) and 15 MB rendered in total; rendering runs off the event loop via `asyncio.to_thread`. A refusal writes `artifact_attachment_refused`; a successful send writes `artifact_attached` — both carry the recipients. Other attachment entries pass through unchanged.\n\n**Enablement, and why it degrades instead of dying.** `MCP_ENABLED` left unset is inferred from the presence of `mcp_servers_config_path` — dropping an `mcp_servers.json` next to `profile.yaml` turns MCP on with no further configuration. An **explicit** setting always wins in both directions: `MCP_ENABLED=false` keeps MCP off with the file still in place. It did not: `_resolve_mcp` tested `not self.mcp_enabled`, which cannot tell \"never set\" from \"set to false\", so the file's presence silently overrode the operator. The file is probed through `config.mcp_config_file_present`, never `Path.exists` directly — that re-raises an EACCES on a parent directory, and from inside a validator that comes out of `Settings()` itself, which `api/main.py` calls at module level. The check now reads `model_fields_set` (the fields the env actually supplied) and stores that on a private attr behind the read-only `mcp_auto_enabled` property, because the validator's own assignment joins that set and would otherwise make every auto-enable look explicit downstream.\n\nStartup is **best-effort**, in `main._start_mcp_gateway`. Two checks come before the subprocess: MCP off is a no-op, and a config defining no servers under `mcpServers` is logged and skipped — extensible-mcp's own loader raises on that and exits, and because the child is already gone the only thing that surfaces is anyio's \"Attempted to exit cancel scope in a different task\" from `stdio_client` unwinding, a traceback naming nothing about configuration. The start is also bounded (120s, generous because that child may still clone extensible-mcp on a cold start if the image's pre-warm failed): `ClientSession` carries no `read_timeout_seconds`, so `initialize()` waits forever on a child that is *alive but silent*, and an unbounded wait is a lifespan that never yields — the same healthcheck-never-passes symptom, which no `except` can see. A gateway that fails anyway is logged at ERROR with the config path, the servers it named, and whether the config file or an explicit `MCP_ENABLED` turned MCP on, then torn down under its own timeout; the API boots **without MCP tools and without the email poller** rather than refusing to boot. The guard catches `BaseException`, not `Exception`, re-raising a bare `CancelledError` first: the original failure came from anyio, which wraps a task group's failures in `BaseExceptionGroup` as soon as one is a `BaseException` — and that group is not an `Exception`, so `except Exception` would miss the very shape this contains. The teardown is contained too, since it runs from inside that `except` and would otherwise replace the actionable log with the crash it prevents. `configured_server_names` never raises either, and deliberately catches broadly: it reads an operator-owned path during startup, where an exception is the crash loop rather than a bug report — `Path.is_file` re-raises an EACCES on a parent directory, and `json.loads` answers deeply-nested input with `RecursionError`, which is not a `ValueError`. It tests `is_file()` so a directory or a symlink to a FIFO is never opened, and caps the read at 1 MiB. That exception used to propagate out of the lifespan and kill the container — under `restart: unless-stopped`, a crash loop whose only outward symptom was a healthcheck that never passed. Outbound tools: per-Person DMs (`send_slack_dm`, `send_discord_dm`, `send_telegram_message`) plus room-targeted `send_department_message` and `send_company_broadcast`. The per-Person DMs are additionally rate-limited and de-duplicated by the outbound anti-spam guard (below).\n\n### Outbound anti-spam guard\n\nEvery per-Person DM passes a deterministic guard (`orchestrator.outbound_guard.check_outbound_allowed`) after the roster gate and recipient-id recovery but before the network send — the single chokepoint **all** proactive DM paths reach (ad-hoc chat sends, the scheduler's followup/nudge dispatch, principal-brief delivery, the reflection turn, and research-finding routing). On a violation it returns a human-readable reason and the handler **suppresses** the send (`{\"status\":\"suppressed\",\"reason\":…}`), writes a `tool_invocation` audit row with `suppressed=true`, and writes **no** `done` activity row — so a blocked attempt never counts toward its own rate cap, and the Executive can read the reason and hold or `schedule_followup` for the recipient's next window. Three controls: **content dedup** (a near-identical message — whitespace/case-normalized, first 160 chars — already sent to the same recipient within `OUTBOUND_DEDUP_WINDOW_MINUTES`, default 360); a **per-recipient rate cap** (`OUTBOUND_MAX_PER_RECIPIENT_PER_WINDOW`, default 5, over `OUTBOUND_RATE_WINDOW_MINUTES`, default 60); and **quiet hours / availability** (`OUTBOUND_RESPECT_QUIET_HOURS`, default on — refuse while the recipient is on leave or outside their `people.channel` availability windows, surfacing the next open window). Delivery history is read from the existing `status='done'` `scheduled_actions` rows (`episodic.recent_sends_for_channel_ref`), so there is no new table. The guard is **fail-open**: any internal lookup error returns \"allow\", so it can never turn a working send into a crash or a silently-dropped message. Principal briefs and the internal heartbeat kinds use the `__internal__` channel and never reach these handlers, so they are unaffected.\n\n### Calendar & Google Meet\n\nThe Executive books meetings through two typed tools over the Calendar MCP. `create_calendar_event` schedules a **future** meeting (propose→approve by default, or auto-execute once that decision class is promoted) and may be used proactively when a stalled goal warrants a sync. `create_instant_meeting` spins up an **impromptu call starting now**, auto-executing without the approval step and skipping the business-hours/horizon caps, so the Executive can hand back a join link immediately. Both attach a **Google Meet** link by default (`add_google_meet`; opt out for in-person), parsed from the created event's `conferenceData` and surfaced to the caller plus persisted on the decision ledger. Either way the caps that matter still hold — roster membership, principal-protection, max attendees, and a daily booking ceiling.\n\n**Around-the-meeting participation.** The Executive doesn't join the call as a live voice; instead, on every successful booking it schedules a best-effort post-meeting follow-up (~5 min after the end) that DMs a human attendee asking for a quick recap — key decisions and action items. The reply flows back through the same cross-session DM context linkage described below, so the Executive can act on it (summarize, follow up) in a later turn. No meeting-transcript or Drive integration is required.\n\n### Cross-session DM context\n\nWhen the principal says \"DM Alex about X\" in one session, OE sends the DM and — if a live conversation is active — records an `outbound_context` linkage row (recipient, full outbound text, originating session id). Email is covered too but recorded one layer deeper — there is no `send_email` tool, so the linkage is written in `orchestrator.mcp_gateway` after a successful `google_workspace__send_gmail_message`, one row per `to`/`cc` recipient keyed by the bare lowercased address (OE's own address skipped). When Alex later replies on the 1:1 DM path — or by email — the shared helper `integrations.inbound_hydration.hydrate_user_message` (called by the Discord, Telegram, and Slack handlers, and by the email poller keyed on the sender address) looks up the most-recent `open` linkage for that sender within 72h and prepends an `<outbound_reply_context>` block — the outbound text plus a backstory excerpt from the originating session — to the message handed to `Executive.chat()`. So OE knows what the reply is about instead of starting from an empty per-person session. The block is context for the LLM turn only: peer memory strips it before recording what the person said (`strip_outbound_reply_context`, applied in `sync_turn`, `sync_department_turn` and to the prefetch query), so the Executive's own DM is never attributed to the person who replied to it. The block lands in the user turn (caching rule) and is injected into a copy only — the pristine reply is persisted to history. The linkage is one-shot (consumed on first matched reply, race-safe) so an unrelated later DM isn't re-hydrated. This is deterministic and independent of the per-person `peer_memory` (Honcho) layer.\n\nEvery adapter that persists a turn (Slack, Discord, Telegram, and the web route) records the message's **resolved sender** on `chat_messages.sender_person_id` — the rostered Person the adapter matched, or NULL for an unrostered sender — independently of the session owner, which falls back to the principal on Discord and Telegram so those threads stay visible. Attunement's open loops and feedback rely on this so an outsider's words are never read as someone on the roster's.",
"mermaid": "flowchart TD\n Channels[\"Slack / Discord<br/>Telegram / GChat / Email\"]\n Resolve[\"find_person_by_*_id\"]\n Gate[\"roster gate\"]\n Drop[\"drop unrostered\"]\n Exec[\"Executive.chat()\"]\n Attach[\"attachments<br/>(vision / inbound_attachments)\"]\n MCP[\"MCP gateway\"]\n Guard[\"outbound anti-spam guard<br/>(dedup / rate cap / quiet hours)\"]\n Out[\"DM / department<br/>/ broadcast tools\"]\n Channels --> Resolve\n Resolve --> Gate\n Gate -- \"unknown sender\" --> Drop\n Gate -- \"Person\" --> Exec\n Gate --> Attach\n Attach --> Exec\n Exec --> MCP\n Exec --> Guard\n Guard -- \"suppress\" --> Drop\n Guard -- \"allow\" --> Out\n Out --> Channels\n class Channels entry\n class Resolve compute\n class Gate compute\n class Drop external\n class Exec hot\n class Attach compute\n class MCP external\n class Guard compute\n class Out compute",
- "generated_at": "2026-09-25T12:32:45.003472+00:00"
+ "generated_at": "2026-09-25T15:09:17.797156+00:00"
}
diff --git a/packages/core/openexecutive/architecture/prebuilt/scheduler.json b/packages/core/openexecutive/architecture/prebuilt/scheduler.json
index bf4388df..3ead248f 100644
--- a/packages/core/openexecutive/architecture/prebuilt/scheduler.json
+++ b/packages/core/openexecutive/architecture/prebuilt/scheduler.json
@@ -1,7 +1,7 @@
{
"section_id": "scheduler",
"title": "Scheduler & Cadences",
- "markdown": "The scheduler is an asyncio task started in the FastAPI lifespan (`openexecutive.scheduler.runner.run_scheduler`). It polls every 30s and reads due rows from `scheduled_actions` (in `episodic_memory.db`). The due query uses `claim_due_actions`, an UPDATE…RETURNING claim, so each row fires at most once per process — this assumes a single scheduler instance per database. Polls are gated on an active company profile via `_company_profile_active()`; before onboarding, due rows stay `pending`.\n\n### Operator pause\n\nA global pause switch (`openexecutive.scheduler.pause`, one row in the `executive_control` table) stops everything the Executive starts on its own. It is the first check of every scheduler tick: while paused the tick does nothing — no alert/watchlist sweep, no claim — so due rows stay `pending` and fire on the first tick after resume. Actions already claimed when the pause lands run to completion; pausing holds work, it never cancels it. The same check gates the Gmail poller (the inbox is left unread) and the workflow resumer (no `wait_for_human` timeouts or resumes, and `apply_resolution` records a reply without kicking the run). Inbound conversations — web chat, Slack, Discord, Telegram, Google Chat — are deliberately not gated. The switch is set from the sidebar, the paused banner or Settings in the UI, or via `POST /executive/pause` / `POST /executive/resume`; each flip writes an `executive_paused` / `executive_resumed` audit row. Any signed-in caller may pause (it only holds work); resuming releases every held action at once, so it is the principal's alone (open only while no principal is on the roster). The state persists across restarts (boot logs a warning while paused) and across client-slot switches. `is_paused()` is read-only: a DB file or table that does not exist yet reads as \"running\", but a read error on an existing DB reads as \"paused\" — the brake fails closed, so a storage fault holds work rather than silently releasing it while the UI still shows \"paused\" (the UI shows \"status unknown\" when it cannot read the state).\n\n### Liveness heartbeat\n\nEvery tick ends by recording when it finished and what it did — `ran`, `paused`, `waiting_for_company`, `rotating`, or `failed` when the tick raised — and `run_scheduler` notes when it started. `scheduler_heartbeat()` returns both; they live in process memory, not the database. Settings → Setup status (`GET /setup/status`) reads them: no start means the task isn't running; no tick five minutes after starting, or none for three poll intervals (at least 90 s), means the loop has stopped; `failed` and `waiting_for_company` get their own light. Liveness is judged before the pause switch, because a paused scheduler still ticks: one that has stopped shows as stopped, where the Resume button wouldn't help. A restart clears the previous run's last tick. Due actions run as their own tasks, so a slow brief never ages the heartbeat.\n\n### Cadence DSL\n\n`openexecutive.departments.cadence` supports, all in UTC for department and workflow cadences:\n\n- `daily@HH:MM`\n- `weekly@DOW@HH:MM` or `weekly@DOW-HH:MM` (DOW is a 3-letter day, e.g. `weekly@thu@09:00`)\n- `quarterly@DD-HH:MM`\n\n`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, so a typo is caught at save time instead of silently never firing. An empty spec means no cadence.\n\nWhen a department cadence is due, the runner invokes the `department_check_in` workflow and chains the following occurrence via `cadence.enqueue_next()`. The fire is not passed through the authority gate: the check-in sends nothing (it grades Goals, writes one audit row and a Honcho note), and every action it proposes carries its own `gate_action` verdict in the report. Before creating a run the runner applies a skip rule (`department_check_in.needs_check_in`): the check-in is skipped when the department has no specialist agent, has no Goals, or nothing is new since its Goals were last reviewed — no decision or audit row tagged to the department (the check-in's own review row aside) since the oldest Goal's `last_reviewed_at`, and no Goal edited after it was graded. A Goal never reviewed always runs it. A skip leaves no run in the activity rail, is recorded as `cancelled` with its reason (`skipped: …` in `last_error`) rather than `done` — a done cadence row means \"the check-in ran\" to the nudge engine — and still chains the next occurrence; so does a check-in that fails once its retries are spent, so one broken department does not fall out of the daily cycle. Chaining is idempotent: while a next occurrence for the department is already pending nothing is added, so a row that chained and then failed to record its outcome never leaves two. Seeded departments start with no Goals, so their daily check-ins cost nothing until someone adds one. Deleting a department cancels its pending `dept_cadence` rows, and `cancel_orphaned_cadences()` sweeps orphans on boot.\n\nIn **solo mode** (one person using Open Executive just for themselves; see Org) there are no department check-ins: `bootstrap_cadences()` is a no-op, switching to solo cancels every pending `dept_cadence` row, a row that was already pending is marked `cancelled` by the runner without running and without chaining — ahead of the authority gate, so a `propose_only` department cannot turn it into an approval card, and cancelled rather than done because the nudge engine reads a done check-in as a recent department pulse — and a check-in already running across the switch finishes without `enqueue_next` scheduling another. Switching back to team re-bootstraps them.\n\nThe parser also takes a zone: `_parse_cadence_spec(spec, after, tz=UTC)` builds the wall-clock time in `tz` and only then converts to UTC, so a local schedule stays at the same local time across daylight-saving changes (a time the spring-forward gap skips fires once, just after the jump; a time the fall-back repeats fires at its first occurrence).\n\n### The principal's rhythm\n\nThe morning brief (`principal_brief_morning`, 08:00), end-of-day digest (`principal_brief_eod`, 18:00) and reflection (`executive_reflection`, 07:30) are seeded once per database by `seed_principal_briefs()` and each chains its next occurrence when it fires. Their default times are local to the user's zone — `memory.workspace_settings.get_user_timezone()`: the zone set through `PUT /workspace`, else `USER_TIMEZONE`, else UTC — computed with the cadence parser above. An operator who pinned a valid `HH:MM` in `PRINCIPAL_BRIEF_MORNING_TIME` / `PRINCIPAL_BRIEF_EOD_TIME` / `PRINCIPAL_REFLECTION_TIME` keeps that time read as UTC, as before zones existed, so a pinned time never moves; a malformed value is logged and treated as unset. An install that set `USER_TIMEZONE` but pinned nothing does move to that zone, from each kind's first fire after the upgrade (a row seeded before it keeps its old UTC time once). When the zone in effect changes, `reschedule_principal_rhythm()` re-times each kind's pending, not-yet-due row **in place** — it only updates `run_at` (guarded on the row being unchanged since it was read), never inserts or cancels, so it cannot race a chain into a duplicate. The new time is the next occurrence in the new zone after `max(now, last fired run + 12h)`, so a kind never runs twice within 12 hours; and if that is more than 12 hours later than the row's current time — moving would skip a day, as when someone switches to Europe/London at 07:59 UTC with the 08:00 UTC brief a minute away — the row keeps its time once. A kind with no such row is left alone: a row that is running, one between being marked done and its chain insert, or a due row held by a pause or a missing company profile. Its chain times the next one in the new zone, and the chain itself starts from `max(now, fired run + 12h)`, so a zone change while a brief runs cannot put a second brief a few hours after it.\n\nUser-created (dynamic) workflows can carry the same cadence DSL. A cadence-enabled definition enqueues a `dynamic_workflow` action (`workflows.dynamic_cadence`); when due, the runner runs the stored `DynamicWorkflow`, DMs the artifact to the definition's `cadence_person_id`, and re-chains the next occurrence. Saving/updating/deleting the definition reconciles its pending `dynamic_workflow` rows. A cadence definition may not contain an approval gate — a cron fire has no human to ask — with one exception, the **held-writes** pause: when an action step holds a write to a new target, the runner checkpoints the run (`checkpoint_gate`, the owner is DMed), still marks the row done and re-chains the cadence, and stamps `deliver_to_person_id` on the resume payload so the resumer DMs the artifact to the cadence recipient once the owner answers (or the 48 h timeout skips the held writes). Any other gate is still refused at execution: it calls `workflows.gate.ensure_workflow_event`, which raises on a gate so the run is recorded as failed. It previously ignored the gate and stored a completed run with `\"(no artifact)\"` as its body, which looked like a success every period.\n\n### Department authority & cancelling\n\nA department-scoped row passes the authority gate (`departments.authority.gate_action`, see Org) before it is dispatched: `auto_execute` dispatches; `propose_only` raises an approval card and marks the row done without dispatching (deferred to the approver's next availability window when they are outside it); `escalate` raises an urgent `[ESCALATION]` card (severity high) straight away — never deferred — and likewise does not dispatch, because approving the card is what sends it. As that card is the action's only trace it always lands: unrouted when there is no approver and no principal, and deduped on the whole action (kind, channel, recipient and intent) rather than the summary's first 60 characters, so another escalation sharing 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, and a card that cannot be written retries the row with backoff and, once the retries are spent, marks it `failed` — never `done`. (It used to raise the card *and* dispatch.) A `dept_cadence` row is not gated at all — gating it turned every check-in on a propose-only department (all eight seeded ones) into a one-shot card, and the row never chained its next occurrence. Nudge-engine rows carry no department and bypass the gate.\n\nA `pending` row can be cancelled with `DELETE /scheduled/{id}` — the Pulse page's Cancel; the update only moves a row that is still `pending`, so one the scheduler has just claimed is never overwritten. Cancelling only stops work, so, like pause, any signed-in user may: the route accepts a signed-in caller through the UI proxy (its `x-caller-email`, trusted only alongside the `BACKEND_SHARED_SECRET` `x-api-key`), a matching `X-Admin-Token` (`SCHEDULED_ADMIN_TOKEN`, for scripts), or a loopback caller when no token is set — otherwise 401 (token set) or 503. Each cancel is audited as `scheduled_action_cancelled` with who did it.\n\n### Channel routing & nudges\n\nThe delivery channel lives on the `scheduled_actions` row (`channel` / `channel_ref`); the runner dispatches through whichever was set at enqueue time — `telegram`, `slack_dm`, `discord_dm`, `email`, or `__internal__` (workflow steps and heartbeats bypass outbound dispatch). Rows left pending by the removed staff-onboarding kinds drain through that same `__internal__` short-circuit (marked done, no dispatch); the removed talent workflows' *ad-hoc* reminders sat on the principal's real DM channel instead, so a one-shot startup sweep (`memory.episodic.cancel_orphaned_talent_reminders`) cancels them — `ad_hoc`, no department, `pending` or `running`, matching the five generated reminder shapes (outreach, interview coordination, reference checks, onboarding check-in, offer expiry) — and clears the awaiting-reply flag on delivered ones so the nudge engine stops chasing them. The marker row in `app_migrations` is claimed first with `INSERT OR IGNORE` in the same transaction, so concurrent boots cannot double-run or crash. The nudge engine (`scheduler.nudge_engine`, default 15 min) scans stalled `awaiting_human` runs, stale commitments, and idle initiatives, then emits `proactive_nudge` rows routed via `people.channel.prefer_channel_for` — honouring each Person's preferred (last-used) channel and availability windows, deferring those outside their window and skipping those with no reachable channel. Emission is capped per `scope_key` (`NUDGE_MAX_PER_SCOPE`, default 3 delivered nudges) so a parked item is not chased forever.\n\nAn idle initiative is chased with its department's head; with no head to resolve — no department (what the episodic extractor stores), an unknown department, or no head set — the principal owns it. That source used to skip every initiative without a head, so in practice it never fired. The principal gets self-addressed wording (\"<title>\" has not moved since <date> — still active, done, or dropped?). If channel routing cannot reach the principal (no channel configured, or unreachable beyond `NUDGE_MAX_DEFER_DAYS`), the nudge becomes an unrouted Briefing card instead, keyed on the initiative and the ISO week: at most one card per initiative per week, and while one is still unread the scan leaves it alone rather than refreshing it every 15 minutes. The emitted nudge still carries no department, and the usual caps and cooldowns apply. A department-tagged initiative is still skipped while its department's check-in actually ran inside the idle window; a skipped check-in does not count.\n\nThe stale-commitment source also chases **open loops** (see Attunement): `scheduled_actions` rows with `kind='open_loop'`, recorded `done` on the `__internal__` channel so the runner never dispatches them, whose `awaiting_response_since` is the loop's *due time*. They are chased as soon as they are overdue — not after `NUDGE_COMMITMENT_STALE_DAYS` — with a check-in intent addressed to the loop's owner (which quotes only the owner's own verbatim words and tells the dispatching turn to treat them as data), through the same `prefer_channel_for` routing, availability windows and outbound guard. Until open loops existed nothing in production set `awaiting_response_since`, so this source had nothing to chase. Each scan first closes loops older than `ATTUNEMENT_LOOP_TTL_DAYS` (21) as `expired`, then marks proactive outreach nobody answered within `ATTUNEMENT_IGNORE_AFTER_HOURS` as `ignored` in the outcome ledger. Ranking uses that ledger: a candidate whose person left their last five resolved nudges of that kind unanswered ranks after all others and waits three times its cooldown; a single answer lifts it. Approving a stalled run (however it's approved) and updating an initiative count as acting on the nudges that chased them. The generic dispatch path tags each send with its source (`_outreach_source`) so the ledger can attribute it.\n\n### Alert lifecycle: expiry sweep and the review heartbeat\n\nTwo alert-maintenance jobs live here. The **expiry sweep** is loop-level, not a heartbeat row: `_maybe_sweep_alerts` runs `alerts.lifecycle.expire_stale_alerts` (and, on the same 15-minute throttle, `monitoring.research.watch_policy.sweep` — expiring unreviewed research watch suggestions, auto-disabling research-added watches that proved noisy or dead, and filing one `watchlist_suggestions` nudge when ≥3 suggestions have waited ≥7 days; see External monitoring) once at boot and every 15 minutes at the top of the tick — before the company-profile and rotation gates, so an old backlog expires even before onboarding completes, flipping `unread` alerts past their category TTL to `expired` and auditing `alert_sweep`. Pure DB hygiene, no model call, reversible via `POST /alerts/{id}/reopen`.\n\nThe **Executive alert review** is a real heartbeat — kind `alert_review_scan`, `__internal__` channel, bootstrapped idempotently at startup when `ALERT_REVIEW_ENABLED` and chained every `ALERT_REVIEW_INTERVAL_HOURS` (6) with the same crash-resilient run → mark-done → chain shape as `nudge_scan`. `_run_principal_brief` also runs a `pre_brief` pass right before the morning brief (a review failure never blocks the brief). Each pass re-examines open alerts with evidence and, within department authority and the privacy rule, routes, nudges, escalates, drafts, merges or resolves them — see the Today section for the policy. The moves go through the real handlers (`message_person`, `draft_artifact`), so the outbound anti-spam guard applies, and `ALERT_REVIEW_MAX_MOVES_PER_SCAN` bounds side effects per pass.\n\n### Principal briefs\n\nThe `principal_brief_morning` / `principal_brief_eod` rows (and the client-rotation digest) are delivered by `_deliver_to_principal`, not through a row channel. The principal's `preferred_channel` (`slack` / `discord` / `telegram` / `email` / `any`) is tried first, then the other chat channels they have an id for (Slack → Discord → Telegram). Email goes through the active MCP gateway and is used only when the preference is `email`, or `any` with no chat channel — so an owner linked by email at setup keeps their Slack delivery without extra email. When no channel can deliver at all (a web-only principal, or email with no gateway), 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, and the next occurrence is chained; see Workflows.\n\n## Client rotation claim pause\n\nThe `client_rotation` kind (multi-client practice mode, opt-in via `CLIENT_ROTATION_ENABLED`) adds one loop-level behavior: while a rotation's `.rotation_in_progress` marker exists, the scheduler **skips claiming entirely** for that tick. Rotation switches the live company context between parked clients; claiming during the window would fire the just-activated client's overdue outbound follow-ups from a context nobody is watching. Everything due fires on the first tick after the original client is restored. Stale markers (crash mid-rotation) are reconciled at scheduler startup, and the rotation row is idempotently re-seeded both at boot and after every slot activation (scheduled rows swap with the client). See the Client Companies section for the rotation's full design.\n\nAn optional `notion_sync_scan` heartbeat (`NOTION_SYNC_ENABLED`, off by default) incrementally re-indexes Notion pages the workspace integration can see into the isolated `notion_wiki` collection (not COMPANY), reconciles un-shared pages, then chains the next tick.",
+ "markdown": "The scheduler is an asyncio task started in the FastAPI lifespan (`openexecutive.scheduler.runner.run_scheduler`). It polls every 30s and reads due rows from `scheduled_actions` (in `episodic_memory.db`). The due query uses `claim_due_actions`, an UPDATE…RETURNING claim, so each row fires at most once per process — this assumes a single scheduler instance per database. Polls are gated on an active company profile via `_company_profile_active()`; before onboarding, due rows stay `pending`.\n\n### Operator pause\n\nA global pause switch (`openexecutive.scheduler.pause`, one row in the `executive_control` table) stops everything the Executive starts on its own. It is the first check of every scheduler tick: while paused the tick does nothing — no alert/watchlist sweep, no claim — so due rows stay `pending` and fire on the first tick after resume. Actions already claimed when the pause lands run to completion; pausing holds work, it never cancels it. The same check gates the Gmail poller (the inbox is left unread) and the workflow resumer (no `wait_for_human` timeouts or resumes, and `apply_resolution` records a reply without kicking the run). Inbound conversations — web chat, Slack, Discord, Telegram, Google Chat — are deliberately not gated. The switch is set from the sidebar, the paused banner or Settings in the UI, or via `POST /executive/pause` / `POST /executive/resume`; each flip writes an `executive_paused` / `executive_resumed` audit row. Any signed-in caller may pause (it only holds work); resuming releases every held action at once, so it is the principal's alone (open only while no principal is on the roster). The state persists across restarts (boot logs a warning while paused) and across client-slot switches. `is_paused()` is read-only: a DB file or table that does not exist yet reads as \"running\", but a read error on an existing DB reads as \"paused\" — the brake fails closed, so a storage fault holds work rather than silently releasing it while the UI still shows \"paused\" (the UI shows \"status unknown\" when it cannot read the state).\n\n### Liveness heartbeat\n\nEvery tick ends by recording when it finished and what it did — `ran`, `paused`, `waiting_for_company`, `rotating`, or `failed` when the tick raised — and `run_scheduler` notes when it started. `scheduler_heartbeat()` returns both; they live in process memory, not the database. Settings → Setup status (`GET /setup/status`) reads them: no start means the task isn't running; no tick five minutes after starting, or none for three poll intervals (at least 90 s), means the loop has stopped; `failed` and `waiting_for_company` get their own light. Liveness is judged before the pause switch, because a paused scheduler still ticks: one that has stopped shows as stopped, where the Resume button wouldn't help. A restart clears the previous run's last tick. Due actions run as their own tasks, so a slow brief never ages the heartbeat.\n\n### Cadence DSL\n\n`openexecutive.departments.cadence` supports, all in UTC for department and workflow cadences:\n\n- `daily@HH:MM`\n- `weekly@DOW@HH:MM` or `weekly@DOW-HH:MM` (DOW is a 3-letter day, e.g. `weekly@thu@09:00`)\n- `quarterly@DD-HH:MM`\n\n`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, so a typo is caught at save time instead of silently never firing. An empty spec means no cadence.\n\nWhen a department cadence is due, the runner invokes the `department_check_in` workflow and chains the following occurrence via `cadence.enqueue_next()`. The fire is not passed through the authority gate: the check-in sends nothing (it grades Goals, writes one audit row and a Honcho note), and every action it proposes carries its own `gate_action` verdict in the report. Before creating a run the runner applies a skip rule (`department_check_in.needs_check_in`): the check-in is skipped when the department has no specialist agent, has no Goals, or nothing is new since its Goals were last reviewed — no decision or audit row tagged to the department (the check-in's own review row aside) since the oldest Goal's `last_reviewed_at`, and no Goal edited after it was graded. A Goal never reviewed always runs it. A skip leaves no run in the activity rail, is recorded as `cancelled` with its reason (`skipped: …` in `last_error`) rather than `done` — a done cadence row means \"the check-in ran\" to the nudge engine — and still chains the next occurrence; so does a check-in that fails once its retries are spent, so one broken department does not fall out of the daily cycle. Chaining is idempotent: while a next occurrence for the department is already pending nothing is added, so a row that chained and then failed to record its outcome never leaves two. Seeded departments start with no Goals, so their daily check-ins cost nothing until someone adds one. Deleting a department cancels its pending `dept_cadence` rows, and `cancel_orphaned_cadences()` sweeps orphans on boot.\n\nIn **solo mode** (one person using Open Executive just for themselves; see Org) there are no department check-ins: `bootstrap_cadences()` is a no-op, switching to solo cancels every pending `dept_cadence` row, a row that was already pending is marked `cancelled` by the runner without running and without chaining — ahead of the authority gate, so a `propose_only` department cannot turn it into an approval card, and cancelled rather than done because the nudge engine reads a done check-in as a recent department pulse — and a check-in already running across the switch finishes without `enqueue_next` scheduling another. Switching back to team re-bootstraps them.\n\nThe parser also takes a zone: `_parse_cadence_spec(spec, after, tz=UTC)` builds the wall-clock time in `tz` and only then converts to UTC, so a local schedule stays at the same local time across daylight-saving changes (a time the spring-forward gap skips fires once, just after the jump; a time the fall-back repeats fires at its first occurrence).\n\n### The principal's rhythm\n\nThe morning brief (`principal_brief_morning`, 08:00), end-of-day digest (`principal_brief_eod`, 18:00) and reflection (`executive_reflection`, 07:30) are seeded once per database by `seed_principal_briefs()` and each chains its next occurrence when it fires. Their default times are local to the user's zone — `memory.workspace_settings.get_user_timezone()`: the zone set through `PUT /workspace`, else `USER_TIMEZONE`, else UTC — computed with the cadence parser above. An operator who pinned a valid `HH:MM` in `PRINCIPAL_BRIEF_MORNING_TIME` / `PRINCIPAL_BRIEF_EOD_TIME` / `PRINCIPAL_REFLECTION_TIME` keeps that time read as UTC, as before zones existed, so a pinned time never moves; a malformed value is logged and treated as unset. An install that set `USER_TIMEZONE` but pinned nothing does move to that zone, from each kind's first fire after the upgrade (a row seeded before it keeps its old UTC time once). When the zone in effect changes, `reschedule_principal_rhythm()` re-times each kind's pending, not-yet-due row **in place** — it only updates `run_at` (guarded on the row being unchanged since it was read), never inserts or cancels, so it cannot race a chain into a duplicate. The new time is the next occurrence in the new zone after `max(now, last fired run + 12h)`, so a kind never runs twice within 12 hours; and if that is more than 12 hours later than the row's current time — moving would skip a day, as when someone switches to Europe/London at 07:59 UTC with the 08:00 UTC brief a minute away — the row keeps its time once. A kind with no such row is left alone: a row that is running, one between being marked done and its chain insert, or a due row held by a pause or a missing company profile. Its chain times the next one in the new zone, and the chain itself starts from `max(now, fired run + 12h)`, so a zone change while a brief runs cannot put a second brief a few hours after it.\n\nUser-created (dynamic) workflows can carry the same cadence DSL. A cadence-enabled definition enqueues a `dynamic_workflow` action (`workflows.dynamic_cadence`); when due, the runner runs the stored `DynamicWorkflow`, DMs the artifact to the definition's `cadence_person_id`, and re-chains the next occurrence. Saving/updating/deleting the definition reconciles its pending `dynamic_workflow` rows. A cadence definition may not contain an approval gate — a cron fire has no human to ask — with one exception, the **held-writes** pause: when an action step holds a write to a new target, the runner checkpoints the run (`checkpoint_gate`, the owner is DMed), still marks the row done and re-chains the cadence, and stamps `deliver_to_person_id` on the resume payload so the resumer DMs the artifact to the cadence recipient once the owner answers (or the 48 h timeout skips the held writes). Any other gate is still refused at execution: it calls `workflows.gate.ensure_workflow_event`, which raises on a gate so the run is recorded as failed. It previously ignored the gate and stored a completed run with `\"(no artifact)\"` as its body, which looked like a success every period.\n\n### Department authority & cancelling\n\nA department-scoped row passes the authority gate (`departments.authority.gate_action`, see Org) before it is dispatched: `auto_execute` dispatches; `propose_only` raises an approval card and marks the row done without dispatching (deferred to the approver's next availability window when they are outside it); `escalate` raises an urgent `[ESCALATION]` card (severity high) straight away — never deferred — and likewise does not dispatch, because approving the card is what sends it. As that card is the action's only trace it always lands: unrouted when there is no approver and no principal, and deduped on the whole action (kind, channel, recipient and intent) rather than the summary's first 60 characters, so another escalation sharing 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, and a card that cannot be written retries the row with backoff and, once the retries are spent, marks it `failed` — never `done`. (It used to raise the card *and* dispatch.) A `dept_cadence` row is not gated at all — gating it turned every check-in on a propose-only department (all eight seeded ones) into a one-shot card, and the row never chained its next occurrence. Nudge-engine rows carry no department and bypass the gate.\n\nA `pending` row can be cancelled with `DELETE /scheduled/{id}` — the Pulse page's Cancel; the update only moves a row that is still `pending`, so one the scheduler has just claimed is never overwritten. Cancelling only stops work, so, like pause, any signed-in user may: the route accepts a signed-in caller through the UI proxy (its `x-caller-email`, trusted only alongside the `BACKEND_SHARED_SECRET` `x-api-key`), a matching `X-Admin-Token` (`SCHEDULED_ADMIN_TOKEN`, for scripts), or a loopback caller when no token is set — otherwise 401 (token set) or 503. Each cancel is audited as `scheduled_action_cancelled` with who did it.\n\n### Channel routing & nudges\n\nThe delivery channel lives on the `scheduled_actions` row (`channel` / `channel_ref`); the runner dispatches through whichever was set at enqueue time — `telegram`, `slack_dm`, `discord_dm`, `email`, or `__internal__` (workflow steps and heartbeats bypass outbound dispatch). Rows left pending by the removed staff-onboarding kinds drain through that same `__internal__` short-circuit (marked done, no dispatch); the removed talent workflows' *ad-hoc* reminders sat on the principal's real DM channel instead, so a one-shot startup sweep (`memory.episodic.cancel_orphaned_talent_reminders`) cancels them — `ad_hoc`, no department, `pending` or `running`, matching the five generated reminder shapes (outreach, interview coordination, reference checks, onboarding check-in, offer expiry) — and clears the awaiting-reply flag on delivered ones so the nudge engine stops chasing them. The marker row in `app_migrations` is claimed first with `INSERT OR IGNORE` in the same transaction, so concurrent boots cannot double-run or crash. The nudge engine (`scheduler.nudge_engine`, default 15 min) scans stalled `awaiting_human` runs, stale commitments, and idle initiatives, then emits `proactive_nudge` rows routed via `people.channel.prefer_channel_for` — honouring each Person's preferred (last-used) channel and availability windows, deferring those outside their window and skipping those with no reachable channel. Emission is capped per `scope_key` (`NUDGE_MAX_PER_SCOPE`, default 3 delivered nudges) so a parked item is not chased forever.\n\nAn idle initiative is chased with its department's head; with no head to resolve — no department (what the episodic extractor stores), an unknown department, or no head set — the principal owns it. That source used to skip every initiative without a head, so in practice it never fired. The principal gets self-addressed wording (\"<title>\" has not moved since <date> — still active, done, or dropped?). If channel routing cannot reach the principal (no channel configured, or unreachable beyond `NUDGE_MAX_DEFER_DAYS`), the nudge becomes an unrouted Briefing card instead, keyed on the initiative and the ISO week: at most one card per initiative per week, and while one is still unread the scan leaves it alone rather than refreshing it every 15 minutes. The emitted nudge still carries no department, and the usual caps and cooldowns apply. A department-tagged initiative is still skipped while its department's check-in actually ran inside the idle window; a skipped check-in does not count.\n\nThe stale-commitment source also chases **open loops** (see Attunement): `scheduled_actions` rows with `kind='open_loop'`, recorded `done` on the `__internal__` channel so the runner never dispatches them, whose `awaiting_response_since` is the loop's *due time*. They are chased as soon as they are overdue — not after `NUDGE_COMMITMENT_STALE_DAYS` — with a check-in intent addressed to the loop's owner (which quotes only the owner's own verbatim words and tells the dispatching turn to treat them as data), through the same `prefer_channel_for` routing, availability windows and outbound guard. Until open loops existed nothing in production set `awaiting_response_since`, so this source had nothing to chase. Each scan first closes loops older than `ATTUNEMENT_LOOP_TTL_DAYS` (21) as `expired`, then marks proactive outreach nobody answered within `ATTUNEMENT_IGNORE_AFTER_HOURS` as `ignored` in the outcome ledger. Ranking uses that ledger: a candidate whose person left their last five resolved nudges of that kind unanswered ranks after all others and waits three times its cooldown; a single answer lifts it. Approving a stalled run (however it's approved) and updating an initiative count as acting on the nudges that chased them. The generic dispatch path tags each send with its source (`_outreach_source`) so the ledger can attribute it.\n\n### Alert lifecycle: expiry sweep and the review heartbeat\n\nTwo alert-maintenance jobs live here. The **expiry sweep** is loop-level, not a heartbeat row: `_maybe_sweep_alerts` runs `alerts.lifecycle.expire_stale_alerts` (and, on the same 15-minute throttle, `monitoring.research.watch_policy.sweep` — expiring unreviewed research watch suggestions, auto-disabling research-added watches that proved noisy or dead, and filing one `watchlist_suggestions` nudge when ≥3 suggestions have waited ≥7 days; see External monitoring) once at boot and every 15 minutes at the top of the tick — before the company-profile and rotation gates, so an old backlog expires even before onboarding completes, flipping `unread` alerts past their category TTL to `expired` and auditing `alert_sweep`. Pure DB hygiene, no model call, reversible via `POST /alerts/{id}/reopen`.\n\nThe **Executive alert review** is a real heartbeat — kind `alert_review_scan`, `__internal__` channel, bootstrapped idempotently at startup when `ALERT_REVIEW_ENABLED` and chained every `ALERT_REVIEW_INTERVAL_HOURS` (6) with the same crash-resilient run → mark-done → chain shape as `nudge_scan`. `_run_principal_brief` also runs a `pre_brief` pass right before the morning brief (a review failure never blocks the brief). Each pass re-examines open alerts with evidence and, within department authority and the privacy rule, routes, nudges, escalates, drafts, merges or resolves them — see the Today section for the policy. The moves go through the real handlers (`message_person`, `draft_artifact`), so the outbound anti-spam guard applies, and `ALERT_REVIEW_MAX_MOVES_PER_SCAN` bounds side effects per pass.\n\n### Principal briefs\n\nThe `principal_brief_morning` / `principal_brief_eod` rows (and the client-rotation digest) are delivered by `_deliver_to_principal`, not through a row channel. The principal's `preferred_channel` (`slack` / `discord` / `telegram` / `email` / `any`) is tried first, then the other chat channels they have an id for (Slack → Discord → Telegram). Email goes through the active MCP gateway: 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 keeps their Slack delivery without extra email, and gets the brief by email only when Slack is missing or fails. The email is formatted HTML (`utils.markdown_email`: raw HTML and images off, unsafe link schemes dropped) with a subject dated in the user's zone (\"Morning Brief — Fri 25 Sep\"). Email counts as ready only when the MCP gateway runs the Google Workspace server. Every run's outcome — delivered, no owner, nowhere to send it, every send failed, or the brief couldn't be written at all (the workflow failed or produced nothing) — is recorded with the channel's name (never an address) under `brief_state`, for the Briefing's notice and the Setup status \"Daily brief\" light. The light also turns amber when a brief got through only on a backup channel, naming the one that failed. When no channel can deliver at all (a web-only principal, or email with no gateway), 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, and the next occurrence is chained; see Workflows.\n\n## Client rotation claim pause\n\nThe `client_rotation` kind (multi-client practice mode, opt-in via `CLIENT_ROTATION_ENABLED`) adds one loop-level behavior: while a rotation's `.rotation_in_progress` marker exists, the scheduler **skips claiming entirely** for that tick. Rotation switches the live company context between parked clients; claiming during the window would fire the just-activated client's overdue outbound follow-ups from a context nobody is watching. Everything due fires on the first tick after the original client is restored. Stale markers (crash mid-rotation) are reconciled at scheduler startup, and the rotation row is idempotently re-seeded both at boot and after every slot activation (scheduled rows swap with the client). See the Client Companies section for the rotation's full design.\n\nAn optional `notion_sync_scan` heartbeat (`NOTION_SYNC_ENABLED`, off by default) incrementally re-indexes Notion pages the workspace integration can see into the isolated `notion_wiki` collection (not COMPANY), reconciles un-shared pages, then chains the next tick.",
"mermaid": "flowchart TD\n Loop[\"run_scheduler<br/>poll every 30s\"]\n Pause{\"is_paused()?<br/>(executive_control)\"}\n Claim[\"claim_due_actions<br/>(status=pending, by kind)\"]\n Table[(\"scheduled_actions\")]\n Dispatch[\"dispatch via row channel<br/>(ad_hoc / proactive_nudge)\"]\n Dept[\"dept_cadence →<br/>department_check_in<br/>(skipped when nothing is new)\"]\n Solo[\"solo workspace →<br/>cancelled, no chain\"]\n Nudge[\"nudge_scan →<br/>nudge_engine scan\"]\n Brief[\"principal_brief_morning / _eod →<br/>morning_brief / end_of_day_digest<br/>(user's local time)\"]\n Reflect[\"executive_reflection →<br/>reflection (artifact only)\"]\n ExtMon[\"external_monitor_scan →<br/>monitoring pipeline\"]\n Research[\"watchlist_research_scan →<br/>executive_research (skip-if-unchanged)\"]\n Notion[\"notion_sync_scan →<br/>isolated wiki ingest\"]\n Chain[\"enqueue_next<br/>(re-arm recurring tick)\"]\n Prefer[\"prefer_channel_for<br/>(availability + last-used)\"]\n Channels[\"Slack / Discord<br/>Telegram / Email\"]\n Principal[\"DM or email principal\"]\n Alerts[\"alerts pipeline → /today\"]\n Loop --> Pause\n Pause -- \"paused: hold, sleep\" --> Loop\n Pause -- \"running\" --> Claim\n Claim -- \"claim due rows\" --> Table\n Claim -- \"ad_hoc / proactive_nudge\" --> Dispatch\n Claim -- \"dept_cadence\" --> Dept\n Claim -- \"dept_cadence (solo)\" --> Solo\n Claim -- \"nudge_scan\" --> Nudge\n Claim -- \"principal_brief_*\" --> Brief\n Claim -- \"executive_reflection\" --> Reflect\n Claim -- \"external_monitor_scan\" --> ExtMon\n Claim -- \"watchlist_research_scan\" --> Research\n Claim -- \"notion_sync_scan\" --> Notion\n Nudge -- \"prefer_channel_for\" --> Prefer\n Prefer -- \"emits proactive_nudge\" --> Table\n Dispatch --> Channels\n Brief --> Principal\n ExtMon --> Alerts\n Dept --> Chain\n Nudge --> Chain\n Brief --> Chain\n Reflect --> Chain\n ExtMon --> Chain\n Research --> Chain\n Notion --> Chain\n Chain --> Table\n class Loop entry\n class Claim compute\n class Table storage\n class Dispatch compute\n class Dept compute\n class Solo compute\n class Nudge compute\n class Brief compute\n class Reflect compute\n class ExtMon compute\n class Research compute\n class Notion compute\n class Chain compute\n class Prefer compute\n class Channels external\n class Principal external\n class Alerts hot",
- "generated_at": "2026-09-25T13:22:33.731500+00:00"
+ "generated_at": "2026-09-25T15:23:57.766111+00:00"
}
diff --git a/packages/core/openexecutive/architecture/prebuilt/today.json b/packages/core/openexecutive/architecture/prebuilt/today.json
index 6b253b4c..920c603c 100644
--- a/packages/core/openexecutive/architecture/prebuilt/today.json
+++ b/packages/core/openexecutive/architecture/prebuilt/today.json
@@ -1,7 +1,7 @@
{
"section_id": "today",
"title": "Today / Morning Brief",
- "markdown": "`openexecutive.api.routes.today` serves the morning brief — a one-screen, read-only view of what is happening across the org. It is the default landing surface (the Next.js root renders `<Briefing>`). Every signed-in page shares one sidebar (`AppSidebar`). Its Recent list is capped at the 7 newest web chats. The full history, including Slack, Telegram and Discord conversations (recognised by their session-id prefix), lives on `/chats`. A chat opens from any page through `/?session=<id>`.\n\n`GET /today` returns `TodayResponse` assembled by `_build_today()`, which is synchronous and caller-agnostic:\n\n- **`departments`** — per-department goal health, rolling up each department's goal counts (`total`, `at_risk`, `off_track`) plus its awaiting-workflow count, and `attention_goals`: the actual off-track/at-risk goals (worst first, capped at 3) with `key_result`, `current`, `target`, and `status`, so the briefing's Department card shows *which* goal is off and how far without a click. Empty for healthy/inactive departments.\n- **`people`** — an attention-ranked roster. Each person carries `awaiting_action` count, soonest SLA, a `status` (`on_leave` / `needs_reply` / `awaiting` / `clear`), reachability, `overdue`, a server `priority` sort key, and a cached one-line `insight`. Sorted by `(-priority, full_name)`. Stale insight notes are regenerated in the background only 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) does not pay a daily model and peer-memory call for a note nobody sees. Cached notes are still served.\n- **`proposals`** — the *live* unread alerts (workflow approvals, triage-classified inbound, Executive signals, flagged artifacts, and gated calendar bookings; an artifact carries `artifact_format` / `artifact_url` and a `body` already rendered to Markdown for its format, so the card badges it as a web page, Word doc, spreadsheet or link and offers *Open artifact*): unread, inside their category TTL, not snoozed — see *Alert lifecycle* below. Each carries `score`, `category` (`action` vs `monitoring`), `surfaced_reason` from `openexecutive.briefing.ranking`, the lifecycle fields (`occurrence_count`, `last_seen_at`, `last_reviewed_at`, `review_verdict`, `review_note`, `recommended_move`, `why_now`, `due_at`, `superseded_count`, `suggested_workflow`), and `decision_instance_id` (set only when the proposal is backed by a decision-ledger row — a calendar booking awaiting approval). The UI splits them into 'mine' vs 'across the team' using `caller_person_id`. For decision-backed proposals the card's Approve/Reject call the `/decisions` endpoints (which book or cancel the event server-side and clear the alert) instead of the ack-and-hand-off-to-chat flow — so meeting bookings are reviewed in the briefing itself rather than on a separate page.\n- **`narrative`** — a per-viewer Executive-voice header synthesized by `synthesize_briefing_narrative`; the principal gets the whole-company scope, teammates a role-scoped one. In the web UI each bullet of this narrative is a click target: clicking one hands off to chat (the same `onContinue` path as the proposal cards) seeded to discuss that item. The Executive recognizes it because every chat turn now carries a `<briefing>` digest of open alerts (see Memory). That digest (`briefing.context.format_open_alerts_for_prompt`) is capped at 30 items; when the board is longer the header says so explicitly and tells the Executive to point at this page for the rest — it previously presented the capped list as the complete board, so the Executive described a slice as everything that was open (#136). Chat adapters get the digest too, but Slack gates it to the principal's DMs: the board is company-wide and must not be pulled into a shared channel. The `[alert_id]` at the start of each line is also what `ack_alert` trusts, because an id quoted inside an alert's own body came from inbound mail or chat and is attacker-controlled. This page's `[Discuss mode — alert_id=N]` handoff primer is a pointer to which item is under discussion, not authority on its own: the server accepts it only if that id is on the live board too. Two things enforce that. Every field the digest interpolates — headline, body, suggested action, tags, review note — is collapsed to a single line, since a newline in any of them would forge a whole extra `[N]` line and with it a fabricated instruction to clear someone else's alert. And the server records the live board it derived, so `ack_alert` refuses any id outside it — on **every** session, not just the chat adapters. The recorded set is the whole live board, not just the rows the digest printed, so a card past the render cap stays ackable. The control stops invented, closed, snoozed and expired ids; it does not stop the model being argued into acking the wrong *live* card. That check used to run only when `origin_channel` was set, which the browser never sets, so the one surface where the principal actually reads their board had no check at all and the model could ack any id, including one quoted out of an alert body by the Discuss handoff. Rendering the block and recording its ids now happen together in `briefing.context.render_and_trust`, which both the web chat route and the channel adapters call: render without recording and the tool refuses everything, record without rendering and the model gets reach it was never shown. A turn that was shown nothing trusts nothing. Recording it is only half the wiring: the tool reads the board off the turn's session through a ContextVar, and the chat route binds that session for the whole SSE body (`set_session`, next to `set_turn`). Bound from inside the Executive's own generator instead, it survives exactly one stream step — `asyncio.wait_for` runs each step in a fresh Task with a copy of the context — and the tool-call loop, which runs later, sees nothing. That shipped, and every web ack was refused on cards that were open the whole time. The digest also carries a short **already handled** tail — recently acked / dismissed / resolved rows, named but deliberately NOT trusted for acking — because a card cleared on the page minutes ago is otherwise simply absent from chat: asked to \"record that as fixed\", the Executive could not tell a settled item from one it had never heard of, and sent the principal back to dismiss a card that was already gone. That tail renders even when nothing is open, which is exactly when it matters. Note it is a different window from the `handled_overnight` rail above: that one runs since the last delivered morning brief, while the chat tail looks back 14 days (matching the action-alert TTL, so it still covers an item cleared late in its life), so chat can name a settled item the rail no longer shows. The narrative is held to what is **live**, and to what it is actually for. The `alert_raised` source is dropped from the activity it reasons over (`_build_activity(..., include_alert_raised=False)`): a closed alert reads as work the principal already settled, and a *live* one is worse than redundant — `lifecycle.is_live` is the very predicate behind `list_live_alerts`, so every live raise is already a proposal card below the header, which the prompt forbids re-listing. The `/today/activity` rail keeps the whole source, because a raise really happened. The activity block is only labelled \"since last brief\" when the caller bounded it with `since` (the standalone briefs do; the header does not), since calling an unbounded history rail a delta made the header present weeks-old rows as overnight news. When the viewer's slice holds nothing that wants a decision — no action proposal, no at-risk/off-track department, nobody awaiting — the regen skips the model call entirely and writes the fixed quiet line (`Quiet right now — nothing pressing.`, or `… nothing needs you.` for a teammate). **The cache key is a hash of the rendered context itself** (`today._narrative_context` builds it once and both the hot path and the background task key off that one string, which is also handed to the model verbatim). That makes the key a function of the model's input: everything the prompt renders is covered, and nothing it omits can trigger a regeneration. Keying on hand-picked fields broke one half or the other each time — headlines alone left the rendered activity block uncovered, while the proposals' review fields are never rendered by this header yet are rewritten with fresh prose by every `alerts.review` pass, so they regenerated each viewer's narrative several times a day to re-synthesize identical input. A quiet board keys off a fixed sentinel instead, so a moving rail cannot re-key an entry whose text is constant. Together: on a fully dismissed board every other input was empty, the rail became the only context, and the model synthesized a confident header out of closed items.\n- **`in_flight`** / **`awaiting`** — upcoming Executive commitments and people we are waiting on.\n- **`handled_overnight`** — the autonomous moves the Executive *completed* since the last delivered morning brief: the alert review's (routed, nudged, escalated, drafted, merged, closed) plus the research watch policy's (`watching` — a watch added on its own because it was grounded in company data; `stopped_watching` — a research watch auto-disabled as noisy or dead; no alert id, re-enable from `/watchlist`). A `changed` verdict (the review rewrote an open alert's headline / body / severity) is deliberately **not** here: the alert is still open in \"Needs you\" and its card carries the note, so the brief reports it under \"what changed\" (a REWRITTEN block) rather than as done. Each row is structured, not just a sentence: `kind`, the audit `summary` (nudge bookkeeping marker stripped), `at`, `alert_id`, `event_type` (for a pre-filtered `/audit` deep link), `headline` (the alert's headline at move time; a watch's slug), `target` (person name for routed / nudged, survivor headline for merged, new severity for escalated, draft title, workflow name), `detail` (the cited evidence or the watch policy's reason), `outcome` (`resolved` | `dismissed` for a close, `proposed` for a route that went through the authority gate), `evidence_ref` (S1 / R2 / A3), `superseded_by_alert_id`, and `status` — the alert's lifecycle state **now** (`open` = live in the queue per `lifecycle.is_live` | `resolved` | `dismissed` | `expired` | `merged` | `acked` | `inactive` for snoozed / past-TTL rows), looked up per row so a close the principal already undid renders as reopened instead of offering a second Undo, and a \"still open\" jump link only appears when there is a card to land on. The morning brief also carries a one-line count of research watch suggestions waiting on `/watchlist`.\n\nThe route resolves the caller from `x-caller-email`, then attaches the viewer-scoped narrative in a `BackgroundTask` so the request never blocks on an LLM call. `GET /today/activity` returns the recent self-initiated action rail — merged from fired scheduled actions (DMs, follow-ups, nudges, cadences), logged decisions, saved advice, completed workflow runs (briefings/check-ins/research), kicked-off initiatives, resolved gated decisions, and raised alerts, so it reflects all of the Executive's activity rather than just dispatched messages. The Pulse page (`/memories`) polls it (limit 100) every ~20s so new events stream into the 'Recent activity' card, which scrolls internally at a fixed height instead of growing the page. The `morning_brief` workflow calls `_build_today()` directly to build the standalone DM (via a different, enumerated prompt). `GET /morning-brief` is a deprecated alias.\n\n**Solo mode in the UI.** The response is the same in both modes; the briefing reads the workspace mode from the app-wide `WorkspaceProvider` (which reads team while loading or on error, so a team install never flashes solo) and, in solo, drops the team surfaces: the Departments card, the People card, the \"Across the team\" lane (every action proposal is the one user's, so all of them land in \"Needs you\"), the people-awaiting, people-overdue and departments-at-risk status pills, and the quiet-day \"Set up a check-in\" link. A \"N goals at risk\" pill (at-risk plus off-track goals, from `departments`) links to `/goals` instead, so the strip never reads \"All clear\" over a goal that is slipping. In the Departments card's place, **Your projects** lists the initiatives with status `active` (`GET /memories/initiatives`): **Done** marks one `completed` through `PATCH /memories/initiatives/{id}` (only `completed` takes an initiative out of the Executive's active context), and **Drop** deletes it through `DELETE /memories/initiatives/{id}` after a confirm. The Pulse page hides its \"Department check-ins\" and \"Awaiting people\" blocks in solo, and its header shows active projects in place of the department check-in count. Team rendering is unchanged.\n\n## Alert lifecycle & the Executive review\n\nAlerts used to be write-once: raised, then never looked at again, so the \"Needs you\" queue grew without bound and the briefs re-listed it daily. Three things now keep it live:\n\n- **Time-to-live** (`openexecutive.alerts.lifecycle`). Action items expire after `ALERT_TTL_DAYS_ACTION` (14 d), unrouted low/medium monitoring signals after `ALERT_TTL_DAYS_MONITORING` (3 d). Every surface reads `list_live_alerts` (the same predicate the scheduler's 15-minute sweep persists as status `expired`), so `/today` is right even before the sweep runs. Artifacts and decision-backed alerts are exempt. `POST /alerts/{id}/reopen` is the Undo.\n- **Coalescing** (`alerts.pipeline` + `store.coalesce_alert`). A repeat of an open alert with the same `(source, dedup_key)` updates that row — `occurrence_count`, `last_seen_at`, severity max — instead of stacking a second card, and only re-pings when severity rose to high/urgent. Monitoring alerts carry a stable `watch:<slug>` key, so one watch means one card.\n- **The review** (`openexecutive.alerts.review`, heartbeat `alert_review_scan`, every 6 h and right before the morning brief). For each open alert the Executive sees what changed since it was raised — newer signals from the same watch, related alerts, activity since, the roster with SLAs, department authority — and returns a verdict (relevant / changed / resolved / stale) plus a recommended move. Deterministic policy then acts: **route** (assign + DM the owner; `propose_via_alert` for propose-only departments), **nudge**, **escalate** (severity + `due_at` + DM the principal only), **draft** (`draft_artifact`), **suggest a workflow** (a link, never a run), **merge** (`superseded_by_alert_id`), or **resolve** — only on high confidence citing a server-minted evidence ref (a newer signal, a related alert, an activity item shown for that alert); free text never closes a card, and anything weaker is annotated `likely_stale`, demoted 30 ranking points, and left for one click. Everything that came from outside is rendered as inert data inside the review prompt, so an injected email body cannot steer the batch. Board / comp / legal matters only ever go to a scope-holder or the principal and keep their text. Route and escalate are idempotent across passes, every DM carries an \"[Alert review] Re: …\" header, outbound moves are capped per pass, passes are single-flight, `ALERT_REVIEW_ENABLED=false` stops every caller, every move is audited with its evidence and prior state, and a distinct `resolved` status keeps Executive closes separate from `ack` (user approved).\n\nOn the page, cards read as decisions: the one-line \"what changed since you last looked\" (`review_note`) leads, the recommended move is the primary control (Nudge <owner> → chat; Run <workflow> → `/jobs/<name>`), with chips for age, seen ×N, why-now / due, folded-in and draft-ready, a \"Reviewed <ago>\" footer, and an amber Likely-stale treatment with one-click Dismiss. \"Needs you\" shows *Start here* + 8 cards + \"Show N more\", a \"Dismiss N older than 7 days\" footer (explicit ids to `POST /alerts/bulk-ack` — never a server-side age sweep, which would hit teammates' routed items), and \"Re-check relevance\" (`POST /alerts/review`). The handled rail (anchor of the \"Executive handled N overnight\" pill) is deliberately one sentence by default: a first-person heading built from counts only — \"Since your last brief: N off your plate (closes still standing, and merges whose survivor is not itself listed; a merge into a listed survivor counts on that survivor's row), N in others' hands (routed / nudged), N waiting on you (escalated)\", plus \"N drafts ready\", \"N workflows suggested\", \"N watch changes\", \"N other moves\" (a kind the UI does not know) and \"N back on your plate\" (a close that is open again) when present — with the rows behind a \"details\" disclosure, and nothing rendered at all when the grouped rows are empty. The pure logic (grouping, headline, links) lives in `packages/ui/src/lib/handled.ts` and is covered by `npm test`. Expanded, it shows one first-person row per alert (\"Resolved *X* — evidence\", \"Dismissed *X* as stale — evidence\", \"Handed *X* to Dana Kim\" / \"Proposed *X* to Dana Kim (awaiting their approval)\", \"Chased Dana Kim on *X*\", \"Raised *X* to high\", \"Drafted *T* from *X*\", \"Folded *X* into *Y*\", \"Started watching *slug*\"), escalations first; rows sharing an alert collapse to the newest move with the others as an \"also …\" trailer — a close always keeps the visible slot (it carries Undo), otherwise an escalation beats routed / nudged / drafted; a merge whose survivor is listed becomes \"N duplicates folded in\" on the survivor. Every row links its `evidence_ref` (or \"evidence\") to `/audit?event_type=…&q=…` (the audit page pre-fills those filters from the query string), a still-open row jumps to its card (`#alert-<id>`), drafted rows link `/artifacts`, watch rows `/watchlist`. Undo is offered only while the close still stands (`status` not `open`); a reverted close shows \"Reopened\". Dismissing a watch-sourced alert lowers that watch's `trust_score` (which discounts ranking and is shown to the review as evidence); the ack body may carry `mute_topic`. Acknowledging or resolving an alert — including the review closing it itself — marks the review's DMs about it `acted` in the Attunement outcome ledger, for the person it is routed to and the principal only; dismissing it, finding it stale or letting it expire voids them (counted neither way). Review DMs are tagged `alert_review` with `alert:<id>`.\n\n## Multi-client practice section\n\nIn multi-client practice mode (2+ client slots — see the Client Companies section), the response gains an additive `practice_clients` list: rollup cards for the **parked** clients (overdue follow-ups, awaiting replies, unread alerts, onboarding due soon, renewal countdowns), each stamped with the save point its data reflects. Single-company installs always receive an empty list and the UI renders nothing.",
+ "markdown": "`openexecutive.api.routes.today` serves the morning brief — a one-screen, read-only view of what is happening across the org. It is the default landing surface (the Next.js root renders `<Briefing>`). Every signed-in page shares one sidebar (`AppSidebar`). Its Recent list is capped at the 7 newest web chats. The full history, including Slack, Telegram and Discord conversations (recognised by their session-id prefix), lives on `/chats`. A chat opens from any page through `/?session=<id>`.\n\n`GET /today` returns `TodayResponse` assembled by `_build_today()`, which is synchronous and caller-agnostic:\n\n- **`departments`** — per-department goal health, rolling up each department's goal counts (`total`, `at_risk`, `off_track`) plus its awaiting-workflow count, and `attention_goals`: the actual off-track/at-risk goals (worst first, capped at 3) with `key_result`, `current`, `target`, and `status`, so the briefing's Department card shows *which* goal is off and how far without a click. Empty for healthy/inactive departments.\n- **`people`** — an attention-ranked roster. Each person carries `awaiting_action` count, soonest SLA, a `status` (`on_leave` / `needs_reply` / `awaiting` / `clear`), reachability, `overdue`, a server `priority` sort key, and a cached one-line `insight`. Sorted by `(-priority, full_name)`. Stale insight notes are regenerated in the background only 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) does not pay a daily model and peer-memory call for a note nobody sees. Cached notes are still served.\n- **`proposals`** — the *live* unread alerts (workflow approvals, triage-classified inbound, Executive signals, flagged artifacts, and gated calendar bookings; an artifact carries `artifact_format` / `artifact_url` and a `body` already rendered to Markdown for its format, so the card badges it as a web page, Word doc, spreadsheet or link and offers *Open artifact*): unread, inside their category TTL, not snoozed — see *Alert lifecycle* below. Each carries `score`, `category` (`action` vs `monitoring`), `surfaced_reason` from `openexecutive.briefing.ranking`, the lifecycle fields (`occurrence_count`, `last_seen_at`, `last_reviewed_at`, `review_verdict`, `review_note`, `recommended_move`, `why_now`, `due_at`, `superseded_count`, `suggested_workflow`), and `decision_instance_id` (set only when the proposal is backed by a decision-ledger row — a calendar booking awaiting approval). The UI splits them into 'mine' vs 'across the team' using `caller_person_id`. For decision-backed proposals the card's Approve/Reject call the `/decisions` endpoints (which book or cancel the event server-side and clear the alert) instead of the ack-and-hand-off-to-chat flow — so meeting bookings are reviewed in the briefing itself rather than on a separate page.\n- **`narrative`** — a per-viewer Executive-voice header synthesized by `synthesize_briefing_narrative`; the principal gets the whole-company scope, teammates a role-scoped one. In the web UI each bullet of this narrative is a click target: clicking one hands off to chat (the same `onContinue` path as the proposal cards) seeded to discuss that item. The Executive recognizes it because every chat turn now carries a `<briefing>` digest of open alerts (see Memory). That digest (`briefing.context.format_open_alerts_for_prompt`) is capped at 30 items; when the board is longer the header says so explicitly and tells the Executive to point at this page for the rest — it previously presented the capped list as the complete board, so the Executive described a slice as everything that was open (#136). Chat adapters get the digest too, but Slack gates it to the principal's DMs: the board is company-wide and must not be pulled into a shared channel. The `[alert_id]` at the start of each line is also what `ack_alert` trusts, because an id quoted inside an alert's own body came from inbound mail or chat and is attacker-controlled. This page's `[Discuss mode — alert_id=N]` handoff primer is a pointer to which item is under discussion, not authority on its own: the server accepts it only if that id is on the live board too. Two things enforce that. Every field the digest interpolates — headline, body, suggested action, tags, review note — is collapsed to a single line, since a newline in any of them would forge a whole extra `[N]` line and with it a fabricated instruction to clear someone else's alert. And the server records the live board it derived, so `ack_alert` refuses any id outside it — on **every** session, not just the chat adapters. The recorded set is the whole live board, not just the rows the digest printed, so a card past the render cap stays ackable. The control stops invented, closed, snoozed and expired ids; it does not stop the model being argued into acking the wrong *live* card. That check used to run only when `origin_channel` was set, which the browser never sets, so the one surface where the principal actually reads their board had no check at all and the model could ack any id, including one quoted out of an alert body by the Discuss handoff. Rendering the block and recording its ids now happen together in `briefing.context.render_and_trust`, which both the web chat route and the channel adapters call: render without recording and the tool refuses everything, record without rendering and the model gets reach it was never shown. A turn that was shown nothing trusts nothing. Recording it is only half the wiring: the tool reads the board off the turn's session through a ContextVar, and the chat route binds that session for the whole SSE body (`set_session`, next to `set_turn`). Bound from inside the Executive's own generator instead, it survives exactly one stream step — `asyncio.wait_for` runs each step in a fresh Task with a copy of the context — and the tool-call loop, which runs later, sees nothing. That shipped, and every web ack was refused on cards that were open the whole time. The digest also carries a short **already handled** tail — recently acked / dismissed / resolved rows, named but deliberately NOT trusted for acking — because a card cleared on the page minutes ago is otherwise simply absent from chat: asked to \"record that as fixed\", the Executive could not tell a settled item from one it had never heard of, and sent the principal back to dismiss a card that was already gone. That tail renders even when nothing is open, which is exactly when it matters. Note it is a different window from the `handled_overnight` rail above: that one runs since the last delivered morning brief, while the chat tail looks back 14 days (matching the action-alert TTL, so it still covers an item cleared late in its life), so chat can name a settled item the rail no longer shows. The narrative is held to what is **live**, and to what it is actually for. The `alert_raised` source is dropped from the activity it reasons over (`_build_activity(..., include_alert_raised=False)`): a closed alert reads as work the principal already settled, and a *live* one is worse than redundant — `lifecycle.is_live` is the very predicate behind `list_live_alerts`, so every live raise is already a proposal card below the header, which the prompt forbids re-listing. The `/today/activity` rail keeps the whole source, because a raise really happened. The activity block is only labelled \"since last brief\" when the caller bounded it with `since` (the standalone briefs do; the header does not), since calling an unbounded history rail a delta made the header present weeks-old rows as overnight news. When the viewer's slice holds nothing that wants a decision — no action proposal, no at-risk/off-track department, nobody awaiting — the regen skips the model call entirely and writes the fixed quiet line (`Quiet right now — nothing pressing.`, or `… nothing needs you.` for a teammate). **The cache key is a hash of the rendered context itself** (`today._narrative_context` builds it once and both the hot path and the background task key off that one string, which is also handed to the model verbatim). That makes the key a function of the model's input: everything the prompt renders is covered, and nothing it omits can trigger a regeneration. Keying on hand-picked fields broke one half or the other each time — headlines alone left the rendered activity block uncovered, while the proposals' review fields are never rendered by this header yet are rewritten with fresh prose by every `alerts.review` pass, so they regenerated each viewer's narrative several times a day to re-synthesize identical input. A quiet board keys off a fixed sentinel instead, so a moving rail cannot re-key an entry whose text is constant. Together: on a fully dismissed board every other input was empty, the rail became the only context, and the model synthesized a confident header out of closed items.\n- **`in_flight`** / **`awaiting`** — upcoming Executive commitments and people we are waiting on.\n- **`handled_overnight`** — the autonomous moves the Executive *completed* since the last delivered morning brief: the alert review's (routed, nudged, escalated, drafted, merged, closed) plus the research watch policy's (`watching` — a watch added on its own because it was grounded in company data; `stopped_watching` — a research watch auto-disabled as noisy or dead; no alert id, re-enable from `/watchlist`). A `changed` verdict (the review rewrote an open alert's headline / body / severity) is deliberately **not** here: the alert is still open in \"Needs you\" and its card carries the note, so the brief reports it under \"what changed\" (a REWRITTEN block) rather than as done. Each row is structured, not just a sentence: `kind`, the audit `summary` (nudge bookkeeping marker stripped), `at`, `alert_id`, `event_type` (for a pre-filtered `/audit` deep link), `headline` (the alert's headline at move time; a watch's slug), `target` (person name for routed / nudged, survivor headline for merged, new severity for escalated, draft title, workflow name), `detail` (the cited evidence or the watch policy's reason), `outcome` (`resolved` | `dismissed` for a close, `proposed` for a route that went through the authority gate), `evidence_ref` (S1 / R2 / A3), `superseded_by_alert_id`, and `status` — the alert's lifecycle state **now** (`open` = live in the queue per `lifecycle.is_live` | `resolved` | `dismissed` | `expired` | `merged` | `acked` | `inactive` for snoozed / past-TTL rows), looked up per row so a close the principal already undid renders as reopened instead of offering a second Undo, and a \"still open\" jump link only appears when there is a card to land on. The morning brief also carries a one-line count of research watch suggestions waiting on `/watchlist`.\n\n**When a brief isn't sent.** Above the Briefing, the owner sees a one-line notice when their latest morning brief or end-of-day digest wasn't sent — \"Your morning brief wasn't sent: nothing is set up to send it to you\" — with the day, what fixes it, a link to read the brief on the Artifacts page (left out when the brief couldn't be written at all) and one to Setup status. It comes from `GET /today/brief-delivery` (the scheduler records each run's outcome), shows nothing while briefs go out or while the scheduler is off, and clears once the cause is fixed. Teammates never see it.\n\nThe route resolves the caller from `x-caller-email`, then attaches the viewer-scoped narrative in a `BackgroundTask` so the request never blocks on an LLM call. `GET /today/activity` returns the recent self-initiated action rail — merged from fired scheduled actions (DMs, follow-ups, nudges, cadences), logged decisions, saved advice, completed workflow runs (briefings/check-ins/research), kicked-off initiatives, resolved gated decisions, and raised alerts, so it reflects all of the Executive's activity rather than just dispatched messages. The Pulse page (`/memories`) polls it (limit 100) every ~20s so new events stream into the 'Recent activity' card, which scrolls internally at a fixed height instead of growing the page. The `morning_brief` workflow calls `_build_today()` directly to build the standalone DM (via a different, enumerated prompt). `GET /morning-brief` is a deprecated alias.\n\n**Solo mode in the UI.** The response is the same in both modes; the briefing reads the workspace mode from the app-wide `WorkspaceProvider` (which reads team while loading or on error, so a team install never flashes solo) and, in solo, drops the team surfaces: the Departments card, the People card, the \"Across the team\" lane (every action proposal is the one user's, so all of them land in \"Needs you\"), the people-awaiting, people-overdue and departments-at-risk status pills, and the quiet-day \"Set up a check-in\" link. A \"N goals at risk\" pill (at-risk plus off-track goals, from `departments`) links to `/goals` instead, so the strip never reads \"All clear\" over a goal that is slipping. In the Departments card's place, **Your projects** lists the initiatives with status `active` (`GET /memories/initiatives`): **Done** marks one `completed` through `PATCH /memories/initiatives/{id}` (only `completed` takes an initiative out of the Executive's active context), and **Drop** deletes it through `DELETE /memories/initiatives/{id}` after a confirm. The Pulse page hides its \"Department check-ins\" and \"Awaiting people\" blocks in solo, and its header shows active projects in place of the department check-in count. Team rendering is unchanged.\n\n## Alert lifecycle & the Executive review\n\nAlerts used to be write-once: raised, then never looked at again, so the \"Needs you\" queue grew without bound and the briefs re-listed it daily. Three things now keep it live:\n\n- **Time-to-live** (`openexecutive.alerts.lifecycle`). Action items expire after `ALERT_TTL_DAYS_ACTION` (14 d), unrouted low/medium monitoring signals after `ALERT_TTL_DAYS_MONITORING` (3 d). Every surface reads `list_live_alerts` (the same predicate the scheduler's 15-minute sweep persists as status `expired`), so `/today` is right even before the sweep runs. Artifacts and decision-backed alerts are exempt. `POST /alerts/{id}/reopen` is the Undo.\n- **Coalescing** (`alerts.pipeline` + `store.coalesce_alert`). A repeat of an open alert with the same `(source, dedup_key)` updates that row — `occurrence_count`, `last_seen_at`, severity max — instead of stacking a second card, and only re-pings when severity rose to high/urgent. Monitoring alerts carry a stable `watch:<slug>` key, so one watch means one card.\n- **The review** (`openexecutive.alerts.review`, heartbeat `alert_review_scan`, every 6 h and right before the morning brief). For each open alert the Executive sees what changed since it was raised — newer signals from the same watch, related alerts, activity since, the roster with SLAs, department authority — and returns a verdict (relevant / changed / resolved / stale) plus a recommended move. Deterministic policy then acts: **route** (assign + DM the owner; `propose_via_alert` for propose-only departments), **nudge**, **escalate** (severity + `due_at` + DM the principal only), **draft** (`draft_artifact`), **suggest a workflow** (a link, never a run), **merge** (`superseded_by_alert_id`), or **resolve** — only on high confidence citing a server-minted evidence ref (a newer signal, a related alert, an activity item shown for that alert); free text never closes a card, and anything weaker is annotated `likely_stale`, demoted 30 ranking points, and left for one click. Everything that came from outside is rendered as inert data inside the review prompt, so an injected email body cannot steer the batch. Board / comp / legal matters only ever go to a scope-holder or the principal and keep their text. Route and escalate are idempotent across passes, every DM carries an \"[Alert review] Re: …\" header, outbound moves are capped per pass, passes are single-flight, `ALERT_REVIEW_ENABLED=false` stops every caller, every move is audited with its evidence and prior state, and a distinct `resolved` status keeps Executive closes separate from `ack` (user approved).\n\nOn the page, cards read as decisions: the one-line \"what changed since you last looked\" (`review_note`) leads, the recommended move is the primary control (Nudge <owner> → chat; Run <workflow> → `/jobs/<name>`), with chips for age, seen ×N, why-now / due, folded-in and draft-ready, a \"Reviewed <ago>\" footer, and an amber Likely-stale treatment with one-click Dismiss. \"Needs you\" shows *Start here* + 8 cards + \"Show N more\", a \"Dismiss N older than 7 days\" footer (explicit ids to `POST /alerts/bulk-ack` — never a server-side age sweep, which would hit teammates' routed items), and \"Re-check relevance\" (`POST /alerts/review`). The handled rail (anchor of the \"Executive handled N overnight\" pill) is deliberately one sentence by default: a first-person heading built from counts only — \"Since your last brief: N off your plate (closes still standing, and merges whose survivor is not itself listed; a merge into a listed survivor counts on that survivor's row), N in others' hands (routed / nudged), N waiting on you (escalated)\", plus \"N drafts ready\", \"N workflows suggested\", \"N watch changes\", \"N other moves\" (a kind the UI does not know) and \"N back on your plate\" (a close that is open again) when present — with the rows behind a \"details\" disclosure, and nothing rendered at all when the grouped rows are empty. The pure logic (grouping, headline, links) lives in `packages/ui/src/lib/handled.ts` and is covered by `npm test`. Expanded, it shows one first-person row per alert (\"Resolved *X* — evidence\", \"Dismissed *X* as stale — evidence\", \"Handed *X* to Dana Kim\" / \"Proposed *X* to Dana Kim (awaiting their approval)\", \"Chased Dana Kim on *X*\", \"Raised *X* to high\", \"Drafted *T* from *X*\", \"Folded *X* into *Y*\", \"Started watching *slug*\"), escalations first; rows sharing an alert collapse to the newest move with the others as an \"also …\" trailer — a close always keeps the visible slot (it carries Undo), otherwise an escalation beats routed / nudged / drafted; a merge whose survivor is listed becomes \"N duplicates folded in\" on the survivor. Every row links its `evidence_ref` (or \"evidence\") to `/audit?event_type=…&q=…` (the audit page pre-fills those filters from the query string), a still-open row jumps to its card (`#alert-<id>`), drafted rows link `/artifacts`, watch rows `/watchlist`. Undo is offered only while the close still stands (`status` not `open`); a reverted close shows \"Reopened\". Dismissing a watch-sourced alert lowers that watch's `trust_score` (which discounts ranking and is shown to the review as evidence); the ack body may carry `mute_topic`. Acknowledging or resolving an alert — including the review closing it itself — marks the review's DMs about it `acted` in the Attunement outcome ledger, for the person it is routed to and the principal only; dismissing it, finding it stale or letting it expire voids them (counted neither way). Review DMs are tagged `alert_review` with `alert:<id>`.\n\n## Multi-client practice section\n\nIn multi-client practice mode (2+ client slots — see the Client Companies section), the response gains an additive `practice_clients` list: rollup cards for the **parked** clients (overdue follow-ups, awaiting replies, unread alerts, onboarding due soon, renewal countdowns), each stamped with the save point its data reflects. Single-company installs always receive an empty list and the UI renders nothing.",
"mermaid": "flowchart TD\n REQ[\"GET /today\"]\n BUILD[\"_build_today()\"]\n DEPTS[\"departments<br/>(per-dept goal health)\"]\n ROSTER[\"people<br/>(attention-ranked roster)\"]\n PROPS[\"proposals<br/>(unread alerts, routed)\"]\n INFLIGHT[\"in_flight<br/>(pending follow-ups / nudges)\"]\n AWAIT[\"awaiting<br/>(replies we await)\"]\n NARR[\"viewer-scoped narrative (BackgroundTask)\"]\n MB[\"morning_brief workflow\"]\n REQ --> BUILD\n BUILD --> DEPTS\n BUILD --> ROSTER\n BUILD --> PROPS\n BUILD --> INFLIGHT\n BUILD --> AWAIT\n REQ -->|\"resolve caller, attach\"| NARR\n MB -->|\"calls directly for standalone DM\"| BUILD\n class REQ entry\n class BUILD compute\n class DEPTS storage\n class ROSTER storage\n class PROPS storage\n class INFLIGHT storage\n class AWAIT storage\n class NARR compute\n class MB compute",
- "generated_at": "2026-09-25T13:57:19.414364+00:00"
+ "generated_at": "2026-09-25T15:23:57.766111+00:00"
}
diff --git a/packages/core/openexecutive/briefing/brief_state.py b/packages/core/openexecutive/briefing/brief_state.py
index 6d8024b2..5eac7797 100644
--- a/packages/core/openexecutive/briefing/brief_state.py
+++ b/packages/core/openexecutive/briefing/brief_state.py
@@ -18,6 +18,12 @@ time. Scopes are only ever read by exact key, so the namespace cannot
collide with the per-viewer header cache. Only the scheduler records a
delivery (after a successful send), so manual workflow runs never advance
the window.
+
+Each run's outcome, sent or not, goes under ``brief_delivery:<kind>``
+(``record_delivery_outcome``): the reason in ``input_hash`` and the channel
+that sent it in ``narrative_text`` — a channel name, never an address. The
+Briefing's "not sent" notice and the Setup status page read it back through
+``current_problem``.
"""
from __future__ import annotations
@@ -25,8 +31,9 @@ import hashlib
import json
import logging
import re
+from dataclasses import dataclass
from datetime import UTC, datetime, timedelta
-from typing import Any
+from typing import Any, Literal, cast, get_args
from openexecutive.alerts.lifecycle import parse_aware
from openexecutive.briefing import narrative_cache
@@ -120,6 +127,123 @@ def record_delivered(kind: str, fingerprint: str, text: str) -> None:
logger.exception("brief_state: write failed for %s", kind)
+# How a brief's latest run ended: sent, or why not (``not_written`` — the run
+# failed or produced nothing; the others are scheduler.runner.
+# PrincipalDelivery.reason).
+DeliveryReason = Literal["delivered", "no_owner", "no_channel", "send_failed", "not_written"]
+_DELIVERY_REASONS: frozenset[str] = frozenset(get_args(DeliveryReason))
+DELIVERY_SCOPE_PREFIX = "brief_delivery:"
+# The recurring briefs whose runs are recorded.
+BRIEF_KINDS: tuple[str, ...] = ("principal_brief_morning", "principal_brief_eod")
+# Delivery channels (scheduler.runner.delivery_order) as the app names them.
+CHANNEL_NAMES: dict[str, str] = {
+ "email": "email",
+ "slack_dm": "Slack",
+ "discord_dm": "Discord",
+ "telegram": "Telegram",
+}
+# Why a brief didn't reach the owner, and what to do about it, in the user's
+# words.
+DELIVERY_PROBLEMS: dict[str, tuple[str, str]] = {
+ "no_owner": (
+ "there's no owner on the People list to send it to",
+ "Finish setup so you're on the People list as the owner.",
+ ),
+ "no_channel": (
+ "nothing is set up to send it to you",
+ "Connect Gmail, or add your Slack, Telegram or Discord to your People profile.",
+ ),
+ "send_failed": (
+ "every way of sending it failed",
+ "The Setup status page shows which connection needs attention.",
+ ),
+ "not_written": (
+ "it couldn't be written",
+ "The Setup status page shows which part needs attention — often the AI model.",
+ ),
+}
+
+
+def brief_name(kind: str) -> str:
+ """The brief's name in the app ("morning brief"): the scheduler's own label."""
+ from openexecutive.scheduler.action_phrasing import KIND_LABEL
+
+ return KIND_LABEL.get(kind, "brief")
+
+
+def channel_phrase(channel: str) -> str:
+ """As in "sent to you by email" or "sent to you on Slack"."""
+ return "by email" if channel == "email" else f"on {CHANNEL_NAMES.get(channel, channel)}"
+
+
+@dataclass(frozen=True)
+class DeliveryOutcome:
+ kind: str
+ reason: DeliveryReason
+ # The delivery channel that sent it ("email", "slack_dm", ...), if one did.
+ channel: str | None
+ at: datetime
+
+
+def record_delivery_outcome(
+ kind: str, *, reason: DeliveryReason, channel: str | None
+) -> None:
+ """Remember how this brief's latest run ended. Never raises."""
+ try:
+ narrative_cache.put(narrative_cache.BriefingNarrative(
+ scope=f"{DELIVERY_SCOPE_PREFIX}{kind}",
+ input_hash=reason,
+ narrative_text=channel or "",
+ generated_at=narrative_cache.utc_now_iso(),
+ ))
+ except Exception:
+ logger.exception("brief_state: delivery outcome write failed for %s", kind)
+
+
+def last_delivery_outcome() -> DeliveryOutcome | None:
+ """The latest run of either recurring brief, or None when neither has run
+ yet (or the store can't be read). Never raises."""
+ latest: DeliveryOutcome | None = None
+ for kind in BRIEF_KINDS:
+ try:
+ row = narrative_cache.get(f"{DELIVERY_SCOPE_PREFIX}{kind}")
+ except Exception:
+ logger.exception("brief_state: delivery outcome read failed for %s", kind)
+ continue
+ at = parse_aware(row.generated_at) if row is not None else None
+ if row is None or at is None or row.input_hash not in _DELIVERY_REASONS:
+ continue
+ outcome = DeliveryOutcome(
+ kind=kind,
+ reason=cast(DeliveryReason, row.input_hash), # checked above
+ channel=row.narrative_text or None,
+ at=at,
+ )
+ if latest is None or outcome.at > latest.at:
+ latest = outcome
+ return latest
+
+
+def current_problem(
+ outcome: DeliveryOutcome | None, *, has_owner: bool, can_deliver: bool
+) -> DeliveryReason | None:
+ """What still keeps the latest brief from the owner, or None.
+
+ A failed send, or a brief that couldn't be written, stays reported until
+ the next brief records a new outcome. Having nowhere to send it is judged
+ from now (``has_owner``, ``can_deliver``), not from the record, so a
+ partial fix reports the problem that is left: once a channel exists the
+ next brief will go, and there is nothing to report.
+ """
+ if outcome is None or outcome.reason == "delivered":
+ return None
+ if outcome.reason in ("send_failed", "not_written"):
+ return outcome.reason
+ if can_deliver:
+ return None
+ return "no_channel" if has_owner else "no_owner"
+
+
def split_proposals(
proposals: list[dict[str, Any]], since: datetime | None
) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]:
@@ -275,14 +399,24 @@ def pending_watch_suggestions() -> int:
__all__ = [
+ "BRIEF_KINDS",
+ "CHANNEL_NAMES",
+ "DELIVERY_PROBLEMS",
"HANDLED_EVENT_KINDS",
"REVIEW_EVENT_TYPES",
"SUPPRESSED_TEMPLATE",
+ "DeliveryOutcome",
+ "DeliveryReason",
+ "brief_name",
"build_brief_fingerprint",
+ "channel_phrase",
+ "current_problem",
"handled_since",
"last_delivered",
+ "last_delivery_outcome",
"pending_watch_suggestions",
"record_delivered",
+ "record_delivery_outcome",
"rewritten_lines",
"rewritten_since",
"scope_for",
diff --git a/packages/core/openexecutive/guide/prebuilt/settings.json b/packages/core/openexecutive/guide/prebuilt/settings.json
index fb470528..4ec0c229 100644
--- a/packages/core/openexecutive/guide/prebuilt/settings.json
+++ b/packages/core/openexecutive/guide/prebuilt/settings.json
@@ -1,7 +1,7 @@
{
"section_id": "settings",
"title": "Settings & Advanced",
- "markdown": "**What it is:** The hub for power-user and admin tools that were pulled out of the day-to-day nav to keep it focused.\n\n**What it does:**\n\n- Links to Setup status, the Agent Council, Audit Log, Token Usage, this User Guide, the Architecture reference, Company Simulator, and Client Companies.\n- Acts as a directory — each tile opens a dedicated screen.\n- Keeps advanced configuration one click away without cluttering the main workspace.\n- Shows whether the Executive is **running** or **paused**, with a switch to pause or resume it.\n- Holds the **Workspace** card: whether you use Open Executive just for yourself or with your team, your time zone, and whether the Executive books meetings without asking.\n\n**How to use:**\n\n1. Click **Settings** at the bottom of the sidebar.\n2. Click the tile for what you want to do:\n - **Setup status** — check that every part of your setup is working, and see what to do about anything that isn't.\n - **Agent Council** — change a specialist's model or prompt, or the Executive's voice.\n - **Audit log** — find out what the Executive did, and why.\n - **Token usage** — see what you're spending and where.\n - **User Guide** — this guide.\n - **Architecture** — the technical reference for how the system is built.\n - **Company Simulator** — try the Executive on a test company.\n - **Client Companies** — switch between clients if you do fractional work.\n\n**Checking your setup:**\n\n- Open **Settings → Setup status**. Each part of your setup gets a light: green is working, amber needs attention, red isn't working, grey isn't set up (and is optional).\n- It tests things for real: the AI key, and each chat app's token, with a quick call that sends nothing. It also checks the Executive's email address, the company setup, the daily schedule and whether anyone on your team list can reach each chat app.\n- Anything that isn't green says what to do in plain words, with a button when the fix is on another page. After you change a setting and restart the app, click **Check again**.\n\n**Workspace:**\n\n- **Using Open Executive** — **Just me** or **With your team**. You pick this when you first set up; change it here. Switching asks you to confirm and says what changes:\n - **Just me** pauses department check-ins and shows **Goals** (grouped by area) in the sidebar instead of Departments. Nothing is deleted — your departments stay, as the areas your goals are grouped by.\n - **With your team** brings back Departments and their daily check-ins, and the People and department cards on the Briefing.\n- **Time zone** — when your morning brief, end-of-day digest and reflection arrive, and how the Executive reads \"tomorrow at 9\". It suggests the zone your browser is in; **Follow server default** uses the server's setting.\n- **Book meetings without asking** — when on, the Executive books meetings on your calendar on its own; when off, each booking waits for your approval on the Briefing. (Shown only when your install supports it.)\n- Only the principal can change the mode and time zone. A persona you customised in Council stays in place in either mode.\n\n**Setting up just for yourself:**\n\n- The first time you set up, Open Executive asks who it is for — **Just me** or **Me and my team** — before anything else, and saves your time zone from the browser. Re-running setup later skips this; change the mode here instead.\n- Just for yourself, the setup conversation asks about what you offer, your customers, pricing, cash and runway, and your goals rather than your team. On **Here's what I understood** there is a single **You** card (your name and role) next to **Your sign-in email**, instead of the team and department lists.\n- The step-by-step form skips the team size, team members and fractional executives steps.\n- In the sidebar, **You** holds **Goals**, **People** and **Business profile**.\n\n**Pausing the Executive:**\n\n- Click **Executive running** at the bottom of the sidebar (or use the card at the top of Settings), add a reason if you like, and click **Pause Executive**.\n- While paused, the Executive starts nothing on its own: no briefs, nudges, monitoring, inbox processing or workflow timers. An amber banner appears on every page.\n- Chat and direct messages (Slack, Telegram, Discord, Google Chat) still get answers.\n- Nothing is lost. Work that falls due during the pause waits, and runs when you click **Resume**. The switch shows how many actions are waiting.\n- Anyone who can sign in can pause the Executive, but only the principal can resume it.\n\n*Tip: if you're looking for a feature that isn't in the sidebar, it's probably here. This guide is also pinned next to Settings at the bottom of the nav.*",
+ "markdown": "**What it is:** The hub for power-user and admin tools that were pulled out of the day-to-day nav to keep it focused.\n\n**What it does:**\n\n- Links to Setup status, the Agent Council, Audit Log, Token Usage, this User Guide, the Architecture reference, Company Simulator, and Client Companies.\n- Acts as a directory — each tile opens a dedicated screen.\n- Keeps advanced configuration one click away without cluttering the main workspace.\n- Shows whether the Executive is **running** or **paused**, with a switch to pause or resume it.\n- Holds the **Workspace** card: whether you use Open Executive just for yourself or with your team, your time zone, and whether the Executive books meetings without asking.\n\n**How to use:**\n\n1. Click **Settings** at the bottom of the sidebar.\n2. Click the tile for what you want to do:\n - **Setup status** — check that every part of your setup is working, and see what to do about anything that isn't.\n - **Agent Council** — change a specialist's model or prompt, or the Executive's voice.\n - **Audit log** — find out what the Executive did, and why.\n - **Token usage** — see what you're spending and where.\n - **User Guide** — this guide.\n - **Architecture** — the technical reference for how the system is built.\n - **Company Simulator** — try the Executive on a test company.\n - **Client Companies** — switch between clients if you do fractional work.\n\n**Checking your setup:**\n\n- Open **Settings → Setup status**. Each part of your setup gets a light: green is working, amber needs attention, red isn't working, grey isn't set up (and is optional).\n- It tests things for real: the AI key, and each chat app's token, with a quick call that sends nothing. It also checks the Executive's email address, the company setup, the daily schedule, when and where your daily brief goes, and whether anyone on your team list can reach each chat app.\n- Anything that isn't green says what to do in plain words, with a button when the fix is on another page. After you change a setting and restart the app, click **Check again**.\n\n**Workspace:**\n\n- **Using Open Executive** — **Just me** or **With your team**. You pick this when you first set up; change it here. Switching asks you to confirm and says what changes:\n - **Just me** pauses department check-ins and shows **Goals** (grouped by area) in the sidebar instead of Departments. Nothing is deleted — your departments stay, as the areas your goals are grouped by.\n - **With your team** brings back Departments and their daily check-ins, and the People and department cards on the Briefing.\n- **Time zone** — when your morning brief, end-of-day digest and reflection arrive, and how the Executive reads \"tomorrow at 9\". It suggests the zone your browser is in; **Follow server default** uses the server's setting.\n- **Book meetings without asking** — when on, the Executive books meetings on your calendar on its own; when off, each booking waits for your approval on the Briefing. (Shown only when your install supports it.)\n- Only the principal can change the mode and time zone. A persona you customised in Council stays in place in either mode.\n\n**Setting up just for yourself:**\n\n- The first time you set up, Open Executive asks who it is for — **Just me** or **Me and my team** — before anything else, and saves your time zone from the browser. Re-running setup later skips this; change the mode here instead.\n- Just for yourself, the setup conversation asks about what you offer, your customers, pricing, cash and runway, and your goals rather than your team. On **Here's what I understood** there is a single **You** card (your name and role) next to **Your sign-in email**, instead of the team and department lists.\n- The step-by-step form skips the team size, team members and fractional executives steps.\n- In the sidebar, **You** holds **Goals**, **People** and **Business profile**.\n\n**Pausing the Executive:**\n\n- Click **Executive running** at the bottom of the sidebar (or use the card at the top of Settings), add a reason if you like, and click **Pause Executive**.\n- While paused, the Executive starts nothing on its own: no briefs, nudges, monitoring, inbox processing or workflow timers. An amber banner appears on every page.\n- Chat and direct messages (Slack, Telegram, Discord, Google Chat) still get answers.\n- Nothing is lost. Work that falls due during the pause waits, and runs when you click **Resume**. The switch shows how many actions are waiting.\n- Anyone who can sign in can pause the Executive, but only the principal can resume it.\n\n*Tip: if you're looking for a feature that isn't in the sidebar, it's probably here. This guide is also pinned next to Settings at the bottom of the nav.*",
"mermaid": null,
- "generated_at": "2026-09-25T13:36:30.792561+00:00"
+ "generated_at": "2026-09-25T15:09:36.057135+00:00"
}
diff --git a/packages/core/openexecutive/guide/prebuilt/today.json b/packages/core/openexecutive/guide/prebuilt/today.json
index 7826fd44..0ae1a089 100644
--- a/packages/core/openexecutive/guide/prebuilt/today.json
+++ b/packages/core/openexecutive/guide/prebuilt/today.json
@@ -1,7 +1,7 @@
{
"section_id": "today",
"title": "Today / Morning Brief",
- "markdown": "**What it is:** A single screen of *what needs you right now* — the proactive digest the Executive prepares so you're not the one chasing status. In the app it's the **Briefing**, the screen the app opens on.\n\n**What it does:**\n\n- Splits items into **Needs you** (waiting on your call) and **Across the team** (everything else in motion).\n- Shows each department's goal health — on-track, at-risk, or off-track — with the at-risk goals called out.\n- Lists people with open items, their reply counts, SLA status, and whether they're on leave.\n- Surfaces proposals and alerts you can click to open a chat thread with full context.\n\n**How to use:**\n\n1. Click **Briefing** in the sidebar (or the Open Executive logo).\n2. Work the **Needs you** lane from the top, starting with the **Start here** card. Each card offers:\n - **✓ Approve** — accept the recommendation; a chat opens so the Executive can carry it out.\n - **✎ Edit & approve** — reword the action first, then **✓ Send approval**; your text is used exactly as written.\n - **💬 Discuss** (or click the card) — open a chat with the context already filled in.\n - **✕ Dismiss** — drop it and stay on the briefing.\n - **↪ Nudge *name*** — shown when the best move is chasing someone for a reply.\n3. Some cards are simpler: a document card has one **✓ Mark reviewed** button, and a calendar-booking card books (or declines) the meeting directly when you click Approve or Dismiss.\n4. Keep the lane tidy: **✕ Dismiss N older than 7 days** clears stale items, and **⟳ Re-check relevance** asks the Executive to review every open item now.\n5. Click a department card to ask for that department's status in chat.\n\n**Example:** in a Discuss thread, just say *\"go ahead\"* to approve the proposal or *\"drop it\"* to dismiss it — no need to go back to the card. (Calendar bookings still need the Approve button.)\n\n**Just for yourself?** If you use Open Executive just for yourself (**Settings → Workspace → Just me**), the Briefing leaves out the team parts: there is no Departments or People card and no \"Across the team\" lane — everything that needs a decision is in **Needs you**. A **goals at risk** badge at the top opens **Goals** when one is slipping. Instead, **Your projects** lists the projects the Executive is tracking for you. Click **✓ Done** when one is finished, or **Drop** to stop tracking it (it asks first, and removes the project from Pulse).\n\n*Note: proposals are routed to the right person automatically based on who has authority over them.*",
+ "markdown": "**What it is:** A single screen of *what needs you right now* — the proactive digest the Executive prepares so you're not the one chasing status. In the app it's the **Briefing**, the screen the app opens on.\n\n**What it does:**\n\n- Splits items into **Needs you** (waiting on your call) and **Across the team** (everything else in motion).\n- Shows each department's goal health — on-track, at-risk, or off-track — with the at-risk goals called out.\n- Lists people with open items, their reply counts, SLA status, and whether they're on leave.\n- If your latest morning brief or end-of-day digest couldn't be sent to you, a line at the top says why and what to connect. It goes away once that's fixed.\n- Surfaces proposals and alerts you can click to open a chat thread with full context.\n\n**How to use:**\n\n1. Click **Briefing** in the sidebar (or the Open Executive logo).\n2. Work the **Needs you** lane from the top, starting with the **Start here** card. Each card offers:\n - **✓ Approve** — accept the recommendation; a chat opens so the Executive can carry it out.\n - **✎ Edit & approve** — reword the action first, then **✓ Send approval**; your text is used exactly as written.\n - **💬 Discuss** (or click the card) — open a chat with the context already filled in.\n - **✕ Dismiss** — drop it and stay on the briefing.\n - **↪ Nudge *name*** — shown when the best move is chasing someone for a reply.\n3. Some cards are simpler: a document card has one **✓ Mark reviewed** button, and a calendar-booking card books (or declines) the meeting directly when you click Approve or Dismiss.\n4. Keep the lane tidy: **✕ Dismiss N older than 7 days** clears stale items, and **⟳ Re-check relevance** asks the Executive to review every open item now.\n5. Click a department card to ask for that department's status in chat.\n\n**Example:** in a Discuss thread, just say *\"go ahead\"* to approve the proposal or *\"drop it\"* to dismiss it — no need to go back to the card. (Calendar bookings still need the Approve button.)\n\n**Just for yourself?** If you use Open Executive just for yourself (**Settings → Workspace → Just me**), the Briefing leaves out the team parts: there is no Departments or People card and no \"Across the team\" lane — everything that needs a decision is in **Needs you**. A **goals at risk** badge at the top opens **Goals** when one is slipping. Instead, **Your projects** lists the projects the Executive is tracking for you. Click **✓ Done** when one is finished, or **Drop** to stop tracking it (it asks first, and removes the project from Pulse).\n\n*Note: proposals are routed to the right person automatically based on who has authority over them.*",
"mermaid": null,
- "generated_at": "2026-09-25T13:57:19.455196+00:00"
+ "generated_at": "2026-09-25T15:09:36.057135+00:00"
}
diff --git a/packages/core/openexecutive/scheduler/runner.py b/packages/core/openexecutive/scheduler/runner.py
index ac2b8202..7fa7ff68 100644
--- a/packages/core/openexecutive/scheduler/runner.py
+++ b/packages/core/openexecutive/scheduler/runner.py
@@ -10,6 +10,7 @@ from __future__ import annotations
import asyncio
import logging
+from dataclasses import dataclass
from datetime import UTC, datetime, timedelta, tzinfo
from typing import TYPE_CHECKING
@@ -26,6 +27,7 @@ from openexecutive.scheduler.pause import is_paused
from openexecutive.workflows.gate import ensure_workflow_event
if TYPE_CHECKING:
+ from openexecutive.briefing.brief_state import DeliveryReason
from openexecutive.people.models import Person
logger = logging.getLogger(__name__)
@@ -1398,20 +1400,21 @@ _PREFERRED_TO_DELIVERY: dict[str, str] = {
"telegram": "telegram",
"email": "email",
}
-# Chat fallback order after the preferred channel. Email is never a fallback
-# for a chat preference — see `_delivery_order`.
+# Chat fallback order after the preferred channel. Email comes after all of
+# them unless it is the preference — see `delivery_order`.
_CHAT_DELIVERY_ORDER: tuple[str, ...] = ("slack_dm", "discord_dm", "telegram")
-def _delivery_order(principal: Person | None, *, email_ready: bool) -> list[str]:
+def delivery_order(principal: Person | None, *, email_ready: bool) -> list[str]:
"""The channels a message can reach ``principal`` on, in the order to try.
Chat channels the principal has an id for come first — the preferred one
ahead of the rest (slack, discord, telegram). Email (it needs the MCP
- gateway, ``email_ready``) is used only when the preference is ``email``
- (tried first), or when it is ``any`` and no chat channel resolves (tried
- last): an owner linked by email at setup has preference ``any``, and must
- not start getting two extra emails a day on top of a working Slack.
+ gateway, ``email_ready``) is tried first when it is the preference, and
+ otherwise last, as the backup: delivery stops at the first channel that
+ sends, so an owner linked by email at setup (preference ``any``) with a
+ working Slack still never gets the briefs by email too — only when every
+ chat channel is missing or fails.
Empty when nothing can deliver — e.g. a principal who only uses the web UI.
"""
if principal is None:
@@ -1428,24 +1431,55 @@ def _delivery_order(principal: Person | None, *, email_ready: bool) -> list[str]
if email_ready and principal.email:
if pref == "email":
order.insert(0, "email")
- elif pref == "any" and not chat:
+ else:
order.append("email")
return order
-def _principal_delivery_plan() -> tuple[Person | None, list[str]]:
+def email_ready() -> bool:
+ """Whether the Executive can send email: the MCP gateway is up and the
+ Google Workspace server (its Gmail tools) is one it runs. Another MCP
+ server alone does not count."""
+ from openexecutive.config import get_settings
+ from openexecutive.orchestrator.mcp_gateway import (
+ configured_server_names,
+ get_active_gateway,
+ )
+
+ if get_active_gateway() is None:
+ return False
+ return "google_workspace" in configured_server_names(get_settings().mcp_servers_config_path)
+
+
+def principal_delivery_plan() -> tuple[Person | None, list[str]]:
"""The principal Person row and the channels to try, in order."""
- from openexecutive.orchestrator.mcp_gateway import get_active_gateway
from openexecutive.people.store import find_principal_person
principal = find_principal_person()
- return principal, _delivery_order(
- principal, email_ready=get_active_gateway() is not None
- )
+ return principal, delivery_order(principal, email_ready=email_ready())
+
+
+def next_brief_runs(after: datetime) -> dict[str, datetime]:
+ """When each recurring brief next goes out after ``after``."""
+ from openexecutive.briefing.brief_state import BRIEF_KINDS
+
+ runs = {kind: _next_principal_run_at(kind, after) for kind in BRIEF_KINDS}
+ return {kind: at for kind, at in runs.items() if at is not None}
+
+
+def _email_subject(label: str, now: datetime | None = None) -> str:
+ """``label`` and today's date where the user is ("Morning Brief — Fri 25
+ Sep"): an evening digest sent from UTC would otherwise carry tomorrow's
+ date for anyone west of it."""
+ from openexecutive.memory.workspace_settings import get_user_timezone
+
+ local = (now or datetime.now(UTC)).astimezone(get_user_timezone())
+ return f"{label} — {local:%a} {local.day} {local:%b}"
async def _email_principal(principal: Person, text: str, label: str) -> bool:
- """Send ``text`` to the principal's address through the active MCP gateway.
+ """Send ``text`` (Markdown) to the principal's address through the active
+ MCP gateway, formatted as HTML (``utils.markdown_email``).
Sent as the Executive's own mailbox (the principal is on the roster, so
the gateway's egress gate allows it). False when there is no gateway or
@@ -1453,6 +1487,7 @@ async def _email_principal(principal: Person, text: str, label: str) -> bool:
"""
from openexecutive.config import get_settings
from openexecutive.orchestrator.mcp_gateway import get_active_gateway
+ from openexecutive.utils.markdown_email import markdown_to_email_html
from openexecutive.workflows.action_step import looks_like_error
gateway = get_active_gateway()
@@ -1463,8 +1498,9 @@ async def _email_principal(principal: Person, text: str, label: str) -> bool:
"arguments": {
"user_google_email": get_settings().exec_email_address,
"to": principal.email,
- "subject": f"{label} — {datetime.now(UTC).strftime('%Y-%m-%d')}",
- "body": text,
+ "subject": _email_subject(label),
+ "body": markdown_to_email_html(text),
+ "body_format": "html",
},
})
if looks_like_error(result):
@@ -1473,20 +1509,34 @@ async def _email_principal(principal: Person, text: str, label: str) -> bool:
return True
-async def _deliver_to_principal(text: str, *, label: str = "Update") -> tuple[bool, str]:
+@dataclass(frozen=True)
+class PrincipalDelivery:
+ """How one message to the principal went."""
+
+ ok: bool
+ # For the log and the audit row; carries the address or id it went to.
+ detail: str
+ reason: DeliveryReason
+ # The delivery channel that sent it ("email", "slack_dm", ...), if one did.
+ channel: str | None = None
+
+
+async def _deliver_to_principal(text: str, *, label: str = "Update") -> PrincipalDelivery:
"""Send ``text`` to the principal on their preferred channel.
- Returns (ok, detail). Tries the channels from ``_principal_delivery_plan``
- in order until one sends; ``label`` names the message in the email
- subject. Returns (False, ...) when no channel is configured or every
- send failed — the caller still marks the action done (no point retrying
- the same misconfiguration) but audits the failure.
+ Tries the channels from ``principal_delivery_plan`` in order until one
+ sends; ``label`` names the message in the email subject. Not ok when no
+ channel is configured or every send failed — the caller still marks the
+ action done (no point retrying the same misconfiguration) but audits the
+ failure.
"""
- principal, plan = _principal_delivery_plan()
+ principal, plan = principal_delivery_plan()
if principal is None:
- return False, "no principal Person row found"
+ return PrincipalDelivery(False, "no principal Person row found", "no_owner")
if not plan:
- return False, "no deliverable channel configured for principal"
+ return PrincipalDelivery(
+ False, "no deliverable channel configured for principal", "no_channel"
+ )
for channel in plan:
try:
@@ -1496,14 +1546,14 @@ async def _deliver_to_principal(text: str, *, label: str = "Update") -> tuple[bo
"user_id": principal.slack_user_id, "text": text,
})
if _delivered_ok(result):
- return True, f"slack_dm → {principal.slack_user_id}"
+ return _sent(channel, principal.slack_user_id)
elif channel == "discord_dm" and principal.discord_user_id:
from openexecutive.orchestrator.schedule_tools import handle_send_discord_dm
result = await handle_send_discord_dm({
"discord_user_id": principal.discord_user_id, "text": text,
})
if _delivered_ok(result):
- return True, f"discord_dm → {principal.discord_user_id}"
+ return _sent(channel, principal.discord_user_id)
elif channel == "telegram" and principal.telegram_chat_id:
from openexecutive.orchestrator.schedule_tools import (
handle_send_telegram_message,
@@ -1512,13 +1562,19 @@ async def _deliver_to_principal(text: str, *, label: str = "Update") -> tuple[bo
"chat_id": int(principal.telegram_chat_id), "text": text,
})
if _delivered_ok(result):
- return True, f"telegram → {principal.telegram_chat_id}"
+ return _sent(channel, principal.telegram_chat_id)
elif channel == "email" and await _email_principal(principal, text, label):
- return True, f"email → {principal.email}"
+ return _sent(channel, principal.email)
except Exception:
logger.exception("scheduler: delivery via %s failed", channel)
- return False, f"delivery failed on every channel ({', '.join(plan)})"
+ return PrincipalDelivery(
+ False, f"delivery failed on every channel ({', '.join(plan)})", "send_failed"
+ )
+
+
+def _sent(channel: str, to: str | None) -> PrincipalDelivery:
+ return PrincipalDelivery(True, f"{channel} → {to}", "delivered", channel)
async def _run_dynamic_workflow(action: ScheduledAction, now: datetime) -> None:
@@ -1632,6 +1688,7 @@ async def _run_principal_brief(action: ScheduledAction, now: datetime) -> None:
import uuid
from openexecutive.audit import log_event as audit_log
+ from openexecutive.briefing import brief_state
from openexecutive.config import get_settings
from openexecutive.knowledge.store import ChromaDBStore
from openexecutive.workflows import WORKFLOW_REGISTRY
@@ -1663,6 +1720,9 @@ async def _run_principal_brief(action: ScheduledAction, now: datetime) -> None:
except Exception:
logger.exception("scheduler: pre-brief alert review failed")
+ # Every run ends with its outcome recorded — sent, not sent, or not
+ # written — for the Briefing's notice and the Setup status page.
+ sending = recorded = False
try:
create_run(
run_id, workflow_name, f"{workflow.title} {now.strftime('%Y-%m-%d')}",
@@ -1683,8 +1743,17 @@ async def _run_principal_brief(action: ScheduledAction, now: datetime) -> None:
raise RuntimeError(event.message)
complete_run(run_id, artifact or "(no artifact)")
- if artifact:
- ok, detail = await _deliver_to_principal(artifact, label=workflow.title)
+ if not artifact:
+ brief_state.record_delivery_outcome(kind, reason="not_written", channel=None)
+ recorded = True
+ else:
+ sending = True
+ delivery = await _deliver_to_principal(artifact, label=workflow.title)
+ ok, detail = delivery.ok, delivery.detail
+ brief_state.record_delivery_outcome(
+ kind, reason=delivery.reason, channel=delivery.channel
+ )
+ recorded = True
if ok:
logger.info("scheduler: %s delivered (%s)", kind, detail)
audit_log(
@@ -1699,8 +1768,6 @@ async def _run_principal_brief(action: ScheduledAction, now: datetime) -> None:
# Only a delivered brief advances the "since last brief"
# window and the unchanged-detection fingerprint.
if fingerprint:
- from openexecutive.briefing import brief_state
-
brief_state.record_delivered(kind, fingerprint, artifact)
else:
logger.warning("scheduler: %s NOT delivered — %s", kind, detail)
@@ -1715,6 +1782,10 @@ async def _run_principal_brief(action: ScheduledAction, now: datetime) -> None:
import contextlib
with contextlib.suppress(Exception):
fail_run(run_id, str(exc))
+ if not recorded:
+ brief_state.record_delivery_outcome(
+ kind, reason="send_failed" if sending else "not_written", channel=None
+ )
# Always chain the next occurrence + mark this row done, so a single
# bad brief doesn't kill the recurring rhythm. Worst case the next
diff --git a/packages/core/openexecutive/utils/markdown_email.py b/packages/core/openexecutive/utils/markdown_email.py
new file mode 100644
index 00000000..fa6ccd6b
--- /dev/null
+++ b/packages/core/openexecutive/utils/markdown_email.py
@@ -0,0 +1,31 @@
+"""Markdown messages as email HTML — the briefs and digests the scheduler emails.
+
+The brief is written in Markdown, and the chat channels show it as such; an
+email client would show the asterisks and hashes instead. So the email body
+is rendered to HTML with markdown-it-py, set up for text the Executive did
+not fully write (a brief quotes alerts, which quote inbound email and web
+pages):
+
+- raw HTML off, so markup in that text shows as text rather than rendering;
+- images off, so opening the email cannot load a remote picture (a read
+ receipt for whoever planted the link) — the link stays, as a link;
+- link targets through markdown-it's own check, which drops ``javascript:``,
+ ``vbscript:``, ``file:`` and ``data:`` URLs.
+"""
+from __future__ import annotations
+
+from markdown_it import MarkdownIt
+
+_RENDERER = MarkdownIt("commonmark", {"html": False}).disable("image")
+
+# Inline styles only: most email clients drop <style> blocks.
+_WRAPPER = (
+ '<div style="font-family: -apple-system, BlinkMacSystemFont, \'Segoe UI\', '
+ 'Roboto, Helvetica, Arial, sans-serif; font-size: 15px; line-height: 1.5; '
+ 'color: #1f2328; max-width: 640px;">{}</div>'
+)
+
+
+def markdown_to_email_html(text: str) -> str:
+ """``text`` (Markdown) as the HTML body of an email."""
+ return _WRAPPER.format(_RENDERER.render(text))
diff --git a/packages/core/pyproject.toml b/packages/core/pyproject.toml
index f17786f6..8eb90f34 100644
--- a/packages/core/pyproject.toml
+++ b/packages/core/pyproject.toml
@@ -36,6 +36,8 @@ dependencies = [
"defusedxml>=0.7.1",
"feedparser>=6.0.11",
"tzdata>=2026.4",
+ # Renders the briefs the scheduler emails (utils/markdown_email.py).
+ "markdown-it-py>=3.0",
]
[project.urls]
diff --git a/packages/core/tests/unit/test_alert_review.py b/packages/core/tests/unit/test_alert_review.py
index 95a46adc..c49fc19d 100644
--- a/packages/core/tests/unit/test_alert_review.py
+++ b/packages/core/tests/unit/test_alert_review.py
@@ -690,9 +690,9 @@ def test_pre_brief_review_runs_before_morning_brief_and_never_blocks_it(db: Path
monkeypatch.setattr(kstore, "ChromaDBStore", _Store)
- async def _deliver(text: str, **_kw: Any) -> tuple[bool, str]:
+ async def _deliver(text: str, **_kw: Any) -> runner.PrincipalDelivery:
order.append("deliver")
- return True, "ok"
+ return runner.PrincipalDelivery(True, "ok", "delivered", "slack_dm")
monkeypatch.setattr(runner, "_deliver_to_principal", _deliver)
monkeypatch.setattr(runner, "_enqueue_next_principal_brief", lambda kind, after: None)
diff --git a/packages/core/tests/unit/test_brief_delivery.py b/packages/core/tests/unit/test_brief_delivery.py
new file mode 100644
index 00000000..5e99b794
--- /dev/null
+++ b/packages/core/tests/unit/test_brief_delivery.py
@@ -0,0 +1,292 @@
+"""Where the daily brief went, and telling the owner when it went nowhere.
+
+ * Each brief's latest run is recorded: the reason, and the channel that
+ sent it (a name, never an address).
+ * The Setup status page's "Daily brief" light says when the briefs go out
+ and where, and turns amber or red when they can't.
+ * ``GET /today/brief-delivery`` gives the owner, and only the owner, the
+ latest brief that didn't reach them, until its cause is fixed.
+"""
+from __future__ import annotations
+
+from datetime import UTC, datetime, timedelta
+from pathlib import Path
+from typing import Any
+
+import pytest
+from fastapi import FastAPI
+from fastapi.testclient import TestClient
+
+from openexecutive.api.setup_checks import Snapshot, check_brief
+from openexecutive.briefing import brief_state, narrative_cache
+from openexecutive.briefing.brief_state import DeliveryOutcome
+from openexecutive.config import Settings
+from openexecutive.people.models import Person
+
+NOW = datetime(2026, 9, 25, 15, 0, tzinfo=UTC)
+MORNING = "principal_brief_morning"
+EVENING = "principal_brief_eod"
+
+
[email protected](autouse=True)
+def isolated_cache(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(narrative_cache, "DB_PATH", tmp_path / "cache.db")
+
+
+# ---------------------------------------------------------------------------
+# The record
+# ---------------------------------------------------------------------------
+
+
+def test_the_latest_send_of_either_brief_is_read_back(monkeypatch: pytest.MonkeyPatch) -> None:
+ assert brief_state.last_delivery_outcome() is None
+ brief_state.record_delivery_outcome(MORNING, reason="delivered", channel="email")
+ later = datetime.now(UTC) + timedelta(minutes=5)
+ monkeypatch.setattr(narrative_cache, "utc_now_iso", lambda: later.isoformat())
+ brief_state.record_delivery_outcome(EVENING, reason="no_channel", channel=None)
+
+ latest = brief_state.last_delivery_outcome()
+ assert latest is not None
+ assert (latest.kind, latest.reason, latest.channel) == (EVENING, "no_channel", None)
+
+
+def test_an_unreadable_record_is_ignored() -> None:
+ narrative_cache.put(narrative_cache.BriefingNarrative(
+ scope=f"{brief_state.DELIVERY_SCOPE_PREFIX}{MORNING}",
+ input_hash="made-up-reason",
+ narrative_text="",
+ generated_at=narrative_cache.utc_now_iso(),
+ ))
+ assert brief_state.last_delivery_outcome() is None
+
+
+ ("recorded", "has_owner", "can_deliver", "problem"),
+ [
+ ("delivered", False, False, None),
+ ("send_failed", True, True, "send_failed"), # stays until the next brief
+ ("not_written", True, True, "not_written"),
+ ("no_channel", True, False, "no_channel"), # still nowhere to send it
+ ("no_channel", True, True, None), # fixed since: the next one will go
+ ("no_owner", True, True, None),
+ # A partial fix reports what is left: an owner now, but still no channel.
+ ("no_owner", True, False, "no_channel"),
+ ("no_channel", False, False, "no_owner"),
+ ],
+)
+def test_current_problem(
+ recorded: str, has_owner: bool, can_deliver: bool, problem: str | None
+) -> None:
+ outcome = DeliveryOutcome(MORNING, recorded, None, NOW) # type: ignore[arg-type]
+ assert brief_state.current_problem(outcome, has_owner=has_owner, can_deliver=can_deliver) == problem
+ assert brief_state.current_problem(None, has_owner=has_owner, can_deliver=can_deliver) is None
+
+
+def test_brief_names_come_from_the_scheduler_labels() -> None:
+ from openexecutive.scheduler.action_phrasing import KIND_LABEL
+
+ for kind in brief_state.BRIEF_KINDS:
+ assert brief_state.brief_name(kind) == KIND_LABEL[kind]
+
+
+def test_email_is_ready_only_with_the_google_workspace_server(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ from openexecutive.orchestrator import mcp_gateway
+ from openexecutive.scheduler import runner
+
+ servers: list[str] = ["notion"]
+ monkeypatch.setattr(mcp_gateway, "configured_server_names", lambda _path: servers)
+ monkeypatch.setattr(mcp_gateway, "_active_gateway", None)
+ assert runner.email_ready() is False # no gateway at all
+ monkeypatch.setattr(mcp_gateway, "_active_gateway", object())
+ assert runner.email_ready() is False # a gateway, but no Gmail behind it
+ servers.append("google_workspace")
+ assert runner.email_ready() is True
+
+
+# ---------------------------------------------------------------------------
+# The "Daily brief" light
+# ---------------------------------------------------------------------------
+
+
+def _settings(**overrides: Any) -> Settings:
+ base: dict[str, Any] = {
+ "ANTHROPIC_API_KEY": "sk-ant-api03-realistic",
+ "EXEC_EMAIL_ADDRESS": "[email protected]",
+ "SCHEDULER_ENABLED": True,
+ }
+ return Settings(**{**base, **overrides})
+
+
+def _snap(**fields: Any) -> Snapshot:
+ values: dict[str, Any] = {
+ "settings": _settings(),
+ "now": NOW,
+ "local_login": False,
+ "people": [],
+ "principal": Person(id=3, full_name="Ada", is_principal=True, email="[email protected]"),
+ "last_inbound": {},
+ "brief_email_ready": True, # Gmail connected
+ "brief_next_runs": {
+ MORNING: datetime(2026, 9, 26, 15, 0, tzinfo=UTC), # 08:00 in Los Angeles
+ EVENING: datetime(2026, 9, 26, 1, 0, tzinfo=UTC), # 18:00 in Los Angeles
+ },
+ "brief_zone": "America/Los_Angeles",
+ }
+ values.update(fields)
+ return Snapshot(**values)
+
+
+def test_the_light_says_when_and_where() -> None:
+ check = check_brief(_snap())
+ assert check.state == "ok"
+ assert check.summary == (
+ "Sent to you by email: the morning brief at 08:00 and the end-of-day digest at 18:00 "
+ "(America/Los_Angeles)."
+ )
+
+
+def test_a_chat_preference_is_named() -> None:
+ ada = Person(id=3, full_name="Ada", is_principal=True, preferred_channel="slack", slack_user_id="U1")
+ assert check_brief(_snap(principal=ada)).summary.startswith("Sent to you on Slack")
+
+
+def test_no_time_zone_means_utc_and_says_so() -> None:
+ check = check_brief(_snap(brief_zone=None))
+ assert check.state == "warn"
+ assert check.summary == (
+ "Sent to you by email: the morning brief at 15:00 and the end-of-day digest at 01:00, "
+ "in UTC because no time zone is set."
+ )
+ assert (check.fix, check.link) == ("Set your time zone in Settings.", "/settings")
+
+
+def test_nowhere_to_send_it() -> None:
+ check = check_brief(_snap(brief_email_ready=False)) # Gmail off, no chat ids
+ assert check.state == "warn"
+ assert check.summary == "Kept in the app only: nothing is set up to send it to you."
+ assert check.link == "/people/3"
+
+
+def test_no_owner() -> None:
+ check = check_brief(_snap(principal=None))
+ assert (check.state, check.link) == ("warn", "/people")
+
+
+def test_a_failed_send_turns_it_red() -> None:
+ failed = DeliveryOutcome(EVENING, "send_failed", None, NOW)
+ check = check_brief(_snap(brief_delivery=failed))
+ assert check.state == "error"
+ assert check.summary == "Your last end-of-day digest wasn't sent: every way of sending it failed."
+
+
+def test_a_brief_that_couldnt_be_written_turns_it_red() -> None:
+ failed = DeliveryOutcome(MORNING, "not_written", None, NOW)
+ check = check_brief(_snap(brief_delivery=failed))
+ assert check.state == "error"
+ assert check.summary == "Your last morning brief wasn't sent: it couldn't be written."
+
+
+def test_a_broken_first_channel_is_named_when_the_backup_carried_it() -> None:
+ # Prefers Slack, Slack failed, email carried it: not all well.
+ ada = Person(
+ id=3, full_name="Ada", is_principal=True, preferred_channel="slack",
+ slack_user_id="U1", email="[email protected]",
+ )
+ carried = DeliveryOutcome(MORNING, "delivered", "email", NOW)
+ check = check_brief(_snap(principal=ada, brief_delivery=carried))
+ assert check.state == "warn"
+ assert check.summary == "Your last morning brief went by email, because Slack didn't work."
+ assert check.fix == 'See the "Slack" light on this page.'
+
+
+def test_a_fixed_cause_is_not_reported() -> None:
+ # It had nowhere to go, and now it has (email is connected in this snapshot).
+ stale = DeliveryOutcome(MORNING, "no_channel", None, NOW)
+ assert check_brief(_snap(brief_delivery=stale)).state == "ok"
+
+
+def test_off_with_the_scheduler() -> None:
+ check = check_brief(_snap(settings=_settings(SCHEDULER_ENABLED=False)))
+ assert check.state == "off"
+
+
+# ---------------------------------------------------------------------------
+# GET /today/brief-delivery
+# ---------------------------------------------------------------------------
+
+
+def notice_client(monkeypatch: pytest.MonkeyPatch) -> Any:
+ from openexecutive.api.routes import chat as chat_route
+ from openexecutive.api.routes import today as today_route
+ from openexecutive.scheduler import runner
+
+ state: dict[str, Any] = {"owner": True, "principal": object(), "plan": []}
+ monkeypatch.setattr(chat_route, "_caller_is_principal_or_unclaimed", lambda _r: state["owner"])
+ monkeypatch.setattr(runner, "principal_delivery_plan", lambda: (state["principal"], state["plan"]))
+ app = FastAPI()
+ app.include_router(today_route.router)
+ return TestClient(app), state
+
+
+def test_the_owner_hears_about_an_unsent_brief(notice_client: Any) -> None:
+ client, _ = notice_client
+ brief_state.record_delivery_outcome(MORNING, reason="no_channel", channel=None)
+ body = client.get("/today/brief-delivery").json()
+ assert body["brief"] == "morning brief"
+ assert body["problem"] == "nothing is set up to send it to you"
+ assert body["fix"].startswith("Connect Gmail")
+ assert body["readable"] is True
+ assert "@" not in str(body)
+
+
+def test_the_notice_names_what_is_left_after_a_partial_fix(notice_client: Any) -> None:
+ client, _ = notice_client # an owner now, still nowhere to send it
+ brief_state.record_delivery_outcome(MORNING, reason="no_owner", channel=None)
+ assert client.get("/today/brief-delivery").json()["problem"] == "nothing is set up to send it to you"
+
+
+def test_a_brief_that_couldnt_be_written_has_nothing_to_read(notice_client: Any) -> None:
+ client, state = notice_client
+ state["plan"] = ["email"]
+ brief_state.record_delivery_outcome(EVENING, reason="not_written", channel=None)
+ body = client.get("/today/brief-delivery").json()
+ assert (body["brief"], body["readable"]) == ("end-of-day digest", False)
+ assert body["problem"] == "it couldn't be written"
+
+
+def test_no_notice_with_the_scheduler_off(
+ notice_client: Any, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ client, _ = notice_client
+ monkeypatch.setenv("SCHEDULER_ENABLED", "false")
+ brief_state.record_delivery_outcome(MORNING, reason="send_failed", channel=None)
+ assert client.get("/today/brief-delivery").json() is None
+
+
+def test_nobody_else_does(notice_client: Any) -> None:
+ client, state = notice_client
+ state["owner"] = False
+ brief_state.record_delivery_outcome(MORNING, reason="send_failed", channel=None)
+ assert client.get("/today/brief-delivery").json() is None
+
+
+ ("reason", "plan"),
+ [
+ ("delivered", ["email"]),
+ ("no_channel", ["email"]), # fixed since
+ ],
+)
+def test_nothing_to_say(notice_client: Any, reason: str, plan: list[str]) -> None:
+ client, state = notice_client
+ state["plan"] = plan
+ brief_state.record_delivery_outcome(MORNING, reason=reason, channel="email") # type: ignore[arg-type]
+ assert client.get("/today/brief-delivery").json() is None
+
+
+def test_nothing_recorded_yet(notice_client: Any) -> None:
+ client, _ = notice_client
+ assert client.get("/today/brief-delivery").json() is None
diff --git a/packages/core/tests/unit/test_markdown_email.py b/packages/core/tests/unit/test_markdown_email.py
new file mode 100644
index 00000000..11819e9d
--- /dev/null
+++ b/packages/core/tests/unit/test_markdown_email.py
@@ -0,0 +1,37 @@
+"""The briefs the scheduler emails: formatted, and safe with text from outside."""
+from __future__ import annotations
+
+from openexecutive.utils.markdown_email import markdown_to_email_html
+
+
+def test_the_brief_is_formatted() -> None:
+ html = markdown_to_email_html("# Today\n\n**Cash** is fine.\n\n- one\n- two")
+ assert "<h1>Today</h1>" in html
+ assert "<strong>Cash</strong> is fine." in html
+ assert "<li>one</li>" in html and "<li>two</li>" in html
+ assert html.startswith("<div style=")
+
+
+def test_markup_from_outside_shows_as_text() -> None:
+ html = markdown_to_email_html(
+ 'Quoted: <script>alert(1)</script> <img src="x" onerror="alert(2)">\n\n<div>block</div>'
+ )
+ assert "<script>" not in html and "<img" not in html and "<div>block" not in html
+ assert "&lt;script&gt;" in html and "&lt;div&gt;block" in html
+
+
+def test_only_safe_links_become_links() -> None:
+ html = markdown_to_email_html(
+ "[ok](https://bank.example/rates?a=1&b=2) [bad](javascript:alert(1)) "
+ "[data](data:text/html,hi) <https://auto.example>"
+ )
+ assert '<a href="https://bank.example/rates?a=1&amp;b=2">ok</a>' in html
+ assert '<a href="https://auto.example">' in html
+ assert 'href="javascript' not in html and 'href="data' not in html
+
+
+def test_images_do_not_load() -> None:
+ html = markdown_to_email_html("![pixel](https://tracker.example/p.gif)")
+ assert "<img" not in html
+ # The address stays visible, as a link the reader chooses to open.
+ assert 'href="https://tracker.example/p.gif"' in html
diff --git a/packages/core/tests/unit/test_principal_briefs.py b/packages/core/tests/unit/test_principal_briefs.py
index 4fa2c940..c0b14477 100644
--- a/packages/core/tests/unit/test_principal_briefs.py
+++ b/packages/core/tests/unit/test_principal_briefs.py
@@ -214,7 +214,14 @@ def _fake_brief_workflow(fingerprint: str, artifact: str = "BRIEF"):
return _Fake()
-def _run_brief(tmp_path: Path, monkeypatch: pytest.MonkeyPatch, *, deliver_ok: bool) -> None:
+def _run_brief(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+ *,
+ deliver_ok: bool = True,
+ workflow: object | None = None,
+ deliver: object | None = None,
+) -> None:
import asyncio
from openexecutive.briefing import narrative_cache
@@ -224,12 +231,16 @@ def _run_brief(tmp_path: Path, monkeypatch: pytest.MonkeyPatch, *, deliver_ok: b
_setup_isolated_db(db, monkeypatch)
monkeypatch.setattr(narrative_cache, "DB_PATH", tmp_path / "cache.db")
monkeypatch.setattr(wf_persistence, "DB_PATH", db)
- monkeypatch.setitem(WORKFLOW_REGISTRY, "morning_brief", _fake_brief_workflow("fp-123"))
+ monkeypatch.setitem(
+ WORKFLOW_REGISTRY, "morning_brief", workflow or _fake_brief_workflow("fp-123")
+ )
- async def _deliver(text: str, **_kw: object) -> tuple[bool, str]:
- return deliver_ok, "discord_dm → 1"
+ async def _deliver(text: str, **_kw: object) -> runner.PrincipalDelivery:
+ if deliver_ok:
+ return runner.PrincipalDelivery(True, "discord_dm → 1", "delivered", "discord_dm")
+ return runner.PrincipalDelivery(False, "delivery failed", "send_failed")
- monkeypatch.setattr(runner, "_deliver_to_principal", _deliver)
+ monkeypatch.setattr(runner, "_deliver_to_principal", deliver or _deliver)
monkeypatch.setattr(runner, "_enqueue_next_principal_brief", lambda kind, after: None)
class _Store:
@@ -256,6 +267,11 @@ def test_run_principal_brief_records_fingerprint_after_delivery(
_run_brief(tmp_path, monkeypatch, deliver_ok=True)
last = brief_state.last_delivered("principal_brief_morning")
assert last is not None and last.input_hash == "fp-123" and last.narrative_text == "BRIEF"
+ outcome = brief_state.last_delivery_outcome()
+ assert outcome is not None
+ assert (outcome.kind, outcome.reason, outcome.channel) == (
+ "principal_brief_morning", "delivered", "discord_dm",
+ )
def test_run_principal_brief_does_not_record_on_delivery_failure(
@@ -265,6 +281,56 @@ def test_run_principal_brief_does_not_record_on_delivery_failure(
_run_brief(tmp_path, monkeypatch, deliver_ok=False)
assert brief_state.last_delivered("principal_brief_morning") is None
+ # The failure is still recorded, for the Briefing's "not sent" notice.
+ outcome = brief_state.last_delivery_outcome()
+ assert outcome is not None and (outcome.reason, outcome.channel) == ("send_failed", None)
+
+
+def _failing_brief_workflow(event: str): # type: ignore[no-untyped-def]
+ from openexecutive.workflows.base import WorkflowEvent
+ from openexecutive.workflows.morning_brief import MorningBriefInput, MorningBriefWorkflow
+
+ class _Fails(MorningBriefWorkflow):
+ async def run(self, inputs, store): # type: ignore[override]
+ if event == "error":
+ yield WorkflowEvent(type="error", message="model unavailable")
+ yield WorkflowEvent(type="done") # "empty": no artifact at all
+
+ def input_model(self): # type: ignore[override]
+ return MorningBriefInput
+
+ return _Fails()
+
+
[email protected]("event", ["error", "empty"])
+def test_a_brief_that_couldnt_be_written_is_recorded(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, event: str
+) -> None:
+ from openexecutive.briefing import brief_state
+
+ sends: list[str] = []
+
+ async def _deliver(text: str, **_kw: object) -> runner.PrincipalDelivery:
+ sends.append(text)
+ return runner.PrincipalDelivery(True, "email → x", "delivered", "email")
+
+ _run_brief(tmp_path, monkeypatch, workflow=_failing_brief_workflow(event), deliver=_deliver)
+ assert sends == []
+ outcome = brief_state.last_delivery_outcome()
+ assert outcome is not None and outcome.reason == "not_written"
+
+
+def test_a_send_that_crashes_is_recorded_as_failed(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ from openexecutive.briefing import brief_state
+
+ async def _crash(text: str, **_kw: object) -> runner.PrincipalDelivery:
+ raise RuntimeError("people store locked")
+
+ _run_brief(tmp_path, monkeypatch, deliver=_crash)
+ outcome = brief_state.last_delivery_outcome()
+ assert outcome is not None and outcome.reason == "send_failed"
# ---------------------------------------------------------------------------
@@ -327,15 +393,18 @@ def _principal(**fields: object) -> int:
def _with_gateway(monkeypatch: pytest.MonkeyPatch, sent: _Sent, **kw: str) -> None:
+ """An MCP gateway running the Google Workspace server, so email is ready."""
from openexecutive.orchestrator import mcp_gateway
monkeypatch.setattr(mcp_gateway, "_active_gateway", _Gateway(sent, **kw))
+ monkeypatch.setattr(mcp_gateway, "configured_server_names", lambda _path: ["google_workspace"])
def _deliver(text: str = "BRIEF", label: str = "Morning Brief") -> tuple[bool, str]:
import asyncio
- return asyncio.run(runner._deliver_to_principal(text, label=label))
+ result = asyncio.run(runner._deliver_to_principal(text, label=label))
+ return result.ok, result.detail
def test_preferred_slack_is_honoured(sent: _Sent) -> None:
@@ -364,7 +433,7 @@ def test_preferred_email_sends_through_the_gateway(
_principal(preferred_channel="email", email="[email protected]", slack_user_id="U1")
_with_gateway(monkeypatch, sent)
- ok, detail = _deliver("the brief", label="Morning Brief")
+ ok, detail = _deliver("**the** brief", label="Morning Brief")
assert ok and detail == "email → [email protected]"
((name, call),) = sent.calls
@@ -373,8 +442,10 @@ def test_preferred_email_sends_through_the_gateway(
args = call["arguments"]
assert args["user_google_email"] == get_settings().exec_email_address
assert args["to"] == "[email protected]"
- assert args["subject"] == f"Morning Brief — {datetime.now(UTC).strftime('%Y-%m-%d')}"
- assert args["body"] == "the brief"
+ assert args["subject"] == runner._email_subject("Morning Brief")
+ # Formatted, not the raw Markdown.
+ assert args["body_format"] == "html"
+ assert "<strong>the</strong> brief" in args["body"] and "**" not in args["body"]
def test_email_error_falls_back_to_chat(sent: _Sent, monkeypatch: pytest.MonkeyPatch) -> None:
@@ -400,7 +471,7 @@ def test_any_with_a_chat_channel_never_emails(
sent: _Sent, monkeypatch: pytest.MonkeyPatch,
) -> None:
"""An owner linked by email at setup (preference "any") who also has Slack
- must not start getting the briefs by email too."""
+ must not get the briefs by email too while Slack works."""
_principal(email="[email protected]", slack_user_id="U1")
_with_gateway(monkeypatch, sent)
@@ -410,6 +481,81 @@ def test_any_with_a_chat_channel_never_emails(
assert [name for name, _ in sent.calls] == ["slack"]
+def test_email_is_the_backup_when_the_preferred_chat_is_not_connected(
+ sent: _Sent, monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ _principal(preferred_channel="slack", email="[email protected]") # no Slack id
+ _with_gateway(monkeypatch, sent)
+
+ ok, detail = _deliver()
+
+ assert ok and detail == "email → [email protected]"
+ assert [name for name, _ in sent.calls] == ["gmail"]
+
+
+def test_email_is_the_backup_when_every_chat_send_fails(
+ sent: _Sent, monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ import json
+
+ from openexecutive.orchestrator import schedule_tools
+
+ _principal(preferred_channel="slack", slack_user_id="U1", email="[email protected]")
+ _with_gateway(monkeypatch, sent)
+
+ async def _slack_down(args: dict) -> str: # type: ignore[type-arg]
+ sent.calls.append(("slack", args))
+ return json.dumps({"error": "token revoked"})
+
+ monkeypatch.setattr(schedule_tools, "handle_send_slack_dm", _slack_down)
+
+ ok, detail = _deliver()
+
+ assert ok and detail == "email → [email protected]"
+ assert [name for name, _ in sent.calls] == ["slack", "gmail"]
+
+
+def _deliver_result() -> runner.PrincipalDelivery:
+ import asyncio
+
+ return asyncio.run(runner._deliver_to_principal("BRIEF"))
+
+
+def test_no_owner_is_its_own_reason(sent: _Sent) -> None:
+ assert _deliver_result().reason == "no_owner"
+
+
+def test_nothing_connected_is_its_own_reason(sent: _Sent) -> None:
+ _principal(email="[email protected]") # no gateway, no chat
+ result = _deliver_result()
+ assert (result.ok, result.reason) == (False, "no_channel")
+
+
+def test_a_failed_send_is_its_own_reason(sent: _Sent, monkeypatch: pytest.MonkeyPatch) -> None:
+ from openexecutive.orchestrator import schedule_tools
+
+ async def _broken(args: dict) -> str: # type: ignore[type-arg]
+ raise RuntimeError("telegram down")
+
+ _principal(telegram_chat_id="42")
+ monkeypatch.setattr(schedule_tools, "handle_send_telegram_message", _broken)
+ result = _deliver_result()
+ assert (result.ok, result.reason, result.channel) == (False, "send_failed", None)
+
+
+def test_the_email_subject_carries_the_users_date(monkeypatch: pytest.MonkeyPatch) -> None:
+ from zoneinfo import ZoneInfo
+
+ from openexecutive.memory import workspace_settings
+
+ monkeypatch.setattr(
+ workspace_settings, "get_user_timezone", lambda *_a: ZoneInfo("America/Los_Angeles")
+ )
+ # 02:00 UTC on Saturday is still Friday evening in California.
+ evening = datetime(2026, 9, 26, 2, 0, tzinfo=UTC)
+ assert runner._email_subject("End-of-Day Digest", evening) == "End-of-Day Digest — Fri 25 Sep"
+
+
def test_email_without_a_gateway_is_not_delivered(sent: _Sent) -> None:
_principal(preferred_channel="email", email="[email protected]")
@@ -443,7 +589,7 @@ def test_client_digest_still_delivers(sent: _Sent, monkeypatch: pytest.MonkeyPat
((_, call),) = sent.calls
assert call["arguments"]["subject"].startswith("Across your clients — ")
- assert call["arguments"]["body"] == "# Across your clients"
+ assert "<h1>Across your clients</h1>" in call["arguments"]["body"]
def test_brief_with_no_deliverable_channel_is_still_generated_and_stored(
@@ -505,6 +651,9 @@ def test_brief_with_no_deliverable_channel_is_still_generated_and_stored(
assert stored is not None and stored["artifact"] == "BRIEF"
# Only a delivered brief advances the window.
assert brief_state.last_delivered("principal_brief_morning") is None
+ # Why it wasn't sent is kept for the Briefing's notice.
+ outcome = brief_state.last_delivery_outcome()
+ assert outcome is not None and outcome.reason == "no_channel"
row = episodic.get_scheduled_action(action_id)
assert row is not None and row.status == "done"
assert chained == ["principal_brief_morning"]
diff --git a/packages/core/uv.lock b/packages/core/uv.lock
index a660ed70..d2f2fc4b 100644
--- a/packages/core/uv.lock
+++ b/packages/core/uv.lock
@@ -2120,6 +2120,7 @@ dependencies = [
{ name = "google-auth" },
{ name = "honcho-ai" },
{ name = "httpx" },
+ { name = "markdown-it-py" },
{ name = "mcp" },
{ name = "openpyxl" },
{ name = "pydantic" },
@@ -2172,6 +2173,7 @@ requires-dist = [
{ name = "google-auth", specifier = ">=2.29.0" },
{ name = "honcho-ai", specifier = ">=2.1,<3" },
{ name = "httpx", specifier = ">=0.27.0" },
+ { name = "markdown-it-py", specifier = ">=3.0" },
{ name = "mcp", specifier = ">=1.2.0,<2" },
{ name = "mypy", marker = "extra == 'dev'", specifier = ">=1.10.0" },
{ name = "openpyxl", specifier = ">=3.1.0" },
diff --git a/packages/ui/src/app/page.tsx b/packages/ui/src/app/page.tsx
index 45f89d98..885e0252 100644
--- a/packages/ui/src/app/page.tsx
+++ b/packages/ui/src/app/page.tsx
@@ -2,6 +2,7 @@
import { useCallback, useEffect, useRef, useState } from "react";
import { useSession } from "next-auth/react";
+import BriefDeliveryNotice from "@/components/BriefDeliveryNotice";
import Briefing from "@/components/Briefing";
import Chat from "@/components/Chat";
import DebugPanel from "@/components/DebugPanel";
@@ -278,6 +279,8 @@ export default function HomePage() {
</div>
)}
+ {mode === "briefing" && <BriefDeliveryNotice />}
+
<div className="flex-1 min-h-0">
{mode === "briefing" ? (
<Briefing
diff --git a/packages/ui/src/components/BriefDeliveryNotice.tsx b/packages/ui/src/components/BriefDeliveryNotice.tsx
new file mode 100644
index 00000000..5417b51b
--- /dev/null
+++ b/packages/ui/src/components/BriefDeliveryNotice.tsx
@@ -0,0 +1,57 @@
+"use client";
+
+import Link from "next/link";
+import { useEffect, useState } from "react";
+
+import { getBriefDelivery, type BriefDeliveryNotice as Notice } from "@/lib/api";
+
+/**
+ * Above the Briefing: the latest morning brief or end-of-day digest that
+ * wasn't sent, why, and what fixes it. The API only tells the owner, and
+ * says nothing while briefs are going out, so most of the time this renders
+ * nothing.
+ */
+export default function BriefDeliveryNotice() {
+ const [notice, setNotice] = useState<Notice | null>(null);
+
+ useEffect(() => {
+ const controller = new AbortController();
+ getBriefDelivery(controller.signal)
+ .then(setNotice)
+ .catch(() => { /* no notice is better than a broken one */ });
+ return () => controller.abort();
+ }, []);
+
+ if (!notice) return null;
+ const day = new Date(notice.at);
+ const when = Number.isNaN(day.getTime())
+ ? ""
+ : ` (${day.toLocaleDateString(undefined, { weekday: "short", day: "numeric", month: "short" })})`;
+ return (
+ <div
+ role="status"
+ className="border-b border-line bg-amber-500/5 px-4 sm:px-6 py-2.5 flex items-start gap-2 flex-shrink-0"
+ >
+ {/* Themed text with an amber marker: amber text is too faint on the light theme. */}
+ <span className="mt-1.5 inline-block w-1.5 h-1.5 rounded-full bg-amber-400 flex-shrink-0" aria-hidden="true" />
+ <p className="flex-1 min-w-0 text-xs text-fg-muted leading-snug">
+ <span className="font-medium text-fg">
+ Your {notice.brief}
+ {when} wasn&apos;t sent:
+ </span>{" "}
+ {notice.problem}. {notice.fix}{" "}
+ {notice.readable ? (
+ <>
+ <Link href="/artifacts" className="text-indigo-400 hover:text-indigo-300 font-medium whitespace-nowrap">
+ Read it
+ </Link>
+ <span aria-hidden="true"> · </span>
+ </>
+ ) : null}
+ <Link href="/settings/status" className="text-indigo-400 hover:text-indigo-300 font-medium whitespace-nowrap">
+ Setup status
+ </Link>
+ </p>
+ </div>
+ );
+}
diff --git a/packages/ui/src/components/memories/CadenceSection.tsx b/packages/ui/src/components/memories/CadenceSection.tsx
index f67d6205..c323dc79 100644
--- a/packages/ui/src/components/memories/CadenceSection.tsx
+++ b/packages/ui/src/components/memories/CadenceSection.tsx
@@ -98,7 +98,7 @@ export default function CadenceSection() {
<div className="max-h-[32rem] overflow-y-auto pr-1 space-y-6">
<RhythmBlock
title="Daily rhythm"
- subtitle="Your daily briefing cycle — the morning brief and end-of-day digest land in your inbox; the reflection sets up the morning brief."
+ subtitle="Your daily briefing cycle — the morning brief and end-of-day digest are sent to you by email or chat (Settings → Setup status shows where); the reflection sets up the morning brief."
icon="clipboard"
tag="Once a day · for you"
tagTone="info"
diff --git a/packages/ui/src/components/settings/SetupStatusView.tsx b/packages/ui/src/components/settings/SetupStatusView.tsx
index 3559b423..e3b7f913 100644
--- a/packages/ui/src/components/settings/SetupStatusView.tsx
+++ b/packages/ui/src/components/settings/SetupStatusView.tsx
@@ -24,8 +24,15 @@ const STATE_STYLE: Record<SetupState, { dot: string; word: string; wordClass: st
const LINK_LABELS: Record<string, string> = {
"/people": "Open the People page",
"/onboard": "Open the setup interview",
+ "/settings": "Open Settings",
};
+function linkLabel(link: string): string {
+ // A person's page: the daily brief light links the owner's own profile.
+ if (link.startsWith("/people/")) return "Open your People profile";
+ return LINK_LABELS[link] ?? "Open";
+}
+
function CheckRow({ check }: { check: SetupCheck }) {
const style = STATE_STYLE[check.state];
const link = safeInAppLink(check.link);
@@ -57,7 +64,7 @@ function CheckRow({ check }: { check: SetupCheck }) {
href={link}
className="mt-2 inline-flex items-center gap-1 text-xs font-medium text-fg hover:underline"
>
- {LINK_LABELS[link] ?? "Open"}
+ {linkLabel(link)}
<Icon name="chevron-right" size="w-3.5 h-3.5" />
</Link>
) : null}
diff --git a/packages/ui/src/lib/api.ts b/packages/ui/src/lib/api.ts
index 931924fe..a0a98001 100644
--- a/packages/ui/src/lib/api.ts
+++ b/packages/ui/src/lib/api.ts
@@ -3305,6 +3305,24 @@ export async function getToday(): Promise<Today> {
return res.json();
}
+// The latest morning brief or end-of-day digest that didn't reach the owner,
+// and what fixes it. Null while briefs are going out, and for anyone but the
+// owner.
+export interface BriefDeliveryNotice {
+ brief: string;
+ at: string;
+ problem: string;
+ fix: string;
+ // False when it couldn't be written, so there is nothing to read.
+ readable: boolean;
+}
+
+export async function getBriefDelivery(signal?: AbortSignal): Promise<BriefDeliveryNotice | null> {
+ const res = await fetch(`${API_BASE}/today/brief-delivery`, { signal });
+ if (!res.ok) throw new Error(`Failed to load brief delivery: ${res.statusText}`);
+ return res.json();
+}
+
// Mark an alert as read/ack/dismissed. Used by the briefing's
// Approve/Dismiss affordance to groom the "Needs you" queue: any
// non-unread status drops the alert from /today's proposals list.