Skip to content

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

feat(scheduler): retry the MCP gateway and say why a brief was not sent (#448)

Rufusd11d80287064
diff --git a/packages/core/openexecutive/api/main.py b/packages/core/openexecutive/api/main.py
index db768da6..2d76d23b 100644
--- a/packages/core/openexecutive/api/main.py
+++ b/packages/core/openexecutive/api/main.py
@@ -161,7 +161,7 @@ _UNAUTHENTICATED_PATHS: frozenset[str] = frozenset(
)
-# How long the MCP gateway gets to come up. The child is
+# How long the MCP gateway gets to come up, per attempt. The child is
# `uvx --from git+https://…/extensible-mcp`, which resolves and may clone that
# repo on a cold start, so this is generous; what it must not be is unbounded.
# `MCPGateway.start` builds `ClientSession` with no `read_timeout_seconds`, so
@@ -169,33 +169,10 @@ _UNAUTHENTICATED_PATHS: frozenset[str] = frozenset(
# lifespan that never yields is a healthcheck that never passes, which is
# #122's symptom with none of its traceback. A dead child is already fine
# (the session's receive loop fails every pending request on close); it is the
-# silent one that needs a clock.
+# silent one that needs a clock. A failed attempt is retried in the
+# background with backoff (orchestrator/gateway_boot.py), so one slow or
+# faulty start no longer costs the whole process its MCP tools.
_MCP_START_TIMEOUT_S = 120.0
-# Tearing down a gateway that just failed walks the same stdio machinery that
-# failed, so it gets a clock too.
-_MCP_CLOSE_TIMEOUT_S = 10.0
-
-
-async def _close_mcp_gateway_quietly(gateway: Any, log: logging.Logger) -> None:
- """Reap a gateway that failed to start. Never raises, never hangs.
-
- `MCPGateway.close` suppresses `Exception` around each step, which is not
- enough here: anyio raises `BaseExceptionGroup` as soon as one sub-exception
- is a `BaseException` such as `CancelledError`, and that is not an
- `Exception`. Since this runs from inside an `except` block, anything it
- raises replaces the actionable log we just wrote with the crash that log
- exists to prevent.
- """
- try:
- await asyncio.wait_for(gateway.close(), timeout=_MCP_CLOSE_TIMEOUT_S)
- except asyncio.CancelledError:
- raise
- except BaseException:
- log.warning(
- "MCP gateway teardown after a failed start did not finish cleanly; "
- "continuing shutdown of the failed gateway anyway",
- exc_info=True,
- )
async def _start_mcp_gateway(
@@ -204,7 +181,11 @@ async def _start_mcp_gateway(
"""Bring the MCP gateway up, or leave MCP off and say why.
Sets ``app.state.mcp_gateway`` — the gateway on success, ``None`` otherwise
- — and returns the email-poller task that rides on it, or ``None``.
+ — and returns the email-poller task that rides on it, or ``None``. The
+ supervisor that made the attempt stays on ``app.state.mcp_supervisor``:
+ when the first attempt fails it keeps retrying with backoff, and a later
+ success wires the gateway, the pinned-tool priming and the email poller
+ exactly as a first-time success does here; ``/health`` reports its state.
Never raises and never blocks indefinitely. The gateway spawns
extensible-mcp as a subprocess, and a failure there used to propagate out
@@ -212,24 +193,22 @@ async def _start_mcp_gateway(
that is a crash loop whose only outward symptom is a healthcheck that never
passes (#122). Booting without MCP costs the Gmail/Calendar/Drive tool
surface and the email poller; refusing to boot costs everything, so degrade
- and log loudly enough to alert on.
-
- ``except BaseException`` rather than ``except Exception``, with real
- cancellation re-raised first: the failure in #122 surfaced from anyio, and
- anyio wraps a task group's failures in ``BaseExceptionGroup`` as soon as one
- of them is a ``BaseException`` such as ``CancelledError``. That group is not
- an ``Exception``, so ``except Exception`` would let through the single
- exception shape this function exists to contain.
+ and log loudly enough to alert on. The supervisor contains the same
+ failure shapes (``except BaseException`` with real cancellation re-raised
+ first: anyio wraps a task group's failures in ``BaseExceptionGroup`` as
+ soon as one of them is a ``CancelledError``, and that group is not an
+ ``Exception``).
"""
app.state.mcp_gateway = None
+ app.state.mcp_supervisor = None
if not settings.mcp_enabled:
return None
from openexecutive.config import mcp_config_file_present
+ from openexecutive.orchestrator.gateway_boot import GatewaySupervisor
from openexecutive.orchestrator.mcp_gateway import (
- MCPGateway,
configured_server_names,
- set_active_gateway,
+ set_gateway_supervisor,
)
log = logging.getLogger("openexecutive")
@@ -263,37 +242,23 @@ async def _start_mcp_gateway(
)
return None
- gateway = MCPGateway()
- try:
- await asyncio.wait_for(
- gateway.start(config_path), timeout=_MCP_START_TIMEOUT_S
- )
- except asyncio.CancelledError:
- raise
- except BaseException:
- log.exception(
- "MCP gateway failed to start within %.0fs; continuing WITHOUT MCP "
- "tools and without the email poller. config=%s servers=[%s] (%s)",
- _MCP_START_TIMEOUT_S, config_path, ", ".join(servers), why,
- )
- await _close_mcp_gateway_quietly(gateway, log)
+ supervisor = GatewaySupervisor(
+ config_path=config_path,
+ servers=servers,
+ app_state=app.state,
+ start_timeout_s=_MCP_START_TIMEOUT_S,
+ why=why,
+ )
+ app.state.mcp_supervisor = supervisor
+ set_gateway_supervisor(supervisor)
+ if not await supervisor.start():
return None
- app.state.mcp_gateway = gateway
- set_active_gateway(gateway)
- if "google_workspace" in servers:
- # Discover the pinned Google tools now, so the model's first direct
- # call_tool doesn't wait on the search. Held on app.state: a bare
- # create_task is only weakly referenced.
- app.state.mcp_prime_task = asyncio.create_task(gateway.prime_pinned_tools())
-
# Say which mail/calendar backends the fixed code paths will use, and warn
# (never fail) when a chosen backend's server is not in the config.
from openexecutive.integrations.workspace.registry import log_provider_status
log_provider_status(settings, config_path)
-
- from openexecutive.integrations.email_poller import run_email_poller
- return asyncio.create_task(run_email_poller(gateway))
+ return supervisor.poller_task
# How long the lifespan waits for the Slack socket to cancel its pending
@@ -793,6 +758,18 @@ async def lifespan(app: FastAPI) -> AsyncIterator[None]:
if slack_connect_task is not None and not slack_connect_task.done():
slack_connect_task.cancel()
+ # The supervisor owns the poller it started (at boot or on a retry), the
+ # priming task and the retries themselves; closing it stops all three
+ # and the gateway. The task returned at boot is the same object, so the
+ # cancel below is a no-op after this.
+ supervisor = getattr(app.state, "mcp_supervisor", None)
+ if supervisor is not None:
+ from openexecutive.orchestrator.mcp_gateway import set_gateway_supervisor
+
+ set_gateway_supervisor(None)
+ with contextlib.suppress(Exception):
+ await supervisor.close()
+
if email_poller_task is not None:
email_poller_task.cancel()
with contextlib.suppress(asyncio.CancelledError, Exception):
diff --git a/packages/core/openexecutive/api/models.py b/packages/core/openexecutive/api/models.py
index 4777a4f5..efe040c1 100644
--- a/packages/core/openexecutive/api/models.py
+++ b/packages/core/openexecutive/api/models.py
@@ -170,6 +170,23 @@ class SyncedDocContent(BaseModel):
content: str
+class GatewayHealth(BaseModel):
+ """The MCP gateway (orchestrator/gateway_boot.py): ``off`` (MCP not
+ enabled), ``no_servers`` (enabled, config names none), ``starting`` (an
+ attempt is running), ``up``, or ``down`` (every attempt failed so far;
+ ``next_retry_at`` says when the next one is). ``attempts`` counts starts
+ tried. The failure's text stays in the log and the owner's Setup notice:
+ the route is open to anyone. ``email_poller`` is whether the poller that
+ rides on the gateway runs."""
+
+ state: str
+ attempts: int = 0
+ last_failed_at: str | None = None
+ up_since: str | None = None
+ next_retry_at: str | None = None
+ email_poller: bool = False
+
+
class HealthResponse(BaseModel):
status: str
builtin_knowledge_chunks: int
@@ -183,6 +200,10 @@ class HealthResponse(BaseModel):
# Setup status says which. A non-empty list means a workspace-mcp rename or
# a tool the configured services and tier never loaded.
google_tools_missing: list[str] | None = None
+ # The MCP gateway's state (``GatewayHealth``). A hosted instance whose
+ # gateway failed to start used to look healthy here while no email went
+ # out or came in.
+ gateway: GatewayHealth | None = None
version: str = "0.5.4" # x-release-please-version
diff --git a/packages/core/openexecutive/api/routes/health.py b/packages/core/openexecutive/api/routes/health.py
index e5dff752..5e07b314 100644
--- a/packages/core/openexecutive/api/routes/health.py
+++ b/packages/core/openexecutive/api/routes/health.py
@@ -4,7 +4,7 @@ from typing import Any
from fastapi import APIRouter, Request
-from openexecutive.api.models import HealthResponse
+from openexecutive.api.models import GatewayHealth, HealthResponse
router = APIRouter()
@@ -47,9 +47,27 @@ async def health_check(request: Request) -> HealthResponse:
builtin_skills=builtin_skills_count,
company_skills=company_skills_count,
google_tools_missing=list(missing) if missing is not None else None,
+ gateway=gateway_health(request.app.state, settings),
)
+def gateway_health(app_state: Any, settings: Any) -> GatewayHealth:
+ """The gateway's state for /health: from the supervisor when boot made
+ one, else from what is on the app (a gateway handed in without a
+ supervisor is up; none with MCP on means the config named no servers)."""
+ supervisor = getattr(app_state, "mcp_supervisor", None)
+ status = getattr(supervisor, "status", None)
+ if callable(status):
+ report = status()
+ as_dict = getattr(report, "as_dict", None)
+ data = as_dict() if callable(as_dict) else dict(report)
+ data.pop("last_error", None) # the route is unauthenticated
+ return GatewayHealth(**data)
+ if getattr(app_state, "mcp_gateway", None) is not None:
+ return GatewayHealth(state="up")
+ return GatewayHealth(state="no_servers" if getattr(settings, "mcp_enabled", False) else "off")
+
+
_HONCHO_PROBE_TIMEOUT_S = 3.0
diff --git a/packages/core/openexecutive/api/routes/today.py b/packages/core/openexecutive/api/routes/today.py
index 07c63c5c..be727ea7 100644
--- a/packages/core/openexecutive/api/routes/today.py
+++ b/packages/core/openexecutive/api/routes/today.py
@@ -1963,13 +1963,13 @@ class BriefDeliveryNotice(BaseModel):
def _brief_delivery_notice() -> BriefDeliveryNotice | None:
from openexecutive.briefing.brief_state import (
- DELIVERY_PROBLEMS,
brief_name,
current_problem,
+ describe_problem,
last_delivery_outcome,
)
from openexecutive.config import get_settings
- from openexecutive.scheduler.runner import principal_delivery_plan
+ from openexecutive.scheduler.runner import mail_gateway_problem, principal_delivery_plan
# With the scheduler off no brief is coming; the Setup status page says so.
if not get_settings().scheduler_enabled:
@@ -1978,10 +1978,16 @@ def _brief_delivery_notice() -> BriefDeliveryNotice | None:
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))
+ blocked = mail_gateway_problem(principal)
+ reason = current_problem(
+ last, has_owner=principal is not None, can_deliver=bool(plan),
+ gateway_down=blocked is not None,
+ )
if reason is None:
return None
- problem, fix = DELIVERY_PROBLEMS[reason]
+ problem, fix = describe_problem(
+ reason, blocked if reason == "gateway_down" else last.detail
+ )
return BriefDeliveryNotice(
brief=brief_name(last.kind),
at=last.at.isoformat(),
diff --git a/packages/core/openexecutive/api/setup_checks.py b/packages/core/openexecutive/api/setup_checks.py
index 249f682f..f8267974 100644
--- a/packages/core/openexecutive/api/setup_checks.py
+++ b/packages/core/openexecutive/api/setup_checks.py
@@ -155,6 +155,11 @@ class Snapshot:
# nobody chose one, so UTC).
brief_delivery: DeliveryOutcome | None = None
brief_email_ready: bool = False
+ # Why the gateway that sends email is down (orchestrator.mcp_gateway.
+ # gateway_problem), or None while it is up; and the servers whose
+ # sign-in has died (``MCPGateway.needs_reconnect``).
+ gateway_problem: str | None = None
+ gateway_needs_reconnect: tuple[str, ...] = ()
brief_next_runs: dict[str, datetime] = field(default_factory=dict)
brief_zone: str | None = None
@@ -828,11 +833,21 @@ def check_gmail(snap: Snapshot) -> SetupCheck:
"To connect Gmail, follow the Google Workspace steps in .env.example.",
)
if snap.mcp_gateway is None:
+ problem = snap.gateway_problem or "the MCP gateway is not running"
return _result(
"gmail",
"error",
- "The connection to Google didn't start, so email is off.",
- f'The API log says why — look for "MCP gateway". Fix that, {_RESTART}',
+ f"The connection to Google didn't start, so email is off: {problem}.",
+ 'It keeps retrying on its own. If it stays off, the API log says why — look for '
+ f'"MCP gateway". Fix that, {_RESTART}',
+ )
+ if "google_workspace" in snap.gateway_needs_reconnect:
+ return _result(
+ "gmail",
+ "error",
+ f"Google turned the Executive's sign-in as {settings.exec_email_address} away: "
+ "it expired or was revoked, so email, calendar and files are off.",
+ f"Sign Google in again as that address (scripts/mint-google-token.py), {_RESTART}",
)
missing = _google_sign_in_missing()
if missing:
@@ -1051,8 +1066,9 @@ def check_brief(snap: Snapshot) -> SetupCheck:
brief_name,
channel_phrase,
current_problem,
+ describe_problem,
)
- from openexecutive.scheduler.runner import delivery_order
+ from openexecutive.scheduler.runner import delivery_order, mail_gateway_problem
if not snap.settings.scheduler_enabled:
return _result("brief", "off", "Off, because the scheduler is turned off.")
@@ -1062,6 +1078,12 @@ def check_brief(snap: Snapshot) -> SetupCheck:
return _result("brief", "warn", f"Not sent: {problem}.", fix, link="/people")
plan = delivery_order(principal, email_ready=snap.brief_email_ready)
if not plan:
+ blocked = mail_gateway_problem(principal, with_error=False)
+ if blocked is not None:
+ # The attempt count, not the error text: every team member reads
+ # this page; the owner's own notice on Home carries the text.
+ problem, fix = describe_problem("gateway_down", blocked)
+ return _result("brief", "error", f"Not sent by email: {problem}.", fix)
problem, fix = DELIVERY_PROBLEMS["no_channel"]
return _result(
"brief",
@@ -1073,7 +1095,12 @@ def check_brief(snap: Snapshot) -> SetupCheck:
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]
+ # The fix may read the detail (a grant that died names a reconnect)
+ # but the summary never quotes it: every team member reads this page,
+ # and the text can name the owner's channels. Home carries it, for
+ # the owner alone.
+ problem, _ = describe_problem(reason)
+ _, fix = describe_problem(reason, last.detail)
return _result(
"brief", "error", f"Your last {brief_name(last.kind)} wasn't sent: {problem}.", fix
)
@@ -1151,6 +1178,10 @@ def gather_snapshot(settings: Settings, *, local_login: bool, app_state: Any) ->
from openexecutive.briefing.brief_state import last_delivery_outcome
from openexecutive.integrations.slack_bot import bot_user_id
from openexecutive.memory.workspace_settings import get_user_timezone, get_workspace
+ from openexecutive.orchestrator.mcp_gateway import (
+ gateway_problem,
+ gateway_reconnect_needed,
+ )
from openexecutive.people.store import find_principal_person, list_people
from openexecutive.scheduler.runner import email_ready, next_brief_runs
@@ -1171,6 +1202,8 @@ def gather_snapshot(settings: Settings, *, local_login: bool, app_state: Any) ->
slack_handler=getattr(app_state, "slack_handler", None),
slack_bot_id_resolved=bot_user_id() is not None,
mcp_gateway=getattr(app_state, "mcp_gateway", None),
+ gateway_problem=gateway_problem(with_error=False),
+ gateway_needs_reconnect=gateway_reconnect_needed(getattr(app_state, "mcp_gateway", None)),
brief_delivery=last_delivery_outcome(),
brief_email_ready=email_ready(),
brief_next_runs=next_brief_runs(now),
diff --git a/packages/core/openexecutive/architecture/architecture-facts.yaml b/packages/core/openexecutive/architecture/architecture-facts.yaml
index b5f15306..8d523c51 100644
--- a/packages/core/openexecutive/architecture/architecture-facts.yaml
+++ b/packages/core/openexecutive/architecture/architecture-facts.yaml
@@ -176,7 +176,13 @@ caching:
guard) + Connected Systems section (prompts/connected_systems.py:
Google Workspace on/off from the running gateway's server_names, and
when on the own-account guidance plus the pinned GOOGLE_TOOL_MANIFEST
- names to call directly; other MCP servers by name; Slack / Discord /
+ names to call directly — or "needs reconnecting", with no tool
+ names, while google_workspace is in MCPGateway.needs_reconnect (set
+ by _note_grant_health when a tool answers with an authorization
+ failure, mcp_gateway.grant_failure; cleared by the next answer that
+ is not one, or mark_reconnected), passed as needs_reconnect=
+ gateway_reconnect_needed(gateway) so the set changing re-renders
+ block 0 once; other MCP servers by name; Slack / Discord /
Telegram / Google Chat on/off; Notion sync; a constant Act as me line
pointing at DELEGATION_ADDENDUM — all process-stable and sorted) +
DELEGATION_ADDENDUM (Act as me — a constant, only while
@@ -6674,7 +6680,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 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 and the (solo) weekly review (`brief_state.DELIVERY_KINDS`; `BRIEF_KINDS` stays the two daily briefs, whose send times the Setup page lists). `current_problem(outcome, has_owner, can_deliver)` says what still keeps it from the owner: send_failed and not_written stay reported until the next brief records a new outcome; having nowhere to send it is judged from now, so a fix clears it and a partial fix reports what is left (an owner added but still no channel reads no_channel). `GET /today/brief-delivery` (the Briefing's notice, owner only, null while the scheduler is off) and the Setup status 'Daily brief' light read it; brief names come from `scheduler.action_phrasing.KIND_LABEL` (`brief_state.brief_name`). SOLO: with effective_workspace_mode solo it uses STANDALONE_BRIEF_SOLO_SYSTEM (top call → what changed → handled overnight → needs you → due this week → goals at risk, named by area; no waiting-on or department sections) over the solo context render, which adds today_data['due_soon'] (open_loops.principal_due_soon: the principal's open loops overdue or due within 7 days) as a DUE THIS WEEK block, and the fingerprint carries the mode, drops the people-awaiting set and, when there are due items, carries them as (loop_id, state) pairs. TOP THREE TODAY (solo only, the DM brief only): `briefing.top_three.build_top_three` picks up to three in code — overdue then due-today commitments, off-track then at-risk goals (by area), commitments due later this week, then active initiatives stalest first — and renders them as a TOP THREE TODAY block the solo prompt turns into a 'Top three today' section right after the top call. When `runner.google_workspace_ready()` (gateway up and the Google Workspace server configured) and the principal has an email, ONE `google_workspace__get_events` call (asyncio.wait_for, 4 s) lists today's events (local midnight to midnight, sent as UTC) on the principal's calendar — `calendar_id` = their address, read as the Executive's account (`user_google_email` = EXEC_EMAIL_ADDRESS), or `primary` when that IS the principal's address; `parse_events` reads workspace-mcp's text listing or JSON and treats an error, a timeout or an unknown shape as NO calendar (never as a free day). With a calendar each item gets its own free block (an hour, never under 30 min) inside CALENDAR_BUSINESS_HOURS_START/_END, not before now, all-day events not blocking, plus a TODAY'S CALENDAR block (titles quoted as data); without one there are no slots and no calendar block. The calendar is read only when something was picked, and nothing here can fail the brief. The fingerprint adds the items' keys (`loop:N:state`, `goal:N:status`, `project:N` — no dates, no slot times) and only a coarse `calendar_hash` (busy blocks rounded to 15 min + the all-day count, no titles, no dates), each only when present, so an unchanged day still suppresses and a solo install with nothing picked keeps its old fingerprint. A day whose calendar read times out after one that did not (or the reverse) changes the fingerprint once — accepted. No slots on a non-business day (`calendar_tools.is_business_day`, shared with the booking caps), though the day's events are still listed. Only a date-only event is all day; a zero-length timed event is listed but blocks nothing; an event whose times cannot be read is dropped from the listing, the busy time and the all-day count, and a reply that lists events but none readable counts as no calendar (never a free day). Logs carry only the reply's length or the exception type — never reply text."
+ - "morning_brief — Shift 3 recurring workflow. Fires once per day from the scheduler (default 08:00 in the user's zone; an explicit PRINCIPAL_BRIEF_MORNING_TIME env var is read as UTC). Targets the principal: utility_fast model renders a ≤200-word Markdown briefing. CHANGE-AWARE: the window is 'since the last DELIVERED morning brief' (`briefing.brief_state.since_for`, 24 h on a cold store, clamped to 7 d); activity comes from `_build_activity(20, since=…)`; proposals (action category only) split into NEW SINCE LAST BRIEF (enumerated, with why_now / next move) vs a one-line CARRIED OVER count (with the likely-stale count); a REWRITTEN block lists carried items the review rewrote in the window (`brief_state.rewritten_since`: verdict `changed`, still open — reported under 'what changed', never as done); a HANDLED OVERNIGHT block lists the alert review's completed moves (`brief_state.handled_since`, `changed` excluded). Section order: top call → what changed → handled overnight → needs you (new only) → waiting on → at risk. A fingerprint of the inputs (`build_brief_fingerprint`, date-free) is compared to the last delivered one: unchanged ⇒ the artifact is the one-liner 'Nothing new since yesterday's brief — N items still waiting on you.' and no model call (`PRINCIPAL_BRIEF_SUPPRESS_UNCHANGED`, bypass with `force_full=true` on a manual run). The workflow yields a `result` event `{brief_fingerprint, suppressed, since}`; only `_run_principal_brief` records the fingerprint, after a successful delivery (`brief_state.record_delivered`, stored in `briefing_narrative` under scope `brief:<kind>`). Delivery (`scheduler.runner._deliver_to_principal`, also used for the client-rotation digest): the principal's `preferred_channel` (slack / discord / telegram / email / any) maps to slack_dm / discord_dm / telegram / email and is tried first, then the other chat channels they have an id for in the order slack_dm → discord_dm → telegram. Email goes through the active MCP gateway when it runs the Google Workspace server (`runner.email_ready()`: another MCP server alone does not make email ready) (`google_workspace__send_gmail_message`, `user_google_email` = the Executive's own address, `to` = the principal's email, subject `<workflow title> — <local date>` in the user's zone, e.g. 'Morning Brief — Fri 25 Sep' (`_email_subject`; a UTC date put tomorrow's date on an evening digest west of UTC); body_format html, the Markdown rendered by `utils.markdown_email` (markdown-it-py: raw HTML off, so quoted outside text shows as text; images off, so opening the email loads nothing remote; javascript:/vbscript:/file:/data: links dropped); an in-band error counts as failed, `workflows.action_step.looks_like_error`). Email is tried first when the preference is `email`, and otherwise last, as the backup after every chat channel: delivery stops at the first channel that sends, so an owner linked by email at setup (`any`) with a working Slack still gets no email — only when every chat channel is missing or fails. Email is not a DM, so the per-Person outbound guard does not apply; the gateway's roster egress gate does. `_deliver_to_principal` returns a `PrincipalDelivery(ok, detail, reason, channel)`; reason is delivered | no_owner | no_channel | gateway_down | send_failed. `gateway_down` is email set up (the mail server in the MCP config, the principal has an address) but no active gateway: the Executive's fault, recorded with the supervisor's start failure (`mcp_gateway.gateway_problem`) instead of `no_channel`, which told the owner to connect what they had. A `send_failed` detail quotes each channel's own error (`email: invalid_grant …; slack_dm: channel_not_found`), stored with the outcome (`record_delivery_outcome(detail=…)`, JSON in the row's text, older bare-channel rows still read) and repeated by the notice and the Daily brief light (`brief_state.describe_problem`, whose fix says to reconnect when the detail shows a dead grant). Before planning, `_deliver_to_principal` / `deliver_to_person` run the lazy re-check `runner.ensure_email_ready` → `mcp_gateway.ensure_active_gateway`: with the gateway down and no attempt running, the supervisor (`orchestrator.gateway_boot.GatewaySupervisor`) tries a start now rather than waiting for its next backoff retry, so a gateway that failed at boot can still carry this brief; `_execute_action` resolves the gateway the same way instead of keeping the None boot handed the scheduler. The order comes from `runner.delivery_order` via `runner.principal_delivery_plan()` — public, because the Briefing notice and the Setup status light use them too. When no channel can deliver (e.g. a web-only principal, or email-only with no gateway) the brief is still generated and stored as a run with its artifact, exactly as before; it is not delivered (audited `delivery_failed`), so the window and fingerprint do not advance, and the next occurrence is chained. Every run's outcome is recorded (`brief_state.record_delivery_outcome`, scope `brief_delivery:<kind>`: the reason, and the channel that sent it — a channel name, never an address), including `not_written` when the workflow raised, emitted an error or produced no artifact (then nothing is sent), and `send_failed` when delivery itself raised. `last_delivery_outcome()` returns the latest of the two briefs and the (solo) weekly review (`brief_state.DELIVERY_KINDS`; `BRIEF_KINDS` stays the two daily briefs, whose send times the Setup page lists). `current_problem(outcome, has_owner, can_deliver)` says what still keeps it from the owner: send_failed and not_written stay reported until the next brief records a new outcome; having nowhere to send it is judged from now, so a fix clears it and a partial fix reports what is left (an owner added but still no channel reads no_channel). `GET /today/brief-delivery` (the Briefing's notice, owner only, null while the scheduler is off) and the Setup status 'Daily brief' light read it; brief names come from `scheduler.action_phrasing.KIND_LABEL` (`brief_state.brief_name`). SOLO: with effective_workspace_mode solo it uses STANDALONE_BRIEF_SOLO_SYSTEM (top call → what changed → handled overnight → needs you → due this week → goals at risk, named by area; no waiting-on or department sections) over the solo context render, which adds today_data['due_soon'] (open_loops.principal_due_soon: the principal's open loops overdue or due within 7 days) as a DUE THIS WEEK block, and the fingerprint carries the mode, drops the people-awaiting set and, when there are due items, carries them as (loop_id, state) pairs. TOP THREE TODAY (solo only, the DM brief only): `briefing.top_three.build_top_three` picks up to three in code — overdue then due-today commitments, off-track then at-risk goals (by area), commitments due later this week, then active initiatives stalest first — and renders them as a TOP THREE TODAY block the solo prompt turns into a 'Top three today' section right after the top call. When `runner.google_workspace_ready()` (gateway up and the Google Workspace server configured) and the principal has an email, ONE `google_workspace__get_events` call (asyncio.wait_for, 4 s) lists today's events (local midnight to midnight, sent as UTC) on the principal's calendar — `calendar_id` = their address, read as the Executive's account (`user_google_email` = EXEC_EMAIL_ADDRESS), or `primary` when that IS the principal's address; `parse_events` reads workspace-mcp's text listing or JSON and treats an error, a timeout or an unknown shape as NO calendar (never as a free day). With a calendar each item gets its own free block (an hour, never under 30 min) inside CALENDAR_BUSINESS_HOURS_START/_END, not before now, all-day events not blocking, plus a TODAY'S CALENDAR block (titles quoted as data); without one there are no slots and no calendar block. The calendar is read only when something was picked, and nothing here can fail the brief. The fingerprint adds the items' keys (`loop:N:state`, `goal:N:status`, `project:N` — no dates, no slot times) and only a coarse `calendar_hash` (busy blocks rounded to 15 min + the all-day count, no titles, no dates), each only when present, so an unchanged day still suppresses and a solo install with nothing picked keeps its old fingerprint. A day whose calendar read times out after one that did not (or the reverse) changes the fingerprint once — accepted. No slots on a non-business day (`calendar_tools.is_business_day`, shared with the booking caps), though the day's events are still listed. Only a date-only event is all day; a zero-length timed event is listed but blocks nothing; an event whose times cannot be read is dropped from the listing, the busy time and the all-day count, and a reply that lists events but none readable counts as no calendar (never a free day). Logs carry only the reply's length or the exception type — never reply text."
- "morning_brief (live world, since the principal-brief rework) — besides the board it reads `live_signals.gather_live_signals(since)`: inbound, stuck, the principal's chats, and today's calendar read fresh in BOTH modes (`refresh_calendar(max_age=0)`) unless the solo top three already rendered TODAY'S CALENDAR. It carries the latest executive_reflection run's 'Flagged for the brief' bullets finished inside the window (`brief_state.reflection_flags_since`, via `persistence.get_run` since list_runs omits the artifact) and drops rhythm runs from its activity (`_build_activity(exclude_workflows=RHYTHM_WORKFLOWS)`): their dated titles moved the fingerprint daily so suppression never fired. Team section order: top call → today → what changed (inbound first) → handled overnight → needs you → waiting on → at risk (the slipping goal or the department left out). Period is the local date. PRIVACY: private rows (the principal's contacts' alerts via `_build_today(include_private=True)`, private audit rows, drafts, chats, the calendar) are read only when `morning_brief.PRINCIPAL_DELIVERY` is set (the scheduler sets it around `_run_principal_brief`) or on the principal's own verified chat turn in a conversation only they can read (`is_principal_on_verified_surface` AND `delegation.settings.private_conversation`: web chat, Slack/Discord DM, private Telegram — never a shared channel, where the reply is posted for everyone). A run that used one reports `private_to_principal` on its result event; the scheduler, `run_workflow` and `POST /workflows/{name}/runs` then store `persistence.PRIVATE_RUN_ARTIFACT` via `stored_artifact` (private_used compares every key and count of the live read with the shared one), because /workflows/runs is readable by every signed-in user. The fingerprint adds `live_keys` (time-free: sender|subject|count, stuck lines, drafts count, conversation titles, calendar shape) and the reflection flags only when non-empty, so a caller passing neither keeps its old fingerprint. INFO log 'morning_brief: context since=… inbound=… stuck=… private_used=… suppressed=…'."
- "end_of_day_digest — Shift 3 recurring workflow. Fires once per day from the scheduler (default 18:00 in the user's zone; an explicit PRINCIPAL_BRIEF_EOD_TIME is read as UTC). Same shape as morning_brief but framed as a recap since the last DELIVERED digest (`brief_state.since_for`, 24 h on a cold store): what OE did today (activity since), alerts it handled today (completed moves only; rewritten-but-open items render as a REWRITTEN block under still pending), what's still pending (NEW SINCE LAST BRIEF, action category only, carried-over as one line), what's at risk for tomorrow, one optional 'sleep on this' question. Same fingerprint / one-liner suppression and `force_full` as morning_brief, under scope `brief:principal_brief_eod`. SOLO: _EOD_DIGEST_SOLO_SYSTEM (what I did today → open decisions → goals at risk tomorrow by area → sleep on this) over a context with GOALS AT RISK BY AREA and no people-waiting block."
- "weekly_review — the principal's weekly look back and ahead (background; inputs all defaulted; playbook `weekly-review`). Steps: goals (every area with goals graded concurrently by its own specialist with the check-in's verdict contract `_parse_verdicts` and write-back `department_check_in.persist_goal_verdicts` → `record_goal_review`, one `goal_status_review` audit row per area with actor `weekly_review`; no goals → skipped, no specialist → listed ungraded, specialist failure → shown as last recorded) → commitments (`open_loops.principal_due_soon`, overdue or due within 7 days) → projects (active initiatives with no update for 7+ days) → decisions (`episodic.decisions_since`, the last 7 days) → revisit (`episodic.decisions_awaiting_outcome`: at most 3 decisions older than 30 days with an empty or whitespace outcome, newest first, shown as [decision N]) → assemble. Every section always renders, with a one-line note when empty. Next week's top 3 comes from one fast-model call (constant `WEEKLY_TOP_THREE_SYSTEM`; the playbook and the review ride in the user turn) trimmed to at most three list items, or — on failure or an empty reply — the ranked pick `briefing.top_three` uses. Yields a `result` event (areas graded/ungraded, due count, quiet project ids, the week's and the revisit decision ids). Role-neutral wording; says area in solo and department in team. Scheduled weekly in solo only (`principal_weekly_review`, see the scheduler key). The artifact starts with `TITLE_PREFIX` + the period and ends with the `TOP_THREE_HEADING` section; `summarize_review(artifact)` reads those back as plain text ({period, top_three, excerpt}) for the solo Briefing's 'This week's review' card (GET /today/weekly-review, see the today key). Evals: `workflow_weekly_review_001`."
diff --git a/packages/core/openexecutive/architecture/prebuilt/api.json b/packages/core/openexecutive/architecture/prebuilt/api.json
index 10fff6a8..1c8e433b 100644
--- a/packages/core/openexecutive/architecture/prebuilt/api.json
+++ b/packages/core/openexecutive/architecture/prebuilt/api.json
@@ -1,7 +1,7 @@
{
"section_id": "api",
"title": "API Reference",
- "markdown": "The FastAPI surface lives in `openexecutive.api.main`, which mounts one router per topic. A shared-secret middleware gates every request via an `x-api-key` header, except `/health` and the `/webhook/*` callbacks (which carry their own verification). With local login (`OE_LOCAL_LOGIN=1`, which only `make dev` sets, and only while neither Google nor SSO sign-in is set up) a second middleware answers 403 to any request whose raw `Host` is not `localhost`, `127.0.0.1` or `[::1]` (except a webhook that verifies its caller: Google Chat and Slack always, Telegram only with a `TELEGRAM_WEBHOOK_SECRET` Telegram can send), and to any write whose `Sec-Fetch-Site` is present and not `same-origin`/`none`. The UI signs that owner in with no password and this API usually has no secret, so without it a web page in the owner's browser could drive the API as the principal — by DNS-rebinding its own hostname to 127.0.0.1, or by posting a plain form from another site or localhost port. CORS is restricted to 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\n**Who is calling** is read in one place, `api/caller.py`, which answers with a `Caller` kind and email; a test fails on any other read of an `x-caller-*` header. By default (`open`) it is the `x-caller-email` the UI proxy stamps from the sign-in, trusted because whoever holds the shared secret is trusted as the proxy, and a request with none runs as the principal. **Signed callers** remove that trust. With `CALLER_ASSERTION_PUBLIC_KEYS` set, the proxy signs every request with an Ed25519 key only the UI holds, and a third middleware checks the `x-caller-assertion` header:\n\n- **What it covers.** It is good for one method, the exact path and query, at most 120 seconds, and one use. The API keeps used ids in memory.\n- **What it names.** A `user`, by email, or the `operator`: local login, which runs as the principal.\n- **No caller header at all** is a `service`, for scripts or MCP clients holding only the secret. It is never the principal, not even on an install with no owner yet, so it can't save a first setup.\n- **Anything else is a 401.** That includes an `x-caller-email` without an assertion (`caller_assertion_required`), and a bad, expired, reused or mismatched assertion (`caller_assertion_invalid`).\n\nPublic keys that can't be read stop the boot, rather than fall back to trusting the header. `scripts/make-caller-keys.py` makes the pair, and `scripts/mint-caller-assertion.py` signs one request for curl. The API holds only public keys. Setup's API-protection check warns while a shared secret is set without them.\n\nEndpoints grouped by router:\n\n| Router | Key endpoints | Purpose |\n|---|---|---|\n| `chat` | `POST /chat`, `POST /chat/stop`, `POST /chat/add`, `POST /chat/background` | SSE stream of a live Executive turn. `POST /chat/background` starts a new chat that the server answers to the end with nobody connected (a phone approving a card, then closing the app): it answers `202` with the new `session_id` once the same caller, access and quota checks as `/chat` pass, the turn saves itself as a `/chat` turn does, and one caller may have three running at once (`429` beyond that). `POST /chat/add` hands the running turn a message the person typed while it works; the turn takes it at its next step and the stream names it in a `message_added` event, and a second `POST /chat` on the same conversation waits for the first to finish. The request body optionally carries `page_context` (route, page title, guide section id, and a form descriptor with current values) — sent only by the Ask OE side panel so the Executive can explain the current page or propose form values. When the Executive calls its `propose_form_values` tool, the stream emits a `form_patch` event (`{type, form_id, fields, rationale, iteration}`) that the panel applies into the on-screen form as highlighted suggestions; the user reviews and saves through the form's normal submit path. Each round of tool calls also emits an `activity` event (`{type, label, tool, iteration}`) naming what is running — progress only, forwarded verbatim and never persisted with the message, unlike an `action_taken` chip. A `session_id` in the body must be a chat the caller may use (the same ownership rule as `sessions`). If it isn't, the turn runs in a fresh chat instead, so nothing is written into someone else's session and the reply looks the same as for an unknown id. An unknown namespaced id (`slack:…`, `telegram:…` and so on) is ignored and a fresh chat is started, because those ids belong to the channel adapters and claiming one first would make the caller its owner. The client mints a `client_turn_id` and sends it with the turn; `POST /chat/stop` takes that id and halts the turn mid-flight, so the button is live from the moment Send is pressed rather than only once the first SSE byte arrives. A stopped turn emits a `stopped` event and then the usual `done` over the same still-open stream — never an `error` — and whatever streamed so far is persisted and flagged. The endpoint returns 404 both for an unknown id and for another caller's turn, so it cannot be used to probe which turns are live. An optional `memory_text` (1–2000 chars) is what peer memory records as the caller's words instead of `message` — the briefing handoffs send it because their seed quotes the Executive's own card; `POST /chat/upload` derives it from the typed text and filenames. Since it never reaches the transcript, the `chat_turn` audit row keeps it beside `message`. After the reply — a stopped or timed-out one too, before the `stopped` / `error` / `done` frames — a turn that looked at anything sends one `sources` event, `{type, session_id, sources: [{kind, title, url}], unavailable: [area]}`: `kind` is `company`, `knowledge`, `notion`, `research`, `document` or `web`, `url` is only ever an http(s) link or, for an earlier document, `/artifacts/<id>`, at most 12 sources (6 from the web, pages the reply cites first), and `unavailable` names parts of the analysis (\"finance\") whose specialist failed or said nothing every time it was asked. It is persisted with the reply as `chat_messages.sources`. A request that carries `x-caller-email` marks its turn signed in (`Session.web_caller_signed_in`), which Act as me needs on a deployment without local login. |\n| `sessions` | `GET /sessions`, `GET /sessions/{id}`, `GET /sessions/{id}/messages`, `DELETE /sessions/{id}`, `POST /sessions/{id}/messages/{message_id}/feedback`, `GET /sessions/{id}/followup` | List, read and delete saved chat sessions (assistant messages carry their row `id` and any `feedback`). The list is scoped to the caller, and each chat carries `preview`: its last message as one plain line, Markdown marks stripped and cut at a word near 120 characters, with `You:` before the person's own words. With `?q=` it is a search: the caller's own chats whose title or message text contains the words (case-insensitive, `LIKE` with wildcards escaped), each with `match_count` (messages that contain them; 0 for a title-only match) and `snippet` (the newest matching message, around the match, prefixed `You:` or `Executive:`). Scoped exactly like the list, so nobody else's conversation can match. The Chats page searches this way and opens a result with `?find=`, so the chat starts on that message and steps through the others. A chat-app conversation started with /new is left off the list until its first turn (`memory.conversations`). Every per-session route checks ownership, because session ids are guessable (`slack:dm:<user id>`, `telegram:<chat id>`): only the session's owner or the principal gets through, and a legacy row with no owner is the principal's alone. A teammate's own chat (a web chat, a DM, a private Telegram chat; not a channel or group conversation, `chat._shared_space`) is theirs alone, the principal included, as their mail with the Executive is. Anyone else gets the same 404 as for an unknown id, so the routes can't be used to find out which chats exist. The one other way in is having started the chat in this process (matched by Person id or verified email, so it survives the caller being added to the roster), which is how a caller the roster can't resolve keeps using their own chat. That record is in memory, so after a restart such an ownerless chat is refused for reads. The principal can continue someone else's ownerless chat without becoming its owner. Deleting a session also drops its in-memory copy, so a later turn naming that id starts fresh. The feedback route records 👍/👎 (`{\"feedback\": \"up\"|\"down\"|null}`) on one assistant reply; only the session's own caller or the principal may rate it. The rater is stored (`feedback_by_person_id`), and a 👎 on a reply to the rater's own message triggers a working-style pass for them (paced; see attunement). The chat stream's `done` event carries `message_id` for the persisted reply. The followup route returns `{\"suggestion\": string|null}` — one suggested next user message, written by the utility-fast model from the last few turns, that the chat composer shows as its greyed placeholder (Tab / → or the inline chip fills it in without sending). It is null unless the session ends on a persisted assistant reply, and null (uncached) when the model fails. Same ownership check as feedback; successful suggestions are cached in-process per (session, reply id). Messages from `GET /sessions/{id}/messages` carry each assistant reply's saved `sources` (the same shape as the chat stream's `sources` event, without `type`), so a reloaded chat shows them again. |\n| `today` | `GET /today`, `GET /today/activity`, `GET /today/activity/daily`, `GET /today/brief-delivery`, `GET /today/top-three`, `GET /today/weekly-review` | Morning-brief aggregation, recent-action rail, and Pulse heartbeat heatmap (per-day activity counts). `GET /today` carries the viewer's cached \"What's going on\" `narrative` with `narrative_generated_at` (when it was written) and `narrative_stale` (a fresher one is being written — the page re-polls; see Today). A proposal backed by a roster request carries `roster_request` (the new sender's server-derived details and held-message previews; the principal's only) and is answered through the `people` routes below. `brief-delivery` returns the latest morning brief or end-of-day digest that didn't reach the owner, as `{brief, at, problem, fix, readable}` in plain language (`readable` is false when it couldn't be written, so there is nothing to read), or null — null while briefs go out, once the cause is fixed, while the scheduler is off, and for anyone but the owner (`chat._caller_is_principal_or_unclaimed`); it carries no address or channel id. `top-three` and `weekly-review` feed the solo Briefing's own cards and answer only in solo mode and only to the principal (`workflows._caller_is_the_principal`: a principal match or no caller header, never an unclaimed roster); anyone else, and team mode, get null. `top-three` returns `{items: [{key, kind, text, why, slot}]}` — the morning brief's top three from the same code (`build_top_three(principal_due_soon())`), `slot` a free block like `10:00–11:00`, `\"\"` when none is left, null when no calendar was read — and is kept off `GET /today` because its calendar read may take up to 4 s. `weekly-review` returns the latest completed `weekly_review` run as `{run_id, completed_at, period, top_three, excerpt}` (next week's top three as plain text; `excerpt` when that list is empty), or null when none has completed. |\n| `people` | `GET\\|POST\\|PATCH /people`, `POST /people/{id}/archive`, `GET /people/requests`, `GET /people/requests/{id}`, `POST /people/requests/{id}/approve`, `POST /people/requests/{id}/decline`, `GET\\|POST /people/{id}/open-loops`, `POST /open-loops/{loop_id}/close`, `GET /people/{id}/outreach`, `GET\\|PUT\\|DELETE /people/{id}/attunement` | Roster CRUD and scope lookups. Every `Person` carries `kind` (`team` / `contact`). `GET /people` lists team members only unless `?include_contacts=true` (the People page asks for both; the department-head and workflow pickers keep the default); `POST` / `PATCH` accept `kind`, and a principal contact is a 422 either way. They also take `email_aliases` (other addresses the person writes from, at most 10; on `PATCH` the full list replaces the current one, omitted leaves it): an alias matches their mail and may be emailed but never signs in; a malformed one is a 422, and an alias — or a new primary `email` — that is already someone else's address or alias is a 409. Every `POST` / `PATCH` then closes any pending roster request whose sender now matches someone and replays its held messages. Adding, editing and archiving (`POST`, `PATCH`, `/archive`) are the principal's only, or anyone's while no one is principal yet so a first setup can add its owner (`chat._caller_is_principal_or_unclaimed`, the check behind `PUT /workspace`; a request with no `x-caller-email`, such as the CLI or local login, counts as the principal). Anyone else, a person editing their own row included, gets 403 before the person lookup, so it can't probe which ids exist. Contacts are private to the principal (`caller_is_principal`: the signed-in email is the principal's, or no `x-caller-email`; stricter than the owner rule above, so while no one is principal nobody is): for anyone else `include_contacts` is ignored, a contact's id is a 404 on `GET /people/{id}` and open-loops (exactly as for a missing id; `PATCH` and archive are already a 403 for them), and creating a contact or turning someone into one is a 403, even on a first setup with no principal yet. `GET /people/me` returns `{person_id, is_principal}` so the UI offers contacts to the principal only. `GET /people/by-scope/{token}` never returns a contact. Archiving a person closes their open loops. The open-loop routes list what a person owes (soonest due first) and close one (`reason`: done / not_needed / cancelled) — both the principal's or the owner's only (403 otherwise, via `people.store.is_principal_or_self`). `POST /people/{id}/open-loops` `{task, due_date?}` assigns that person a task (201 with the loop; `due_date` is a local date, due 17:00 in the user's timezone, clamped to 60 days, default 2 days): any active team member may assign anyone on the team, 403 for anyone else; 409 for an archived person, a contact (as seen by the principal), a person at the open-loop cap, a duplicate or open loops turned off; 422 for an empty task. Nobody is messaged at assignment — the owner is chased once it is due. `/outreach` returns, per kind of proactive outreach over 30 days, `sent` / `replied` / `acted` / `ignored` / `pending` (voided DMs are excluded) — same access rule, checked before the person lookup so it can't probe which ids exist. `/attunement` reads, replaces (`rules`: up to 4 strings, or omitted to only set `locked`) or resets the person's working-style rules — same access rule, 404 for an archived person; `PUT` rejects a rule that is not purely about style with 422. Archiving a person also drops their working style and frees their aliases. The **roster-request** routes (declared before `/people/{person_id}`) are the principal's alone (`caller_is_principal`; anyone else gets 404, as for a missing id): `GET /people/requests?status=pending|approved|linked|declined|expired|superseded|all` lists up to 100 (`id`, `channel`, `channel_ref`, sanitised `display_name`, `profile_email`, `on_company_domain`, `suggested_kind`, `suggested_person_id` / `_name`, `status`, `resolved_person_id` / `_kind`, `message_count`, timestamps, `ack_sent`, and `previews` of the held messages while pending — shown to the principal, never to a model); `approve` takes either `link_person_id` (+ `replace_channel_id`) or `full_name` + `kind` (no default: 422 without both) + optional `role`; `decline` takes no body. An answered request is a 409, a chat id or address already on someone else is a 409; the held messages are replayed (or dropped) in the background. |\n| `departments` | `GET\\|POST\\|PATCH\\|DELETE /departments`, `.../goals` | Department state and per-department goals. `PATCH /departments/{slug}` also takes `watched_entities` (≤50 names, `[]` clears) — the entities the research watch policy may add watches for and route to this department. A `cadences` spec that does not parse is rejected with a 422 (empty means no cadence). A new `head_person_id` must be a team member: an unknown id and one of the principal's contacts get the same name-free 422 (`person_id N is not on the team.`), so the route — open to any signed-in user — never reveals that a contact exists; an unchanged head is not re-checked. `POST .../goals` requires only `key_result`: a missing or blank `period_value` is filled with the current period for `period_type` in the user's zone (the same label `create_goal` uses), and `target` defaults to empty. `PATCH .../goals/{id}` rejects a blank `key_result` or `period_value` with a 422; `target` may be cleared. |\n| `agents` | `GET /agents`, `GET /agents/models`, `GET /agents/models/options`, `GET /agents/presets`, `POST /agents/presets/{id}`, `PATCH /agents/{id}`, `POST /agents/{id}/test` | Specialist metadata and Council overrides. `/agents/models` is the flat model allowlist the PATCH validator uses; `/agents/models/options` returns the same ids in the same order, each tagged with `provider`, `provider_label`, `route` (`direct` / `openrouter` / `local`) and a display `label`, for the Council's Provider → Model picker. `AgentDetail` carries `instructions` (additional instructions, appended after `prompt`, which stays the built-in prompt or its replacement); `PATCH` and `/test` accept `instructions` (max 4,000 chars, blank clears it). `GET /agents/presets` lists the Fast, Balanced and Thorough quality presets (each with `available` and the resolved `model` for this install) plus `active` (null when the council is Custom), `base` and `custom_agents`; `POST /agents/presets/{id}` applies one by writing per-agent model and deep-reasoning overrides and returns the same shape (404 unknown preset, 409 when the install allows none of its models). Each `AgentMeta` carries `visibility` (`core` or `internal`) so the Council's simple view can list core agents first. |\n| `personas` | `GET\\|PUT\\|POST\\|DELETE /personas` | Executive persona definitions. |\n| `alerts` | `POST /alerts/{id}/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`, `supersedes_id` and, for an extension's kind of document, `collection` / `collection_label` on every summary (`orchestrator.extensions`; archive, restore and delete tell the collection first and answer 502 if it refuses). `download` renders the file (Word/Excel built at request time from the stored text; any Markdown artifact, workflow output included, can export `?as=docx`) and is always an attachment with `nosniff` and a sandbox CSP. Every route answers for the signed-in caller (`artifact_records.Viewer`): a drafted artifact is its owner's alone (`alerts.owner_person_id`, the person whose conversation published it; none = the principal's), a workflow output follows its run (`persistence.run_visible_to`), and anything the caller may not see is a 404 like a missing id, the principal included. `POST /alerts/{id}/ack` and `/reopen` answer 404 for someone else's drafted artifact the same way. |\n| `decisions` | `GET /decisions`, `POST /decisions/{id}/{approve,reject,cancel}`, `GET`/`PUT /decisions/classes/meeting_scheduling`, `GET /audit/reliability` | Approval-gated decision instances (e.g. calendar bookings). What approve/reject/cancel do is per class (`DECISION_CLASSES`, one `DecisionClassSpec` each; meeting booking books on approve and deletes on cancel; `delegation_reply`, an inbox reply card, is its approver's alone (`approver_only`) — hidden from everyone else, the principal included when it is a team member's — sends its Gmail draft on approve and, after a reject, deletes the draft unless it was edited), and an instance of a class with no spec gets 409 instead of being carried out as another. Only the principal, or the person the decision went to for approval (`approver_person_id`), may approve, reject or cancel it. Anyone else gets 403, and a decision nobody was asked about, or one private to the principal, is the principal's alone. The resolver is recorded as `resolver_person_id`, and a reject that loses the race to another answer is a 409. `GET /audit/reliability` is the principal's alone (403 otherwise), because it counts private decisions too. A proposed booking is surfaced on the briefing as a companion alert; approve/reject/cancel here also clear that alert. An approval whose caller resolves to the principal runs the booking inside `grant_contact_egress()`, so a meeting the principal proposed with a contact can be created. Such a booking's payload is marked `private`: it is proposed to the principal, left out of anyone else's `GET /decisions`, and a 404 for them on `GET /decisions/{id}` and every action route. Reviewed in the briefing — there is no separate proposals page. The class routes read and set how meetings are handled: both return `{decision_class: \"meeting_scheduling\", mode: \"propose\" \\| \"auto_execute\"}` (default `propose`); the `PUT` body is `{mode}`, principal-only (403 otherwise, open before a principal exists — but then only `propose` can be set: `auto_execute` is a 409 until a non-archived principal is on the roster), 422 on any other mode, and a change writes a `decision_class_mode_changed` audit row. In solo mode the class mode decides a booking, and `auto_execute` applies only to a turn the principal started on a verified surface — any other turn gets a proposal. |\n| `delegation` | `GET`/`PUT /delegation`, `GET`/`PUT`/`DELETE /delegation/voice`, `POST /delegation/voice/learn`, `POST /delegation/voice/describe`, `POST /delegation/voice/signature`, `PUT /delegation/inbox`, `POST /delegation/inbox/check`, `GET /delegation/replies`, `PUT /delegation/replies/{id}/text`, `GET /delegation/actions`, `PUT /delegation/handle-it`, `PUT /delegation/training`, `DELETE /delegation/learned/{id}`, `GET /delegation/handled`, `PUT /delegation/team` | Act as me — the **caller's own** delegation only; nobody sets it for anyone else. It answers the principal, and a team member once the owner lets them; anyone else gets 403 `not_available_yet`. `GET /delegation` returns `{enabled, gmail: {status, message, email, connect_command, outlook_connect_command, provider}, inbox: {enabled, status, message, watch_since, last_poll_at, checking}, handle_it: {enabled, mode, available, sent_today, lead, lead_available}, training: {replies, follow_ups, actions, drafts, learned}, team}`, where `team` is the owner's switch for the principal while `DELEGATION_TEAM_MEMBERS` allows it — `{enabled, members: [{person_id, name, enabled, inbox, drafts_30d, sent_30d}]}`, counts only — and `null` otherwise. `PUT /delegation/handle-it` takes `{enabled?, mode?}` (`mode` is `careful`, `balanced` or `bold`; anything else is a 422 `bad_mode`) from a caller the API knows is that person — 403 `not_yours`, 409 `caller_signing_required` with only the shared secret — and turning it on needs Act as me and Draft replies to my inbox on (409 `act_as_me_off` / `inbox_off`); `GET /delegation/handled` returns `{replies: [{decision_id, sent_at, to_name, to_email, subject, body, open_questions, gmail_link, source}]}`, the caller's replies and follow-ups (`source` `follow_up`) sent on its own in the last 7 days; a card on `GET /delegation/replies` carries `source` the same way, `can_allow` while Replies (Follow-ups, on a follow-up) is in training, and `learns_style` while Drafts is. `PUT /delegation/training` takes `{replies?, follow_ups?, actions?, drafts?}` (any other field is a 422) and returns the `GET /delegation` shape; putting Replies or Follow-ups in, or Suggested actions out, needs no signed sign-in, anything else does (409 `caller_signing_required`), and putting Replies or Follow-ups in turns Take the lead as you off (`PUT /delegation/take-the-lead` on answers 409 `in_training` while they are). `training.learned` is `[{id, label, setting, example, uses, created_at}]`, what the caller allowed or kept in training (`setting` `replies`, `follow_ups`, `actions` or `drafts`; the kept example, or \"\"); `DELETE /delegation/learned/{id}` removes one of the caller's own (404 for anyone else's). `PUT /delegation/team` takes `{enabled}` from the principal alone (403 `principal_only`; 409 `not_available` when the install doesn't allow it). The Gmail `status` is `connected`, `not_configured`, `needs_reconnect`, `mismatch`, `no_email`, `shared_mailbox` or `error`, checked live with Google on each call. `PUT` takes `{enabled}` (any other field is a 422); turning it on needs the caller's own Gmail connected, otherwise a 409 whose code says why (`gmail_not_connected`, `gmail_needs_reconnect`, `gmail_mismatch`, `no_email`, `shared_mailbox`, `gmail_error`). The voice routes show, learn (from the caller's sent mail, one pass at a time — a 409 `in_progress`, `locked`, `too_soon`, `not_enough_mail`, `no_profile` or `changed` when it was locked or edited while learning, or a Gmail code), write it from the caller's own description (`POST /delegation/voice/describe` with `{description}`: one model call applies their words to the profile they have and returns it with a short `sample_reply`, saving nothing, so they review it and save it with `PUT`; a 409 `empty`, `too_long`, `in_progress`, `too_many` past 10 an hour or `no_profile`; no mailbox needed), edit and lock, and reset \"How I write\": a typed field that fails validation is a 422 `invalid_voice` listing each `rejected` field, and `clear_exemplars` / `clear_signature` drop those. `POST /delegation/voice/signature` reads the signature from the caller's Gmail settings again and changes nothing else (a locked profile stays locked), with the same Gmail codes as learning: a 409 when their mailbox isn't connected, it refuses the sign-in or the check itself fails (`gmail_error`), and a 502 `gmail_error` when reading the signature fails. On an Outlook mailbox it is a 409 `signature_unavailable`, since Outlook gives apps no signature to read, and the stored one is left alone. A caller `can_delegate` refuses — anyone but the principal, for now — gets 403 `not_available_yet`, which hides the Settings card. A request with no `x-caller-email` is a 403 `sign_in_required` unless the API runs under local login — a header-less call is not a sign-in (the caller is read through `api/caller.py`, as on every principal-only route). `PUT /delegation/inbox` takes `{enabled}` and turns **Draft replies to my inbox** on or off, returning the same shape as `GET /delegation`: on needs Act as me on (409 `act_as_me_off`) and the mailbox connected (the Gmail codes above, which keep their names for an Outlook mailbox too), and turning Act as me off turns it off too. `POST /delegation/inbox/check` starts a scan now in the background and answers 202 with the `inbox` state (409 `inbox_off` or `in_progress`). `GET /delegation/replies` returns `{cards: [...]}`, the caller's open reply cards from the database alone (no Gmail call): the decision id, the sender's name, address, relation and whether it was verified, the subject, when it arrived, what they wrote, the draft's recipients, subject and body, `open_questions`, `flags` and a Gmail link built from a fixed prefix. **Send** is `POST /decisions/{id}/approve`: it sends the card's draft exactly as it is in Gmail, after checking again that the caller is its owner — which on a server needs signed callers (409 `caller_signing_required` otherwise) — that both switches are on (`inbox_off`), no client slot is active (`client_slot`), the Gmail is connected (the Gmail codes), the draft is still there and unanswered (`draft_gone`, `you_replied`) and its recipients are allowed (`no_recipients`, `too_many_recipients`, `executive_recipient`, `not_from_you`). Recipients that changed, or a newer message in the thread, answer 409 `{code: \"confirm\", message, reasons, recipients}`; approving again with `edits: {recipients: <the list shown>, thread_moved_on: true}` is the second yes. **Send + allow** adds `edits.allow: true`: 422 `cant_allow` unless Replies (Follow-ups, on a follow-up card) is in training, 409 `learned_full` when their list is full, both before anything is sent; `edits.example: true` keeps a draft edited in the mailbox as how they write to that person while Drafts is in training. A draft edited in Gmail between those checks and the send is not sent (`draft_changed`). A double tap sends once (`already_handled`); Gmail refusing answers 429 `rate_limited` or 502 `gmail_error` with nothing sent, and a send Gmail didn't confirm answers 502 `send_unconfirmed` and is settled by the next inbox scan. Dismiss is `POST /decisions/{id}/reject`. `GET /delegation/actions` returns `{cards: [...]}`, the caller's own approval cards (`delegation_actions`): the decision id, when it was made, a one-line `why`, and each action's `index`, `kind` (`invite`, `message`, `add_contact`), `summary` and `text` (a message as it will be sent, or a meeting's description). **Approve** is `POST /decisions/{id}/approve` with `edits: {only: [indexes]}` (and `allow: true` for Approve + allow while Suggested actions is in training: 422 `cant_allow` otherwise or when nothing on it can be allowed, 409 `learned_full`; a card carries `can_allow`); it needs the card's own person signed in (403 `not_yours`, 409 `caller_signing_required`), Act as me on (409 `act_as_me_off`) and a card under a week old (409 `expired`), runs once (409 `already_handled`), and returns the decision with `final_payload_json.results`: per action `done`, `waiting` (sent to whoever approves meetings), `failed` with why, or `skipped`. Every change writes a private audit row. |\n| `history` | `GET /memories/history` (`?q=`), `PUT /memories/history/settings`, `PATCH`/`DELETE /memories/history/{id}`, `POST /memories/history/{id}/forget-conversation` | Always in the loop: the **caller's own** notes and switches only, resolved as for Act as me (a signed-in person on the roster, or the principal under local login; otherwise 403 `sign_in_required` / `not_on_roster`). `GET` returns `{notes, reply_notes, retention_days, effective_retention_days, company_retention_days, retention_choices, can_keep_notes, can_note_replies, can_set_company_retention, share_work_style, can_share_work_style}` (`can_keep_notes`: a team member on the People list may turn notes on; `can_note_replies`: they can use Act as me, so email replies are noted too; `share_work_style`: their own \"Share my work style with the team\" switch, `can_share_work_style`: a team member in a team workspace). `PUT` turns notes on only for someone who may keep them, and `share_work_style` on only for someone who may share it (403 `not_available` for either; turning either off always works), takes a person's retention only when shorter than the company's (422 `invalid_setting`), and the company retention only from the principal (403 `principal_only`). `PATCH` pins or corrects a note; `DELETE` forgets it; `forget-conversation` is \"Don't remember this\". A note that isn't the caller's is 404. Every change is audited privately to its person. |\n| `audit` | `GET /audit/logs`, `GET /audit/logs/{id}`, `GET /audit/sessions/{id}`, `GET /audit/usage`, `POST /audit/log` | Durable audit trail of side effects. `/audit/sessions/{id}` adds a per-session token cost summary; `/audit/usage` aggregates token usage and OpenRouter cost across all sessions (totals, by day, by model, and by source — the part of the system that made the calls — including server-side web-search counts), plus `scripts`: how many `run_script` scripts ran (and worked, and in workflows), the tool calls they made, their time, and `turns_avoided` — an upper bound on the model turns those calls would otherwise have needed (each call past a script's first) — and `python_jobs`: how many Python jobs ran (and worked, ran a kept Custom tool, took a chat attachment), their time, CPU, largest peak memory and bytes in and out, and the tokens and charge of the turns that ran one. The Token usage page shows it as a Scripts section. Rows private to the principal (`private_to_principal`: a turn about their private mail, or a row naming one of their contacts on their own turn) are theirs alone: for any other caller, resolved as for `/alerts`, the usage totals leave them out. Once a principal is on the roster, anyone else reads only their own rows (a teammate's own turns, their Act as me work) in the list, by id and in a session, and the principal reads those as actions only — what was done, when and in whose conversation, with the text, details and `full` left out, and no text search over them; any other row's id is a 404, and a session shows only the rows the caller reads. |\n| `architecture` | `GET /architecture/sections`, `.../sections/{id}` | This documentation surface. |\n| `guide` | `GET /guide/sections`, `.../sections/{id}` | Plain-language user-guide content surface — mirrors `architecture` (static, version-controlled files; no LLM on the serving path). |\n| `health` | `GET /health`, `GET /health/honcho` | Liveness probes. Only `/health` is unauthenticated; `/health/honcho` sits behind the gate like everything else, because the exemption is an exact-path set. `/health` also carries `google_tools_missing`, the pinned Google tools startup priming could not find: `[]` once it has checked and they are all there, a list of names when a workspace-mcp rename or the configured services and tool tier left one out, and `null` for no answer — Google Workspace is not configured, or the probe has not finished or it failed. Only `[]` asserts they are present, so a probe that died cannot read as healthy; Setup status says which of the three `null` means. |\n| `version` | `GET /version` | The running version, the latest release on GitHub and `update_available`, for Settings → About. The GitHub answer is cached 6h, only a semver `tag_name` is used and the release link is built from it; `UPDATE_CHECK_ENABLED=false` skips the call and still returns the running version. No in-app updater: upgrading is host-side (`docs/deployment.md#upgrading`). |\n| `setup_status` | `GET /setup/status` | Settings → Setup status: one light per part of the install — AI model, company setup, owner, the Executive's address, API protection, Gmail, your own mailbox (Act as me), Slack, Discord, Telegram, Google Chat, the scheduler, the daily brief (when and where it goes) and Honcho — as `{checked_at, checks: [{id, label, state, summary, fix, link, last_activity}]}`, where `state` is `ok`, `warn`, `error` or `off` (optional and not set up), `fix` says what to do in plain language, `link` is an in-app page that helps (`/people`, `/onboard`) and `last_activity` is the channel's latest `integration_inbound` audit time. It tests live, with at most one free read-only call per service, each bounded to 5 s: Anthropic `models.list` (so an organisation key missing `ANTHROPIC_WORKSPACE_ID` shows up), Slack `auth.test`, Telegram `getMe` and `getWebhookInfo`, Discord `users/@me` only while the bot is still connecting, and — once the owner's own Gmail credential exists — Google's token refresh and Gmail `users/me/profile`. It also reads the listeners the lifespan leaves on `app.state` (Slack's socket, the Discord bot and its task, the MCP gateway), the scheduler heartbeat and the pause switch. When `google_workspace` is configured, the lifespan also starts `MCPGateway.prime_pinned_tools()` in the background (held on `app.state.mcp_prime_task`, cancelled at shutdown), so the pinned Google tools named in the prompt are callable without a search. With `DRIVE_SYNC_ENABLED` the lifespan also bootstraps the `drive_sync_scan` heartbeat beside Notion's (see Scheduler); the Drive folder sync has no HTTP route, only the `openexecutive sync-drive` / `purge-drive` CLI. With `CONFLUENCE_SYNC_ENABLED` it bootstraps the `confluence_sync_scan` heartbeat the same way; that sync is run by hand with `openexecutive sync-confluence` / `purge-confluence`. Sample values copied from `.env.example` are named as such without being sent anywhere. No token reaches a response or a log line: probes report a status code, a service's short error code or an exception's class name. Requests within 5 s of a run get that run's answer and concurrent requests share one run (kept per app on `app.state`), so the button can't become a stream of calls to those services. Gated like every other route; the UI adds a sign-in light of its own, from its own settings. |\n| `documents` | `POST\\|GET\\|DELETE /documents`, `GET /documents/{filename}`, `GET /documents/sources`, `POST /documents/sources/{drive\\|onedrive\\|notion}/sync`, `GET /documents/{drive\\|onedrive\\|notion}`, `GET /documents/{drive\\|onedrive\\|notion}/{id}` | Upload, list, view extracted text, and delete indexed company docs. `GET /documents` rows carry `source: \"upload\"` and the `domain` the upload was indexed under. The connected-source routes back the knowledge page's single Company documents list: `/documents/sources` gives each source's `{id, label, enabled, syncing, last_run, last_error, interval_minutes, file_count}`; `/documents/drive`, `/documents/onedrive` and `/documents/notion` list synced files from the sync state (`{enabled, last_run, last_error, files: [{id, name, url, modified_at, synced_at, indexed}]}`); `/documents/{drive\\|onedrive\\|notion}/{id}` returns the stored text (a OneDrive id is `<drive id>:<item id>`) for an id on record (the path comes from the state, never the caller). They are read-only — a synced file is removed where it lives. `POST …/sync` starts one tick of the same sync the scheduler runs as a background task (202); 409 when the source is not connected or a tick is already running (every sync holds a per-process run lock, so a manual run never overlaps the heartbeat; the route also keeps its own started task per source and re-checks just before starting one, so two simultaneous requests start one tick, not two), 429 with `Retry-After` within 60 s of the last successful run or of the end of the last tick in this process, failed ones included, so a failing or slow source can't be re-run back-to-back. The page's text view never loads images from synced content (a remote image would be a read beacon for whoever edits the shared folder). Upload is keyed on the filename, so re-uploading a document replaces its chunks rather than duplicating them, and `DELETE` removes the rows as well as the file. `domain` must be one of the nine specialist domains (including `sales`) or `general`; anything else is a 400 rather than a 200 that indexes where no specialist can retrieve. A scanned PDF is converted (`knowledge.pdf_reader`) before it is indexed and in the text view, as are scanned PDFs in `POST /chat/upload` and the client / onboarding intake uploads. The upload is streamed to disk 1 MB at a time and refused with a 413 once it passes 50 MB, and the file is parsed in a short-lived child process (see the RAG section), so a large document does not stay in the API process's memory. A Word or Excel file that cannot be parsed, or whose parse runs out of time, is a 422 with a readable reason. When every parser is busy, the response is a 503 with `Retry-After`. |\n| `executive` | `GET /executive/status`, `POST /executive/pause`, `POST /executive/resume` | Operator pause switch for all autonomous work (scheduler, Gmail poller, workflow resumer); inbound chat and DMs stay live. Status returns `{paused, paused_at, paused_by, reason, held_actions, can_resume}` — `held_actions` counts due `pending` rows that fire on resume. `pause` takes an optional `reason` (≤200 chars) and is idempotent (re-pausing keeps the original start and reason); `paused_by` is the UI proxy's `x-caller-email`, else `api`. Behind the shared-secret middleware — not `SCHEDULED_ADMIN_TOKEN`, which the UI cannot send. Any caller may pause; `resume` is principal-only (`is_principal_or_self`, 403 otherwise; open while no principal is rostered; a header-less caller resolves to the principal as in `chat`), and status carries `can_resume` for the viewer so the UI hides Resume from everyone else. |\n| `workspace` | `GET /workspace`, `PUT /workspace` | Solo/team mode, the user's time zone and the principal's role (`memory.workspace_settings`). Both return `{mode, timezone, effective_timezone, role_kind, role_title, reports_to, remit, measured_on, company_domains, company_domains_custom}` — `timezone` is what the user set (null when unset), `effective_timezone` the zone in effect (`timezone`, else `USER_TIMEZONE`, else UTC), and each role field is null until set. `PUT` is a partial update: only the fields sent change; `mode` is `solo` or `team` (not null), `timezone` an IANA zone, or null/blank to clear it; `role_kind` is `owner`, `in_house`, `independent` or `other`, and `role_title` / `reports_to` / `remit` / `measured_on` are free text (trimmed, at most 120 / 120 / 500 / 300 characters), each null or blank to clear it; an unknown zone, a bad mode or role kind, an over-long role field or an unknown field is a 422 and changes nothing. Switching to solo cancels every pending department check-in, switching to team re-schedules them, and a new zone re-times the pending briefs and reflection; a role change has no side effects (the next turn reads it). `company_domains` is the company's own email domains (a teammate matches by local part on them — see Org): `GET` returns the ones in effect (the stored list, or the domain of the principal's primary address, with `company_domains_custom` false) only to the same caller the role is shown to, `[]` for anyone else; `PUT` takes a list (at most 10 plain domain names, never a free-mail provider's — 422 otherwise, the value never quoted) or null / `[]` to go back to deriving them, and a change is audited with the new list. Each change writes a `workspace_settings_changed` audit row (a role change adds `details.role_fields_changed`, the names of the fields that changed — never their text). The role is the principal's: `GET` returns it only to a caller `PUT` would accept and reads it as nulls for anyone else. `PUT` is the principal's alone (`is_principal_or_self`, 403 otherwise; a header-less caller resolves to the principal as in `chat`) and open while no principal is rostered, so first-run setup can pick a mode. Both work before onboarding — unlike `company-profile`, nothing here needs a profile. |\n| `scheduled` | `GET\\|DELETE` scheduled actions (`?status=…&order=asc\\|desc`) | Pending and fired scheduled actions; `order` flips the `run_at` sort (asc=soonest-first for the upcoming queue, desc=most-recent-first for terminal-status history). `DELETE /scheduled/{id}` cancels a `pending` row (409 otherwise). Like pause it only stops work, so any signed-in user may — the UI proxy's `x-caller-email` is trusted when the request also carries the `BACKEND_SHARED_SECRET` `x-api-key` — as may a matching `X-Admin-Token` (`SCHEDULED_ADMIN_TOKEN`) or a loopback caller with no token set; otherwise 401 (token set) or 503. Audited as `scheduled_action_cancelled`. |\n| `watchlist` | `GET\\|POST\\|PATCH\\|DELETE /watchlist`, `POST /watchlist/{slug}/approve`, `POST /watchlist/{slug}/decline` | External-monitoring watchlist + signals. Rows carry `origin` (`manual` \\| `executive` \\| `research` \\| `research_proposed`); `approve` turns a research suggestion (`research_proposed`, `dry_run`) into a live watch, `decline` `{reason: not_relevant \\| too_noisy \\| wrong_source}` removes it and records the decline (or, for `too_noisy`, keeps it live at a high floor), both 409 unless the row is a pending suggestion; `DELETE ?reason=` on a research-origin row records the decline too. |\n| `workflows` | `GET /workflows`, `POST /workflows/{name}/runs`, `GET\\|POST\\|PUT\\|DELETE /workflows/custom`, `GET\\|DELETE /workflows/custom/{name}/targets`, `POST /workflows/runs/{run_id}/decision`, `GET /workflows/tools/search?q=`, `GET /workflows/tools/describe?names=` | Workflow catalog, run management, and user-created (dynamic) workflow CRUD. Custom definitions come back with a server-managed `owner_person_id` (the creator — the web caller on `POST`, set on insert only; a client-sent value is ignored), who is asked to approve a workflow's first write to a new target. `GET /workflows/custom/{name}/targets` lists the targets its tool steps may write to without asking and `DELETE …/targets?value=` forgets one. `POST /workflows/{name}/runs` is a 403 (\"Only the principal can run this workflow.\"), audited, before any run row exists, when the workflow is one only the principal may start in the workspace's mode (`weekly_review` always, `morning_brief` in solo) and the caller is not the principal. A request with no `x-caller-email` counts as the principal; with no principal on the roster, no signed-in caller does. This governs starting a run only. A run started by hand (this endpoint, or `run_workflow` / research in chat) records its starter as `owner_person_id` and is theirs alone: `GET /workflows/runs` lists the team's (scheduled, no owner) runs plus the caller's own and the ones waiting on them, and `GET` / `DELETE /workflows/runs/{run_id}` and `POST /workflows/runs/{run_id}/decision` are a 404 for anyone else's, the principal included. A signed-in email that is on nobody's People entry cannot start one (403), and a run whose starter can't be read is refused (503); its steps read and draft documents as the starter only. `POST /workflows/runs/{run_id}/decision` with `{decision: \"approve\"|\"reject\"}` answers a run awaiting a yes/no sign-off from the web app — 403 unless the caller is the person it waits on or the principal, 409 if it isn't awaiting or needs a written reply — through the same `apply_resolution` a chat reply uses. Custom create/update also rejects (422) any action-step tool that does not resolve, and so does `POST /workflows/custom/{name}/activate` when turning a workflow **on** — that click is the approval for a tool workflow chat saved switched off (turning off is never checked). Turning on a workflow with action steps requires the body `{is_active: true, definition}` carrying the definition the user reviewed; if the stored one differs (ignoring `is_active` and timestamps) it returns 409, and the switch itself is a compare-and-set on the validated revision (`dynamic_store.activate_if_unchanged`, keyed on `updated_at`), so a save that lands while the tool check awaits the gateway — even from another process — is a 409 too, so only what was shown gets switched on. `GET /workflows/custom` lists inactive definitions too; `GET /workflows/{name}` 404s for them. The two `tools` endpoints return `{tools: [{name, description, read_only, source}]}` for the advanced editor's tool picker and the review card; `read_only` is true only when the name says it reads (a label, not a control). The run stream adds a `progress` event (`step_id`, `summary`) while an action step uses tools. Each catalog entry (`WorkflowMeta`) carries `is_custom`, `background` (true for the system-run built-ins the UI files under “System”) and `quick` (true for a Quick workflow, one per playbook nothing else follows, named `quick_<playbook>`). The run endpoint streams SSE; its `awaiting_human` event carries `delivery` (`self` \\| `sent` \\| `suppressed` \\| `alerted` \\| `failed`) alongside `person_id` / `question` / `awaiting_until`, because the outbound guard or an unreachable approver means the question may never have been asked — a client must not render “waiting on them” for those. A paused run ends the stream with neither `done` nor `error`, so that `awaiting_human` frame carries `terminal: true` to say so explicitly, plus `resumable` — whether the run continues by itself once answered or stops at the gate. `GET /workflows/runs/{run_id}` returns the run row with the resume payload replaced by a small `resume_progress` summary (`gate_step_id`, `completed_step_ids`, or `null`): the payload holds every completed step's full text, and the run-detail page polls this endpoint while a run is unfinished. |\n| `knowledge` | `/knowledge/builtin`, `/external`, `/search` | MBA knowledge base and external sources. `/search` is the introspection parallel of `retriever.retrieve` and mirrors its filters — including the `general` catch-all on the company collection — so the panel cannot report a specialist seeing nothing that it does retrieve in chat. It accepts `general` in `domain_filter` for the same reason. `/search` applies the same review gate as `retrieve()` — withheld (pending or rejected) built-in, external and failure rows are dropped, so the panel never advertises knowledge the Executive cannot use; it degrades to unfiltered rather than failing if review state is unreadable. `POST /knowledge/builtin` refuses a name already held by shipped content, and `POST|DELETE /knowledge/failures` now register and deregister for review — without that a user-authored failure case study had no review row, so no SME decision could block it. |\n| `skills` | `/skills`, `/skills/search`, `/skills/{name}/restore` | Skill registry (the UI's **Playbooks**) CRUD and search. `PUT` on a built-in saves a company customization that shadows it; `DELETE` returns `{name, outcome}` — `deleted`, `reverted` (customization removed, built-in back) or `hidden` (built-in hidden for this company); `restore` un-hides; `GET /skills?include_hidden=true` lists hidden built-ins. List and detail carry `used_by` — `[{name, title, is_custom}]` of the workflows that follow the playbook (switched-off custom ones included) (`WorkflowMeta.playbooks` is the other direction). |\n| `evals` | `/evals/scenarios`, `/evals/runs` | Eval scenarios and run results. `POST /evals/runs` is a 403 when a workflow scenario names a workflow that only the principal may start in the mode it runs in (the weekly review; the morning brief in solo) and the caller is not the principal — the Jobs page's rule for starting a run; stored results are read under the existing `/evals/runs` rules. |\n| `memories` | `/memories/{decisions,initiatives,advice}`, `GET /memories/facts`, `POST /memories/facts/{fact_id}/{retire,approve,decline}`, `GET /memories/facts/approval`, `PUT /memories/facts/approval/{person_id}`, `GET /memories/people`, `GET /memories/people/{person_id}/conclusions` | Episodic-memory record management; the standing facts the Pulse Corrections tab reads (`{facts: [...], can_retire, retirable_ids, can_review}`; each fact carries `recorded_by_role` / `recorded_by_name`; `?include_inactive=` default true, honoured for the principal only; anyone else gets the active rows plus their own `proposed` ones, with the provenance (`session_id`, `turn_id`, `recorded_by_person_id`, `retired_reason`, and `source_quote` except on their own facts) blanked, never retired, replaced or declined text; `?limit=` 1–500) and their retire (the principal any fact, a teammate only one they recorded that the principal has not approved — else 403; the audit row names the teammate; 404 for an unknown or `profile` row, 409 when no longer active; writes a private `fact_retired` audit row); approve / decline a teammate's `proposed` fact (principal only, else 403; 409 when it is not proposed; private `fact_reviewed` row); and the per-teammate \"needs my approval\" switch (on by default; `GET` lists `[{person_id, full_name, needs_approval}]` for every active team member but the principal, `true` for anyone not yet set; `PUT` takes `{needs_approval}`, 404 for anyone else; both principal only; private `fact_approval_changed` row); plus the read-only peer-memory overview the Pulse People tab reads (`{status: ok|disabled|error, people: [...], conclusion_total}`; `?recent=` 1–50, default 5) and one person's full conclusion list, paged newest first (`{status, person_id, items, page, size, total, has_more}`; `?page=` ≥1, `?size=` 1–100, default 50; 404 when the person has no peer). Peer memory is each person's own: the overview holds only the caller's entry (none for a caller off the roster; `conclusion_total` counts only theirs), the principal included, and `/conclusions` for anyone but the caller is a 404. |\n| `review` | `/review/items`, `/review/stats`, `/review/trusted-defaults`, `POST /review/curate`, `POST /review/bulk-approve` | Knowledge review queue and annotations. Shipped knowledge registers as a trusted default (`approved` with a NULL `reviewed_at`), so the queue starts empty; `curate` (`{domain, action: start|stop}`, domain required) opts one domain in or out, and `trusted-defaults` returns domain → unreviewed count. `bulk-approve` takes a non-empty `domain`, `item_ids` (max 500) or `all_pending: true`, and 400s with no selector; it returns `{approved_count, item_ids}`. |\n| `onboarding` | `/onboard/interview/understand`, `/onboard/interview/start`, `/onboard/interview/message`, `/onboard/interview/draft`, `/onboard/interview/{id}`, `/onboard/interview/commit` | Conversational company setup. The `onboarding_interviewer` agent asks clarifying questions, then emits a draft profile + people + departments. **Nothing is persisted until `POST /onboard/interview/commit`** — the interview itself never writes. `start` is multipart (description + optional deck/one-pager uploads). `commit` answers 403 when the draft would make a different person the owner and the caller is not the current owner (setup demotes the old principal, and any signed-in user can open it). It also takes an optional `owner_email` — the principal's sign-in email, which the review screen pre-fills from the signed-in user — checked before anything is written (422 if it is malformed, already another person's, or would replace the principal's existing email — setup only fills in a missing one; 403 if the caller is not the owner and it is not the address they signed in with, since the roster is the sign-in allow-list) and saved on the principal's People row, so the owner's chats resolve to them from the first turn. |\n| `workflow_designer` | `POST /workflows/designer/start`, `POST /workflows/designer/edit`, `POST /workflows/designer/message`, `POST /workflows/designer/draft`, `GET /workflows/designer/{session_id}` | The conversational New workflow wizard, and editing a saved workflow by conversation. `/edit` (`{name}`) opens a session on a saved custom workflow with no model call: the stored definition is the starting draft, and every response then carries `editing` (its name) and `original` (the stored definition as the session opened on it); drafts keep that name and its on/off state whatever the model writes (404 for an unknown workflow). The UI saves one with `POST /workflows/custom/{name}/save-edit` (`{session_id, definition}`): the server saves the session's own draft, never a client-sent body, and only when it equals the `definition` the user reviewed (a later message is a 409, so the click saves only what was shown); it re-validates it, keeps the stored on/off state, and writes only if the stored workflow is still the version the conversation opened on — otherwise 409, as it is for a session about another workflow or one with nothing drafted yet. It sits under `/workflows/custom` so anything that limits writes to custom workflows covers it too. The `workflow_designer` agent asks clarifying questions (`phase: \"question\"`, with `hint` and up to four suggested `options`), then returns `phase: \"draft\"` with `draft.definition` (exactly the body `POST /workflows/custom` takes), `summary`, and `assumptions`; every response carries the `transcript`. **Nothing is persisted here** — sessions are in memory, and the UI saves through `POST /workflows/custom`. Errors are fixed strings (422 over the 8,000-char message cap or the transcript cap, 404 for an expired session, 409 while another turn on the same session is still running, 502/504 for model failure or timeout). Mounted ahead of the `workflows` router. |\n| `python_jobs` | `GET /python-jobs/{job_id}/{name}` | A result file a Python job (`run_python_job`) wrote, the principal's alone (403 otherwise), served as a download (`Content-Disposition: attachment`, `Content-Security-Policy: sandbox`, `nosniff`, `Cache-Control: no-store`); 404 for a bad id or name or a file past its 7 days. |\n| `saved_tools` | `GET /saved-tools`, `GET\\|PUT /saved-tools/{name}`, `POST /saved-tools/{name}/rollback` | The scripts the Executive saved as tools (Settings → Advanced → Saved tools), the owner's alone (403 otherwise). The list gives each tool's name, description, on/off, current version, `kind` (`script` or `python`, a kept Python job) and the tools it calls, plus whether `SAVED_TOOLS_ENABLED` is on; the detail adds the script, every version and the last 20 runs. `PUT {enabled?, workflows?, version?}` turns one on or off (off also turns it off for workflows, so turning it back on never re-arms unattended runs), and turns the named `version` — the one the owner looked at, never whatever is current by then — on for workflows (or workflows off); a Python tool never turns on for workflows (409) — turning workflows on lets more run unattended, so it needs a request tied to the owner (signed sign-ins or local login, as Take the lead's switches do; 409 otherwise); `rollback {version}` makes that version the one that runs. Both are audited as `saved_tool_changed`. The Executive saves tools itself through `run_script`; there is no create route. |\n| `onboarding` (fallback) | `/onboard/start`, `/onboard/answer`, `/onboard/status/{id}` | The original 12-step form wizard, kept as a fallback (UI at `/onboard?mode=form`) and used by the `openexecutive onboard` CLI. Its final answer saves the profile and adds people with their emails and a principal, so once there is an owner only they can send it (403, and the session rolls back so the owner can still finish it). `/onboard/start` reads the workspace mode once for the session: solo skips the Team Size, Team Members and Fractional Executives steps. Each status response's `current_step` / `total_steps` count only the steps that session asks, and `optional` says whether the current step can be skipped. |\n| `company-profile` | `GET\\|PATCH /company-profile` | Structured company profile. |\n| `alerts` (private cards) | `POST /alerts/{id}/ack`, `/reopen`, `/alerts/bulk-ack` | An alert tagged `private:principal` (see Today) is a 404 on ack and reopen for anyone but the principal, and their bulk sweep skips it. A roster-request card (source `roster_request`) is a 409 on `ack` even for the principal — it is answered at `/people/requests/{id}`, since acking would leave the sender waiting with nothing to show it — and, as an exempt source, `bulk-ack` and `reopen` skip it. |\n| `auth` | `GET /auth/allowed-emails` | Non-archived **team members** with an email, offered to the UI's sign-in gate — a contact is never on it, so adding a client to reach them by email no longer lets them sign in. The gate takes the **union** of this roster and its own `ALLOWED_EMAILS` env list, so env entries always work (and are checked first, short-circuiting the fetch) and roster entries are additive — a roster change can never revoke a configured operator. With local login (`make dev` with Google sign-in not set up — the UI then listens on 127.0.0.1 only) the UI signs in without an email, sends no `x-caller-email`, and the backend resolves the caller to the principal, as it does for the CLI. |\n| `fixtures` | `/fixtures`, `/fixtures/{name}/load` | Demo-company fixture load/reset/snapshot. `POST /fixtures/reset` leaves no departments, like a new install (`departments_seeded` is always 0). |\n| `clients` | `/clients`, `/clients/generate`, `/clients/cockpit`, `/clients/save`, `/clients/{slug}/activate` | Client-company slots — multi-client mode for fractional use; create from current/blank/AI-generated intake draft (pasted notes and/or file attachments, multipart on `/clients/generate`), save-back switching, engagement metadata (PATCH), cross-client cockpit, delete. See the Client Companies section. |\n| webhooks | `POST /webhook/telegram`, `POST /webhook/google-chat`, `POST /webhook/slack` | Inbound integration callbacks (self-verified). `/webhook/slack` answers 503 unless `SLACK_SIGNING_SECRET` is set. |\n| MCP server | `POST\\|GET /mcp` | Open Executive exposed as an MCP server (Streamable-HTTP). Not a router — a mounted FastMCP sub-app. Same shared-secret gate (`x-api-key`); exposes company context as resources and the specialist council as tools. See the MCP Server section. |\n\n**Take the lead** (`api/routes/take_the_lead.py`): `GET /take-the-lead` returns the As the Executive switch, its six Ask first switches (`{kind, label, hint, on}`, the hint a plain line on what each one catches), the company's rules, whether this server can tie a change to the owner (`available`), and whether the Executive is paused. `PUT /take-the-lead` takes `{enabled?, ask_first?}`, and `POST /take-the-lead/rules` / `DELETE /take-the-lead/rules/{id}` add or remove a company rule (`{kind: person|domain|words|amount, value}`, 422 on a bad one). All four are the principal's alone (403). Anything that lets more happen on its own (turning it on, turning an Ask first off, removing a rule) needs a caller the API can tie to them (`delegation.verified.caller_refusal`, else 409). `GET /today/activity` adds `took_the_lead` rows (what Take the lead did, named, not quoted) and, for the caller alone, `sent_as_you` rows for what Handle it for me sent as them. Under `/delegation`: `PUT /delegation/take-the-lead {enabled}` is Take the lead as you (the owner's only for now; turning it on turns Handle it for me on), and `GET|POST /delegation/take-the-lead/rules` and `DELETE …/rules/{id}` manage the caller's own rules. `HandleItOut` gains `lead` and `lead_available`. A `take_the_lead_action` decision is approved or rejected through the existing `/decisions/{id}/approve|reject`. Training: the response also carries `training` (In training: everything waits unless allowed), `learned` (`{id, label, feature, example, uses, created_at}`: what it was allowed, the edit kept as an example by field) and `suggested` (`{key, label, approvals}`); `PUT` takes `training?` too, and leaving training while on needs the same provable owner as turning it on. `POST /take-the-lead/learned {key}` allows a current suggestion (404 for anything else; provable owner), `DELETE /take-the-lead/learned/{id}` makes it ask first again. `learned` also lists the owner's own Act as me senders (`feature` `act_as_me`), never anyone else's, and Remove works on those too. On a `take_the_lead_action` card, `POST /decisions/{id}/approve` takes `edits.input` (the card's editable fields, 422 for any other; the principal's alone, 403 for an area approver) and `edits.allow: true` (a training card only, 422 otherwise; the principal from a provable request, 403 otherwise), finishing `approved_with_edit` when a field changed.",
+ "markdown": "The FastAPI surface lives in `openexecutive.api.main`, which mounts one router per topic. A shared-secret middleware gates every request via an `x-api-key` header, except `/health` and the `/webhook/*` callbacks (which carry their own verification). With local login (`OE_LOCAL_LOGIN=1`, which only `make dev` sets, and only while neither Google nor SSO sign-in is set up) a second middleware answers 403 to any request whose raw `Host` is not `localhost`, `127.0.0.1` or `[::1]` (except a webhook that verifies its caller: Google Chat and Slack always, Telegram only with a `TELEGRAM_WEBHOOK_SECRET` Telegram can send), and to any write whose `Sec-Fetch-Site` is present and not `same-origin`/`none`. The UI signs that owner in with no password and this API usually has no secret, so without it a web page in the owner's browser could drive the API as the principal — by DNS-rebinding its own hostname to 127.0.0.1, or by posting a plain form from another site or localhost port. CORS is restricted to 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\n**Who is calling** is read in one place, `api/caller.py`, which answers with a `Caller` kind and email; a test fails on any other read of an `x-caller-*` header. By default (`open`) it is the `x-caller-email` the UI proxy stamps from the sign-in, trusted because whoever holds the shared secret is trusted as the proxy, and a request with none runs as the principal. **Signed callers** remove that trust. With `CALLER_ASSERTION_PUBLIC_KEYS` set, the proxy signs every request with an Ed25519 key only the UI holds, and a third middleware checks the `x-caller-assertion` header:\n\n- **What it covers.** It is good for one method, the exact path and query, at most 120 seconds, and one use. The API keeps used ids in memory.\n- **What it names.** A `user`, by email, or the `operator`: local login, which runs as the principal.\n- **No caller header at all** is a `service`, for scripts or MCP clients holding only the secret. It is never the principal, not even on an install with no owner yet, so it can't save a first setup.\n- **Anything else is a 401.** That includes an `x-caller-email` without an assertion (`caller_assertion_required`), and a bad, expired, reused or mismatched assertion (`caller_assertion_invalid`).\n\nPublic keys that can't be read stop the boot, rather than fall back to trusting the header. `scripts/make-caller-keys.py` makes the pair, and `scripts/mint-caller-assertion.py` signs one request for curl. The API holds only public keys. Setup's API-protection check warns while a shared secret is set without them.\n\nEndpoints grouped by router:\n\n| Router | Key endpoints | Purpose |\n|---|---|---|\n| `chat` | `POST /chat`, `POST /chat/stop`, `POST /chat/add`, `POST /chat/background` | SSE stream of a live Executive turn. `POST /chat/background` starts a new chat that the server answers to the end with nobody connected (a phone approving a card, then closing the app): it answers `202` with the new `session_id` once the same caller, access and quota checks as `/chat` pass, the turn saves itself as a `/chat` turn does, and one caller may have three running at once (`429` beyond that). `POST /chat/add` hands the running turn a message the person typed while it works; the turn takes it at its next step and the stream names it in a `message_added` event, and a second `POST /chat` on the same conversation waits for the first to finish. The request body optionally carries `page_context` (route, page title, guide section id, and a form descriptor with current values) — sent only by the Ask OE side panel so the Executive can explain the current page or propose form values. When the Executive calls its `propose_form_values` tool, the stream emits a `form_patch` event (`{type, form_id, fields, rationale, iteration}`) that the panel applies into the on-screen form as highlighted suggestions; the user reviews and saves through the form's normal submit path. Each round of tool calls also emits an `activity` event (`{type, label, tool, iteration}`) naming what is running — progress only, forwarded verbatim and never persisted with the message, unlike an `action_taken` chip. A `session_id` in the body must be a chat the caller may use (the same ownership rule as `sessions`). If it isn't, the turn runs in a fresh chat instead, so nothing is written into someone else's session and the reply looks the same as for an unknown id. An unknown namespaced id (`slack:…`, `telegram:…` and so on) is ignored and a fresh chat is started, because those ids belong to the channel adapters and claiming one first would make the caller its owner. The client mints a `client_turn_id` and sends it with the turn; `POST /chat/stop` takes that id and halts the turn mid-flight, so the button is live from the moment Send is pressed rather than only once the first SSE byte arrives. A stopped turn emits a `stopped` event and then the usual `done` over the same still-open stream — never an `error` — and whatever streamed so far is persisted and flagged. The endpoint returns 404 both for an unknown id and for another caller's turn, so it cannot be used to probe which turns are live. An optional `memory_text` (1–2000 chars) is what peer memory records as the caller's words instead of `message` — the briefing handoffs send it because their seed quotes the Executive's own card; `POST /chat/upload` derives it from the typed text and filenames. Since it never reaches the transcript, the `chat_turn` audit row keeps it beside `message`. After the reply — a stopped or timed-out one too, before the `stopped` / `error` / `done` frames — a turn that looked at anything sends one `sources` event, `{type, session_id, sources: [{kind, title, url}], unavailable: [area]}`: `kind` is `company`, `knowledge`, `notion`, `research`, `document` or `web`, `url` is only ever an http(s) link or, for an earlier document, `/artifacts/<id>`, at most 12 sources (6 from the web, pages the reply cites first), and `unavailable` names parts of the analysis (\"finance\") whose specialist failed or said nothing every time it was asked. It is persisted with the reply as `chat_messages.sources`. A request that carries `x-caller-email` marks its turn signed in (`Session.web_caller_signed_in`), which Act as me needs on a deployment without local login. |\n| `sessions` | `GET /sessions`, `GET /sessions/{id}`, `GET /sessions/{id}/messages`, `DELETE /sessions/{id}`, `POST /sessions/{id}/messages/{message_id}/feedback`, `GET /sessions/{id}/followup` | List, read and delete saved chat sessions (assistant messages carry their row `id` and any `feedback`). The list is scoped to the caller, and each chat carries `preview`: its last message as one plain line, Markdown marks stripped and cut at a word near 120 characters, with `You:` before the person's own words. With `?q=` it is a search: the caller's own chats whose title or message text contains the words (case-insensitive, `LIKE` with wildcards escaped), each with `match_count` (messages that contain them; 0 for a title-only match) and `snippet` (the newest matching message, around the match, prefixed `You:` or `Executive:`). Scoped exactly like the list, so nobody else's conversation can match. The Chats page searches this way and opens a result with `?find=`, so the chat starts on that message and steps through the others. A chat-app conversation started with /new is left off the list until its first turn (`memory.conversations`). Every per-session route checks ownership, because session ids are guessable (`slack:dm:<user id>`, `telegram:<chat id>`): only the session's owner or the principal gets through, and a legacy row with no owner is the principal's alone. A teammate's own chat (a web chat, a DM, a private Telegram chat; not a channel or group conversation, `chat._shared_space`) is theirs alone, the principal included, as their mail with the Executive is. Anyone else gets the same 404 as for an unknown id, so the routes can't be used to find out which chats exist. The one other way in is having started the chat in this process (matched by Person id or verified email, so it survives the caller being added to the roster), which is how a caller the roster can't resolve keeps using their own chat. That record is in memory, so after a restart such an ownerless chat is refused for reads. The principal can continue someone else's ownerless chat without becoming its owner. Deleting a session also drops its in-memory copy, so a later turn naming that id starts fresh. The feedback route records 👍/👎 (`{\"feedback\": \"up\"|\"down\"|null}`) on one assistant reply; only the session's own caller or the principal may rate it. The rater is stored (`feedback_by_person_id`), and a 👎 on a reply to the rater's own message triggers a working-style pass for them (paced; see attunement). The chat stream's `done` event carries `message_id` for the persisted reply. The followup route returns `{\"suggestion\": string|null}` — one suggested next user message, written by the utility-fast model from the last few turns, that the chat composer shows as its greyed placeholder (Tab / → or the inline chip fills it in without sending). It is null unless the session ends on a persisted assistant reply, and null (uncached) when the model fails. Same ownership check as feedback; successful suggestions are cached in-process per (session, reply id). Messages from `GET /sessions/{id}/messages` carry each assistant reply's saved `sources` (the same shape as the chat stream's `sources` event, without `type`), so a reloaded chat shows them again. |\n| `today` | `GET /today`, `GET /today/activity`, `GET /today/activity/daily`, `GET /today/brief-delivery`, `GET /today/top-three`, `GET /today/weekly-review` | Morning-brief aggregation, recent-action rail, and Pulse heartbeat heatmap (per-day activity counts). `GET /today` carries the viewer's cached \"What's going on\" `narrative` with `narrative_generated_at` (when it was written) and `narrative_stale` (a fresher one is being written — the page re-polls; see Today). A proposal backed by a roster request carries `roster_request` (the new sender's server-derived details and held-message previews; the principal's only) and is answered through the `people` routes below. `brief-delivery` returns the latest morning brief or end-of-day digest that didn't reach the owner, as `{brief, at, problem, fix, readable}` in plain language (`readable` is false when it couldn't be written, so there is nothing to read), or null — null while briefs go out, once the cause is fixed, while the scheduler is off, and for anyone but the owner (`chat._caller_is_principal_or_unclaimed`); it carries no address or channel id. `top-three` and `weekly-review` feed the solo Briefing's own cards and answer only in solo mode and only to the principal (`workflows._caller_is_the_principal`: a principal match or no caller header, never an unclaimed roster); anyone else, and team mode, get null. `top-three` returns `{items: [{key, kind, text, why, slot}]}` — the morning brief's top three from the same code (`build_top_three(principal_due_soon())`), `slot` a free block like `10:00–11:00`, `\"\"` when none is left, null when no calendar was read — and is kept off `GET /today` because its calendar read may take up to 4 s. `weekly-review` returns the latest completed `weekly_review` run as `{run_id, completed_at, period, top_three, excerpt}` (next week's top three as plain text; `excerpt` when that list is empty), or null when none has completed. |\n| `people` | `GET\\|POST\\|PATCH /people`, `POST /people/{id}/archive`, `GET /people/requests`, `GET /people/requests/{id}`, `POST /people/requests/{id}/approve`, `POST /people/requests/{id}/decline`, `GET\\|POST /people/{id}/open-loops`, `POST /open-loops/{loop_id}/close`, `GET /people/{id}/outreach`, `GET\\|PUT\\|DELETE /people/{id}/attunement` | Roster CRUD and scope lookups. Every `Person` carries `kind` (`team` / `contact`). `GET /people` lists team members only unless `?include_contacts=true` (the People page asks for both; the department-head and workflow pickers keep the default); `POST` / `PATCH` accept `kind`, and a principal contact is a 422 either way. They also take `email_aliases` (other addresses the person writes from, at most 10; on `PATCH` the full list replaces the current one, omitted leaves it): an alias matches their mail and may be emailed but never signs in; a malformed one is a 422, and an alias — or a new primary `email` — that is already someone else's address or alias is a 409. Every `POST` / `PATCH` then closes any pending roster request whose sender now matches someone and replays its held messages. Adding, editing and archiving (`POST`, `PATCH`, `/archive`) are the principal's only, or anyone's while no one is principal yet so a first setup can add its owner (`chat._caller_is_principal_or_unclaimed`, the check behind `PUT /workspace`; a request with no `x-caller-email`, such as the CLI or local login, counts as the principal). Anyone else, a person editing their own row included, gets 403 before the person lookup, so it can't probe which ids exist. Contacts are private to the principal (`caller_is_principal`: the signed-in email is the principal's, or no `x-caller-email`; stricter than the owner rule above, so while no one is principal nobody is): for anyone else `include_contacts` is ignored, a contact's id is a 404 on `GET /people/{id}` and open-loops (exactly as for a missing id; `PATCH` and archive are already a 403 for them), and creating a contact or turning someone into one is a 403, even on a first setup with no principal yet. `GET /people/me` returns `{person_id, is_principal}` so the UI offers contacts to the principal only. `GET /people/by-scope/{token}` never returns a contact. Archiving a person closes their open loops. The open-loop routes list what a person owes (soonest due first) and close one (`reason`: done / not_needed / cancelled) — both the principal's or the owner's only (403 otherwise, via `people.store.is_principal_or_self`). `POST /people/{id}/open-loops` `{task, due_date?}` assigns that person a task (201 with the loop; `due_date` is a local date, due 17:00 in the user's timezone, clamped to 60 days, default 2 days): any active team member may assign anyone on the team, 403 for anyone else; 409 for an archived person, a contact (as seen by the principal), a person at the open-loop cap, a duplicate or open loops turned off; 422 for an empty task. Nobody is messaged at assignment — the owner is chased once it is due. `/outreach` returns, per kind of proactive outreach over 30 days, `sent` / `replied` / `acted` / `ignored` / `pending` (voided DMs are excluded) — same access rule, checked before the person lookup so it can't probe which ids exist. `/attunement` reads, replaces (`rules`: up to 4 strings, or omitted to only set `locked`) or resets the person's working-style rules — same access rule, 404 for an archived person; `PUT` rejects a rule that is not purely about style with 422. Archiving a person also drops their working style and frees their aliases. The **roster-request** routes (declared before `/people/{person_id}`) are the principal's alone (`caller_is_principal`; anyone else gets 404, as for a missing id): `GET /people/requests?status=pending|approved|linked|declined|expired|superseded|all` lists up to 100 (`id`, `channel`, `channel_ref`, sanitised `display_name`, `profile_email`, `on_company_domain`, `suggested_kind`, `suggested_person_id` / `_name`, `status`, `resolved_person_id` / `_kind`, `message_count`, timestamps, `ack_sent`, and `previews` of the held messages while pending — shown to the principal, never to a model); `approve` takes either `link_person_id` (+ `replace_channel_id`) or `full_name` + `kind` (no default: 422 without both) + optional `role`; `decline` takes no body. An answered request is a 409, a chat id or address already on someone else is a 409; the held messages are replayed (or dropped) in the background. |\n| `departments` | `GET\\|POST\\|PATCH\\|DELETE /departments`, `.../goals` | Department state and per-department goals. `PATCH /departments/{slug}` also takes `watched_entities` (≤50 names, `[]` clears) — the entities the research watch policy may add watches for and route to this department. A `cadences` spec that does not parse is rejected with a 422 (empty means no cadence). A new `head_person_id` must be a team member: an unknown id and one of the principal's contacts get the same name-free 422 (`person_id N is not on the team.`), so the route — open to any signed-in user — never reveals that a contact exists; an unchanged head is not re-checked. `POST .../goals` requires only `key_result`: a missing or blank `period_value` is filled with the current period for `period_type` in the user's zone (the same label `create_goal` uses), and `target` defaults to empty. `PATCH .../goals/{id}` rejects a blank `key_result` or `period_value` with a 422; `target` may be cleared. |\n| `agents` | `GET /agents`, `GET /agents/models`, `GET /agents/models/options`, `GET /agents/presets`, `POST /agents/presets/{id}`, `PATCH /agents/{id}`, `POST /agents/{id}/test` | Specialist metadata and Council overrides. `/agents/models` is the flat model allowlist the PATCH validator uses; `/agents/models/options` returns the same ids in the same order, each tagged with `provider`, `provider_label`, `route` (`direct` / `openrouter` / `local`) and a display `label`, for the Council's Provider → Model picker. `AgentDetail` carries `instructions` (additional instructions, appended after `prompt`, which stays the built-in prompt or its replacement); `PATCH` and `/test` accept `instructions` (max 4,000 chars, blank clears it). `GET /agents/presets` lists the Fast, Balanced and Thorough quality presets (each with `available` and the resolved `model` for this install) plus `active` (null when the council is Custom), `base` and `custom_agents`; `POST /agents/presets/{id}` applies one by writing per-agent model and deep-reasoning overrides and returns the same shape (404 unknown preset, 409 when the install allows none of its models). Each `AgentMeta` carries `visibility` (`core` or `internal`) so the Council's simple view can list core agents first. |\n| `personas` | `GET\\|PUT\\|POST\\|DELETE /personas` | Executive persona definitions. |\n| `alerts` | `POST /alerts/{id}/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`, `supersedes_id` and, for an extension's kind of document, `collection` / `collection_label` on every summary (`orchestrator.extensions`; archive, restore and delete tell the collection first and answer 502 if it refuses). `download` renders the file (Word/Excel built at request time from the stored text; any Markdown artifact, workflow output included, can export `?as=docx`) and is always an attachment with `nosniff` and a sandbox CSP. Every route answers for the signed-in caller (`artifact_records.Viewer`): a drafted artifact is its owner's alone (`alerts.owner_person_id`, the person whose conversation published it; none = the principal's), a workflow output follows its run (`persistence.run_visible_to`), and anything the caller may not see is a 404 like a missing id, the principal included. `POST /alerts/{id}/ack` and `/reopen` answer 404 for someone else's drafted artifact the same way. |\n| `decisions` | `GET /decisions`, `POST /decisions/{id}/{approve,reject,cancel}`, `GET`/`PUT /decisions/classes/meeting_scheduling`, `GET /audit/reliability` | Approval-gated decision instances (e.g. calendar bookings). What approve/reject/cancel do is per class (`DECISION_CLASSES`, one `DecisionClassSpec` each; meeting booking books on approve and deletes on cancel; `delegation_reply`, an inbox reply card, is its approver's alone (`approver_only`) — hidden from everyone else, the principal included when it is a team member's — sends its Gmail draft on approve and, after a reject, deletes the draft unless it was edited), and an instance of a class with no spec gets 409 instead of being carried out as another. Only the principal, or the person the decision went to for approval (`approver_person_id`), may approve, reject or cancel it. Anyone else gets 403, and a decision nobody was asked about, or one private to the principal, is the principal's alone. The resolver is recorded as `resolver_person_id`, and a reject that loses the race to another answer is a 409. `GET /audit/reliability` is the principal's alone (403 otherwise), because it counts private decisions too. A proposed booking is surfaced on the briefing as a companion alert; approve/reject/cancel here also clear that alert. An approval whose caller resolves to the principal runs the booking inside `grant_contact_egress()`, so a meeting the principal proposed with a contact can be created. Such a booking's payload is marked `private`: it is proposed to the principal, left out of anyone else's `GET /decisions`, and a 404 for them on `GET /decisions/{id}` and every action route. Reviewed in the briefing — there is no separate proposals page. The class routes read and set how meetings are handled: both return `{decision_class: \"meeting_scheduling\", mode: \"propose\" \\| \"auto_execute\"}` (default `propose`); the `PUT` body is `{mode}`, principal-only (403 otherwise, open before a principal exists — but then only `propose` can be set: `auto_execute` is a 409 until a non-archived principal is on the roster), 422 on any other mode, and a change writes a `decision_class_mode_changed` audit row. In solo mode the class mode decides a booking, and `auto_execute` applies only to a turn the principal started on a verified surface — any other turn gets a proposal. |\n| `delegation` | `GET`/`PUT /delegation`, `GET`/`PUT`/`DELETE /delegation/voice`, `POST /delegation/voice/learn`, `POST /delegation/voice/describe`, `POST /delegation/voice/signature`, `PUT /delegation/inbox`, `POST /delegation/inbox/check`, `GET /delegation/replies`, `PUT /delegation/replies/{id}/text`, `GET /delegation/actions`, `PUT /delegation/handle-it`, `PUT /delegation/training`, `DELETE /delegation/learned/{id}`, `GET /delegation/handled`, `PUT /delegation/team` | Act as me — the **caller's own** delegation only; nobody sets it for anyone else. It answers the principal, and a team member once the owner lets them; anyone else gets 403 `not_available_yet`. `GET /delegation` returns `{enabled, gmail: {status, message, email, connect_command, outlook_connect_command, provider}, inbox: {enabled, status, message, watch_since, last_poll_at, checking}, handle_it: {enabled, mode, available, sent_today, lead, lead_available}, training: {replies, follow_ups, actions, drafts, learned}, team}`, where `team` is the owner's switch for the principal while `DELEGATION_TEAM_MEMBERS` allows it — `{enabled, members: [{person_id, name, enabled, inbox, drafts_30d, sent_30d}]}`, counts only — and `null` otherwise. `PUT /delegation/handle-it` takes `{enabled?, mode?}` (`mode` is `careful`, `balanced` or `bold`; anything else is a 422 `bad_mode`) from a caller the API knows is that person — 403 `not_yours`, 409 `caller_signing_required` with only the shared secret — and turning it on needs Act as me and Draft replies to my inbox on (409 `act_as_me_off` / `inbox_off`); `GET /delegation/handled` returns `{replies: [{decision_id, sent_at, to_name, to_email, subject, body, open_questions, gmail_link, source}]}`, the caller's replies and follow-ups (`source` `follow_up`) sent on its own in the last 7 days; a card on `GET /delegation/replies` carries `source` the same way, `can_allow` while Replies (Follow-ups, on a follow-up) is in training, and `learns_style` while Drafts is. `PUT /delegation/training` takes `{replies?, follow_ups?, actions?, drafts?}` (any other field is a 422) and returns the `GET /delegation` shape; putting Replies or Follow-ups in, or Suggested actions out, needs no signed sign-in, anything else does (409 `caller_signing_required`), and putting Replies or Follow-ups in turns Take the lead as you off (`PUT /delegation/take-the-lead` on answers 409 `in_training` while they are). `training.learned` is `[{id, label, setting, example, uses, created_at}]`, what the caller allowed or kept in training (`setting` `replies`, `follow_ups`, `actions` or `drafts`; the kept example, or \"\"); `DELETE /delegation/learned/{id}` removes one of the caller's own (404 for anyone else's). `PUT /delegation/team` takes `{enabled}` from the principal alone (403 `principal_only`; 409 `not_available` when the install doesn't allow it). The Gmail `status` is `connected`, `not_configured`, `needs_reconnect`, `mismatch`, `no_email`, `shared_mailbox` or `error`, checked live with Google on each call. `PUT` takes `{enabled}` (any other field is a 422); turning it on needs the caller's own Gmail connected, otherwise a 409 whose code says why (`gmail_not_connected`, `gmail_needs_reconnect`, `gmail_mismatch`, `no_email`, `shared_mailbox`, `gmail_error`). The voice routes show, learn (from the caller's sent mail, one pass at a time — a 409 `in_progress`, `locked`, `too_soon`, `not_enough_mail`, `no_profile` or `changed` when it was locked or edited while learning, or a Gmail code), write it from the caller's own description (`POST /delegation/voice/describe` with `{description}`: one model call applies their words to the profile they have and returns it with a short `sample_reply`, saving nothing, so they review it and save it with `PUT`; a 409 `empty`, `too_long`, `in_progress`, `too_many` past 10 an hour or `no_profile`; no mailbox needed), edit and lock, and reset \"How I write\": a typed field that fails validation is a 422 `invalid_voice` listing each `rejected` field, and `clear_exemplars` / `clear_signature` drop those. `POST /delegation/voice/signature` reads the signature from the caller's Gmail settings again and changes nothing else (a locked profile stays locked), with the same Gmail codes as learning: a 409 when their mailbox isn't connected, it refuses the sign-in or the check itself fails (`gmail_error`), and a 502 `gmail_error` when reading the signature fails. On an Outlook mailbox it is a 409 `signature_unavailable`, since Outlook gives apps no signature to read, and the stored one is left alone. A caller `can_delegate` refuses — anyone but the principal, for now — gets 403 `not_available_yet`, which hides the Settings card. A request with no `x-caller-email` is a 403 `sign_in_required` unless the API runs under local login — a header-less call is not a sign-in (the caller is read through `api/caller.py`, as on every principal-only route). `PUT /delegation/inbox` takes `{enabled}` and turns **Draft replies to my inbox** on or off, returning the same shape as `GET /delegation`: on needs Act as me on (409 `act_as_me_off`) and the mailbox connected (the Gmail codes above, which keep their names for an Outlook mailbox too), and turning Act as me off turns it off too. `POST /delegation/inbox/check` starts a scan now in the background and answers 202 with the `inbox` state (409 `inbox_off` or `in_progress`). `GET /delegation/replies` returns `{cards: [...]}`, the caller's open reply cards from the database alone (no Gmail call): the decision id, the sender's name, address, relation and whether it was verified, the subject, when it arrived, what they wrote, the draft's recipients, subject and body, `open_questions`, `flags` and a Gmail link built from a fixed prefix. **Send** is `POST /decisions/{id}/approve`: it sends the card's draft exactly as it is in Gmail, after checking again that the caller is its owner — which on a server needs signed callers (409 `caller_signing_required` otherwise) — that both switches are on (`inbox_off`), no client slot is active (`client_slot`), the Gmail is connected (the Gmail codes), the draft is still there and unanswered (`draft_gone`, `you_replied`) and its recipients are allowed (`no_recipients`, `too_many_recipients`, `executive_recipient`, `not_from_you`). Recipients that changed, or a newer message in the thread, answer 409 `{code: \"confirm\", message, reasons, recipients}`; approving again with `edits: {recipients: <the list shown>, thread_moved_on: true}` is the second yes. **Send + allow** adds `edits.allow: true`: 422 `cant_allow` unless Replies (Follow-ups, on a follow-up card) is in training, 409 `learned_full` when their list is full, both before anything is sent; `edits.example: true` keeps a draft edited in the mailbox as how they write to that person while Drafts is in training. A draft edited in Gmail between those checks and the send is not sent (`draft_changed`). A double tap sends once (`already_handled`); Gmail refusing answers 429 `rate_limited` or 502 `gmail_error` with nothing sent, and a send Gmail didn't confirm answers 502 `send_unconfirmed` and is settled by the next inbox scan. Dismiss is `POST /decisions/{id}/reject`. `GET /delegation/actions` returns `{cards: [...]}`, the caller's own approval cards (`delegation_actions`): the decision id, when it was made, a one-line `why`, and each action's `index`, `kind` (`invite`, `message`, `add_contact`), `summary` and `text` (a message as it will be sent, or a meeting's description). **Approve** is `POST /decisions/{id}/approve` with `edits: {only: [indexes]}` (and `allow: true` for Approve + allow while Suggested actions is in training: 422 `cant_allow` otherwise or when nothing on it can be allowed, 409 `learned_full`; a card carries `can_allow`); it needs the card's own person signed in (403 `not_yours`, 409 `caller_signing_required`), Act as me on (409 `act_as_me_off`) and a card under a week old (409 `expired`), runs once (409 `already_handled`), and returns the decision with `final_payload_json.results`: per action `done`, `waiting` (sent to whoever approves meetings), `failed` with why, or `skipped`. Every change writes a private audit row. |\n| `history` | `GET /memories/history` (`?q=`), `PUT /memories/history/settings`, `PATCH`/`DELETE /memories/history/{id}`, `POST /memories/history/{id}/forget-conversation` | Always in the loop: the **caller's own** notes and switches only, resolved as for Act as me (a signed-in person on the roster, or the principal under local login; otherwise 403 `sign_in_required` / `not_on_roster`). `GET` returns `{notes, reply_notes, retention_days, effective_retention_days, company_retention_days, retention_choices, can_keep_notes, can_note_replies, can_set_company_retention, share_work_style, can_share_work_style}` (`can_keep_notes`: a team member on the People list may turn notes on; `can_note_replies`: they can use Act as me, so email replies are noted too; `share_work_style`: their own \"Share my work style with the team\" switch, `can_share_work_style`: a team member in a team workspace). `PUT` turns notes on only for someone who may keep them, and `share_work_style` on only for someone who may share it (403 `not_available` for either; turning either off always works), takes a person's retention only when shorter than the company's (422 `invalid_setting`), and the company retention only from the principal (403 `principal_only`). `PATCH` pins or corrects a note; `DELETE` forgets it; `forget-conversation` is \"Don't remember this\". A note that isn't the caller's is 404. Every change is audited privately to its person. |\n| `audit` | `GET /audit/logs`, `GET /audit/logs/{id}`, `GET /audit/sessions/{id}`, `GET /audit/usage`, `POST /audit/log` | Durable audit trail of side effects. `/audit/sessions/{id}` adds a per-session token cost summary; `/audit/usage` aggregates token usage and OpenRouter cost across all sessions (totals, by day, by model, and by source — the part of the system that made the calls — including server-side web-search counts), plus `scripts`: how many `run_script` scripts ran (and worked, and in workflows), the tool calls they made, their time, and `turns_avoided` — an upper bound on the model turns those calls would otherwise have needed (each call past a script's first) — and `python_jobs`: how many Python jobs ran (and worked, ran a kept Custom tool, took a chat attachment), their time, CPU, largest peak memory and bytes in and out, and the tokens and charge of the turns that ran one. The Token usage page shows it as a Scripts section. Rows private to the principal (`private_to_principal`: a turn about their private mail, or a row naming one of their contacts on their own turn) are theirs alone: for any other caller, resolved as for `/alerts`, the usage totals leave them out. Once a principal is on the roster, anyone else reads only their own rows (a teammate's own turns, their Act as me work) in the list, by id and in a session, and the principal reads those as actions only — what was done, when and in whose conversation, with the text, details and `full` left out, and no text search over them; any other row's id is a 404, and a session shows only the rows the caller reads. |\n| `architecture` | `GET /architecture/sections`, `.../sections/{id}` | This documentation surface. |\n| `guide` | `GET /guide/sections`, `.../sections/{id}` | Plain-language user-guide content surface — mirrors `architecture` (static, version-controlled files; no LLM on the serving path). |\n| `health` | `GET /health`, `GET /health/honcho` | Liveness probes. Only `/health` is unauthenticated; `/health/honcho` sits behind the gate like everything else, because the exemption is an exact-path set. `/health` also carries `google_tools_missing`, the pinned Google tools startup priming could not find: `[]` once it has checked and they are all there, a list of names when a workspace-mcp rename or the configured services and tool tier left one out, and `null` for no answer — Google Workspace is not configured, or the probe has not finished or it failed. Only `[]` asserts they are present. It also carries `gateway`, the MCP gateway's state from its supervisor (`orchestrator.gateway_boot`): `state` is `off` (MCP not enabled), `no_servers` (enabled, the config names none), `starting` (an attempt is running), `up` or `down` (every attempt so far failed; `next_retry_at` is the next one), with `attempts`, `up_since` and `email_poller` (whether the poller that rides on the gateway runs); the failure's own text stays out, since the route is open to anyone, and goes to the log and the owner's notice on Home. A hosted instance whose gateway never came up used to answer `ok` here with no email going out or in. Only `[]` asserts the tools are present, so a probe that died cannot read as healthy; Setup status says which of the three `null` means. |\n| `version` | `GET /version` | The running version, the latest release on GitHub and `update_available`, for Settings → About. The GitHub answer is cached 6h, only a semver `tag_name` is used and the release link is built from it; `UPDATE_CHECK_ENABLED=false` skips the call and still returns the running version. No in-app updater: upgrading is host-side (`docs/deployment.md#upgrading`). |\n| `setup_status` | `GET /setup/status` | Settings → Setup status: one light per part of the install — AI model, company setup, owner, the Executive's address, API protection, Gmail, your own mailbox (Act as me), Slack, Discord, Telegram, Google Chat, the scheduler, the daily brief (when and where it goes) and Honcho — as `{checked_at, checks: [{id, label, state, summary, fix, link, last_activity}]}`, where `state` is `ok`, `warn`, `error` or `off` (optional and not set up), `fix` says what to do in plain language, `link` is an in-app page that helps (`/people`, `/onboard`) and `last_activity` is the channel's latest `integration_inbound` audit time. It tests live, with at most one free read-only call per service, each bounded to 5 s: Anthropic `models.list` (so an organisation key missing `ANTHROPIC_WORKSPACE_ID` shows up), Slack `auth.test`, Telegram `getMe` and `getWebhookInfo`, Discord `users/@me` only while the bot is still connecting, and — once the owner's own Gmail credential exists — Google's token refresh and Gmail `users/me/profile`. It also reads the listeners the lifespan leaves on `app.state` (Slack's socket, the Discord bot and its task, the MCP gateway), the scheduler heartbeat and the pause switch. When `google_workspace` is configured, the lifespan also starts `MCPGateway.prime_pinned_tools()` in the background (held on `app.state.mcp_prime_task`, cancelled at shutdown), so the pinned Google tools named in the prompt are callable without a search. With `DRIVE_SYNC_ENABLED` the lifespan also bootstraps the `drive_sync_scan` heartbeat beside Notion's (see Scheduler); the Drive folder sync has no HTTP route, only the `openexecutive sync-drive` / `purge-drive` CLI. With `CONFLUENCE_SYNC_ENABLED` it bootstraps the `confluence_sync_scan` heartbeat the same way; that sync is run by hand with `openexecutive sync-confluence` / `purge-confluence`. Sample values copied from `.env.example` are named as such without being sent anywhere. No token reaches a response or a log line: probes report a status code, a service's short error code or an exception's class name. Requests within 5 s of a run get that run's answer and concurrent requests share one run (kept per app on `app.state`), so the button can't become a stream of calls to those services. Gated like every other route; the UI adds a sign-in light of its own, from its own settings. |\n| `documents` | `POST\\|GET\\|DELETE /documents`, `GET /documents/{filename}`, `GET /documents/sources`, `POST /documents/sources/{drive\\|onedrive\\|notion}/sync`, `GET /documents/{drive\\|onedrive\\|notion}`, `GET /documents/{drive\\|onedrive\\|notion}/{id}` | Upload, list, view extracted text, and delete indexed company docs. `GET /documents` rows carry `source: \"upload\"` and the `domain` the upload was indexed under. The connected-source routes back the knowledge page's single Company documents list: `/documents/sources` gives each source's `{id, label, enabled, syncing, last_run, last_error, interval_minutes, file_count}`; `/documents/drive`, `/documents/onedrive` and `/documents/notion` list synced files from the sync state (`{enabled, last_run, last_error, files: [{id, name, url, modified_at, synced_at, indexed}]}`); `/documents/{drive\\|onedrive\\|notion}/{id}` returns the stored text (a OneDrive id is `<drive id>:<item id>`) for an id on record (the path comes from the state, never the caller). They are read-only — a synced file is removed where it lives. `POST …/sync` starts one tick of the same sync the scheduler runs as a background task (202); 409 when the source is not connected or a tick is already running (every sync holds a per-process run lock, so a manual run never overlaps the heartbeat; the route also keeps its own started task per source and re-checks just before starting one, so two simultaneous requests start one tick, not two), 429 with `Retry-After` within 60 s of the last successful run or of the end of the last tick in this process, failed ones included, so a failing or slow source can't be re-run back-to-back. The page's text view never loads images from synced content (a remote image would be a read beacon for whoever edits the shared folder). Upload is keyed on the filename, so re-uploading a document replaces its chunks rather than duplicating them, and `DELETE` removes the rows as well as the file. `domain` must be one of the nine specialist domains (including `sales`) or `general`; anything else is a 400 rather than a 200 that indexes where no specialist can retrieve. A scanned PDF is converted (`knowledge.pdf_reader`) before it is indexed and in the text view, as are scanned PDFs in `POST /chat/upload` and the client / onboarding intake uploads. The upload is streamed to disk 1 MB at a time and refused with a 413 once it passes 50 MB, and the file is parsed in a short-lived child process (see the RAG section), so a large document does not stay in the API process's memory. A Word or Excel file that cannot be parsed, or whose parse runs out of time, is a 422 with a readable reason. When every parser is busy, the response is a 503 with `Retry-After`. |\n| `executive` | `GET /executive/status`, `POST /executive/pause`, `POST /executive/resume` | Operator pause switch for all autonomous work (scheduler, Gmail poller, workflow resumer); inbound chat and DMs stay live. Status returns `{paused, paused_at, paused_by, reason, held_actions, can_resume}` — `held_actions` counts due `pending` rows that fire on resume. `pause` takes an optional `reason` (≤200 chars) and is idempotent (re-pausing keeps the original start and reason); `paused_by` is the UI proxy's `x-caller-email`, else `api`. Behind the shared-secret middleware — not `SCHEDULED_ADMIN_TOKEN`, which the UI cannot send. Any caller may pause; `resume` is principal-only (`is_principal_or_self`, 403 otherwise; open while no principal is rostered; a header-less caller resolves to the principal as in `chat`), and status carries `can_resume` for the viewer so the UI hides Resume from everyone else. |\n| `workspace` | `GET /workspace`, `PUT /workspace` | Solo/team mode, the user's time zone and the principal's role (`memory.workspace_settings`). Both return `{mode, timezone, effective_timezone, role_kind, role_title, reports_to, remit, measured_on, company_domains, company_domains_custom}` — `timezone` is what the user set (null when unset), `effective_timezone` the zone in effect (`timezone`, else `USER_TIMEZONE`, else UTC), and each role field is null until set. `PUT` is a partial update: only the fields sent change; `mode` is `solo` or `team` (not null), `timezone` an IANA zone, or null/blank to clear it; `role_kind` is `owner`, `in_house`, `independent` or `other`, and `role_title` / `reports_to` / `remit` / `measured_on` are free text (trimmed, at most 120 / 120 / 500 / 300 characters), each null or blank to clear it; an unknown zone, a bad mode or role kind, an over-long role field or an unknown field is a 422 and changes nothing. Switching to solo cancels every pending department check-in, switching to team re-schedules them, and a new zone re-times the pending briefs and reflection; a role change has no side effects (the next turn reads it). `company_domains` is the company's own email domains (a teammate matches by local part on them — see Org): `GET` returns the ones in effect (the stored list, or the domain of the principal's primary address, with `company_domains_custom` false) only to the same caller the role is shown to, `[]` for anyone else; `PUT` takes a list (at most 10 plain domain names, never a free-mail provider's — 422 otherwise, the value never quoted) or null / `[]` to go back to deriving them, and a change is audited with the new list. Each change writes a `workspace_settings_changed` audit row (a role change adds `details.role_fields_changed`, the names of the fields that changed — never their text). The role is the principal's: `GET` returns it only to a caller `PUT` would accept and reads it as nulls for anyone else. `PUT` is the principal's alone (`is_principal_or_self`, 403 otherwise; a header-less caller resolves to the principal as in `chat`) and open while no principal is rostered, so first-run setup can pick a mode. Both work before onboarding — unlike `company-profile`, nothing here needs a profile. |\n| `scheduled` | `GET\\|DELETE` scheduled actions (`?status=…&order=asc\\|desc`) | Pending and fired scheduled actions; `order` flips the `run_at` sort (asc=soonest-first for the upcoming queue, desc=most-recent-first for terminal-status history). `DELETE /scheduled/{id}` cancels a `pending` row (409 otherwise). Like pause it only stops work, so any signed-in user may — the UI proxy's `x-caller-email` is trusted when the request also carries the `BACKEND_SHARED_SECRET` `x-api-key` — as may a matching `X-Admin-Token` (`SCHEDULED_ADMIN_TOKEN`) or a loopback caller with no token set; otherwise 401 (token set) or 503. Audited as `scheduled_action_cancelled`. |\n| `watchlist` | `GET\\|POST\\|PATCH\\|DELETE /watchlist`, `POST /watchlist/{slug}/approve`, `POST /watchlist/{slug}/decline` | External-monitoring watchlist + signals. Rows carry `origin` (`manual` \\| `executive` \\| `research` \\| `research_proposed`); `approve` turns a research suggestion (`research_proposed`, `dry_run`) into a live watch, `decline` `{reason: not_relevant \\| too_noisy \\| wrong_source}` removes it and records the decline (or, for `too_noisy`, keeps it live at a high floor), both 409 unless the row is a pending suggestion; `DELETE ?reason=` on a research-origin row records the decline too. |\n| `workflows` | `GET /workflows`, `POST /workflows/{name}/runs`, `GET\\|POST\\|PUT\\|DELETE /workflows/custom`, `GET\\|DELETE /workflows/custom/{name}/targets`, `POST /workflows/runs/{run_id}/decision`, `GET /workflows/tools/search?q=`, `GET /workflows/tools/describe?names=` | Workflow catalog, run management, and user-created (dynamic) workflow CRUD. Custom definitions come back with a server-managed `owner_person_id` (the creator — the web caller on `POST`, set on insert only; a client-sent value is ignored), who is asked to approve a workflow's first write to a new target. `GET /workflows/custom/{name}/targets` lists the targets its tool steps may write to without asking and `DELETE …/targets?value=` forgets one. `POST /workflows/{name}/runs` is a 403 (\"Only the principal can run this workflow.\"), audited, before any run row exists, when the workflow is one only the principal may start in the workspace's mode (`weekly_review` always, `morning_brief` in solo) and the caller is not the principal. A request with no `x-caller-email` counts as the principal; with no principal on the roster, no signed-in caller does. This governs starting a run only. A run started by hand (this endpoint, or `run_workflow` / research in chat) records its starter as `owner_person_id` and is theirs alone: `GET /workflows/runs` lists the team's (scheduled, no owner) runs plus the caller's own and the ones waiting on them, and `GET` / `DELETE /workflows/runs/{run_id}` and `POST /workflows/runs/{run_id}/decision` are a 404 for anyone else's, the principal included. A signed-in email that is on nobody's People entry cannot start one (403), and a run whose starter can't be read is refused (503); its steps read and draft documents as the starter only. `POST /workflows/runs/{run_id}/decision` with `{decision: \"approve\"|\"reject\"}` answers a run awaiting a yes/no sign-off from the web app — 403 unless the caller is the person it waits on or the principal, 409 if it isn't awaiting or needs a written reply — through the same `apply_resolution` a chat reply uses. Custom create/update also rejects (422) any action-step tool that does not resolve, and so does `POST /workflows/custom/{name}/activate` when turning a workflow **on** — that click is the approval for a tool workflow chat saved switched off (turning off is never checked). Turning on a workflow with action steps requires the body `{is_active: true, definition}` carrying the definition the user reviewed; if the stored one differs (ignoring `is_active` and timestamps) it returns 409, and the switch itself is a compare-and-set on the validated revision (`dynamic_store.activate_if_unchanged`, keyed on `updated_at`), so a save that lands while the tool check awaits the gateway — even from another process — is a 409 too, so only what was shown gets switched on. `GET /workflows/custom` lists inactive definitions too; `GET /workflows/{name}` 404s for them. The two `tools` endpoints return `{tools: [{name, description, read_only, source}]}` for the advanced editor's tool picker and the review card; `read_only` is true only when the name says it reads (a label, not a control). The run stream adds a `progress` event (`step_id`, `summary`) while an action step uses tools. Each catalog entry (`WorkflowMeta`) carries `is_custom`, `background` (true for the system-run built-ins the UI files under “System”) and `quick` (true for a Quick workflow, one per playbook nothing else follows, named `quick_<playbook>`). The run endpoint streams SSE; its `awaiting_human` event carries `delivery` (`self` \\| `sent` \\| `suppressed` \\| `alerted` \\| `failed`) alongside `person_id` / `question` / `awaiting_until`, because the outbound guard or an unreachable approver means the question may never have been asked — a client must not render “waiting on them” for those. A paused run ends the stream with neither `done` nor `error`, so that `awaiting_human` frame carries `terminal: true` to say so explicitly, plus `resumable` — whether the run continues by itself once answered or stops at the gate. `GET /workflows/runs/{run_id}` returns the run row with the resume payload replaced by a small `resume_progress` summary (`gate_step_id`, `completed_step_ids`, or `null`): the payload holds every completed step's full text, and the run-detail page polls this endpoint while a run is unfinished. |\n| `knowledge` | `/knowledge/builtin`, `/external`, `/search` | MBA knowledge base and external sources. `/search` is the introspection parallel of `retriever.retrieve` and mirrors its filters — including the `general` catch-all on the company collection — so the panel cannot report a specialist seeing nothing that it does retrieve in chat. It accepts `general` in `domain_filter` for the same reason. `/search` applies the same review gate as `retrieve()` — withheld (pending or rejected) built-in, external and failure rows are dropped, so the panel never advertises knowledge the Executive cannot use; it degrades to unfiltered rather than failing if review state is unreadable. `POST /knowledge/builtin` refuses a name already held by shipped content, and `POST|DELETE /knowledge/failures` now register and deregister for review — without that a user-authored failure case study had no review row, so no SME decision could block it. |\n| `skills` | `/skills`, `/skills/search`, `/skills/{name}/restore` | Skill registry (the UI's **Playbooks**) CRUD and search. `PUT` on a built-in saves a company customization that shadows it; `DELETE` returns `{name, outcome}` — `deleted`, `reverted` (customization removed, built-in back) or `hidden` (built-in hidden for this company); `restore` un-hides; `GET /skills?include_hidden=true` lists hidden built-ins. List and detail carry `used_by` — `[{name, title, is_custom}]` of the workflows that follow the playbook (switched-off custom ones included) (`WorkflowMeta.playbooks` is the other direction). |\n| `evals` | `/evals/scenarios`, `/evals/runs` | Eval scenarios and run results. `POST /evals/runs` is a 403 when a workflow scenario names a workflow that only the principal may start in the mode it runs in (the weekly review; the morning brief in solo) and the caller is not the principal — the Jobs page's rule for starting a run; stored results are read under the existing `/evals/runs` rules. |\n| `memories` | `/memories/{decisions,initiatives,advice}`, `GET /memories/facts`, `POST /memories/facts/{fact_id}/{retire,approve,decline}`, `GET /memories/facts/approval`, `PUT /memories/facts/approval/{person_id}`, `GET /memories/people`, `GET /memories/people/{person_id}/conclusions` | Episodic-memory record management; the standing facts the Pulse Corrections tab reads (`{facts: [...], can_retire, retirable_ids, can_review}`; each fact carries `recorded_by_role` / `recorded_by_name`; `?include_inactive=` default true, honoured for the principal only; anyone else gets the active rows plus their own `proposed` ones, with the provenance (`session_id`, `turn_id`, `recorded_by_person_id`, `retired_reason`, and `source_quote` except on their own facts) blanked, never retired, replaced or declined text; `?limit=` 1–500) and their retire (the principal any fact, a teammate only one they recorded that the principal has not approved — else 403; the audit row names the teammate; 404 for an unknown or `profile` row, 409 when no longer active; writes a private `fact_retired` audit row); approve / decline a teammate's `proposed` fact (principal only, else 403; 409 when it is not proposed; private `fact_reviewed` row); and the per-teammate \"needs my approval\" switch (on by default; `GET` lists `[{person_id, full_name, needs_approval}]` for every active team member but the principal, `true` for anyone not yet set; `PUT` takes `{needs_approval}`, 404 for anyone else; both principal only; private `fact_approval_changed` row); plus the read-only peer-memory overview the Pulse People tab reads (`{status: ok|disabled|error, people: [...], conclusion_total}`; `?recent=` 1–50, default 5) and one person's full conclusion list, paged newest first (`{status, person_id, items, page, size, total, has_more}`; `?page=` ≥1, `?size=` 1–100, default 50; 404 when the person has no peer). Peer memory is each person's own: the overview holds only the caller's entry (none for a caller off the roster; `conclusion_total` counts only theirs), the principal included, and `/conclusions` for anyone but the caller is a 404. |\n| `review` | `/review/items`, `/review/stats`, `/review/trusted-defaults`, `POST /review/curate`, `POST /review/bulk-approve` | Knowledge review queue and annotations. Shipped knowledge registers as a trusted default (`approved` with a NULL `reviewed_at`), so the queue starts empty; `curate` (`{domain, action: start|stop}`, domain required) opts one domain in or out, and `trusted-defaults` returns domain → unreviewed count. `bulk-approve` takes a non-empty `domain`, `item_ids` (max 500) or `all_pending: true`, and 400s with no selector; it returns `{approved_count, item_ids}`. |\n| `onboarding` | `/onboard/interview/understand`, `/onboard/interview/start`, `/onboard/interview/message`, `/onboard/interview/draft`, `/onboard/interview/{id}`, `/onboard/interview/commit` | Conversational company setup. The `onboarding_interviewer` agent asks clarifying questions, then emits a draft profile + people + departments. **Nothing is persisted until `POST /onboard/interview/commit`** — the interview itself never writes. `start` is multipart (description + optional deck/one-pager uploads). `commit` answers 403 when the draft would make a different person the owner and the caller is not the current owner (setup demotes the old principal, and any signed-in user can open it). It also takes an optional `owner_email` — the principal's sign-in email, which the review screen pre-fills from the signed-in user — checked before anything is written (422 if it is malformed, already another person's, or would replace the principal's existing email — setup only fills in a missing one; 403 if the caller is not the owner and it is not the address they signed in with, since the roster is the sign-in allow-list) and saved on the principal's People row, so the owner's chats resolve to them from the first turn. |\n| `workflow_designer` | `POST /workflows/designer/start`, `POST /workflows/designer/edit`, `POST /workflows/designer/message`, `POST /workflows/designer/draft`, `GET /workflows/designer/{session_id}` | The conversational New workflow wizard, and editing a saved workflow by conversation. `/edit` (`{name}`) opens a session on a saved custom workflow with no model call: the stored definition is the starting draft, and every response then carries `editing` (its name) and `original` (the stored definition as the session opened on it); drafts keep that name and its on/off state whatever the model writes (404 for an unknown workflow). The UI saves one with `POST /workflows/custom/{name}/save-edit` (`{session_id, definition}`): the server saves the session's own draft, never a client-sent body, and only when it equals the `definition` the user reviewed (a later message is a 409, so the click saves only what was shown); it re-validates it, keeps the stored on/off state, and writes only if the stored workflow is still the version the conversation opened on — otherwise 409, as it is for a session about another workflow or one with nothing drafted yet. It sits under `/workflows/custom` so anything that limits writes to custom workflows covers it too. The `workflow_designer` agent asks clarifying questions (`phase: \"question\"`, with `hint` and up to four suggested `options`), then returns `phase: \"draft\"` with `draft.definition` (exactly the body `POST /workflows/custom` takes), `summary`, and `assumptions`; every response carries the `transcript`. **Nothing is persisted here** — sessions are in memory, and the UI saves through `POST /workflows/custom`. Errors are fixed strings (422 over the 8,000-char message cap or the transcript cap, 404 for an expired session, 409 while another turn on the same session is still running, 502/504 for model failure or timeout). Mounted ahead of the `workflows` router. |\n| `python_jobs` | `GET /python-jobs/{job_id}/{name}` | A result file a Python job (`run_python_job`) wrote, the principal's alone (403 otherwise), served as a download (`Content-Disposition: attachment`, `Content-Security-Policy: sandbox`, `nosniff`, `Cache-Control: no-store`); 404 for a bad id or name or a file past its 7 days. |\n| `saved_tools` | `GET /saved-tools`, `GET\\|PUT /saved-tools/{name}`, `POST /saved-tools/{name}/rollback` | The scripts the Executive saved as tools (Settings → Advanced → Saved tools), the owner's alone (403 otherwise). The list gives each tool's name, description, on/off, current version, `kind` (`script` or `python`, a kept Python job) and the tools it calls, plus whether `SAVED_TOOLS_ENABLED` is on; the detail adds the script, every version and the last 20 runs. `PUT {enabled?, workflows?, version?}` turns one on or off (off also turns it off for workflows, so turning it back on never re-arms unattended runs), and turns the named `version` — the one the owner looked at, never whatever is current by then — on for workflows (or workflows off); a Python tool never turns on for workflows (409) — turning workflows on lets more run unattended, so it needs a request tied to the owner (signed sign-ins or local login, as Take the lead's switches do; 409 otherwise); `rollback {version}` makes that version the one that runs. Both are audited as `saved_tool_changed`. The Executive saves tools itself through `run_script`; there is no create route. |\n| `onboarding` (fallback) | `/onboard/start`, `/onboard/answer`, `/onboard/status/{id}` | The original 12-step form wizard, kept as a fallback (UI at `/onboard?mode=form`) and used by the `openexecutive onboard` CLI. Its final answer saves the profile and adds people with their emails and a principal, so once there is an owner only they can send it (403, and the session rolls back so the owner can still finish it). `/onboard/start` reads the workspace mode once for the session: solo skips the Team Size, Team Members and Fractional Executives steps. Each status response's `current_step` / `total_steps` count only the steps that session asks, and `optional` says whether the current step can be skipped. |\n| `company-profile` | `GET\\|PATCH /company-profile` | Structured company profile. |\n| `alerts` (private cards) | `POST /alerts/{id}/ack`, `/reopen`, `/alerts/bulk-ack` | An alert tagged `private:principal` (see Today) is a 404 on ack and reopen for anyone but the principal, and their bulk sweep skips it. A roster-request card (source `roster_request`) is a 409 on `ack` even for the principal — it is answered at `/people/requests/{id}`, since acking would leave the sender waiting with nothing to show it — and, as an exempt source, `bulk-ack` and `reopen` skip it. |\n| `auth` | `GET /auth/allowed-emails` | Non-archived **team members** with an email, offered to the UI's sign-in gate — a contact is never on it, so adding a client to reach them by email no longer lets them sign in. The gate takes the **union** of this roster and its own `ALLOWED_EMAILS` env list, so env entries always work (and are checked first, short-circuiting the fetch) and roster entries are additive — a roster change can never revoke a configured operator. With local login (`make dev` with Google sign-in not set up — the UI then listens on 127.0.0.1 only) the UI signs in without an email, sends no `x-caller-email`, and the backend resolves the caller to the principal, as it does for the CLI. |\n| `fixtures` | `/fixtures`, `/fixtures/{name}/load` | Demo-company fixture load/reset/snapshot. `POST /fixtures/reset` leaves no departments, like a new install (`departments_seeded` is always 0). |\n| `clients` | `/clients`, `/clients/generate`, `/clients/cockpit`, `/clients/save`, `/clients/{slug}/activate` | Client-company slots — multi-client mode for fractional use; create from current/blank/AI-generated intake draft (pasted notes and/or file attachments, multipart on `/clients/generate`), save-back switching, engagement metadata (PATCH), cross-client cockpit, delete. See the Client Companies section. |\n| webhooks | `POST /webhook/telegram`, `POST /webhook/google-chat`, `POST /webhook/slack` | Inbound integration callbacks (self-verified). `/webhook/slack` answers 503 unless `SLACK_SIGNING_SECRET` is set. |\n| MCP server | `POST\\|GET /mcp` | Open Executive exposed as an MCP server (Streamable-HTTP). Not a router — a mounted FastMCP sub-app. Same shared-secret gate (`x-api-key`); exposes company context as resources and the specialist council as tools. See the MCP Server section. |\n\n**Take the lead** (`api/routes/take_the_lead.py`): `GET /take-the-lead` returns the As the Executive switch, its six Ask first switches (`{kind, label, hint, on}`, the hint a plain line on what each one catches), the company's rules, whether this server can tie a change to the owner (`available`), and whether the Executive is paused. `PUT /take-the-lead` takes `{enabled?, ask_first?}`, and `POST /take-the-lead/rules` / `DELETE /take-the-lead/rules/{id}` add or remove a company rule (`{kind: person|domain|words|amount, value}`, 422 on a bad one). All four are the principal's alone (403). Anything that lets more happen on its own (turning it on, turning an Ask first off, removing a rule) needs a caller the API can tie to them (`delegation.verified.caller_refusal`, else 409). `GET /today/activity` adds `took_the_lead` rows (what Take the lead did, named, not quoted) and, for the caller alone, `sent_as_you` rows for what Handle it for me sent as them. Under `/delegation`: `PUT /delegation/take-the-lead {enabled}` is Take the lead as you (the owner's only for now; turning it on turns Handle it for me on), and `GET|POST /delegation/take-the-lead/rules` and `DELETE …/rules/{id}` manage the caller's own rules. `HandleItOut` gains `lead` and `lead_available`. A `take_the_lead_action` decision is approved or rejected through the existing `/decisions/{id}/approve|reject`. Training: the response also carries `training` (In training: everything waits unless allowed), `learned` (`{id, label, feature, example, uses, created_at}`: what it was allowed, the edit kept as an example by field) and `suggested` (`{key, label, approvals}`); `PUT` takes `training?` too, and leaving training while on needs the same provable owner as turning it on. `POST /take-the-lead/learned {key}` allows a current suggestion (404 for anything else; provable owner), `DELETE /take-the-lead/learned/{id}` makes it ask first again. `learned` also lists the owner's own Act as me senders (`feature` `act_as_me`), never anyone else's, and Remove works on those too. On a `take_the_lead_action` card, `POST /decisions/{id}/approve` takes `edits.input` (the card's editable fields, 422 for any other; the principal's alone, 403 for an area approver) and `edits.allow: true` (a training card only, 422 otherwise; the principal from a provable request, 403 otherwise), finishing `approved_with_edit` when a field changed.",
"mermaid": null,
- "generated_at": "2026-10-12T18:43:44Z"
+ "generated_at": "2026-10-13T11:57:15Z"
}
diff --git a/packages/core/openexecutive/architecture/prebuilt/caching.json b/packages/core/openexecutive/architecture/prebuilt/caching.json
index ed8f286c..db260f07 100644
--- a/packages/core/openexecutive/architecture/prebuilt/caching.json
+++ b/packages/core/openexecutive/architecture/prebuilt/caching.json
@@ -1,7 +1,7 @@
{
"section_id": "caching",
"title": "Prompt Caching",
- "markdown": "The Executive system prompt is partitioned for Anthropic prompt caching by `openexecutive.prompts.cache_manager.build_system_blocks`. It emits at most two `cache_control` blocks, consolidated down from four to stay within Anthropic's 4-block API limit alongside the tool definitions and the agent loop's intra-turn marker.\n\n- **Block 0 — persona + knowledge (1h TTL, always present):** the executive persona constant — `EXECUTIVE_PERSONA_PROMPT` for a team, `EXECUTIVE_PERSONA_SOLO_PROMPT` in solo mode — or an admin override, which wins as-is in either mode, with the `{VOICE_PERSONA}` substitution, then the admin's Council **additional instructions** for the Executive (`persona_instructions`, wrapped in `<additional_instructions>`; blank leaves the block byte-identical, and like the override it changes only on save), conditional `WEB_SEARCH_ADDENDUM` / `MCP_ADDENDUM`, the constant `TOOL_BUILDING_ADDENDUM` (when to build a tool with `run_script`, check `list_saved_tools` first, keep what will be needed again, and talk about it without saying \"script\"; present with a gateway unless `CHAT_SCRIPTS=false`, a setting, so constant per deployment), the identity addendum (exec name/email, impersonation guard), the *Connected Systems* section (whose Google part is derived from `WORKSPACE_MCP_TOOLS` and `WORKSPACE_MCP_TOOL_TIER` — process-constant settings, so it is as cacheable as the rest), the constant `DELEGATION_ADDENDUM` while anyone on the install has Act as me on, the timezone addendum, and `KNOWLEDGE_INDEX_SUMMARY`. The timezone addendum names the user's zone, read fresh on every build from the workspace settings (`memory.workspace_settings.get_user_timezone`: the workspace's zone, else `USER_TIMEZONE`, else UTC). Every component is a constant or changes only when an admin or the user changes a setting, so the TTL is long. Setting a new time zone changes the addendum, so the 1h block misses once on that change and is warm again from the next turn — accepted, since a stale zone would mis-schedule follow-ups. Act as me works the same way: its addendum is keyed on the install-level setting (`delegation.settings.block0_delegation_on`), never on the turn or the speaker, so switching it on or off misses the 1h block once; off, block 0 is byte-identical to an install without the feature.\n The *Connected Systems* section (`prompts.connected_systems.render_connected_systems`) tells the model what is connected so it never has to discover it: Google Workspace on or off (on only when `google_workspace` is among the servers the running gateway started with, `MCPGateway.server_names`, so a gateway that failed to start never reads as connected), and when on, how to act from its own account plus the pinned Google tool names by service (`GOOGLE_TOOL_MANIFEST`: Gmail, Calendar, Drive, Docs, Sheets, as workspace-mcp 1.29.0 names them) to call directly; any other configured MCP servers by name (`_comment` keys skipped); Slack / Discord / Telegram / Google Chat on or off from their settings (names only, never a token); Notion knowledge sync; a Confluence knowledge sync line only when that sync is on (a setting, so constant per deployment); and one constant Act as me line that points at `DELEGATION_ADDENDUM`, so switching Act as me still changes block 0 by that addendum alone. The \"never ask which address to send from\" guidance lives here now, shown only while Google is connected; the identity addendum keeps the name, address and impersonation guard. Every input is fixed per process and the output is sorted, so block 0 stays warm; it is appended even under a persona override. It replaces what the model used to learn from `search_tools`, an uncached proxy whose results were gone by the next turn.\n- **Block 1 — company + org (5m TTL, only if non-empty):** `company_profile.to_prompt_block()` plus `render_org_block(mode=…)` — for a team: departments, heads, principals, charters and the People roster; in solo: the principal's own line, their role lines when set (a static lead-in marking the role private to the principal, then kind in plain words, title, reports to, remit, measured on — from the role pinned for the turn: the workspace settings, or a session's `principal_role` override), and their goals grouped by area. The role is set once per install and changes only when the principal edits it, so it is as stable as the rest of the block. Shorter TTL so org edits propagate quickly. The principal's contacts are private to them, so `build_system_blocks(include_contacts=...)` adds the `## Contacts` section, after the team or solo block, only on the principal's own verified turn (`executive._contacts_in_prompt`). That gives block 1 exactly two stable variants per mode — with and without contacts — and never anything per-request; every other turn's block is byte-identical to an install with no contacts.\n\n## Solo mode: one prefix per mode\n\nSolo mode — one person using Open Executive for themselves — changes three cached parts, all resolved **once per turn** by `pin_turn_workspace_mode(session)` (the session's override, else the workspace setting) so they always agree: the block-0 persona, the block-1 org block, and the tool list, which drops `send_company_broadcast`, `send_department_message` and `set_department_head` *before* the sort, so it stays sorted and keeps its 1h marker on the last tool. The resolved mode is pinned on the session for the rest of the turn, so the tool handlers use it too and a switch made mid-turn applies from the next turn. Every part is a constant or stable per install, so each mode keeps its own warm cache and switching modes misses once.\n\nThe two personas share most of their text. `prompts/executive_persona.py` holds plain string literals — a shared head, body and tail plus team or solo sections — concatenated at import and never formatted, so both prompts are constants. The team prompt is byte-for-byte what it was before the split; a test pins its sha256.\n\nTool schemas are static: nothing in a definition depends on company data — `create_goal` takes its area as free text rather than an enum of the current departments, which would change the cached tool prefix every time an area was added, and `record_decision_outcome` takes a plain decision id. The solo persona is still one constant: its goal and decision-outcome lines (`_SOLO_CREATE_GOAL`, `_SOLO_DECISION_OUTCOME`) are literals concatenated at import, and the team persona is byte-identical (a test pins its sha256). The scheduler's proactive-trigger run (a Session marked `unattended`) is sent the list without `schedule_tools.UNATTENDED_WITHHELD_TOOLS`, so it has a stable tool prefix of its own, as each mode does. So does a turn private to the principal (`Session.private_to_principal`: mail from one of their contacts, or mail they forwarded): it is sent the list without `schedule_tools.PRIVATE_TURN_WITHHELD_TOOLS`, dropped before the sort, so private turns in a mode share one sorted prefix with its marker on the last tool. Act as me adds tools rather than dropping any: on a turn `delegation.settings.pin_turn_delegation` offered it to (the principal's own verified, attended turn in a private conversation, with it on), `ghostwrite_email`, the four mailbox reads (`search_my_email`, `read_my_email`, `read_my_email_attachment`, `my_email_awaiting_reply`), `remind_me` and `propose_actions` join the pool together before the sort, so those turns share one more sorted prefix and every other turn's list is byte-identical to before. The offer never depends on the Gmail connection, so a lapsed token never flips the prefix. `recall_history` (Always in the loop) joins the same way, before the sort, on a turn whose speaker may read their own notes; its offer reads only their switch and the surface, never the notes themselves. The chat note-taker runs after the turn, outside the cached prompt. Tool definitions are sorted by name so their serialized order is stable across requests; the `web_search` server tool is appended after the sorted list so it never receives a `cache_control` marker. The last client tool carries the third marker (1h TTL).\n\n## Tools opened on demand\n\nThe less common tools are not in the list at all. `orchestrator.tool_groups` puts them in named groups — calendar, people, goals, watch_and_alerts, workflows, documents, messaging, skills — and `tool_groups.split` takes them out of the turn's offered tools after every filter above (mode, unattended, private turn) and before the sort, adding two small tools in their place: `open_tools(group)`, whose description names each offered group and its tools, and `use_tool(name, input)`. When the model opens a group, the loop answers with that group's tools (name, description, input schema) as a **tool result**. It never adds them to the list: the list is the start of the cached prefix, so a list that grew mid-turn would miss the cache for the tools, both system blocks and the whole history. The list is the same on every call of every turn, and a group's descriptions are paid for only on a turn that opens it. That took the direct list from about 19,500 tokens to about 6,500, re-sent on every model call.\n\n`open_tools`'s description and its results name only the tools the turn offers (`tool_groups.open_tools_tool`), so a private turn never sees a withheld tool's name. The description depends only on that set, which is fixed for each kind of turn, so each still has one stable list. A `use_tool` call is rewritten into the tool's own call, same id, before dispatch (`tool_groups.unwrap`); the model's assistant block stays as it was sent, so the result pairs with the id it used. The rewritten call meets the same guards, handler, progress events and audit rows as a direct call. `use_tool` takes only names in `tool_groups.DEFERRED`; anything else, or an input that is not an object, gets an error tool result. The everyday tools (`consult_specialist`, `propose_form_values`, people and memory lookups, follow-ups, the MCP meta-tools) stay direct.\n\n## The intra-turn marker\n\nThe fourth and final breakpoint belongs to the tool-use loop. After each iteration appends its `tool_result` blocks, `executive._apply_loop_cache_marker` moves a single ephemeral marker onto the **newest non-empty tool result**. Without it the loop caches only the static tools+system prefix, so every iteration re-sends the whole accumulated transcript at full input price — the runtime signature is `cache_read_input_tokens` pinned flat while the prompt grows iteration over iteration.\n\nThe marker **moves rather than accumulates**: each pass first sweeps every `tool_result` clean, then re-marks the newest one. A marker left in place per iteration would reach `max_iterations` breakpoints and blow the 4-block limit. Sweeping first also makes the helper idempotent — there is no bookkeeping index to drift.\n\nOn the loop's **first call** there is no tool result yet, so the same slot marks the **message being answered** instead (`executive._mark_turn_message`, 5m): the question plus this turn's context (facts, memory, knowledge excerpts). Without it the first call sends that context uncached and the second call writes the same tokens to the cache, so it is paid twice; with it the first call writes it once and later calls read it back. The marker sits on a copy of the message, never the caller's dict, and comes off (`_clear_turn_marker`) as soon as the loop marker lands on a tool result, so a request never carries both.\n\n## The history marker\n\nOnce a conversation has history, the agent loop also marks the **newest non-empty history turn** (normally the previous reply) with a **1h** breakpoint (`executive._apply_history_cache_marker`), so the next message reads the whole conversation back from cache and writes only what is new: the last exchange, this turn's context and its tool calls. History turns are rebuilt from plain text, so the previous turn's loop entries, which ended inside that turn's retrieved context and tool results, never match; without this marker every message re-wrote the whole conversation into the cache. 1h because people reply in minutes, not seconds.\n\nThe history marker takes the company block's slot: block 1 stays in the prefix, covered by the history marker, and dropping its 5m marker keeps the TTLs in the order the API requires, longer before shorter. On a first message (no history) block 1 keeps its 5m marker as before. `_build_messages` itself never marks history, so the committee revision call, which reuses those messages, keeps the plain layout. `Session.get_recent_history` moves its window's start in steps of 10 turns (keeping 20 to 30), so a long conversation's first history message, and the cached prefix with it, stays put between steps instead of shifting every turn. On the OpenRouter path the translator keeps assistant turns as typed text parts whenever a request carries the history marker (`translator._request_caches_assistant_text`), so the marker reaches Anthropic and every reply has the same shape whether or not it is the one marked. A rolling marker on every history turn used to claim a latent fifth breakpoint, which Anthropic rejects outright.\n\n**The breakpoint budget, in full:** last client tool (1h) + persona+knowledge (1h) + company+org (5m, first message only) or history (1h) + the turn's message on the first call, then the newest tool result (5m) = at most 4, longer TTLs first.\n\nRAG context is **never** placed in a cached system block — retrieved hits vary per query and would poison the cache. It is injected into the **user turn** instead. The chat surfaces (web chat, Telegram, Discord, Google Chat) cap it at `KNOWLEDGE_CHAT_MAX_CHARS` (default 6,000 characters, 0 = no cap): `retriever._fit_to_budget` keeps the closest chunks across every collection until the cap, because each excerpt is re-sent on every call of the turn.\n\nSpecialist calls follow the same rule. Each specialist caches only its static domain prompt (`BaseAgent.analyze`, one ephemeral block); everything per call — retrieved knowledge, failure cases, past decisions, department memory, the company's stage (`<company_stage>`) and, in solo mode, the principal's role (`<principal_role>`) — goes in the specialist's user turn, so the cached domain prompt is byte-identical across companies and profile edits.\n\nThe ghostwriter's call (Act as me) carries no cache markers: its system prompt is the constant `GHOSTWRITER_PROMPT` plus that person's voice block — short, and sent only when a draft is written — and the thread and the intent go in its user turn.\n\n## Tool-result bound\n\n`TOOL_RESULT_MAX_CHARS` (default 20,000 characters, about 5,000 tokens) caps a single tool result before it enters the prompt, applied at the one point every result reaches the model rather than at each producer — so it also covers specialist output, tool errors and the unknown-tool fallback, while non-model consumers (the `propose_form_values` JSON parse, the audit trail) still read the full text. A turn's results also share one reading budget, `TOOL_RESULTS_TURN_MAX_CHARS` (default 40,000 characters; 0 turns it off): once the turn's results reach it, each further result shows its first 3,000 characters and its marker says, in place of the advice to ask again more narrowly (that re-read would be cut too), that the question has read as much as it can, so the model answers from what it has and says what it could not read, and it never edits or rewrites anything from that cut result, so a partial read never becomes a lossy write. The read it needs to edit may be the one that was cut, so each question gets one full re-read (`executive._TurnReadingBudget`): repeating a cut call with exactly the same input is answered with the result the turn already has, under the per-result cap, and the marker says so while that re-read is left. The tool never runs again, because the budget cuts any tool's result and a repeated write would happen twice. After it is used, the marker says to offer the edit as its own request, which starts with a fresh budget. A turn therefore reads at most the budget plus one more result (`executive._turn_result_limit`). A specialist's answer is the analysis itself, not a read, so it neither counts nor is cut. A built tool's (`run_script`) result counts but is never cut below the per-result cap: it lists the writes that already ran, and a short cut would hide some and get them repeated. Tool discovery (`open_tools`, `search_tools`) is treated the same way, since its result is the schema the next call needs. The per-result cap is a circuit breaker, not a routine clipper: ordinary tool output (a status, an email thread, a specialist's analysis) stays under it. A long document read does not, and the marker asks for a narrower request, such as a page range or a section, because a result stays in the prompt for every remaining call of the turn. A cut result carries an explicit marker naming the tool and stating that the result is incomplete — truncating silently is worse than not truncating, because the model reads the cut text as the whole answer.\n\n**The invariant:** never put dynamic content in a `cache_control` block. A single mutating value breaks the cache and drives roughly a 10x cost increase.",
+ "markdown": "The Executive system prompt is partitioned for Anthropic prompt caching by `openexecutive.prompts.cache_manager.build_system_blocks`. It emits at most two `cache_control` blocks, consolidated down from four to stay within Anthropic's 4-block API limit alongside the tool definitions and the agent loop's intra-turn marker.\n\n- **Block 0 — persona + knowledge (1h TTL, always present):** the executive persona constant — `EXECUTIVE_PERSONA_PROMPT` for a team, `EXECUTIVE_PERSONA_SOLO_PROMPT` in solo mode — or an admin override, which wins as-is in either mode, with the `{VOICE_PERSONA}` substitution, then the admin's Council **additional instructions** for the Executive (`persona_instructions`, wrapped in `<additional_instructions>`; blank leaves the block byte-identical, and like the override it changes only on save), conditional `WEB_SEARCH_ADDENDUM` / `MCP_ADDENDUM`, the constant `TOOL_BUILDING_ADDENDUM` (when to build a tool with `run_script`, check `list_saved_tools` first, keep what will be needed again, and talk about it without saying \"script\"; present with a gateway unless `CHAT_SCRIPTS=false`, a setting, so constant per deployment), the identity addendum (exec name/email, impersonation guard), the *Connected Systems* section (whose Google part is derived from `WORKSPACE_MCP_TOOLS` and `WORKSPACE_MCP_TOOL_TIER` — process-constant settings, so it is as cacheable as the rest), the constant `DELEGATION_ADDENDUM` while anyone on the install has Act as me on, the timezone addendum, and `KNOWLEDGE_INDEX_SUMMARY`. The timezone addendum names the user's zone, read fresh on every build from the workspace settings (`memory.workspace_settings.get_user_timezone`: the workspace's zone, else `USER_TIMEZONE`, else UTC). Every component is a constant or changes only when an admin or the user changes a setting, so the TTL is long. Setting a new time zone changes the addendum, so the 1h block misses once on that change and is warm again from the next turn — accepted, since a stale zone would mis-schedule follow-ups. Act as me works the same way: its addendum is keyed on the install-level setting (`delegation.settings.block0_delegation_on`), never on the turn or the speaker, so switching it on or off misses the 1h block once; off, block 0 is byte-identical to an install without the feature.\n The *Connected Systems* section (`prompts.connected_systems.render_connected_systems`) tells the model what is connected so it never has to discover it: Google Workspace on or off (on only when `google_workspace` is among the servers the running gateway started with, `MCPGateway.server_names`, so a gateway that failed to start never reads as connected; and *needs reconnecting* instead of connected while the server is in `MCPGateway.needs_reconnect` — set when a Google tool answers with an authorization failure such as `invalid_grant` (`mcp_gateway.grant_failure`), cleared by the next answer that is not one or by `mark_reconnected` — so the model stops promising mail it cannot read; the set changing re-renders block 0 and costs one cache miss), and when on, how to act from its own account plus the pinned Google tool names by service (`GOOGLE_TOOL_MANIFEST`: Gmail, Calendar, Drive, Docs, Sheets, as workspace-mcp 1.29.0 names them) to call directly; any other configured MCP servers by name (`_comment` keys skipped); Slack / Discord / Telegram / Google Chat on or off from their settings (names only, never a token); Notion knowledge sync; a Confluence knowledge sync line only when that sync is on (a setting, so constant per deployment); and one constant Act as me line that points at `DELEGATION_ADDENDUM`, so switching Act as me still changes block 0 by that addendum alone. The \"never ask which address to send from\" guidance lives here now, shown only while Google is connected; the identity addendum keeps the name, address and impersonation guard. Every input is fixed per process and the output is sorted, so block 0 stays warm; it is appended even under a persona override. It replaces what the model used to learn from `search_tools`, an uncached proxy whose results were gone by the next turn.\n- **Block 1 — company + org (5m TTL, only if non-empty):** `company_profile.to_prompt_block()` plus `render_org_block(mode=…)` — for a team: departments, heads, principals, charters and the People roster; in solo: the principal's own line, their role lines when set (a static lead-in marking the role private to the principal, then kind in plain words, title, reports to, remit, measured on — from the role pinned for the turn: the workspace settings, or a session's `principal_role` override), and their goals grouped by area. The role is set once per install and changes only when the principal edits it, so it is as stable as the rest of the block. Shorter TTL so org edits propagate quickly. The principal's contacts are private to them, so `build_system_blocks(include_contacts=...)` adds the `## Contacts` section, after the team or solo block, only on the principal's own verified turn (`executive._contacts_in_prompt`). That gives block 1 exactly two stable variants per mode — with and without contacts — and never anything per-request; every other turn's block is byte-identical to an install with no contacts.\n\n## Solo mode: one prefix per mode\n\nSolo mode — one person using Open Executive for themselves — changes three cached parts, all resolved **once per turn** by `pin_turn_workspace_mode(session)` (the session's override, else the workspace setting) so they always agree: the block-0 persona, the block-1 org block, and the tool list, which drops `send_company_broadcast`, `send_department_message` and `set_department_head` *before* the sort, so it stays sorted and keeps its 1h marker on the last tool. The resolved mode is pinned on the session for the rest of the turn, so the tool handlers use it too and a switch made mid-turn applies from the next turn. Every part is a constant or stable per install, so each mode keeps its own warm cache and switching modes misses once.\n\nThe two personas share most of their text. `prompts/executive_persona.py` holds plain string literals — a shared head, body and tail plus team or solo sections — concatenated at import and never formatted, so both prompts are constants. The team prompt is byte-for-byte what it was before the split; a test pins its sha256.\n\nTool schemas are static: nothing in a definition depends on company data — `create_goal` takes its area as free text rather than an enum of the current departments, which would change the cached tool prefix every time an area was added, and `record_decision_outcome` takes a plain decision id. The solo persona is still one constant: its goal and decision-outcome lines (`_SOLO_CREATE_GOAL`, `_SOLO_DECISION_OUTCOME`) are literals concatenated at import, and the team persona is byte-identical (a test pins its sha256). The scheduler's proactive-trigger run (a Session marked `unattended`) is sent the list without `schedule_tools.UNATTENDED_WITHHELD_TOOLS`, so it has a stable tool prefix of its own, as each mode does. So does a turn private to the principal (`Session.private_to_principal`: mail from one of their contacts, or mail they forwarded): it is sent the list without `schedule_tools.PRIVATE_TURN_WITHHELD_TOOLS`, dropped before the sort, so private turns in a mode share one sorted prefix with its marker on the last tool. Act as me adds tools rather than dropping any: on a turn `delegation.settings.pin_turn_delegation` offered it to (the principal's own verified, attended turn in a private conversation, with it on), `ghostwrite_email`, the four mailbox reads (`search_my_email`, `read_my_email`, `read_my_email_attachment`, `my_email_awaiting_reply`), `remind_me` and `propose_actions` join the pool together before the sort, so those turns share one more sorted prefix and every other turn's list is byte-identical to before. The offer never depends on the Gmail connection, so a lapsed token never flips the prefix. `recall_history` (Always in the loop) joins the same way, before the sort, on a turn whose speaker may read their own notes; its offer reads only their switch and the surface, never the notes themselves. The chat note-taker runs after the turn, outside the cached prompt. Tool definitions are sorted by name so their serialized order is stable across requests; the `web_search` server tool is appended after the sorted list so it never receives a `cache_control` marker. The last client tool carries the third marker (1h TTL).\n\n## Tools opened on demand\n\nThe less common tools are not in the list at all. `orchestrator.tool_groups` puts them in named groups — calendar, people, goals, watch_and_alerts, workflows, documents, messaging, skills — and `tool_groups.split` takes them out of the turn's offered tools after every filter above (mode, unattended, private turn) and before the sort, adding two small tools in their place: `open_tools(group)`, whose description names each offered group and its tools, and `use_tool(name, input)`. When the model opens a group, the loop answers with that group's tools (name, description, input schema) as a **tool result**. It never adds them to the list: the list is the start of the cached prefix, so a list that grew mid-turn would miss the cache for the tools, both system blocks and the whole history. The list is the same on every call of every turn, and a group's descriptions are paid for only on a turn that opens it. That took the direct list from about 19,500 tokens to about 6,500, re-sent on every model call.\n\n`open_tools`'s description and its results name only the tools the turn offers (`tool_groups.open_tools_tool`), so a private turn never sees a withheld tool's name. The description depends only on that set, which is fixed for each kind of turn, so each still has one stable list. A `use_tool` call is rewritten into the tool's own call, same id, before dispatch (`tool_groups.unwrap`); the model's assistant block stays as it was sent, so the result pairs with the id it used. The rewritten call meets the same guards, handler, progress events and audit rows as a direct call. `use_tool` takes only names in `tool_groups.DEFERRED`; anything else, or an input that is not an object, gets an error tool result. The everyday tools (`consult_specialist`, `propose_form_values`, people and memory lookups, follow-ups, the MCP meta-tools) stay direct.\n\n## The intra-turn marker\n\nThe fourth and final breakpoint belongs to the tool-use loop. After each iteration appends its `tool_result` blocks, `executive._apply_loop_cache_marker` moves a single ephemeral marker onto the **newest non-empty tool result**. Without it the loop caches only the static tools+system prefix, so every iteration re-sends the whole accumulated transcript at full input price — the runtime signature is `cache_read_input_tokens` pinned flat while the prompt grows iteration over iteration.\n\nThe marker **moves rather than accumulates**: each pass first sweeps every `tool_result` clean, then re-marks the newest one. A marker left in place per iteration would reach `max_iterations` breakpoints and blow the 4-block limit. Sweeping first also makes the helper idempotent — there is no bookkeeping index to drift.\n\nOn the loop's **first call** there is no tool result yet, so the same slot marks the **message being answered** instead (`executive._mark_turn_message`, 5m): the question plus this turn's context (facts, memory, knowledge excerpts). Without it the first call sends that context uncached and the second call writes the same tokens to the cache, so it is paid twice; with it the first call writes it once and later calls read it back. The marker sits on a copy of the message, never the caller's dict, and comes off (`_clear_turn_marker`) as soon as the loop marker lands on a tool result, so a request never carries both.\n\n## The history marker\n\nOnce a conversation has history, the agent loop also marks the **newest non-empty history turn** (normally the previous reply) with a **1h** breakpoint (`executive._apply_history_cache_marker`), so the next message reads the whole conversation back from cache and writes only what is new: the last exchange, this turn's context and its tool calls. History turns are rebuilt from plain text, so the previous turn's loop entries, which ended inside that turn's retrieved context and tool results, never match; without this marker every message re-wrote the whole conversation into the cache. 1h because people reply in minutes, not seconds.\n\nThe history marker takes the company block's slot: block 1 stays in the prefix, covered by the history marker, and dropping its 5m marker keeps the TTLs in the order the API requires, longer before shorter. On a first message (no history) block 1 keeps its 5m marker as before. `_build_messages` itself never marks history, so the committee revision call, which reuses those messages, keeps the plain layout. `Session.get_recent_history` moves its window's start in steps of 10 turns (keeping 20 to 30), so a long conversation's first history message, and the cached prefix with it, stays put between steps instead of shifting every turn. On the OpenRouter path the translator keeps assistant turns as typed text parts whenever a request carries the history marker (`translator._request_caches_assistant_text`), so the marker reaches Anthropic and every reply has the same shape whether or not it is the one marked. A rolling marker on every history turn used to claim a latent fifth breakpoint, which Anthropic rejects outright.\n\n**The breakpoint budget, in full:** last client tool (1h) + persona+knowledge (1h) + company+org (5m, first message only) or history (1h) + the turn's message on the first call, then the newest tool result (5m) = at most 4, longer TTLs first.\n\nRAG context is **never** placed in a cached system block — retrieved hits vary per query and would poison the cache. It is injected into the **user turn** instead. The chat surfaces (web chat, Telegram, Discord, Google Chat) cap it at `KNOWLEDGE_CHAT_MAX_CHARS` (default 6,000 characters, 0 = no cap): `retriever._fit_to_budget` keeps the closest chunks across every collection until the cap, because each excerpt is re-sent on every call of the turn.\n\nSpecialist calls follow the same rule. Each specialist caches only its static domain prompt (`BaseAgent.analyze`, one ephemeral block); everything per call — retrieved knowledge, failure cases, past decisions, department memory, the company's stage (`<company_stage>`) and, in solo mode, the principal's role (`<principal_role>`) — goes in the specialist's user turn, so the cached domain prompt is byte-identical across companies and profile edits.\n\nThe ghostwriter's call (Act as me) carries no cache markers: its system prompt is the constant `GHOSTWRITER_PROMPT` plus that person's voice block — short, and sent only when a draft is written — and the thread and the intent go in its user turn.\n\n## Tool-result bound\n\n`TOOL_RESULT_MAX_CHARS` (default 20,000 characters, about 5,000 tokens) caps a single tool result before it enters the prompt, applied at the one point every result reaches the model rather than at each producer — so it also covers specialist output, tool errors and the unknown-tool fallback, while non-model consumers (the `propose_form_values` JSON parse, the audit trail) still read the full text. A turn's results also share one reading budget, `TOOL_RESULTS_TURN_MAX_CHARS` (default 40,000 characters; 0 turns it off): once the turn's results reach it, each further result shows its first 3,000 characters and its marker says, in place of the advice to ask again more narrowly (that re-read would be cut too), that the question has read as much as it can, so the model answers from what it has and says what it could not read, and it never edits or rewrites anything from that cut result, so a partial read never becomes a lossy write. The read it needs to edit may be the one that was cut, so each question gets one full re-read (`executive._TurnReadingBudget`): repeating a cut call with exactly the same input is answered with the result the turn already has, under the per-result cap, and the marker says so while that re-read is left. The tool never runs again, because the budget cuts any tool's result and a repeated write would happen twice. After it is used, the marker says to offer the edit as its own request, which starts with a fresh budget. A turn therefore reads at most the budget plus one more result (`executive._turn_result_limit`). A specialist's answer is the analysis itself, not a read, so it neither counts nor is cut. A built tool's (`run_script`) result counts but is never cut below the per-result cap: it lists the writes that already ran, and a short cut would hide some and get them repeated. Tool discovery (`open_tools`, `search_tools`) is treated the same way, since its result is the schema the next call needs. The per-result cap is a circuit breaker, not a routine clipper: ordinary tool output (a status, an email thread, a specialist's analysis) stays under it. A long document read does not, and the marker asks for a narrower request, such as a page range or a section, because a result stays in the prompt for every remaining call of the turn. A cut result carries an explicit marker naming the tool and stating that the result is incomplete — truncating silently is worse than not truncating, because the model reads the cut text as the whole answer.\n\n**The invariant:** never put dynamic content in a `cache_control` block. A single mutating value breaks the cache and drives roughly a 10x cost increase.",
"mermaid": "flowchart TD\n Tools[\"Tool defs (sorted by name)<br/>less common ones behind open_tools<br/>last one: cache_control 1h\"] --> B0\n Mode{{\"effective_workspace_mode<br/>(team or solo, once per turn)\"}} --> Tools\n Mode --> B0\n Mode --> B1\n Deleg{{\"Act as me on?<br/>(install-level, not per turn)\"}} --> B0\n Offer{{\"ghostwrite_email offered?<br/>(pinned once per turn)\"}} --> Tools\n B0[\"Block 0: persona (team or solo) + knowledge<br/>cache_control 1h\"] --> B1\n B1[\"Block 1: company + org (team or solo render)<br/>cache_control 5m on a first message\"] --> Limit{{\"≤ 4 cache_control blocks\"}}\n Loop[\"Newest tool_result<br/>cache_control 5m (moves each iteration)\"] --> Limit\n Hist[\"Newest history turn<br/>cache_control 1h (replaces block 1 marker)\"] --> Limit\n Limit --> Turn[\"User turn\"]\n RAG[\"RAG hits<br/>(vary per query)\"] --> Turn\n Turn --> API[\"Anthropic API\"]\n class B0 cache\n class B1 cache\n class RAG hot\n class Turn hot\n class Tools compute\n class Mode compute\n class Loop cache\n class API external\n class Deleg compute\n class Offer compute",
- "generated_at": "2026-10-11T16:30:20Z"
+ "generated_at": "2026-10-13T11:57:15Z"
}
diff --git a/packages/core/openexecutive/architecture/prebuilt/scheduler.json b/packages/core/openexecutive/architecture/prebuilt/scheduler.json
index 9c1d8774..f0fc3ebe 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. Each due row runs in its own task, started with no audit scope (`audit.context.unscoped_audit_rows`): a scheduled action is unattended and never part of the turn that scheduled it, so its audit rows follow the ordinary rule. 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. Solo has one kind of its own, the **weekly review** (`principal_weekly_review`, below): switching to solo seeds it (`seed_weekly_review`), switching to team cancels its pending row (`cancel_weekly_reviews`), and one that fires while the stored mode is team is marked `cancelled` without running or chaining. That check reads the mode strictly (`workspace_settings.read_stored_mode`) and fails open: a mode that can't be read (a locked database) is not taken for team, so one bad read neither retires the review nor breaks its chain — the next run checks again.\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. In a solo workspace it also seeds the **weekly review** (`principal_weekly_review`, Friday 16:00 local by default), which runs the `weekly_review` workflow and is delivered like the briefs; its `PRINCIPAL_WEEKLY_REVIEW_TIME` takes a whole weekly spec (`weekly@fri@16:00`), read as UTC when valid, like the pinned times below, and it chains only while the workspace is still solo — and never when a weekly row is already pending, so a switch to solo while a review finishes cannot leave two. 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. The weekly review follows the same rules with a 3.5-day gap (`_min_gap`) in place of 12 hours, so a zone change can neither run it twice in a week nor skip one.\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`. The same throttled call also deletes Always in the loop notes past their expiry (`memory.history.sweep_expired`; reads already skip them, and it never raises). Each tick also calls `_maybe_remind_notes` → `memory.history_reminders.maybe_remind` (its own 15-minute throttle, 09:00–18:00 local, one task at a time): a person whose notes say something they promised by email is due today gets one message saying how many, through `deliver_to_person` — the brief's own channel order for any Person, never a shared channel (`delivery_order` now skips a Telegram group id, for the briefs too), with the senders' audit rows private to that person. A hook rather than a `scheduled_actions` row, which `/scheduled` would show to everyone (see Memory).\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\nThe /today **\"What's going on\" header** is kept current from the tick too, so it is fresh before anyone opens the page. `_maybe_refresh_narrative` is a throttled call inside the loop, like the alert sweep — no `scheduled_actions` row. It runs after the pause, company-profile and rotation gates, every `BRIEFING_NARRATIVE_REFRESH_MINUTES` (10; 0 turns it off) and only between `BRIEFING_NARRATIVE_REFRESH_START_HOUR` and `_END_HOUR` (06–22) in the user's zone. It starts `today.refresh_principal_narrative` as its own task, so a slow model call never holds the tick, and never starts a second while one runs. That refreshes the cached calendar read (`live_signals.refresh_calendar`, at most once per 15 minutes) and rewrites the principal's header only when its key moved — new mail, a held reply, a proposal, the hour — with the route's own per-scope lock, so a page view and the tick never write the same header twice (see Today).\n\nAct as me's **reminders** are loop-level too: `_maybe_send_reminders` starts `delegation.reminders.maybe_send` at most once a minute, which claims each due `delegation_reminders` row once (due times are stored in UTC, so they compare in order) (compare-and-set on `claimed_at`) and sends its stored text, prefixed \"Reminder you set on <date>:\", to the person who set it alone through `deliver_to_person`. No model and no tool run; a reminder missed by more than two days is dropped rather than sent late, and one due in the person's quiet hours or leave waits, unclaimed, until they end; audit rows are private to the person. They are not `scheduled_actions` rows for the same reason as the scan below: that list is everyone's, and its rows run an Executive turn when they fire.\n\nAct as me's **inbox watcher** is loop-level the same way: `_maybe_scan_inbox`, after the same gates, starts the due scans (`delegation.inbox.maybe_scan`) as one task and never a second while one runs. A person is due every `DELEGATION_INBOX_POLL_MINUTES` (default 5) once their **Draft replies to my inbox** switch is on, unless a Gmail failure set a back-off; nobody is scanned while a client slot is active. It is deliberately not a `scheduled_actions` row: those are listed on `/scheduled` for everyone and anyone may cancel them, and a scan reads the owner's own mail. Every row a scan writes is private to the principal (see Act as Me).\n\n### Principal briefs\n\nThe `principal_brief_morning` / `principal_brief_eod` / `principal_weekly_review` 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 weekly review's outcome too — `brief_state.DELIVERY_KINDS` — so a weekly review that wasn't sent is reported the same way). The light also turns amber when a brief got through only on a backup channel, naming the one that failed. `_run_principal_brief` sets `morning_brief.PRINCIPAL_DELIVERY` for the run, because it goes to the principal alone: only then (or on the principal's own verified chat turn) does the morning brief read what is private to them. When the workflow reports `private_to_principal` on its `result` event — it did read such a row — the run history keeps `persistence.PRIVATE_RUN_ARTIFACT` in place of the text (`stored_artifact`), since `/workflows/runs` is readable by everyone signed in; the principal gets the full text where it is delivered. 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. An optional `drive_sync_scan` heartbeat (`DRIVE_SYNC_ENABLED`, off by default, bootstrapped in the lifespan beside it) does the same for the configured Google Drive folders, into the isolated `drive_docs` collection (see RAG). An optional `onedrive_sync_scan` heartbeat (`ONEDRIVE_SYNC_ENABLED`, off by default) does the same for the configured OneDrive folders, into `onedrive_docs`. An optional `confluence_sync_scan` heartbeat (`CONFLUENCE_SYNC_ENABLED`, off by default, bootstrapped in the lifespan the same way) re-indexes the changed pages of the configured Confluence spaces into the isolated `confluence_wiki` collection, leaving out restricted pages, and purges pages that were deleted, moved out or restricted.\n\n**Take the lead wakes.** With Take the lead as the Executive on, a turn from a channel (mail, Slack, Discord, Telegram, Google Chat) calls `take_the_lead.wake`, which inserts one `take_the_lead_wake` `__internal__` action five minutes out. It does nothing while one is pending or running, and nothing within 30 minutes of the last wake. The runner's `_run_take_the_lead_wake` runs the same reflection as the daily rhythm (`_reflect`, shared with `_run_executive_reflection`), only if the switch is still on, and never chains. The pause holds it like every claim.",
+ "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. Each due row runs in its own task, started with no audit scope (`audit.context.unscoped_audit_rows`): a scheduled action is unattended and never part of the turn that scheduled it, so its audit rows follow the ordinary rule. 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. Solo has one kind of its own, the **weekly review** (`principal_weekly_review`, below): switching to solo seeds it (`seed_weekly_review`), switching to team cancels its pending row (`cancel_weekly_reviews`), and one that fires while the stored mode is team is marked `cancelled` without running or chaining. That check reads the mode strictly (`workspace_settings.read_stored_mode`) and fails open: a mode that can't be read (a locked database) is not taken for team, so one bad read neither retires the review nor breaks its chain — the next run checks again.\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. In a solo workspace it also seeds the **weekly review** (`principal_weekly_review`, Friday 16:00 local by default), which runs the `weekly_review` workflow and is delivered like the briefs; its `PRINCIPAL_WEEKLY_REVIEW_TIME` takes a whole weekly spec (`weekly@fri@16:00`), read as UTC when valid, like the pinned times below, and it chains only while the workspace is still solo — and never when a weekly row is already pending, so a switch to solo while a review finishes cannot leave two. 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. The weekly review follows the same rules with a 3.5-day gap (`_min_gap`) in place of 12 hours, so a zone change can neither run it twice in a week nor skip one.\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`. The same throttled call also deletes Always in the loop notes past their expiry (`memory.history.sweep_expired`; reads already skip them, and it never raises). Each tick also calls `_maybe_remind_notes` → `memory.history_reminders.maybe_remind` (its own 15-minute throttle, 09:00–18:00 local, one task at a time): a person whose notes say something they promised by email is due today gets one message saying how many, through `deliver_to_person` — the brief's own channel order for any Person, never a shared channel (`delivery_order` now skips a Telegram group id, for the briefs too), with the senders' audit rows private to that person. A hook rather than a `scheduled_actions` row, which `/scheduled` would show to everyone (see Memory).\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\nThe /today **\"What's going on\" header** is kept current from the tick too, so it is fresh before anyone opens the page. `_maybe_refresh_narrative` is a throttled call inside the loop, like the alert sweep — no `scheduled_actions` row. It runs after the pause, company-profile and rotation gates, every `BRIEFING_NARRATIVE_REFRESH_MINUTES` (10; 0 turns it off) and only between `BRIEFING_NARRATIVE_REFRESH_START_HOUR` and `_END_HOUR` (06–22) in the user's zone. It starts `today.refresh_principal_narrative` as its own task, so a slow model call never holds the tick, and never starts a second while one runs. That refreshes the cached calendar read (`live_signals.refresh_calendar`, at most once per 15 minutes) and rewrites the principal's header only when its key moved — new mail, a held reply, a proposal, the hour — with the route's own per-scope lock, so a page view and the tick never write the same header twice (see Today).\n\nAct as me's **reminders** are loop-level too: `_maybe_send_reminders` starts `delegation.reminders.maybe_send` at most once a minute, which claims each due `delegation_reminders` row once (due times are stored in UTC, so they compare in order) (compare-and-set on `claimed_at`) and sends its stored text, prefixed \"Reminder you set on <date>:\", to the person who set it alone through `deliver_to_person`. No model and no tool run; a reminder missed by more than two days is dropped rather than sent late, and one due in the person's quiet hours or leave waits, unclaimed, until they end; audit rows are private to the person. They are not `scheduled_actions` rows for the same reason as the scan below: that list is everyone's, and its rows run an Executive turn when they fire.\n\nAct as me's **inbox watcher** is loop-level the same way: `_maybe_scan_inbox`, after the same gates, starts the due scans (`delegation.inbox.maybe_scan`) as one task and never a second while one runs. A person is due every `DELEGATION_INBOX_POLL_MINUTES` (default 5) once their **Draft replies to my inbox** switch is on, unless a Gmail failure set a back-off; nobody is scanned while a client slot is active. It is deliberately not a `scheduled_actions` row: those are listed on `/scheduled` for everyone and anyone may cancel them, and a scan reads the owner's own mail. Every row a scan writes is private to the principal (see Act as Me).\n\n### Principal briefs\n\nThe `principal_brief_morning` / `principal_brief_eod` / `principal_weekly_review` 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. Before planning, the delivery asks the gateway supervisor for a start if the gateway is down (`runner.ensure_email_ready` → `mcp_gateway.ensure_active_gateway`, the lazy re-check), and a row action resolves the gateway at execution time rather than from what boot had, so a gateway that failed at boot and came up on a retry carries the brief. The outcome names what happened: `gateway_down` when email is set up but the gateway is not running (the Executive's fault, with the start failure, never `no_channel`, which blamed the owner's setup), and a `send_failed` detail that quotes each channel's own error (`email: invalid_grant …`, `slack_dm: channel_not_found`), stored with the outcome (`brief_state.record_delivery_outcome(detail=…)`) and shown on the Briefing notice and the Setup page's *Daily brief* light, whose fix says to reconnect when the detail shows a dead grant. 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 weekly review's outcome too — `brief_state.DELIVERY_KINDS` — so a weekly review that wasn't sent is reported the same way). The light also turns amber when a brief got through only on a backup channel, naming the one that failed. `_run_principal_brief` sets `morning_brief.PRINCIPAL_DELIVERY` for the run, because it goes to the principal alone: only then (or on the principal's own verified chat turn) does the morning brief read what is private to them. When the workflow reports `private_to_principal` on its `result` event — it did read such a row — the run history keeps `persistence.PRIVATE_RUN_ARTIFACT` in place of the text (`stored_artifact`), since `/workflows/runs` is readable by everyone signed in; the principal gets the full text where it is delivered. 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. An optional `drive_sync_scan` heartbeat (`DRIVE_SYNC_ENABLED`, off by default, bootstrapped in the lifespan beside it) does the same for the configured Google Drive folders, into the isolated `drive_docs` collection (see RAG). An optional `onedrive_sync_scan` heartbeat (`ONEDRIVE_SYNC_ENABLED`, off by default) does the same for the configured OneDrive folders, into `onedrive_docs`. An optional `confluence_sync_scan` heartbeat (`CONFLUENCE_SYNC_ENABLED`, off by default, bootstrapped in the lifespan the same way) re-indexes the changed pages of the configured Confluence spaces into the isolated `confluence_wiki` collection, leaving out restricted pages, and purges pages that were deleted, moved out or restricted.\n\n**Take the lead wakes.** With Take the lead as the Executive on, a turn from a channel (mail, Slack, Discord, Telegram, Google Chat) calls `take_the_lead.wake`, which inserts one `take_the_lead_wake` `__internal__` action five minutes out. It does nothing while one is pending or running, and nothing within 30 minutes of the last wake. The runner's `_run_take_the_lead_wake` runs the same reflection as the daily rhythm (`_reflect`, shared with `_run_executive_reflection`), only if the switch is still on, and never chains. The pause holds it like every claim.",
"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 Weekly[\"principal_weekly_review (solo) →<br/>weekly_review, Fri 16:00 local\"]\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 Drive[\"drive_sync_scan →<br/>isolated Drive folder ingest\"]\n Confluence[\"confluence_sync_scan →<br/>isolated Confluence space 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 -- \"principal_weekly_review\" --> Weekly\n Claim -- \"executive_reflection\" --> Reflect\n Claim -- \"external_monitor_scan\" --> ExtMon\n Claim -- \"watchlist_research_scan\" --> Research\n Claim -- \"notion_sync_scan\" --> Notion\n Claim -- \"drive_sync_scan\" --> Drive\n Claim -- \"confluence_sync_scan\" --> Confluence\n Nudge -- \"prefer_channel_for\" --> Prefer\n Prefer -- \"emits proactive_nudge\" --> Table\n Dispatch --> Channels\n Brief --> Principal\n Weekly --> Principal\n ExtMon --> Alerts\n Dept --> Chain\n Nudge --> Chain\n Brief --> Chain\n Weekly -- \"while solo\" --> Chain\n Reflect --> Chain\n ExtMon --> Chain\n Research --> Chain\n Notion --> Chain\n Drive --> Chain\n Confluence --> 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 Weekly compute\n class Reflect compute\n class ExtMon compute\n class Research compute\n class Notion compute\n class Drive compute\n class Confluence compute\n class Chain compute\n class Prefer compute\n class Channels external\n class Principal external\n class Alerts hot",
- "generated_at": "2026-10-08T10:00:00Z"
+ "generated_at": "2026-10-13T11:57:15Z"
}
diff --git a/packages/core/openexecutive/architecture/prebuilt/today.json b/packages/core/openexecutive/architecture/prebuilt/today.json
index 627b02c2..de8703d9 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- **Private cards.** An alert tagged `private:principal` (`alerts.models.PRIVATE_ALERT_TAG` — raised on a turn about mail from one of the principal's contacts or mail they forwarded, or a meeting proposal with a contact) is in `proposals` only when the caller is the principal. `_build_today` leaves it out by default, so the end-of-day digest, the reflection and Discord's `/today` never see it, and the morning brief reads it only on a run for the principal (the scheduler's, or the principal's own verified chat turn in a conversation only they can read — see Workflows). The narrative is written from one only in the principal's own `principal` scope, which nobody else is served; the shared `company` scope an unresolved caller gets, and a teammate's scope, never are. The activity rail skips it, and the chat digest includes it only on the principal's own verified turn.\n- **Roster-request cards.** When someone not on the People list writes in (see Org and Integrations), `people.roster_requests.surface_card` raises an alert of source `roster_request` (medium, tagged `roster_request:<id>` and `private:principal`, routed to the principal), so it follows every private-card rule above. `GET /today` attaches `roster_request` to that proposal (`_roster_request_card`: channel, address or account id, the sender's sanitised and unverified name, profile email, company-domain flag, suggested kind and person, message count, whether they were acknowledged, first seen, and the held messages' first lines) while the request is still pending. The Briefing renders it as its own card (`RosterRequestCard`: add as a new person with a name and an explicit team/contact choice — pre-filled as team on a company domain — or \"someone already on the list\", with a replace-account option for a chat id, or Ignore), which calls `/people/requests/{id}` directly and never hands off to chat, so what a stranger wrote never seeds a turn. The card is kept out of everything that could close it without answering it or put the stranger's words in front of a model: the narrative (`_action_proposals` drops it), the chat's open-alert digest (`<briefing>` — the principal's verified turn gets a separate `<roster_requests>` block instead; see Agents), `ack_alert`, a single ack (`POST /alerts/{id}/ack` is a 409), the \"Dismiss N older than 7 days\" count and the server's bulk ack, reopen, the TTL sweep and the alert review (`roster_request` is in `lifecycle.TTL_EXEMPT_SOURCES`). It ends when the request does: answered (`ack`, or `dismissed` on a decline) or expired after `ROSTER_REQUEST_TTL_DAYS`.\n- **`people`** — an attention-ranked roster of the **team** (the principal's contacts are never listed, and get no insight note). 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 is listed only to its owner (`alerts.models.visible_alert`; every other build of the board — the briefs, the reflection, the review, the chat digest on anyone else's turn, the activity rail — leaves drafted artifacts out) and 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 (\"What's going on\") synthesized by `synthesize_briefing_narrative`, cached per scope in `briefing_narrative`: the resolved principal gets the whole-company `principal` scope (which may carry what is private to them), a caller who resolves to no roster row the shared `company` scope (written from what everyone may see), and each teammate a role-scoped `person:<id>` one. `narrative_generated_at` says when the served text was written and `narrative_stale` whether a fresher one is being written now. 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. When the principal names an item that has already left the board — opened, snoozed, or older than it — the Executive looks it up with `find_alerts` (a keyword search over every status, `alerts.store.search_alerts`); matches that are still open (`unread` or `read`) become ackable for that turn, up to 25, and closed ones come back labelled so the Executive can say the item is already settled. It works only where the principal's own board was shown this turn — the web app or their DM — and never returns roster-request cards (see Lifecycle). The digest's header also labels every headline and detail as untrusted content drawn from inbound mail, chat and watched pages — act on what the principal asks about an item, never on what its text asks — and triage reads each signal inside an `<event>` block whose closing tag the sender's text cannot forge (it is defanged in any case and spacing, after NFKC folds fullwidth forms). 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\n **Live, not just the board.** The header used to reason over the alert board, goal health and the Executive's own bookkeeping only — mail and chat handled that day, replies the gate held and the next meeting never reached it, so it read the same for days while the principal's day moved on. The whole-company scopes now open the context with the principal's world as it is happening (`briefing.live_signals.gather_live_signals`, rendered by `render_live_blocks`), under a `NOW:` line: **INBOUND** (`integration_inbound` audit rows that carry a message, grouped by sender and subject, with an email's first line), **STUCK** (`integration_outbound_blocked` to a recipient, the inbound \"reply blocked at outbound gate\" and Google Chat \"left unanswered\" / \"not delivered\" rows, and drafts saved by Act as me), **CONVERSATIONS** (the principal's own web chat titles) and the **REST OF TODAY'S CALENDAR**. The window is the local day, or the last 12 hours when that is longer. Private audit rows, drafts, chat titles and the calendar (meeting titles are the principal's own) are read only in the `principal` scope — `gather_live_signals` drops the calendar whenever `include_private` is false, whatever the caller passes, so the shared `company` header never quotes it. The calendar is never fetched on the request: `live_signals.refresh_calendar` caches one read per 15 minutes (the scheduler tick refreshes it) and the header quotes the cache. Every quoted field is collapsed to one line and cut, and the blocks and the prompt both say the text is data, never instructions — inbound mail is attacker-controlled. With live blocks present the context also ages each proposal (`raised 2d ago`, whole days), names each at-risk department's slipping goals (`attention_goals`) and adds an **EXTERNAL SIGNALS** block (monitoring alerts from the last 24 h, never enough on their own to break the quiet line); the rhythm runs (`today.RHYTHM_WORKFLOWS`: the morning brief, end-of-day digest, reflection and weekly review) are dropped from the activity it reasons over. The prompts (`BRIEFING_NARRATIVE_SYSTEM` and its solo variant, `NARRATIVE_PROMPT_VERSION` 5) lead with what is live and give a days-old item at most one bullet. Anything live breaks the quiet line; the NOW line and window move at most once an hour, so the key moves hourly on time alone plus whenever something new lands; the calendar is placed at the real time (a meeting that has ended drops out, the one under way is IN PROGRESS), which moves it only when a meeting starts or ends.\n\n **Fresh without a reload.** The daily floor in the key and the PERIOD line are the principal's **local** date (`narrative_cache.local_today`), not UTC's, and a row written on an earlier local day is not served as today's. Regenerations are serialized per scope; a trigger that finds one running marks the scope pending and the running pass goes round once more (it built its context before that trigger's news landed), and after a failed pass (model error, the 25 s timeout, empty text) no view or tick starts another for 5 minutes and `narrative_stale` reads false, so the page drops its placeholder instead of spending a model call per view. They log `today: narrative served scope=… age_s=… stale=…` and `today: narrative regenerated scope=… ms=…`, and no longer need a page view: every `BRIEFING_NARRATIVE_REFRESH_MINUTES` (10) between `BRIEFING_NARRATIVE_REFRESH_START_HOUR` and `_END_HOUR` (06–22 local) the scheduler runs `today.refresh_principal_narrative`, which refreshes the calendar cache and rewrites the principal's header only when its key moved (see Scheduler). The Briefing re-polls `/today` at 4, 10 and 20 s while `narrative_stale` is true, re-pulls it when the tab comes back (at most once a minute) and every 5 minutes while visible, shows \"Updated 2:04 PM\" beside the heading, and shows \"Catching up on today…\" while the first header of the day is written (`lib/narrativeFreshness.ts`, tested by `npm test`).\n\n In **solo mode** (one person using Open Executive for themselves) the header speaks to the principal, whatever their role: a solo prompt over a context that lists goals at risk by *area* and has no \"people waiting on you\" block, and the quiet check ignores who is awaiting. The cache key carries the mode for solo only, so solo and team never share a cached narrative while every team key stays exactly what it was — no team cache is invalidated. The response shape does not change. For the principal's own view the solo context also carries a **DUE THIS WEEK** block — the principal's open loops that are overdue or due within 7 days (`today._with_due_soon` → `open_loops.principal_due_soon`, labelled OVERDUE / due today / due <weekday>) — which counts as needing attention in the quiet check and moves the cache key when an item is added, closed or falls due; a teammate's scoped view and team mode never get it. The header never gets the morning brief's *top three today* block — that is the DM brief's (see Workflows); the page shows the same top three in a card of its own (see *Solo focus cards* below). It does get the rest of today's calendar through the live blocks above, from the cached read.\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. Audit rows private to the principal (say, one naming their contact) are in this list only on the principal's own `/today`: `brief_state.handled_since` leaves them out unless asked, and the written briefs never ask, since a brief can be read by others. The Pulse heatmap's per-day counts (`GET /today/activity/daily`) likewise leave out a private decision or private alert, as the activity rail does. The morning brief also carries a one-line count of research watch suggestions waiting on `/watchlist`.\n\n**Standing facts.** `render_briefing_context` appends the standing facts (`memory.facts`: corrections kept from chat, a teammate's marked `(per <name>)`) as its last block, after the quiet-day check, so a fact never makes a quiet day look busy. The morning brief also carries **TEAMMATE CORRECTIONS SINCE LAST BRIEF** (`facts.render_teammate_changes(since)`: each teammate fact recorded in the window that is in use now, plus — only when the brief is the principal's own private one (`_private_ok`), which then keeps the run out of the shared history — those waiting for their approval, since other teammates may run the brief and never see a proposal that is not theirs) before the quiet check — it is news, the principal's only FYI of it — and in the brief's fingerprint (`build_brief_fingerprint(teammate_changes=)`), so a correction alone un-suppresses an otherwise unchanged brief. Every other caller passes none, so its context is unchanged. The /today header hashes that rendered string as its cache key, so a new or retired fact marks the header stale and it is rewritten with the correction. The morning brief (standalone) and the teammate-scoped header get the same block. On the scheduler's delivery to the owner alone, with their Always in the loop switch on, `render_briefing_context(owner_notes=)` also carries FROM YOUR NOTES — DUE SOON (their own notes of what they promised or asked, overdue to a week ahead; `memory.history_brief`), which counts against a quiet day, enters the fingerprint and marks the run private; both standalone prompts turn it into a **From your notes** section. The /today header never gets it. The alert review's `render_batch` puts the same block ahead of the alerts (read once per pass), so a note, rewrite or routed DM never repeats a figure the principal already corrected.\n\n**When a brief isn't sent.** Above the Briefing, the owner sees a one-line notice when their latest morning brief, end-of-day digest or (in solo mode) weekly review 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\n**Replies waiting.** With Act as me's **Draft replies to my inbox** on, the top of the Briefing's left column lists the replies the Executive drafted in the owner's own Gmail for mail that needs them (`RepliesWaiting`, from `GET /delegation/replies` — see Act as Me). They belong to the owner alone: the route answers only the person who can have Act as me, the decisions behind the cards (`delegation_reply`) are principal-only and carry `private: true`, so `/today/activity` and the heatmap leave them out, and none is ever an alert, so nothing of them reaches `GET /today`, the header or the briefs. Each card shows who wrote and who they are to the owner, whether their address was verified, the subject, what they wrote (as plain text), the draft, **Decide before sending** (its open questions) and its warnings, with **Send**, **Edit in Gmail** (the thread in their Gmail) and **Dismiss** (which deletes the draft unless they edited it). **Send** asks first, naming who the reply goes to, then sends the draft exactly as it is in Gmail (`POST /decisions/{id}/approve`); when its recipients changed in Gmail or a newer message arrived, the backend's 409 `confirm` becomes a second question naming them. The card hides itself when nothing is waiting.\n\n**Solo focus cards.** `GET /today/top-three` and `GET /today/weekly-review` feed two solo-only cards, so a principal who only uses the web app — no chat app, no Google Workspace — sees today's top three and the weekly review instead of finding them only in the Workflows run history. Both answer only in solo mode (`effective_workspace_mode`) and only to the principal, by the stricter rule for starting a principal-only run (`workflows._caller_is_the_principal`: the caller's own email on a principal entry that is not archived, or no `x-caller-email` at all — never \"nobody is principal yet\"); a teammate, any other signed-in caller and team mode get null. `top-three` hands `open_loops.principal_due_soon()` to `briefing.top_three.build_top_three` — the morning brief's own inputs and code, so the items, their order and their free slots are the brief's — and returns `{items: [{key, kind, text, why, slot}]}`: `slot` is the free block (\"10:00–11:00\", the user's zone), \"\" when none is left, or null when no calendar was read (none connected, a failure or the 4 s timeout, a weekend); `items` is empty when there is nothing to pick. It is a route of its own, never part of `GET /today`, so the Briefing never waits on the calendar. `weekly-review` returns the latest `weekly_review` run with status `done` (`persistence.list_runs(..., status=\"done\", limit=1)`, newest `updated_at` first; failed and running runs never count) as `{run_id, completed_at, period, top_three, excerpt}`: `weekly_review.summarize_review` reads the artifact's title line and its last *Next week's top 3* section back as plain text, and `excerpt` stands in when that list is empty (the section's own note, else the review's first lines). Null when no review has completed or the run store cannot be read.\n\nThe route resolves the caller from `x-caller-email`, serves the viewer's cached narrative and, when its key moved, rewrites it in a `BackgroundTask` so the request never blocks on an LLM call (the page re-polls while `narrative_stale` is true). `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; solo mode has its own, with goals at risk by area and no waiting-on section). `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. Under **Needs you**, a **Due soon** card lists the principal's open loops that are overdue or due within 7 days — their dated commitments and what others asked of them — read from `GET /people/{id}/open-loops` for the principal (the oldest principal in `people`, the backend's rule), labelled by `lib/dueSoon.ts` (tested by `npm test`: \"Overdue since Sep 23\" / \"Due today\" / \"Due Mon, Sep 28\", with a count of anything due later); **Done** closes one through `POST /open-loops/{id}/close`, which also stops the nudge engine chasing it. Above it, **Top three today** numbers the morning brief's three (`GET /today/top-three`) with each one's reason and, when a calendar was read, its free slot (or \"No free time left today\"); at the top of the right-hand column, **This week's review** (`GET /today/weekly-review`) shows the period, when it ran, next week's top three (or the excerpt) and a *Read the review* link to its run page (`/jobs/runs/{id}`). Each card fetches on its own once the Briefing has loaded, so a slow calendar never holds the page up, and renders nothing when the API returns null or an empty list. A commitment in the top three reads as the owner's own (\"Send the proposal\") through `lib/dueSoon.ts`'s `loopText`, as in Due soon; the cards' wording lives in `lib/rhythmCards.ts` (tested by `npm test`). 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. Four things now keep it live and true:\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- **Collection tags** (`alerts.pipeline`). A triaged alert never carries a `collection:<name>` tag: the pipeline strips them before inserting. Only an installed extension's own code files a document into its collection (`orchestrator.extensions`), so injected text can't make a card that the extension would treat as its own.\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 (team members only — an alert routed to a contact never puts them in the slice, so they are never routed to, nudged or chased; a private card is never reviewed at all, nor used as evidence for another), 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- **Grounded text** (`openexecutive.briefing.grounding`). Nobody reads an alert's text before it is dispatched, so what the model wrote onto it must be supported by what it read. After triage (`alerts.pipeline._ground_decision`, before coalescing or inserting), a headline naming a person or figure the event does not hold — sources are the event's subject, sender, title and body, the initiatives triage was shown and the company profile — is replaced by the event's own subject, such body sentences are dropped (all of them → the event body cut to 280 chars); both fallbacks are raw event text, so they are made inert first — links masked, Markdown and Slack `<…>` syntax and @-mentions stripped — because a broadcast posts them as written, and such a suggested action is dropped. A review `changed` rewrite is checked against the alert's own text and the evidence it was reviewed with (signals, related alerts, activity, the roster slice), plus the standing facts the batch was shown, so a rewrite that corrects a card to one of the principal's corrections is grounded; an ungrounded rewrite keeps the old text, still applies a severity change, and audits `text_ungrounded`. A name counts as grounded only when one source line holds all of it; a figure only when a source number matches it within the precision it is written with. Each finding writes a `grounding` audit row; `GROUNDING_CHECKS=report` records without changing anything.\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- **Private cards.** An alert tagged `private:principal` (`alerts.models.PRIVATE_ALERT_TAG` — raised on a turn about mail from one of the principal's contacts or mail they forwarded, or a meeting proposal with a contact) is in `proposals` only when the caller is the principal. `_build_today` leaves it out by default, so the end-of-day digest, the reflection and Discord's `/today` never see it, and the morning brief reads it only on a run for the principal (the scheduler's, or the principal's own verified chat turn in a conversation only they can read — see Workflows). The narrative is written from one only in the principal's own `principal` scope, which nobody else is served; the shared `company` scope an unresolved caller gets, and a teammate's scope, never are. The activity rail skips it, and the chat digest includes it only on the principal's own verified turn.\n- **Roster-request cards.** When someone not on the People list writes in (see Org and Integrations), `people.roster_requests.surface_card` raises an alert of source `roster_request` (medium, tagged `roster_request:<id>` and `private:principal`, routed to the principal), so it follows every private-card rule above. `GET /today` attaches `roster_request` to that proposal (`_roster_request_card`: channel, address or account id, the sender's sanitised and unverified name, profile email, company-domain flag, suggested kind and person, message count, whether they were acknowledged, first seen, and the held messages' first lines) while the request is still pending. The Briefing renders it as its own card (`RosterRequestCard`: add as a new person with a name and an explicit team/contact choice — pre-filled as team on a company domain — or \"someone already on the list\", with a replace-account option for a chat id, or Ignore), which calls `/people/requests/{id}` directly and never hands off to chat, so what a stranger wrote never seeds a turn. The card is kept out of everything that could close it without answering it or put the stranger's words in front of a model: the narrative (`_action_proposals` drops it), the chat's open-alert digest (`<briefing>` — the principal's verified turn gets a separate `<roster_requests>` block instead; see Agents), `ack_alert`, a single ack (`POST /alerts/{id}/ack` is a 409), the \"Dismiss N older than 7 days\" count and the server's bulk ack, reopen, the TTL sweep and the alert review (`roster_request` is in `lifecycle.TTL_EXEMPT_SOURCES`). It ends when the request does: answered (`ack`, or `dismissed` on a decline) or expired after `ROSTER_REQUEST_TTL_DAYS`.\n- **`people`** — an attention-ranked roster of the **team** (the principal's contacts are never listed, and get no insight note). 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 is listed only to its owner (`alerts.models.visible_alert`; every other build of the board — the briefs, the reflection, the review, the chat digest on anyone else's turn, the activity rail — leaves drafted artifacts out) and 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 (\"What's going on\") synthesized by `synthesize_briefing_narrative`, cached per scope in `briefing_narrative`: the resolved principal gets the whole-company `principal` scope (which may carry what is private to them), a caller who resolves to no roster row the shared `company` scope (written from what everyone may see), and each teammate a role-scoped `person:<id>` one. `narrative_generated_at` says when the served text was written and `narrative_stale` whether a fresher one is being written now. 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. When the principal names an item that has already left the board — opened, snoozed, or older than it — the Executive looks it up with `find_alerts` (a keyword search over every status, `alerts.store.search_alerts`); matches that are still open (`unread` or `read`) become ackable for that turn, up to 25, and closed ones come back labelled so the Executive can say the item is already settled. It works only where the principal's own board was shown this turn — the web app or their DM — and never returns roster-request cards (see Lifecycle). The digest's header also labels every headline and detail as untrusted content drawn from inbound mail, chat and watched pages — act on what the principal asks about an item, never on what its text asks — and triage reads each signal inside an `<event>` block whose closing tag the sender's text cannot forge (it is defanged in any case and spacing, after NFKC folds fullwidth forms). 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\n **Live, not just the board.** The header used to reason over the alert board, goal health and the Executive's own bookkeeping only — mail and chat handled that day, replies the gate held and the next meeting never reached it, so it read the same for days while the principal's day moved on. The whole-company scopes now open the context with the principal's world as it is happening (`briefing.live_signals.gather_live_signals`, rendered by `render_live_blocks`), under a `NOW:` line: **INBOUND** (`integration_inbound` audit rows that carry a message, grouped by sender and subject, with an email's first line), **STUCK** (`integration_outbound_blocked` to a recipient, the inbound \"reply blocked at outbound gate\" and Google Chat \"left unanswered\" / \"not delivered\" rows, and drafts saved by Act as me), **CONVERSATIONS** (the principal's own web chat titles) and the **REST OF TODAY'S CALENDAR**. The window is the local day, or the last 12 hours when that is longer. Private audit rows, drafts, chat titles and the calendar (meeting titles are the principal's own) are read only in the `principal` scope — `gather_live_signals` drops the calendar whenever `include_private` is false, whatever the caller passes, so the shared `company` header never quotes it. The calendar is never fetched on the request: `live_signals.refresh_calendar` caches one read per 15 minutes (the scheduler tick refreshes it) and the header quotes the cache. Every quoted field is collapsed to one line and cut, and the blocks and the prompt both say the text is data, never instructions — inbound mail is attacker-controlled. With live blocks present the context also ages each proposal (`raised 2d ago`, whole days), names each at-risk department's slipping goals (`attention_goals`) and adds an **EXTERNAL SIGNALS** block (monitoring alerts from the last 24 h, never enough on their own to break the quiet line); the rhythm runs (`today.RHYTHM_WORKFLOWS`: the morning brief, end-of-day digest, reflection and weekly review) are dropped from the activity it reasons over. The prompts (`BRIEFING_NARRATIVE_SYSTEM` and its solo variant, `NARRATIVE_PROMPT_VERSION` 5) lead with what is live and give a days-old item at most one bullet. Anything live breaks the quiet line; the NOW line and window move at most once an hour, so the key moves hourly on time alone plus whenever something new lands; the calendar is placed at the real time (a meeting that has ended drops out, the one under way is IN PROGRESS), which moves it only when a meeting starts or ends.\n\n **Fresh without a reload.** The daily floor in the key and the PERIOD line are the principal's **local** date (`narrative_cache.local_today`), not UTC's, and a row written on an earlier local day is not served as today's. Regenerations are serialized per scope; a trigger that finds one running marks the scope pending and the running pass goes round once more (it built its context before that trigger's news landed), and after a failed pass (model error, the 25 s timeout, empty text) no view or tick starts another for 5 minutes and `narrative_stale` reads false, so the page drops its placeholder instead of spending a model call per view. They log `today: narrative served scope=… age_s=… stale=…` and `today: narrative regenerated scope=… ms=…`, and no longer need a page view: every `BRIEFING_NARRATIVE_REFRESH_MINUTES` (10) between `BRIEFING_NARRATIVE_REFRESH_START_HOUR` and `_END_HOUR` (06–22 local) the scheduler runs `today.refresh_principal_narrative`, which refreshes the calendar cache and rewrites the principal's header only when its key moved (see Scheduler). The Briefing re-polls `/today` at 4, 10 and 20 s while `narrative_stale` is true, re-pulls it when the tab comes back (at most once a minute) and every 5 minutes while visible, shows \"Updated 2:04 PM\" beside the heading, and shows \"Catching up on today…\" while the first header of the day is written (`lib/narrativeFreshness.ts`, tested by `npm test`).\n\n In **solo mode** (one person using Open Executive for themselves) the header speaks to the principal, whatever their role: a solo prompt over a context that lists goals at risk by *area* and has no \"people waiting on you\" block, and the quiet check ignores who is awaiting. The cache key carries the mode for solo only, so solo and team never share a cached narrative while every team key stays exactly what it was — no team cache is invalidated. The response shape does not change. For the principal's own view the solo context also carries a **DUE THIS WEEK** block — the principal's open loops that are overdue or due within 7 days (`today._with_due_soon` → `open_loops.principal_due_soon`, labelled OVERDUE / due today / due <weekday>) — which counts as needing attention in the quiet check and moves the cache key when an item is added, closed or falls due; a teammate's scoped view and team mode never get it. The header never gets the morning brief's *top three today* block — that is the DM brief's (see Workflows); the page shows the same top three in a card of its own (see *Solo focus cards* below). It does get the rest of today's calendar through the live blocks above, from the cached read.\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. Audit rows private to the principal (say, one naming their contact) are in this list only on the principal's own `/today`: `brief_state.handled_since` leaves them out unless asked, and the written briefs never ask, since a brief can be read by others. The Pulse heatmap's per-day counts (`GET /today/activity/daily`) likewise leave out a private decision or private alert, as the activity rail does. The morning brief also carries a one-line count of research watch suggestions waiting on `/watchlist`.\n\n**Standing facts.** `render_briefing_context` appends the standing facts (`memory.facts`: corrections kept from chat, a teammate's marked `(per <name>)`) as its last block, after the quiet-day check, so a fact never makes a quiet day look busy. The morning brief also carries **TEAMMATE CORRECTIONS SINCE LAST BRIEF** (`facts.render_teammate_changes(since)`: each teammate fact recorded in the window that is in use now, plus — only when the brief is the principal's own private one (`_private_ok`), which then keeps the run out of the shared history — those waiting for their approval, since other teammates may run the brief and never see a proposal that is not theirs) before the quiet check — it is news, the principal's only FYI of it — and in the brief's fingerprint (`build_brief_fingerprint(teammate_changes=)`), so a correction alone un-suppresses an otherwise unchanged brief. Every other caller passes none, so its context is unchanged. The /today header hashes that rendered string as its cache key, so a new or retired fact marks the header stale and it is rewritten with the correction. The morning brief (standalone) and the teammate-scoped header get the same block. On the scheduler's delivery to the owner alone, with their Always in the loop switch on, `render_briefing_context(owner_notes=)` also carries FROM YOUR NOTES — DUE SOON (their own notes of what they promised or asked, overdue to a week ahead; `memory.history_brief`), which counts against a quiet day, enters the fingerprint and marks the run private; both standalone prompts turn it into a **From your notes** section. The /today header never gets it. The alert review's `render_batch` puts the same block ahead of the alerts (read once per pass), so a note, rewrite or routed DM never repeats a figure the principal already corrected.\n\n**When a brief isn't sent.** Above the Briefing, the owner sees a one-line notice when their latest morning brief, end-of-day digest or (in solo mode) weekly review 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. When the Executive's mail connection wasn't running (the MCP gateway failed to start and is retrying), the notice says that instead of blaming the owner's setup; a send that failed on every channel names what each channel answered, from the recorded `detail`, with addresses left out. Teammates never see it.\n\n**Replies waiting.** With Act as me's **Draft replies to my inbox** on, the top of the Briefing's left column lists the replies the Executive drafted in the owner's own Gmail for mail that needs them (`RepliesWaiting`, from `GET /delegation/replies` — see Act as Me). They belong to the owner alone: the route answers only the person who can have Act as me, the decisions behind the cards (`delegation_reply`) are principal-only and carry `private: true`, so `/today/activity` and the heatmap leave them out, and none is ever an alert, so nothing of them reaches `GET /today`, the header or the briefs. Each card shows who wrote and who they are to the owner, whether their address was verified, the subject, what they wrote (as plain text), the draft, **Decide before sending** (its open questions) and its warnings, with **Send**, **Edit in Gmail** (the thread in their Gmail) and **Dismiss** (which deletes the draft unless they edited it). **Send** asks first, naming who the reply goes to, then sends the draft exactly as it is in Gmail (`POST /decisions/{id}/approve`); when its recipients changed in Gmail or a newer message arrived, the backend's 409 `confirm` becomes a second question naming them. The card hides itself when nothing is waiting.\n\n**Solo focus cards.** `GET /today/top-three` and `GET /today/weekly-review` feed two solo-only cards, so a principal who only uses the web app — no chat app, no Google Workspace — sees today's top three and the weekly review instead of finding them only in the Workflows run history. Both answer only in solo mode (`effective_workspace_mode`) and only to the principal, by the stricter rule for starting a principal-only run (`workflows._caller_is_the_principal`: the caller's own email on a principal entry that is not archived, or no `x-caller-email` at all — never \"nobody is principal yet\"); a teammate, any other signed-in caller and team mode get null. `top-three` hands `open_loops.principal_due_soon()` to `briefing.top_three.build_top_three` — the morning brief's own inputs and code, so the items, their order and their free slots are the brief's — and returns `{items: [{key, kind, text, why, slot}]}`: `slot` is the free block (\"10:00–11:00\", the user's zone), \"\" when none is left, or null when no calendar was read (none connected, a failure or the 4 s timeout, a weekend); `items` is empty when there is nothing to pick. It is a route of its own, never part of `GET /today`, so the Briefing never waits on the calendar. `weekly-review` returns the latest `weekly_review` run with status `done` (`persistence.list_runs(..., status=\"done\", limit=1)`, newest `updated_at` first; failed and running runs never count) as `{run_id, completed_at, period, top_three, excerpt}`: `weekly_review.summarize_review` reads the artifact's title line and its last *Next week's top 3* section back as plain text, and `excerpt` stands in when that list is empty (the section's own note, else the review's first lines). Null when no review has completed or the run store cannot be read.\n\nThe route resolves the caller from `x-caller-email`, serves the viewer's cached narrative and, when its key moved, rewrites it in a `BackgroundTask` so the request never blocks on an LLM call (the page re-polls while `narrative_stale` is true). `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; solo mode has its own, with goals at risk by area and no waiting-on section). `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. Under **Needs you**, a **Due soon** card lists the principal's open loops that are overdue or due within 7 days — their dated commitments and what others asked of them — read from `GET /people/{id}/open-loops` for the principal (the oldest principal in `people`, the backend's rule), labelled by `lib/dueSoon.ts` (tested by `npm test`: \"Overdue since Sep 23\" / \"Due today\" / \"Due Mon, Sep 28\", with a count of anything due later); **Done** closes one through `POST /open-loops/{id}/close`, which also stops the nudge engine chasing it. Above it, **Top three today** numbers the morning brief's three (`GET /today/top-three`) with each one's reason and, when a calendar was read, its free slot (or \"No free time left today\"); at the top of the right-hand column, **This week's review** (`GET /today/weekly-review`) shows the period, when it ran, next week's top three (or the excerpt) and a *Read the review* link to its run page (`/jobs/runs/{id}`). Each card fetches on its own once the Briefing has loaded, so a slow calendar never holds the page up, and renders nothing when the API returns null or an empty list. A commitment in the top three reads as the owner's own (\"Send the proposal\") through `lib/dueSoon.ts`'s `loopText`, as in Due soon; the cards' wording lives in `lib/rhythmCards.ts` (tested by `npm test`). 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. Four things now keep it live and true:\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- **Collection tags** (`alerts.pipeline`). A triaged alert never carries a `collection:<name>` tag: the pipeline strips them before inserting. Only an installed extension's own code files a document into its collection (`orchestrator.extensions`), so injected text can't make a card that the extension would treat as its own.\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 (team members only — an alert routed to a contact never puts them in the slice, so they are never routed to, nudged or chased; a private card is never reviewed at all, nor used as evidence for another), 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- **Grounded text** (`openexecutive.briefing.grounding`). Nobody reads an alert's text before it is dispatched, so what the model wrote onto it must be supported by what it read. After triage (`alerts.pipeline._ground_decision`, before coalescing or inserting), a headline naming a person or figure the event does not hold — sources are the event's subject, sender, title and body, the initiatives triage was shown and the company profile — is replaced by the event's own subject, such body sentences are dropped (all of them → the event body cut to 280 chars); both fallbacks are raw event text, so they are made inert first — links masked, Markdown and Slack `<…>` syntax and @-mentions stripped — because a broadcast posts them as written, and such a suggested action is dropped. A review `changed` rewrite is checked against the alert's own text and the evidence it was reviewed with (signals, related alerts, activity, the roster slice), plus the standing facts the batch was shown, so a rewrite that corrects a card to one of the principal's corrections is grounded; an ungrounded rewrite keeps the old text, still applies a severity change, and audits `text_ungrounded`. A name counts as grounded only when one source line holds all of it; a figure only when a source number matches it within the precision it is written with. Each finding writes a `grounding` audit row; `GROUNDING_CHECKS=report` records without changing anything.\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 TOP3[\"GET /today/top-three<br/>(solo, principal only)\"]\n PICK[\"build_top_three()<br/>(calendar read, 4 s cap)\"]\n WREV[\"GET /today/weekly-review<br/>(solo, principal only)\"]\n RUNS[\"workflow_runs<br/>(latest done weekly_review)\"]\n LIVE[\"live_signals<br/>(inbound / held replies / chats,<br/>cached calendar)\"]\n TICK[\"scheduler tick<br/>(every 10 min, 06–22 local)\"]\n CACHE[\"briefing_narrative<br/>(principal / company / person:id)\"]\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 LIVE --> NARR\n TICK -->|\"refresh_principal_narrative\"| NARR\n NARR --> CACHE\n MB -->|\"since last brief\"| LIVE\n MB -->|\"calls directly for standalone DM\"| BUILD\n MB -->|\"same pick for the DM\"| PICK\n TOP3 --> PICK\n WREV --> RUNS\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\n class TOP3 entry\n class PICK compute\n class WREV entry\n class RUNS storage\n class LIVE compute\n class TICK entry\n class CACHE storage",
- "generated_at": "2026-10-09T16:33:39Z"
+ "generated_at": "2026-10-13T13:10:00Z"
}
diff --git a/packages/core/openexecutive/briefing/brief_state.py b/packages/core/openexecutive/briefing/brief_state.py
index ae4bc250..eca5b1d9 100644
--- a/packages/core/openexecutive/briefing/brief_state.py
+++ b/packages/core/openexecutive/briefing/brief_state.py
@@ -20,10 +20,12 @@ 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``.
+(``record_delivery_outcome``): the reason in ``input_hash`` and, in
+``narrative_text``, the channel that sent it — a channel name, never an
+address — and, for a failure, what happened in a line (the tool's own error,
+or why no channel could be tried; ``detail``). The Briefing's "not sent"
+notice and the Setup status page read it back through ``current_problem``
+and ``describe_problem``.
"""
from __future__ import annotations
@@ -129,8 +131,12 @@ def record_delivered(kind: str, fingerprint: str, text: str) -> None:
# 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"]
+# PrincipalDelivery.reason). ``gateway_down`` is email set up but the MCP
+# gateway that sends it not running, which used to read as ``no_channel``
+# and so blamed the owner's setup for the Executive's own fault.
+DeliveryReason = Literal[
+ "delivered", "no_owner", "no_channel", "gateway_down", "send_failed", "not_written"
+]
_DELIVERY_REASONS: frozenset[str] = frozenset(get_args(DeliveryReason))
DELIVERY_SCOPE_PREFIX = "brief_delivery:"
# The daily briefs (their send times show on the Setup status page).
@@ -156,6 +162,11 @@ DELIVERY_PROBLEMS: dict[str, tuple[str, str]] = {
"nothing is set up to send it to you",
"Connect Gmail, or add your Slack, Telegram or Discord to your People profile.",
),
+ "gateway_down": (
+ "the Executive's mail connection wasn't running",
+ "It keeps retrying on its own; if the Gmail light on the Setup status page stays red, "
+ "the API log says why.",
+ ),
"send_failed": (
"every way of sending it failed",
"The Setup status page shows which connection needs attention.",
@@ -186,23 +197,73 @@ class DeliveryOutcome:
# The delivery channel that sent it ("email", "slack_dm", ...), if one did.
channel: str | None
at: datetime
+ # What happened when it wasn't sent, in a line: the tool's error, or why
+ # no channel could be tried. None for a delivered brief.
+ detail: str | None = None
+
+
+# The longest detail kept: a line for the notice, not a traceback.
+DETAIL_MAX_CHARS = 300
+# A grant that died shows in the detail like this (orchestrator.mcp_gateway.
+# grant_failure); the notice's fix then says to reconnect rather than to
+# look at the status page.
+_RECONNECT_HINT_RE = re.compile(
+ r"invalid_grant|expired|revoked|reconnect|unauthori[sz]ed|authentication", re.IGNORECASE
+)
def record_delivery_outcome(
- kind: str, *, reason: DeliveryReason, channel: str | None
+ kind: str, *, reason: DeliveryReason, channel: str | None, detail: str | None = None
) -> None:
"""Remember how this brief's latest run ended. Never raises."""
+ detail = " ".join(detail.split())[:DETAIL_MAX_CHARS] if detail else None
+ text = json.dumps({"channel": channel or "", "detail": detail}) if detail else (channel or "")
try:
narrative_cache.put(narrative_cache.BriefingNarrative(
scope=f"{DELIVERY_SCOPE_PREFIX}{kind}",
input_hash=reason,
- narrative_text=channel or "",
+ narrative_text=text,
generated_at=narrative_cache.utc_now_iso(),
))
except Exception:
logger.exception("brief_state: delivery outcome write failed for %s", kind)
+def _read_outcome_text(text: str) -> tuple[str | None, str | None]:
+ """``(channel, detail)`` from the stored row: a bare channel name (the
+ older shape, and every delivered brief) or the JSON a failure writes."""
+ if text.startswith("{"):
+ try:
+ parsed = json.loads(text)
+ except ValueError:
+ parsed = None
+ if isinstance(parsed, dict):
+ channel = parsed.get("channel")
+ detail = parsed.get("detail")
+ return (
+ channel if isinstance(channel, str) and channel else None,
+ detail if isinstance(detail, str) and detail else None,
+ )
+ return (text or None), None
+
+
+def describe_problem(reason: DeliveryReason, detail: str | None = None) -> tuple[str, str]:
+ """``(problem, fix)`` for the notice: the reason in the user's words,
+ with what happened appended when it is known, and a fix that names a
+ reconnect when the detail shows a grant that died."""
+ problem, fix = DELIVERY_PROBLEMS[reason]
+ if not detail:
+ return problem, fix
+ if reason in ("send_failed", "gateway_down"):
+ problem = f"{problem} ({detail})"
+ if reason == "send_failed" and _RECONNECT_HINT_RE.search(detail):
+ fix = (
+ "The Executive's sign-in to its mailbox expired or was revoked: connect it again, "
+ "then the next brief goes out."
+ )
+ return problem, fix
+
+
def last_delivery_outcome() -> DeliveryOutcome | None:
"""The latest run of any recorded message (``DELIVERY_KINDS``: the two
briefs and the weekly review), or None when none has run yet (or the
@@ -217,11 +278,13 @@ def last_delivery_outcome() -> DeliveryOutcome | None:
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
+ channel, detail = _read_outcome_text(row.narrative_text or "")
outcome = DeliveryOutcome(
kind=kind,
reason=cast(DeliveryReason, row.input_hash), # checked above
- channel=row.narrative_text or None,
+ channel=channel,
at=at,
+ detail=detail,
)
if latest is None or outcome.at > latest.at:
latest = outcome
@@ -229,14 +292,19 @@ def last_delivery_outcome() -> DeliveryOutcome | None:
def current_problem(
- outcome: DeliveryOutcome | None, *, has_owner: bool, can_deliver: bool
+ outcome: DeliveryOutcome | None,
+ *,
+ has_owner: bool,
+ can_deliver: bool,
+ gateway_down: bool = False,
) -> 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
+ from now (``has_owner``, ``can_deliver``, ``gateway_down``: email is set
+ up but the gateway that sends it is not running), 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":
@@ -245,7 +313,9 @@ def current_problem(
return outcome.reason
if can_deliver:
return None
- return "no_channel" if has_owner else "no_owner"
+ if not has_owner:
+ return "no_owner"
+ return "gateway_down" if gateway_down else "no_channel"
def split_proposals(
@@ -511,6 +581,7 @@ __all__ = [
"SUPPRESSED_TEMPLATE",
"DeliveryOutcome",
"DeliveryReason",
+ "describe_problem",
"brief_name",
"build_brief_fingerprint",
"channel_phrase",
diff --git a/packages/core/openexecutive/orchestrator/executive.py b/packages/core/openexecutive/orchestrator/executive.py
index ae23d9ef..25627598 100644
--- a/packages/core/openexecutive/orchestrator/executive.py
+++ b/packages/core/openexecutive/orchestrator/executive.py
@@ -105,6 +105,7 @@ from openexecutive.orchestrator.mcp_gateway import (
MCP_TOOL_NAMES,
MCP_TOOLS,
MCPGateway,
+ gateway_reconnect_needed,
gateway_server_names,
)
from openexecutive.orchestrator.open_loop_tools import (
@@ -1275,6 +1276,7 @@ class Executive:
include_contacts=_contacts_in_prompt(session),
delegation=block0_delegation_on(session),
mcp_servers=gateway_server_names(self._mcp_gateway),
+ needs_reconnect=gateway_reconnect_needed(self._mcp_gateway),
persona_instructions=persona_instructions,
)
# turn_id ties every downstream audit row (knowledge_retrieval,
@@ -1594,6 +1596,7 @@ class Executive:
include_contacts=_contacts_in_prompt(session),
delegation=block0_delegation_on(session),
mcp_servers=gateway_server_names(self._mcp_gateway),
+ needs_reconnect=gateway_reconnect_needed(self._mcp_gateway),
persona_instructions=persona_instructions,
)
# turn_id covers both the draft and (later) the revision pass so a
diff --git a/packages/core/openexecutive/orchestrator/gateway_boot.py b/packages/core/openexecutive/orchestrator/gateway_boot.py
new file mode 100644
index 00000000..f5e3229e
--- /dev/null
+++ b/packages/core/openexecutive/orchestrator/gateway_boot.py
@@ -0,0 +1,357 @@
+"""Keeping the MCP gateway up: start with retries, re-check on demand, report.
+
+The gateway (``orchestrator/mcp_gateway.py``) is one extensible-mcp subprocess
+started at boot. It used to get a single try with a 120 s cap and no second
+chance: after a slow cold start, a transient fault in the child or a package
+cache that had to be rebuilt, the process ran until its next restart with no
+MCP tools. No email went out or came in, and the daily brief recorded "no
+deliverable channel configured" as if nothing had been set up.
+
+``GatewaySupervisor`` owns the attempts:
+
+* ``start`` makes the first attempt at boot, under the same cap as before.
+* When it fails, the supervisor keeps trying in the background with a growing
+ wait between attempts (``BACKOFF_S``, capped at its last value), for as
+ long as the process runs.
+* ``ensure`` is the lazy re-check for work that needs the gateway now (a
+ scheduled brief, an email follow-up, the poller): while the gateway is
+ down and no attempt is running, one is made right away instead of waiting
+ for the next retry; an attempt already running is awaited.
+* A successful attempt does what boot did: the gateway becomes the active
+ one (``set_active_gateway``), its pinned Google tools are primed and the
+ email poller starts.
+* ``status`` is what ``/health`` reports under ``gateway`` and what the Setup
+ status page and the brief's "not sent" notice read.
+
+The supervisor never raises out of an attempt except for a real cancellation
+of the task awaiting it: the failure modes are the ones ``api/main.py``
+contained in #122 (anyio exception groups, a silent child), and they are
+contained here the same way.
+"""
+from __future__ import annotations
+
+import asyncio
+import contextlib
+import logging
+from collections.abc import Sequence
+from dataclasses import dataclass
+from datetime import UTC, datetime
+from pathlib import Path
+from typing import TYPE_CHECKING, Any, Literal
+
+if TYPE_CHECKING:
+ from openexecutive.orchestrator.mcp_gateway import MCPGateway
+
+logger = logging.getLogger("openexecutive.orchestrator.gateway_boot")
+
+# Seconds to wait before each retry after a failed attempt: the first retry
+# after 30 s, then doubling, then every 10 minutes for good. A cold start
+# that has to clone extensible-mcp can genuinely take a couple of minutes, so
+# the early retries are not wasted on a child that just needed longer.
+BACKOFF_S: tuple[float, ...] = (30.0, 60.0, 120.0, 300.0, 600.0)
+# How long one attempt may take. The child is `uvx --from git+…`, which
+# resolves and may clone on a cold start, so this is generous; what it must
+# not be is unbounded: `ClientSession.initialize()` waits forever on a child
+# that is alive but silent.
+START_TIMEOUT_S = 120.0
+# Tearing down a gateway that just failed walks the same stdio machinery that
+# failed, so it gets a clock too.
+CLOSE_TIMEOUT_S = 10.0
+# How much of a failure's text /health and the Setup page carry.
+ERROR_TEXT_MAX = 300
+
+GatewayState = Literal["off", "no_servers", "starting", "up", "down"]
+
+
+@dataclass(frozen=True)
+class GatewayStatus:
+ """The gateway as /health reports it.
+
+ ``state``: ``off`` (MCP is not enabled), ``no_servers`` (enabled, but the
+ config names none), ``starting`` (an attempt is running: the first one,
+ or a retry), ``up`` or ``down`` (every attempt so far failed; the next
+ one is at ``next_retry_at``). ``attempts`` counts starts tried, so an
+ operator can tell a gateway that came up first time from one that needed
+ three tries. ``last_error`` is the last failure's text, kept after a
+ recovery so the log line is still findable.
+ """
+
+ state: GatewayState
+ attempts: int = 0
+ last_error: str | None = None
+ last_failed_at: datetime | None = None
+ up_since: datetime | None = None
+ next_retry_at: datetime | None = None
+ email_poller: bool = False
+
+ def as_dict(self) -> dict[str, Any]:
+ return {
+ "state": self.state,
+ "attempts": self.attempts,
+ "last_error": self.last_error,
+ "last_failed_at": self.last_failed_at.isoformat() if self.last_failed_at else None,
+ "up_since": self.up_since.isoformat() if self.up_since else None,
+ "next_retry_at": self.next_retry_at.isoformat() if self.next_retry_at else None,
+ "email_poller": self.email_poller,
+ }
+
+
+# How soon after a failed start ``ensure`` tries again on demand: the first
+# backoff step, so a burst of scheduled work doesn't chain start attempts.
+ENSURE_COOLDOWN_S = 30.0
+
+
+def _error_text(exc: BaseException) -> str:
+ text = f"{type(exc).__name__}: {exc}" if str(exc) else type(exc).__name__
+ return text[:ERROR_TEXT_MAX]
+
+
+class GatewaySupervisor:
+ """Starts the gateway, retries while it is down, and reports on it.
+
+ ``app_state`` is the FastAPI app's ``state`` (or anything with settable
+ attributes): the supervisor keeps ``mcp_gateway`` and ``mcp_prime_task``
+ on it, as boot always did, so ``/health`` and the Setup page read the
+ gateway from the app whether it came up at boot or later. ``servers`` is
+ what the config names (``configured_server_names``), already checked to
+ be non-empty by the caller, which also logs the reason MCP is on.
+ """
+
+ def __init__(
+ self,
+ *,
+ config_path: Path,
+ servers: Sequence[str],
+ app_state: Any = None,
+ start_timeout_s: float = START_TIMEOUT_S,
+ backoff_s: Sequence[float] = BACKOFF_S,
+ ensure_cooldown_s: float = ENSURE_COOLDOWN_S,
+ why: str = "",
+ ) -> None:
+ self._ensure_cooldown_s = ensure_cooldown_s
+ self._config_path = config_path
+ self._servers = tuple(servers)
+ self._app_state = app_state
+ self._start_timeout_s = start_timeout_s
+ self._backoff_s = tuple(backoff_s) or BACKOFF_S
+ self._why = why
+ self.gateway: MCPGateway | None = None
+ self.poller_task: asyncio.Task[None] | None = None
+ self.prime_task: asyncio.Task[Any] | None = None
+ self._retry_task: asyncio.Task[None] | None = None
+ self._attempt: asyncio.Task[bool] | None = None
+ self._lock = asyncio.Lock()
+ self._closed = False
+ self.attempts = 0
+ self.last_error: str | None = None
+ self.last_failed_at: datetime | None = None
+ self.up_since: datetime | None = None
+ self.next_retry_at: datetime | None = None
+
+ # -- state ---------------------------------------------------------------
+
+ @property
+ def is_up(self) -> bool:
+ return self.gateway is not None
+
+ def status(self) -> GatewayStatus:
+ if self.gateway is not None:
+ state: GatewayState = "up"
+ elif self._attempt is not None and not self._attempt.done():
+ state = "starting"
+ else:
+ state = "down"
+ return GatewayStatus(
+ state=state,
+ attempts=self.attempts,
+ last_error=self.last_error,
+ last_failed_at=self.last_failed_at,
+ up_since=self.up_since,
+ next_retry_at=self.next_retry_at if state == "down" else None,
+ email_poller=self.poller_task is not None and not self.poller_task.done(),
+ )
+
+ def problem(self, *, with_error: bool = True) -> str | None:
+ """Why the gateway is down, in one line, or None while it is up.
+ ``with_error`` appends the last failure's text: for the owner's own
+ notice and the log, not for a page every team member reads."""
+ if self.gateway is not None:
+ return None
+ if self.attempts == 0:
+ return "the MCP gateway has not started yet"
+ if self._attempt is not None and not self._attempt.done():
+ return f"the MCP gateway is starting (attempt {self.attempts + 1})"
+ detail = f": {self.last_error}" if self.last_error and with_error else ""
+ return f"the MCP gateway failed to start ({self.attempts} attempt{'s' if self.attempts != 1 else ''}){detail}"
+
+ # -- attempts ------------------------------------------------------------
+
+ async def start(self) -> bool:
+ """The boot attempt. On failure the background retries begin."""
+ ok = await self.attempt()
+ if not ok and not self._closed:
+ self._schedule_retry()
+ return ok
+
+ async def attempt(self) -> bool:
+ """One start, serialized: a second caller waits for the running one
+ and gets its outcome rather than starting a second child."""
+ if self.gateway is not None:
+ return True
+ if self._attempt is not None and not self._attempt.done():
+ return await asyncio.shield(self._attempt)
+ self._attempt = asyncio.ensure_future(self._attempt_once())
+ return await asyncio.shield(self._attempt)
+
+ async def ensure(self) -> MCPGateway | None:
+ """The gateway, starting it now if it is down and no attempt is
+ running. For work that needs it at this moment: a brief about to go
+ out should not wait ten minutes for the next scheduled retry when the
+ child may well come up now."""
+ if self.gateway is not None or self._closed:
+ return self.gateway
+ if (
+ self.last_failed_at is not None
+ and (datetime.now(UTC) - self.last_failed_at).total_seconds() < self._ensure_cooldown_s
+ and (self._attempt is None or self._attempt.done())
+ ):
+ # Just failed: a start now would only fail the same way and hold
+ # the caller for the whole timeout. The retry loop has it.
+ return None
+ try:
+ await self.attempt()
+ except asyncio.CancelledError:
+ raise
+ except BaseException:
+ logger.exception("MCP gateway re-check failed unexpectedly")
+ return self.gateway
+
+ async def _attempt_once(self) -> bool:
+ async with self._lock:
+ if self.gateway is not None:
+ return True
+ if self._closed:
+ return False
+ from openexecutive.orchestrator import mcp_gateway as gw_mod
+
+ self.attempts += 1
+ n = self.attempts
+ gateway = gw_mod.MCPGateway()
+ try:
+ await asyncio.wait_for(gateway.start(self._config_path), timeout=self._start_timeout_s)
+ except asyncio.CancelledError:
+ raise
+ except BaseException as exc:
+ self.last_error = _error_text(exc)
+ self.last_failed_at = datetime.now(UTC)
+ logger.exception(
+ "MCP gateway failed to start within %.0fs (attempt %d); continuing WITHOUT "
+ "MCP tools and without the email poller until a retry succeeds. "
+ "config=%s servers=[%s] (%s)",
+ self._start_timeout_s, n, self._config_path, ", ".join(self._servers), self._why,
+ )
+ await _close_quietly(gateway)
+ return False
+ self.gateway = gateway
+ self.up_since = datetime.now(UTC)
+ self.next_retry_at = None
+ self._wire(gateway, attempt=n)
+ return True
+
+ def _wire(self, gateway: MCPGateway, *, attempt: int) -> None:
+ """What boot did on a successful start, now on any successful start."""
+ from openexecutive.orchestrator import mcp_gateway as gw_mod
+
+ if self._app_state is not None:
+ self._app_state.mcp_gateway = gateway
+ gw_mod.set_active_gateway(gateway)
+ if "google_workspace" in self._servers:
+ # Discover the pinned Google tools now, so the model's first
+ # direct call_tool doesn't wait on the search. Held here: a bare
+ # create_task is only weakly referenced.
+ self.prime_task = asyncio.create_task(gateway.prime_pinned_tools())
+ if self._app_state is not None:
+ self._app_state.mcp_prime_task = self.prime_task
+ from openexecutive.integrations.email_poller import run_email_poller
+
+ self.poller_task = asyncio.create_task(run_email_poller(gateway))
+ if attempt > 1:
+ logger.warning(
+ "MCP gateway came up on attempt %d; MCP tools and the email poller are on",
+ attempt,
+ )
+
+ def _schedule_retry(self) -> None:
+ if self._retry_task is not None and not self._retry_task.done():
+ return
+ self._set_next_retry(self._delay_for(self.attempts))
+ self._retry_task = asyncio.create_task(self._retry_loop(), name="mcp-gateway-retry")
+
+ def _delay_for(self, failures: int) -> float:
+ index = min(max(failures - 1, 0), len(self._backoff_s) - 1)
+ return self._backoff_s[index]
+
+ def _set_next_retry(self, delay: float) -> None:
+ self.next_retry_at = datetime.fromtimestamp(datetime.now(UTC).timestamp() + delay, tz=UTC)
+
+ async def _retry_loop(self) -> None:
+ try:
+ while self.gateway is None and not self._closed:
+ delay = self._delay_for(self.attempts)
+ self._set_next_retry(delay)
+ logger.warning("MCP gateway retry in %.0fs", delay)
+ await asyncio.sleep(delay)
+ if self.gateway is not None or self._closed:
+ return
+ try:
+ await self.attempt()
+ except asyncio.CancelledError:
+ raise
+ except BaseException:
+ logger.exception("MCP gateway retry failed unexpectedly")
+ except asyncio.CancelledError:
+ raise
+ finally:
+ self.next_retry_at = None
+
+ # -- shutdown ------------------------------------------------------------
+
+ async def close(self) -> None:
+ """Stop retrying, stop the poller and priming, and close the gateway."""
+ self._closed = True
+ for task in (self._retry_task, self._attempt, self.poller_task, self.prime_task):
+ if task is not None and not task.done():
+ task.cancel()
+ with contextlib.suppress(asyncio.CancelledError, Exception):
+ await task
+ gateway, self.gateway = self.gateway, None
+ if gateway is not None:
+ from openexecutive.orchestrator import mcp_gateway as gw_mod
+
+ if gw_mod.get_active_gateway() is gateway:
+ gw_mod.set_active_gateway(None)
+ if self._app_state is not None:
+ self._app_state.mcp_gateway = None
+ await gateway.close()
+
+
+async def _close_quietly(gateway: Any) -> None:
+ """Reap a gateway that failed to start. Never raises, never hangs.
+
+ ``MCPGateway.close`` suppresses ``Exception`` around each step, which is
+ not enough here: anyio raises ``BaseExceptionGroup`` as soon as one
+ sub-exception is a ``BaseException`` such as ``CancelledError``, and that
+ is not an ``Exception``. Since this runs from inside an ``except`` block,
+ anything it raises replaces the actionable log just written with the crash
+ that log exists to prevent.
+ """
+ try:
+ await asyncio.wait_for(gateway.close(), timeout=CLOSE_TIMEOUT_S)
+ except asyncio.CancelledError:
+ raise
+ except BaseException:
+ logger.warning(
+ "MCP gateway teardown after a failed start did not finish cleanly; "
+ "continuing without the failed gateway anyway",
+ exc_info=True,
+ )
diff --git a/packages/core/openexecutive/orchestrator/mcp_gateway.py b/packages/core/openexecutive/orchestrator/mcp_gateway.py
index e8bd45ef..604bf7a3 100644
--- a/packages/core/openexecutive/orchestrator/mcp_gateway.py
+++ b/packages/core/openexecutive/orchestrator/mcp_gateway.py
@@ -2736,6 +2736,32 @@ class MCPGateway:
# as "every pinned tool is present" — only PinnedToolsProbe(missing=())
# asserts that.
self.pinned_tools: PinnedToolsProbe | None = None
+ # Servers whose sign-in has died (``mark_needs_reconnect``): the
+ # Connected Systems prompt section says so instead of "connected",
+ # and the Setup page shows it. Cleared by ``mark_reconnected`` or by
+ # the next call to one of that server's tools that answers without
+ # an authorization error.
+ self.needs_reconnect: set[str] = set()
+
+ def mark_needs_reconnect(self, server: str, reason: str | None = None) -> bool:
+ """Note that ``server``'s grant no longer works. True when this is
+ news (the first report), so the caller can log or notify once."""
+ if server in self.needs_reconnect:
+ return False
+ self.needs_reconnect.add(server)
+ logger.warning(
+ "MCP server %s needs reconnecting%s; the prompt now says so",
+ server, f": {reason[:200]}" if reason else "",
+ )
+ return True
+
+ def mark_reconnected(self, server: str) -> bool:
+ """The grant works again (a reconnect, or a call that succeeded)."""
+ if server not in self.needs_reconnect:
+ return False
+ self.needs_reconnect.discard(server)
+ logger.info("MCP server %s is connected again", server)
+ return True
async def start(self, config_path: Path) -> None:
from mcp import ClientSession, StdioServerParameters
@@ -3028,6 +3054,7 @@ class MCPGateway:
and not _reveal_tokens.get()
):
result_text = hide_roster_tokens(result_text)
+ self._note_grant_health(tool_name, result_text)
if tool_name in drive_reads.DRIVE_READ_TOOLS:
result_text = _remember_drive_read(tool_name, arguments, result_text)
if normalized == _M365_DOWNLOAD_TOOL and isinstance(arguments.get("target"), str):
@@ -3057,6 +3084,19 @@ class MCPGateway:
)
return result_text
+ def _note_grant_health(self, tool_name: object, result_text: str) -> None:
+ """Read a tool's answer for a dead grant (``grant_failure``) and keep
+ ``needs_reconnect`` in step: an authorization failure marks the
+ server, an answer that is not one clears it."""
+ server = _server_of(tool_name)
+ if server is None:
+ return
+ failure = grant_failure(result_text)
+ if failure is not None:
+ self.mark_needs_reconnect(server, failure)
+ elif server in self.needs_reconnect:
+ self.mark_reconnected(server)
+
async def load_mcp_server(self, tool_input: dict[str, Any]) -> str:
from openexecutive.delegation.lockdown import outside_reach_refusal
@@ -3152,6 +3192,69 @@ def get_active_gateway() -> MCPGateway | None:
return _active_gateway
+# What a Google or Microsoft tool answers once the stored grant is dead:
+# workspace-mcp relays google-auth's "invalid_grant: Token has been expired or
+# revoked", the Graph server a 401 / InvalidAuthenticationToken. A rate limit,
+# a missing scope on one call or a 403 on a single file is not a dead grant,
+# so none of those match.
+_GRANT_FAILURE_RE = re.compile(
+ r"invalid_grant|token has been (?:expired|revoked)|refresh ?token (?:is )?(?:expired|revoked|invalid)"
+ r"|invalidauthenticationtoken|(?:^|[^\w])401(?:[^\w]|$).{0,80}unauthori[sz]ed"
+ r"|unauthori[sz]ed.{0,80}(?:^|[^\w])401(?:[^\w]|$)|reauthentication (?:is )?required"
+ r"|credentials (?:have |are )?(?:expired|been revoked)|invalid authentication credentials"
+ r"|\bUNAUTHENTICATED\b",
+ re.IGNORECASE | re.DOTALL,
+)
+# How much of a result is read for it: an error comes first; a long mailbox
+# listing quoting the words "invalid_grant" is not one.
+_GRANT_FAILURE_SCAN_CHARS = 4000
+
+
+# How a failed call reads as text (the gateway's gates and the MCP client
+# render errors these ways; workflows/action_step.py reads the same). A
+# successful answer that happens to open with "error" ("Errors in Q3…") is
+# not one, and a model-echoed argument never starts a result.
+_ERROR_TEXT_PREFIXES = ("Error: ", "Error calling tool ", "Tool error:", "Error executing tool ")
+
+
+def grant_failure(result_text: object) -> str | None:
+ """The authorization failure a tool result reports, in a line, or None
+ when the result is not one. Only an error payload counts (``{"error":
+ …}``, or text that opens with an error marker), never a successful
+ answer that merely quotes those words."""
+ if not isinstance(result_text, str) or not result_text:
+ return None
+ head = result_text[:_GRANT_FAILURE_SCAN_CHARS]
+ error: str | None = None
+ try:
+ parsed = json.loads(head) if head.lstrip().startswith("{") else None
+ except (ValueError, TypeError):
+ parsed = None
+ if isinstance(parsed, dict):
+ if "error" not in parsed:
+ return None
+ error = json.dumps(parsed.get("error"))[:_GRANT_FAILURE_SCAN_CHARS]
+ elif head.lstrip().startswith(_ERROR_TEXT_PREFIXES):
+ error = head
+ if error is None:
+ return None
+ match = _GRANT_FAILURE_RE.search(error)
+ if match is None:
+ return None
+ start = max(match.start() - 40, 0)
+ return " ".join(error[start:match.end() + 80].split())[:200]
+
+
+def _server_of(tool_name: object) -> str | None:
+ """The server a prefixed tool name belongs to (``google_workspace__x`` →
+ ``google_workspace``), or None."""
+ if not isinstance(tool_name, str):
+ return None
+ normalized = _normalize_tool_name(tool_name)
+ server, sep, _ = normalized.partition("__")
+ return server if sep and server else None
+
+
def gateway_server_names(gateway: object) -> tuple[str, ...]:
"""The servers ``gateway`` started with, or () for no gateway (or a
stand-in without the attribute)."""
@@ -3159,3 +3262,57 @@ def gateway_server_names(gateway: object) -> tuple[str, ...]:
if not isinstance(names, tuple | list):
return ()
return tuple(n for n in names if isinstance(n, str))
+
+
+def gateway_reconnect_needed(gateway: object) -> tuple[str, ...]:
+ """The servers ``gateway`` has marked as needing a reconnect, sorted; ()
+ for no gateway or a stand-in without the attribute."""
+ names = getattr(gateway, "needs_reconnect", ())
+ if not isinstance(names, set | frozenset | tuple | list):
+ return ()
+ return tuple(sorted(n for n in names if isinstance(n, str)))
+
+
+# The supervisor that starts the gateway and retries while it is down
+# (orchestrator/gateway_boot.py). Set by the app lifespan next to the active
+# gateway, so code that is about to need the gateway can ask for a start now
+# (``ensure_active_gateway``) and the Setup page can say why it is down.
+_supervisor: Any = None
+
+
+def set_gateway_supervisor(supervisor: Any) -> None:
+ global _supervisor
+ _supervisor = supervisor
+
+
+def get_gateway_supervisor() -> Any:
+ return _supervisor
+
+
+async def ensure_active_gateway() -> MCPGateway | None:
+ """The active gateway, after a start attempt if it is down and the
+ supervisor is not already in one. The lazy re-check before a scheduled
+ delivery: with no supervisor (tests, a process started without the
+ lifespan) this is just ``get_active_gateway``."""
+ if _active_gateway is not None or _supervisor is None:
+ return _active_gateway
+ try:
+ await _supervisor.ensure()
+ except asyncio.CancelledError:
+ raise
+ except Exception:
+ logger.exception("MCP gateway re-check failed")
+ return _active_gateway
+
+
+def gateway_problem(*, with_error: bool = True) -> str | None:
+ """Why there is no active gateway, in one line, or None while there is
+ one. Without a supervisor the answer is only that it is not running.
+ ``with_error=False`` leaves the failure's text out (a page every team
+ member reads)."""
+ if _active_gateway is not None:
+ return None
+ if _supervisor is None:
+ return "the MCP gateway is not running"
+ problem = _supervisor.problem(with_error=with_error)
+ return str(problem) if problem else "the MCP gateway is not running"
diff --git a/packages/core/openexecutive/prompts/cache_manager.py b/packages/core/openexecutive/prompts/cache_manager.py
index fb0d6147..80c6da46 100644
--- a/packages/core/openexecutive/prompts/cache_manager.py
+++ b/packages/core/openexecutive/prompts/cache_manager.py
@@ -40,6 +40,7 @@ def build_system_blocks(
include_contacts: bool = False,
delegation: bool = False,
mcp_servers: Sequence[str] = (),
+ needs_reconnect: Sequence[str] = (),
persona_instructions: str | None = None,
) -> list[dict[str, Any]]:
"""Build system prompt blocks with correct cache_control ordering.
@@ -156,7 +157,9 @@ def build_system_blocks(
# (Executive._script_tools): a setting, so constant per deployment.
+ (TOOL_BUILDING_ADDENDUM if mcp_enabled and _chat_scripts_on(settings) else "")
+ identity_addendum
- + render_connected_systems(mcp_servers=mcp_servers, settings=settings)
+ + render_connected_systems(
+ mcp_servers=mcp_servers, settings=settings, needs_reconnect=needs_reconnect
+ )
+ (DELEGATION_ADDENDUM if delegation else "")
+ tz_addendum
)
diff --git a/packages/core/openexecutive/prompts/connected_systems.py b/packages/core/openexecutive/prompts/connected_systems.py
index 2d2ce9ec..02dc5f94 100644
--- a/packages/core/openexecutive/prompts/connected_systems.py
+++ b/packages/core/openexecutive/prompts/connected_systems.py
@@ -147,17 +147,23 @@ def render_connected_systems(
*,
mcp_servers: Sequence[str],
settings: Settings,
+ needs_reconnect: Sequence[str] = (),
) -> str:
"""The ``## Connected Systems`` section of block 0.
``mcp_servers`` is what the running gateway was configured with (empty
when MCP is off or the gateway failed to start, so a Google server that
- never came up is never described as connected). Act as me is named by a
- constant line that points at ``DELEGATION_ADDENDUM``, which block 0
- carries only while it is on.
+ never came up is never described as connected). ``needs_reconnect`` is
+ the servers whose sign-in has died (``MCPGateway.needs_reconnect``): a
+ Google server in it is described as needing a reconnect, not as
+ connected, so the model stops promising mail it cannot read. The block
+ is re-rendered, and re-cached once, when that set changes. Act as me is
+ named by a constant line that points at ``DELEGATION_ADDENDUM``, which
+ block 0 carries only while it is on.
"""
servers = sorted({s for s in mcp_servers if _SERVER_NAME_RE.fullmatch(s)})
google = GOOGLE_SERVER in servers
+ google_dead = google and GOOGLE_SERVER in set(needs_reconnect)
others = [s for s in servers if s != GOOGLE_SERVER]
email = settings.exec_email_address
@@ -168,7 +174,16 @@ def render_connected_systems(
"to find out.\n",
]
- if google:
+ if google_dead:
+ lines.append(
+ f"- **Google Workspace: needs reconnecting.** Your sign-in as {email} "
+ "has expired or was revoked, so you cannot read or send email, see "
+ "calendars, or open Drive, Docs or Sheets files until the owner "
+ "connects Google again (Settings → Status). If asked, say so plainly "
+ "and do not call the Google tools: every call fails with the same "
+ "authorization error until then."
+ )
+ elif google:
manifest = google_tool_manifest(settings)
# Derived, never hardcoded: naming all five while a subset is loaded is
# the whole bug. Ordered as the manifest is, so the text is stable.
diff --git a/packages/core/openexecutive/scheduler/runner.py b/packages/core/openexecutive/scheduler/runner.py
index 8ea54404..0f2729c6 100644
--- a/packages/core/openexecutive/scheduler/runner.py
+++ b/packages/core/openexecutive/scheduler/runner.py
@@ -1070,14 +1070,25 @@ async def _execute_action(
logger.info("scheduler: action %d (__internal__) completed without dispatch", action.id)
return
+ # The gateway the scheduler was started with is the one boot had, which
+ # is None when the first start failed; a retry may have brought one up
+ # since, and this is the moment to try once more if not
+ # (orchestrator.gateway_boot).
+ if gateway is None and action.channel == "email":
+ from openexecutive.orchestrator.mcp_gateway import ensure_active_gateway
+
+ gateway = await ensure_active_gateway()
+
# Email channel requires MCP (the mail send tool is an MCP tool, whichever
# backend EMAIL_PROVIDER names). Without a gateway, the Executive cannot
# deliver — short-circuit with a clear error rather than burning attempts
# on silent failures.
if action.channel == "email" and gateway is None:
+ from openexecutive.orchestrator.mcp_gateway import gateway_problem
+
mark_action_failed_or_retry(
action.id,
- "email channel requires MCP gateway, which is not configured",
+ f"email channel requires the MCP gateway: {gateway_problem()}",
)
logger.warning(
"scheduler: action %d (email) cannot run without MCP gateway",
@@ -1792,24 +1803,53 @@ def google_workspace_ready() -> bool:
return "google_workspace" in configured_server_names(get_settings().mcp_servers_config_path)
-def email_ready() -> bool:
- """Whether the Executive can send email: the MCP gateway is up and runs
- the server of the configured mail backend (``EMAIL_PROVIDER``: the Google
- Workspace server for Gmail, the Microsoft 365 one for Outlook)."""
+def mail_server_configured() -> bool:
+ """Whether the MCP config names the server of the configured mail backend
+ (``EMAIL_PROVIDER``: the Google Workspace server for Gmail, the Microsoft
+ 365 one for Outlook) — email is set up, whether or not the gateway that
+ runs it is up right now."""
from openexecutive.config import get_settings
from openexecutive.integrations.workspace.registry import get_mail_provider
- from openexecutive.orchestrator.mcp_gateway import (
- configured_server_names,
- get_active_gateway,
- )
+ from openexecutive.orchestrator.mcp_gateway import configured_server_names
- if get_active_gateway() is None:
- return False
settings = get_settings()
server = get_mail_provider(settings).server_name
return server in configured_server_names(settings.mcp_servers_config_path)
+def email_ready() -> bool:
+ """Whether the Executive can send email: the MCP gateway is up and runs
+ the server of the configured mail backend (``mail_server_configured``)."""
+ from openexecutive.orchestrator.mcp_gateway import get_active_gateway
+
+ return get_active_gateway() is not None and mail_server_configured()
+
+
+def mail_gateway_problem(person: Person | None, *, with_error: bool = True) -> str | None:
+ """Why email to ``person`` is blocked by the gateway, in a line, or None.
+
+ Only when email is the Executive's fault: ``person`` has an address and
+ the mail server is configured, but the gateway that sends is not
+ running. Nothing when email was never set up, or when it works.
+ """
+ from openexecutive.orchestrator.mcp_gateway import gateway_problem
+
+ if person is None or not getattr(person, "email", None) or not mail_server_configured():
+ return None
+ return gateway_problem(with_error=with_error)
+
+
+async def ensure_email_ready() -> bool:
+ """``email_ready``, after the lazy re-check: with the gateway down and
+ email otherwise set up, ask the supervisor for a start now rather than
+ sending nothing and waiting for the next scheduled retry."""
+ if mail_server_configured():
+ from openexecutive.orchestrator.mcp_gateway import ensure_active_gateway
+
+ await ensure_active_gateway()
+ return email_ready()
+
+
def principal_delivery_plan() -> tuple[Person | None, list[str]]:
"""The principal Person row and the channels to try, in order."""
from openexecutive.people.store import find_principal_person
@@ -1836,22 +1876,25 @@ def _email_subject(label: str, now: datetime | None = None) -> str:
return f"{label} — {local:%a} {local.day} {local:%b}"
-async def _email_principal(principal: Person, text: str, label: str) -> bool:
+async def _email_principal(principal: Person, text: str, label: str) -> str | None:
"""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
- the tool reports an error in-band.
+ the gateway's egress gate allows it). None on a clean send; otherwise
+ what went wrong in a line — no gateway, no address, or the error the
+ tool reported in-band — for the delivery record.
"""
from openexecutive.integrations.workspace.registry import send_from_executive
- from openexecutive.orchestrator.mcp_gateway import get_active_gateway
+ from openexecutive.orchestrator.mcp_gateway import gateway_problem, 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()
- if gateway is None or not principal.email:
- return False
+ if not principal.email:
+ return "no email address"
+ if gateway is None:
+ return gateway_problem() or "the MCP gateway is not running"
result = await send_from_executive(
gateway,
to=principal.email,
@@ -1861,8 +1904,31 @@ async def _email_principal(principal: Person, text: str, label: str) -> bool:
)
if looks_like_error(result):
logger.warning("scheduler: email to the principal failed: %s", result[:300])
- return False
- return True
+ return _error_line(result)
+ return None
+
+
+def _error_line(result: str) -> str:
+ """The error a tool handler reported, in a line: the ``error`` value of
+ its JSON, else the text itself, cut short."""
+ import json as _json
+
+ text = result
+ try:
+ parsed = _json.loads(result)
+ except (ValueError, TypeError):
+ parsed = None
+ if isinstance(parsed, dict):
+ error = parsed.get("error")
+ if error is not None:
+ text = error if isinstance(error, str) else _json.dumps(error)
+ elif parsed.get("status") != "sent":
+ text = f"status {parsed.get('status')!r}, not sent"
+ return " ".join(str(text).split())[:_FAILURE_LINE_MAX]
+
+
+# The longest per-channel failure kept in a delivery's detail.
+_FAILURE_LINE_MAX = 200
@dataclass(frozen=True)
@@ -1886,9 +1952,12 @@ async def _deliver_to_principal(text: str, *, label: str = "Update") -> Principa
action done (no point retrying the same misconfiguration) but audits the
failure.
"""
- principal, plan = principal_delivery_plan()
+ from openexecutive.people.store import find_principal_person
+
+ principal = find_principal_person()
if principal is None:
return PrincipalDelivery(False, "no principal Person row found", "no_owner")
+ plan = delivery_order(principal, email_ready=await ensure_email_ready())
return await _send_on_plan(principal, plan, text, label=label)
@@ -1896,7 +1965,8 @@ async def deliver_to_person(person: Person, text: str, *, label: str = "Update")
"""Send ``text`` to ``person`` alone, the way the briefs reach the
principal: their own Slack or Discord DM, their Telegram chat, or email
to their own address (``delivery_order``, which skips a Telegram group)."""
- return await _send_on_plan(person, delivery_order(person, email_ready=email_ready()), text, label=label)
+ plan = delivery_order(person, email_ready=await ensure_email_ready())
+ return await _send_on_plan(person, plan, text, label=label)
async def _send_on_plan(
@@ -1905,10 +1975,17 @@ async def _send_on_plan(
"""Try ``plan``'s channels for ``principal`` (any Person) in order until
one sends."""
if not plan:
+ # Email set up but its gateway down is the Executive's fault, not a
+ # missing setting: say so, with the start failure, instead of
+ # "nothing is set up" (which told the owner to connect what they had).
+ blocked = mail_gateway_problem(principal)
+ if blocked is not None:
+ return PrincipalDelivery(False, f"email not available: {blocked}", "gateway_down")
return PrincipalDelivery(
False, "no deliverable channel configured for principal", "no_channel"
)
+ failures: list[str] = []
for channel in plan:
try:
if channel == "slack_dm" and principal.slack_user_id:
@@ -1918,6 +1995,7 @@ async def _send_on_plan(
})
if _delivered_ok(result):
return _sent(channel, principal.slack_user_id)
+ failures.append(f"{channel}: {_error_line(result)}")
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({
@@ -1925,6 +2003,7 @@ async def _send_on_plan(
})
if _delivered_ok(result):
return _sent(channel, principal.discord_user_id)
+ failures.append(f"{channel}: {_error_line(result)}")
elif channel == "telegram" and principal.telegram_chat_id:
from openexecutive.orchestrator.schedule_tools import (
handle_send_telegram_message,
@@ -1934,13 +2013,20 @@ async def _send_on_plan(
})
if _delivered_ok(result):
return _sent(channel, principal.telegram_chat_id)
- elif channel == "email" and await _email_principal(principal, text, label):
- return _sent(channel, principal.email)
- except Exception:
+ failures.append(f"{channel}: {_error_line(result)}")
+ elif channel == "email":
+ error = await _email_principal(principal, text, label)
+ if error is None:
+ return _sent(channel, principal.email)
+ failures.append(f"email: {error}")
+ else:
+ failures.append(f"{channel}: no id to send to")
+ except Exception as exc:
logger.exception("scheduler: delivery via %s failed", channel)
+ failures.append(f"{channel}: {_error_line(str(exc) or type(exc).__name__)}")
return PrincipalDelivery(
- False, f"delivery failed on every channel ({', '.join(plan)})", "send_failed"
+ False, "delivery failed on every channel: " + "; ".join(failures), "send_failed"
)
@@ -2146,7 +2232,8 @@ async def _run_principal_brief(action: ScheduledAction, now: datetime) -> None:
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
+ kind, reason=delivery.reason, channel=delivery.channel,
+ detail=None if ok else detail,
)
recorded = True
if ok:
@@ -2179,7 +2266,8 @@ async def _run_principal_brief(action: ScheduledAction, now: datetime) -> None:
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
+ kind, reason="send_failed" if sending else "not_written", channel=None,
+ detail=f"{type(exc).__name__}: {exc}" if str(exc) else type(exc).__name__,
)
# Always chain the next occurrence + mark this row done, so a single
diff --git a/packages/core/tests/unit/test_delivery_failure_reasons.py b/packages/core/tests/unit/test_delivery_failure_reasons.py
new file mode 100644
index 00000000..c25e5858
--- /dev/null
+++ b/packages/core/tests/unit/test_delivery_failure_reasons.py
@@ -0,0 +1,418 @@
+"""What the owner is told when a brief doesn't reach them, and why.
+
+ * Email set up but the MCP gateway down is ``gateway_down`` — the
+ Executive's fault, named as such — not ``no_channel`` (which told the
+ owner to connect what they had already connected).
+ * A send that fails records what happened, per channel, and the notice
+ repeats it; a dead grant in it turns the fix into "reconnect".
+ * A delivery asks the gateway supervisor for a start first.
+ * A Google tool answering with an authorization failure marks the server
+ as needing a reconnect: the prompt block stops saying "connected", the
+ Setup page says so, and a working answer clears it.
+"""
+from __future__ import annotations
+
+import asyncio
+import json
+from datetime import UTC, datetime
+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, check_gmail
+from openexecutive.briefing import brief_state, narrative_cache
+from openexecutive.briefing.brief_state import DeliveryOutcome
+from openexecutive.config import Settings
+from openexecutive.orchestrator import mcp_gateway
+from openexecutive.orchestrator.mcp_gateway import (
+ MCPGateway,
+ gateway_reconnect_needed,
+ grant_failure,
+)
+from openexecutive.people.models import Person
+from openexecutive.prompts.connected_systems import render_connected_systems
+from openexecutive.scheduler import runner
+
+NOW = datetime(2026, 10, 13, 8, 0, tzinfo=UTC)
+MORNING = "principal_brief_morning"
+DEAD_GRANT = json.dumps({
+ "error": "RefreshError: ('invalid_grant: Token has been expired or revoked.', "
+ "{'error': 'invalid_grant', 'error_description': 'Token has been expired or revoked.'})"
+})
+
+
[email protected](autouse=True)
+def _env(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
+ monkeypatch.setenv("ANTHROPIC_API_KEY", "test-key")
+ monkeypatch.setenv("EXEC_EMAIL_ADDRESS", "[email protected]")
+ monkeypatch.setattr(narrative_cache, "DB_PATH", tmp_path / "cache.db")
+ monkeypatch.setattr(mcp_gateway, "_active_gateway", None)
+ monkeypatch.setattr(mcp_gateway, "_supervisor", None)
+
+
+def _owner(**fields: Any) -> Person:
+ return Person(**{"id": 3, "full_name": "Ada", "is_principal": True, "email": "[email protected]", **fields})
+
+
+def _mail_configured(monkeypatch: pytest.MonkeyPatch, configured: bool = True) -> None:
+ monkeypatch.setattr(
+ mcp_gateway, "configured_server_names",
+ lambda _path: ["google_workspace"] if configured else [],
+ )
+
+
+# -- the record and the notice ---------------------------------------------------
+
+
+def test_the_detail_round_trips_and_older_rows_still_read() -> None:
+ brief_state.record_delivery_outcome(
+ MORNING, reason="send_failed", channel=None, detail="email: invalid_grant\n revoked",
+ )
+ latest = brief_state.last_delivery_outcome()
+ assert latest is not None
+ assert (latest.reason, latest.channel, latest.detail) == ("send_failed", None, "email: invalid_grant revoked")
+
+ brief_state.record_delivery_outcome(MORNING, reason="delivered", channel="email")
+ latest = brief_state.last_delivery_outcome()
+ assert latest is not None and (latest.channel, latest.detail) == ("email", None)
+
+
+def test_a_long_detail_is_cut_to_a_line() -> None:
+ brief_state.record_delivery_outcome(MORNING, reason="send_failed", channel=None, detail="x" * 1000)
+ latest = brief_state.last_delivery_outcome()
+ assert latest is not None and latest.detail is not None
+ assert len(latest.detail) == brief_state.DETAIL_MAX_CHARS
+
+
+ ("reason", "detail", "problem", "fix_has"),
+ [
+ ("gateway_down", "the MCP gateway failed to start (3 attempts): RuntimeError: boom",
+ "the Executive's mail connection wasn't running (the MCP gateway failed to start (3 attempts): "
+ "RuntimeError: boom)", "retrying on its own"),
+ ("send_failed", "email: invalid_grant: Token has been expired or revoked",
+ "every way of sending it failed (email: invalid_grant: Token has been expired or revoked)",
+ "connect it again"),
+ ("send_failed", "slack_dm: channel_not_found",
+ "every way of sending it failed (slack_dm: channel_not_found)", "Setup status page"),
+ ("no_channel", "ignored", "nothing is set up to send it to you", "Connect Gmail"),
+ ("send_failed", None, "every way of sending it failed", "Setup status page"),
+ ],
+)
+def test_describe_problem(reason: str, detail: str | None, problem: str, fix_has: str) -> None:
+ got_problem, got_fix = brief_state.describe_problem(reason, detail) # type: ignore[arg-type]
+ assert got_problem == problem
+ assert fix_has in got_fix
+
+
+ ("recorded", "gateway_down", "can_deliver", "problem"),
+ [
+ ("no_channel", True, False, "gateway_down"), # it was the gateway all along
+ ("gateway_down", True, False, "gateway_down"),
+ ("gateway_down", False, False, "no_channel"), # the gateway is up, nothing else is
+ ("gateway_down", False, True, None), # fixed since
+ ("no_owner", True, False, "gateway_down"),
+ ],
+)
+def test_current_problem_names_the_gateway(
+ recorded: str, gateway_down: 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=True, can_deliver=can_deliver, gateway_down=gateway_down
+ ) == problem
+
+
+def test_no_owner_still_wins_over_the_gateway() -> None:
+ outcome = DeliveryOutcome(MORNING, "no_channel", None, NOW)
+ assert brief_state.current_problem(outcome, has_owner=False, can_deliver=False, gateway_down=True) == "no_owner"
+
+
+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
+
+ state: dict[str, Any] = {"principal": _owner(), "plan": [], "problem": None}
+ monkeypatch.setattr(chat_route, "_caller_is_principal_or_unclaimed", lambda _r: True)
+ monkeypatch.setattr(runner, "principal_delivery_plan", lambda: (state["principal"], state["plan"]))
+ monkeypatch.setattr(runner, "mail_gateway_problem", lambda _p, **_kw: state["problem"])
+ app = FastAPI()
+ app.include_router(today_route.router)
+ return TestClient(app), state
+
+
+def test_the_notice_blames_the_gateway_not_the_owner(notice_client: Any) -> None:
+ client, state = notice_client
+ state["problem"] = "the MCP gateway failed to start (2 attempts): RuntimeError: boom"
+ brief_state.record_delivery_outcome(MORNING, reason="gateway_down", channel=None, detail="stale")
+ body = client.get("/today/brief-delivery").json()
+ assert body["problem"] == (
+ "the Executive's mail connection wasn't running "
+ "(the MCP gateway failed to start (2 attempts): RuntimeError: boom)"
+ )
+ assert "retrying on its own" in body["fix"]
+
+
+def test_the_notice_repeats_what_the_send_said(notice_client: Any) -> None:
+ client, state = notice_client
+ state["plan"] = ["email"]
+ brief_state.record_delivery_outcome(
+ MORNING, reason="send_failed", channel=None, detail="email: invalid_grant: Token has been expired or revoked",
+ )
+ body = client.get("/today/brief-delivery").json()
+ assert "invalid_grant" in body["problem"] and "connect it again" in body["fix"]
+
+
+# -- the delivery path -----------------------------------------------------------
+
+
+class _Supervisor:
+ def __init__(self, gateway: Any = None, problem: str | None = "the MCP gateway failed to start (1 attempt)") -> None:
+ self.gateway = gateway
+ self.ensured = 0
+ self._problem = problem
+
+ async def ensure(self) -> Any:
+ self.ensured += 1
+ if self.gateway is not None:
+ mcp_gateway.set_active_gateway(self.gateway)
+ return self.gateway
+
+ def problem(self, *, with_error: bool = True) -> str | None:
+ return None if self.gateway is not None else self._problem
+
+
+def test_email_only_with_the_gateway_down_is_gateway_down(monkeypatch: pytest.MonkeyPatch) -> None:
+ _mail_configured(monkeypatch)
+ sup = _Supervisor()
+ mcp_gateway.set_gateway_supervisor(sup)
+
+ result = asyncio.run(runner.deliver_to_person(_owner(), "BRIEF", label="Morning Brief"))
+
+ assert sup.ensured == 1, "the delivery asked for a start first"
+ assert result.reason == "gateway_down" and not result.ok
+ assert result.detail == "email not available: the MCP gateway failed to start (1 attempt)"
+
+
+def test_no_email_set_up_is_still_no_channel(monkeypatch: pytest.MonkeyPatch) -> None:
+ _mail_configured(monkeypatch, configured=False)
+ sup = _Supervisor()
+ mcp_gateway.set_gateway_supervisor(sup)
+
+ result = asyncio.run(runner.deliver_to_person(_owner(), "BRIEF"))
+
+ assert sup.ensured == 0, "nothing to start for"
+ assert result.reason == "no_channel"
+
+
+def test_a_late_gateway_carries_the_brief(monkeypatch: pytest.MonkeyPatch) -> None:
+ """The gateway was down at boot; the re-check before the send brings it
+ up, and the brief goes by email."""
+ _mail_configured(monkeypatch)
+ sent: list[dict[str, Any]] = []
+
+ class _Gateway:
+ async def call_tool(self, tool_input: dict[str, Any]) -> str:
+ sent.append(tool_input)
+ return "Email sent! Message ID: m-1"
+
+ mcp_gateway.set_gateway_supervisor(_Supervisor(gateway=_Gateway()))
+
+ result = asyncio.run(runner.deliver_to_person(_owner(), "BRIEF", label="Morning Brief"))
+
+ assert result.ok and result.channel == "email" and len(sent) == 1
+
+
+def test_every_channel_failing_says_what_each_said(monkeypatch: pytest.MonkeyPatch) -> None:
+ _mail_configured(monkeypatch)
+
+ class _Gateway:
+ async def call_tool(self, tool_input: dict[str, Any]) -> str:
+ return DEAD_GRANT
+
+ mcp_gateway.set_active_gateway(_Gateway()) # type: ignore[arg-type]
+
+ async def _slack(args: dict[str, Any]) -> str:
+ return json.dumps({"error": "channel_not_found"})
+
+ monkeypatch.setattr("openexecutive.orchestrator.schedule_tools.handle_send_slack_dm", _slack)
+
+ result = asyncio.run(runner.deliver_to_person(_owner(slack_user_id="U1"), "BRIEF"))
+
+ assert result.reason == "send_failed"
+ assert result.detail.startswith("delivery failed on every channel: slack_dm: channel_not_found; email: ")
+ assert "invalid_grant" in result.detail
+
+
+def test_a_handler_that_raises_is_named_too(monkeypatch: pytest.MonkeyPatch) -> None:
+ _mail_configured(monkeypatch, configured=False)
+
+ async def _slack(args: dict[str, Any]) -> str:
+ raise RuntimeError("Slack is down")
+
+ monkeypatch.setattr("openexecutive.orchestrator.schedule_tools.handle_send_slack_dm", _slack)
+ result = asyncio.run(runner.deliver_to_person(_owner(slack_user_id="U1"), "BRIEF"))
+ assert result.detail == "delivery failed on every channel: slack_dm: Slack is down"
+
+
+def test_mail_gateway_problem_only_when_email_is_the_executives_fault(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ _mail_configured(monkeypatch)
+ mcp_gateway.set_gateway_supervisor(_Supervisor(problem="boom"))
+ assert runner.mail_gateway_problem(_owner()) == "boom"
+ assert runner.mail_gateway_problem(_owner(email="")) is None
+ assert runner.mail_gateway_problem(None) is None
+ _mail_configured(monkeypatch, configured=False)
+ assert runner.mail_gateway_problem(_owner()) is None
+
+
+# -- a grant that died ------------------------------------------------------------
+
+
+ "text",
+ [
+ DEAD_GRANT,
+ json.dumps({"error": {"code": 401, "message": "Request had invalid authentication credentials. "
+ "Expected OAuth 2 access token", "status": "UNAUTHENTICATED"}}),
+ "Error: InvalidAuthenticationToken: Access token has expired or is not yet valid.",
+ '{"error": "Reauthentication is required"}',
+ ],
+)
+def test_grant_failure_reads_an_authorization_error(text: str) -> None:
+ assert grant_failure(text) is not None
+
+
+ "text",
+ [
+ "",
+ json.dumps({"result": "3 messages", "messages": [{"subject": "Re: invalid_grant on the staging box"}]}),
+ json.dumps({"error": "Rate limit exceeded; retry after 30s"}),
+ json.dumps({"error": "403 Forbidden: the caller does not have permission on file X"}),
+ "Email sent! Message ID: m-1",
+ "Errors in Q3: the invalid_grant tickets were closed; token expired on the staging box",
+ "failed to find a slot; the token expired note is in the thread",
+ ],
+)
+def test_grant_failure_ignores_other_answers(text: str) -> None:
+ assert grant_failure(text) is None
+
+
+def test_a_dead_grant_marks_the_server_and_a_working_answer_clears_it() -> None:
+ gateway = MCPGateway()
+ gateway.server_names = ("google_workspace",)
+ assert gateway_reconnect_needed(gateway) == ()
+
+ gateway._note_grant_health("google_workspace__search_gmail_messages", DEAD_GRANT)
+ assert gateway_reconnect_needed(gateway) == ("google_workspace",)
+ assert gateway.mark_needs_reconnect("google_workspace") is False, "already known"
+
+ gateway._note_grant_health("fetch__get", '{"error": "invalid_grant"}')
+ assert gateway_reconnect_needed(gateway) == ("fetch", "google_workspace")
+
+ gateway._note_grant_health("google_workspace__get_events", '{"result": []}')
+ assert gateway_reconnect_needed(gateway) == ("fetch",)
+ assert gateway_reconnect_needed(object()) == ()
+
+
+def test_the_prompt_block_stops_saying_connected() -> None:
+ from openexecutive.config import get_settings
+
+ settings = get_settings()
+ connected = render_connected_systems(mcp_servers=("google_workspace",), settings=settings)
+ dead = render_connected_systems(
+ mcp_servers=("google_workspace",), settings=settings, needs_reconnect=("google_workspace",),
+ )
+ assert "Google Workspace: connected" in connected
+ assert "Google Workspace: connected" not in dead
+ assert "needs reconnecting" in dead and "[email protected]" in dead
+ assert "google_workspace__send_gmail_message" not in dead, "no tool names to reach for"
+ # Another server dying says nothing about Google.
+ other = render_connected_systems(
+ mcp_servers=("google_workspace",), settings=settings, needs_reconnect=("fetch",),
+ )
+ assert other == connected
+
+
+def test_the_executive_rerenders_block_0_from_the_gateway_state(monkeypatch: pytest.MonkeyPatch) -> None:
+ from openexecutive.prompts.cache_manager import build_system_blocks
+
+ seen: list[tuple[str, ...]] = []
+ real = render_connected_systems
+
+ def _spy(**kw: Any) -> str:
+ seen.append(tuple(kw.get("needs_reconnect", ())))
+ return real(**kw)
+
+ monkeypatch.setattr("openexecutive.prompts.cache_manager.render_connected_systems", _spy)
+ build_system_blocks(None, mcp_servers=("google_workspace",), needs_reconnect=("google_workspace",))
+ assert seen == [("google_workspace",)]
+
+
+# -- the Setup status page ---------------------------------------------------------
+
+
+def _settings(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Settings:
+ config = tmp_path / "mcp_servers.json"
+ config.write_text(json.dumps({"mcpServers": {"google_workspace": {"command": "true"}}}))
+ monkeypatch.setenv("GOOGLE_OAUTH_CLIENT_ID", "id.apps.googleusercontent.com")
+ monkeypatch.setenv("GOOGLE_OAUTH_CLIENT_SECRET", "oauth-secret")
+ return Settings(
+ ANTHROPIC_API_KEY="sk-ant-api03-realistic", EXEC_EMAIL_ADDRESS="[email protected]",
+ SCHEDULER_ENABLED=True, MCP_ENABLED=True, MCP_SERVERS_CONFIG_PATH=str(config),
+ )
+
+
+def _snap(settings: Settings, **fields: Any) -> Snapshot:
+ values: dict[str, Any] = {
+ "settings": settings, "now": NOW, "local_login": False, "people": [], "principal": _owner(),
+ "last_inbound": {}, "brief_zone": "UTC",
+ }
+ values.update(fields)
+ return Snapshot(**values)
+
+
+def test_the_gmail_light_says_why_and_that_it_retries(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ check = check_gmail(_snap(
+ _settings(tmp_path, monkeypatch), mcp_gateway=None,
+ gateway_problem="the MCP gateway failed to start (2 attempts): TimeoutError",
+ ))
+ assert check.state == "error"
+ assert "didn't start" in check.summary and "2 attempts" in check.summary
+ assert "retrying" in (check.fix or "")
+
+
+def test_the_gmail_light_names_a_dead_grant(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ check = check_gmail(_snap(
+ _settings(tmp_path, monkeypatch), mcp_gateway=object(), gateway_needs_reconnect=("google_workspace",),
+ ))
+ assert check.state == "error"
+ assert "expired or was revoked" in check.summary and "[email protected]" in check.summary
+ assert "Sign Google in again" in (check.fix or "")
+
+
+def test_the_brief_light_blames_the_gateway(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ settings = _settings(tmp_path, monkeypatch)
+ monkeypatch.setattr(runner, "mail_gateway_problem", lambda _p, **_kw: "the MCP gateway failed to start (1 attempt)")
+ check = check_brief(_snap(settings, brief_email_ready=False))
+ assert check.state == "error"
+ assert check.summary == (
+ "Not sent by email: the Executive's mail connection wasn't running "
+ "(the MCP gateway failed to start (1 attempt))."
+ )
+
+
+def test_the_brief_light_repeats_a_failed_sends_detail(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ settings = _settings(tmp_path, monkeypatch)
+ last = DeliveryOutcome(MORNING, "send_failed", None, NOW, detail="email: invalid_grant: revoked")
+ check = check_brief(_snap(settings, brief_email_ready=True, brief_delivery=last))
+ assert check.state == "error"
+ assert "invalid_grant" not in check.summary, "every team member reads this page"
+ assert "connect it again" in (check.fix or "")
diff --git a/packages/core/tests/unit/test_gateway_boot.py b/packages/core/tests/unit/test_gateway_boot.py
new file mode 100644
index 00000000..5cc64464
--- /dev/null
+++ b/packages/core/tests/unit/test_gateway_boot.py
@@ -0,0 +1,326 @@
+"""The MCP gateway supervisor: a failed start is retried with backoff, work
+that needs the gateway can ask for a start now, a late success wires what
+boot would have, and /health says where it stands."""
+from __future__ import annotations
+
+import asyncio
+import json
+import logging
+from collections.abc import Iterator
+from datetime import UTC, datetime
+from pathlib import Path
+from typing import Any
+from unittest.mock import AsyncMock, MagicMock
+
+import pytest
+from fastapi import FastAPI
+from fastapi.testclient import TestClient
+
+from openexecutive.api.routes import health as health_route
+from openexecutive.orchestrator import mcp_gateway
+from openexecutive.orchestrator.gateway_boot import GatewaySupervisor
+
+CONFIG = Path("/tmp/mcp_servers.json")
+
+
+def oe_logs() -> Iterator[list[str]]:
+ """Rendered messages from the ``openexecutive`` logger tree (caplog
+ would miss them once the app's logging config stops propagation)."""
+ messages: list[str] = []
+
+ class _Collect(logging.Handler):
+ def emit(self, record: logging.LogRecord) -> None:
+ messages.append(record.getMessage())
+
+ logger = logging.getLogger("openexecutive")
+ handler = _Collect()
+ logger.addHandler(handler)
+ try:
+ yield messages
+ finally:
+ logger.removeHandler(handler)
+
+
[email protected](autouse=True)
+def _required_env(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setenv("ANTHROPIC_API_KEY", "test-key")
+ monkeypatch.setenv("EXEC_EMAIL_ADDRESS", "[email protected]")
+ monkeypatch.setattr(mcp_gateway, "_active_gateway", None)
+ monkeypatch.setattr(mcp_gateway, "_supervisor", None)
+
+
+class _Flaky:
+ """A gateway whose first ``fail_times`` starts raise."""
+
+ def __init__(self, fail_times: int) -> None:
+ self.fail_times = fail_times
+ self.starts = 0
+ self.closed = 0
+ self.server_names = ("google_workspace",)
+ self.needs_reconnect: set[str] = set()
+ self.prime_pinned_tools = AsyncMock(return_value=[])
+
+ async def start(self, _path: Path) -> None:
+ self.starts += 1
+ if self.starts <= self.fail_times:
+ raise RuntimeError(f"child died ({self.starts})")
+
+ async def close(self) -> None:
+ self.closed += 1
+
+
+def _stub(monkeypatch: pytest.MonkeyPatch, gateway: Any) -> list[Any]:
+ """One stub gateway for every MCPGateway() and a poller that records
+ what it was handed."""
+ monkeypatch.setattr(mcp_gateway, "MCPGateway", MagicMock(return_value=gateway))
+ pollers: list[Any] = []
+
+ async def _poller(gw: Any) -> None:
+ pollers.append(gw)
+ await asyncio.Event().wait()
+
+ monkeypatch.setattr("openexecutive.integrations.email_poller.run_email_poller", _poller)
+ return pollers
+
+
+def _supervisor(app_state: Any = None, **kw: Any) -> GatewaySupervisor:
+ return GatewaySupervisor(
+ config_path=CONFIG, servers=("google_workspace",), app_state=app_state,
+ start_timeout_s=1.0, backoff_s=(0.01, 0.02), ensure_cooldown_s=0.0, **kw,
+ )
+
+
+# -- retries ---------------------------------------------------------------------
+
+
+def test_a_failed_boot_is_retried_until_it_comes_up(monkeypatch: pytest.MonkeyPatch) -> None:
+ gateway = _Flaky(fail_times=2)
+ pollers = _stub(monkeypatch, gateway)
+ state = MagicMock()
+
+ async def _run() -> GatewaySupervisor:
+ sup = _supervisor(state)
+ assert await sup.start() is False
+ assert sup.status().state == "down"
+ assert sup.status().attempts == 1
+ assert sup.status().next_retry_at is not None
+ for _ in range(200):
+ if sup.is_up:
+ break
+ await asyncio.sleep(0.005)
+ assert sup.is_up
+ await asyncio.sleep(0)
+ return sup
+
+ sup = asyncio.run(_run())
+
+ assert gateway.starts == 3
+ assert gateway.closed == 2, "each failed start is reaped"
+ # A late success does what a first-time success does.
+ assert state.mcp_gateway is gateway
+ assert mcp_gateway.get_active_gateway() is gateway
+ assert pollers == [gateway]
+ gateway.prime_pinned_tools.assert_awaited_once()
+ status = sup.status()
+ assert status.state == "up" and status.attempts == 3
+ assert status.last_error == "RuntimeError: child died (2)", "kept after the recovery"
+ assert status.next_retry_at is None
+
+
+def test_the_backoff_grows_and_caps() -> None:
+ sup = GatewaySupervisor(config_path=CONFIG, servers=("x",), backoff_s=(30, 60, 600))
+ assert [sup._delay_for(n) for n in (1, 2, 3, 4, 9)] == [30, 60, 600, 600, 600]
+
+
+def test_the_log_names_the_attempt_and_the_config(
+ monkeypatch: pytest.MonkeyPatch, oe_logs: list[str]
+) -> None:
+ _stub(monkeypatch, _Flaky(fail_times=1))
+
+ async def _run() -> None:
+ sup = _supervisor(why="MCP_ENABLED was set explicitly")
+ await sup.attempt()
+ await sup.close()
+
+ asyncio.run(_run())
+ logged = "\n".join(oe_logs)
+ assert "attempt 1" in logged and str(CONFIG) in logged and "google_workspace" in logged
+ assert "MCP_ENABLED was set explicitly" in logged
+
+
+# -- the lazy re-check -----------------------------------------------------------
+
+
+def test_ensure_starts_now_instead_of_waiting_for_the_retry(monkeypatch: pytest.MonkeyPatch) -> None:
+ gateway = _Flaky(fail_times=1)
+ _stub(monkeypatch, gateway)
+
+ async def _run() -> tuple[Any, int]:
+ sup = GatewaySupervisor(
+ config_path=CONFIG, servers=("google_workspace",), start_timeout_s=1.0,
+ backoff_s=(3600.0,), ensure_cooldown_s=0.0, # the retry is an hour away
+ )
+ assert await sup.start() is False
+ got = await sup.ensure()
+ await sup.close()
+ return got, gateway.starts
+
+ got, starts = asyncio.run(_run())
+ assert got is gateway and starts == 2
+
+
+def test_ensure_waits_for_an_attempt_already_running(monkeypatch: pytest.MonkeyPatch) -> None:
+ release = asyncio.Event()
+ gateway = MagicMock()
+ gateway.server_names = ("google_workspace",)
+ gateway.prime_pinned_tools = AsyncMock(return_value=[])
+ gateway.close = AsyncMock()
+ starts = 0
+
+ async def _slow(_path: Path) -> None:
+ nonlocal starts
+ starts += 1
+ await release.wait()
+
+ gateway.start = _slow
+ _stub(monkeypatch, gateway)
+
+ async def _run() -> None:
+ sup = _supervisor()
+ first = asyncio.ensure_future(sup.attempt())
+ await asyncio.sleep(0.01)
+ assert sup.status().state == "starting"
+ second = asyncio.ensure_future(sup.ensure())
+ await asyncio.sleep(0.01)
+ release.set()
+ assert await first is True
+ assert await second is gateway
+ await sup.close()
+
+ asyncio.run(_run())
+ assert starts == 1, "a second caller never starts a second child"
+
+
+def test_ensure_waits_out_a_fresh_failure(monkeypatch: pytest.MonkeyPatch) -> None:
+ gateway = _Flaky(fail_times=1)
+ _stub(monkeypatch, gateway)
+
+ async def _run() -> tuple[Any, int, str | None, str | None]:
+ sup = GatewaySupervisor(
+ config_path=CONFIG, servers=("google_workspace",), start_timeout_s=1.0,
+ backoff_s=(3600.0,), ensure_cooldown_s=3600.0,
+ )
+ assert await sup.start() is False
+ got = await sup.ensure()
+ out = (got, gateway.starts, sup.problem(), sup.problem(with_error=False))
+ await sup.close()
+ return out
+
+ got, starts, with_error, without = asyncio.run(_run())
+ assert got is None and starts == 1, "a start that just failed is not repeated on demand"
+ assert with_error == "the MCP gateway failed to start (1 attempt): RuntimeError: child died (1)"
+ assert without == "the MCP gateway failed to start (1 attempt)"
+
+
+def test_module_hooks_reach_the_supervisor(monkeypatch: pytest.MonkeyPatch) -> None:
+ gateway = _Flaky(fail_times=1)
+ _stub(monkeypatch, gateway)
+
+ async def _run() -> list[Any]:
+ assert await mcp_gateway.ensure_active_gateway() is None, "no supervisor: nothing to try"
+ assert mcp_gateway.gateway_problem() == "the MCP gateway is not running"
+ sup = GatewaySupervisor(
+ config_path=CONFIG, servers=("google_workspace",), start_timeout_s=1.0, backoff_s=(3600.0,),
+ ensure_cooldown_s=0.0,
+ )
+ mcp_gateway.set_gateway_supervisor(sup)
+ out: list[Any] = [mcp_gateway.gateway_problem()]
+ await sup.start()
+ out.append(mcp_gateway.gateway_problem())
+ out.append(await mcp_gateway.ensure_active_gateway())
+ out.append(mcp_gateway.gateway_problem())
+ await sup.close()
+ return out
+
+ before, after_failure, ensured, after = asyncio.run(_run())
+ assert before == "the MCP gateway has not started yet"
+ assert after_failure == "the MCP gateway failed to start (1 attempt): RuntimeError: child died (1)"
+ assert ensured is gateway and after is None
+
+
+# -- shutdown --------------------------------------------------------------------
+
+
+def test_close_stops_the_retries_the_poller_and_the_gateway(monkeypatch: pytest.MonkeyPatch) -> None:
+ gateway = _Flaky(fail_times=0)
+ pollers = _stub(monkeypatch, gateway)
+ state = MagicMock()
+
+ async def _run() -> GatewaySupervisor:
+ sup = _supervisor(state)
+ assert await sup.start() is True
+ await asyncio.sleep(0)
+ mcp_gateway.set_gateway_supervisor(sup)
+ await sup.close()
+ return sup
+
+ sup = asyncio.run(_run())
+ assert pollers == [gateway] and sup.poller_task is not None and sup.poller_task.cancelled()
+ assert gateway.closed == 1
+ assert state.mcp_gateway is None and mcp_gateway.get_active_gateway() is None
+
+
+def test_a_real_cancellation_is_not_swallowed(monkeypatch: pytest.MonkeyPatch) -> None:
+ gateway = MagicMock()
+ gateway.start = AsyncMock(side_effect=asyncio.CancelledError())
+ gateway.close = AsyncMock()
+ _stub(monkeypatch, gateway)
+
+ with pytest.raises(asyncio.CancelledError):
+ asyncio.run(_supervisor().attempt())
+
+
+# -- /health ---------------------------------------------------------------------
+
+
+def _health(app_state_fields: dict[str, Any], *, mcp_enabled: bool = True) -> dict[str, Any]:
+ from openexecutive.onboarding import profile_builder
+
+ app = FastAPI()
+ app.include_router(health_route.router)
+ for key, value in app_state_fields.items():
+ setattr(app.state, key, value)
+ with pytest.MonkeyPatch.context() as mp:
+ mp.setattr(
+ profile_builder, "load_or_create_profile",
+ lambda *a, **k: MagicMock(is_empty=lambda: True, name=None),
+ )
+ mp.setenv("MCP_ENABLED", "true" if mcp_enabled else "false")
+ body = TestClient(app).get("/health").json()
+ return dict(body["gateway"])
+
+
+def test_health_reports_the_supervisor_state() -> None:
+ sup = _supervisor()
+ sup.attempts = 2
+ sup.last_error = "RuntimeError: child died"
+ sup.last_failed_at = datetime(2026, 10, 13, 8, 0, tzinfo=UTC)
+ sup.next_retry_at = datetime(2026, 10, 13, 8, 5, tzinfo=UTC)
+ body = _health({"mcp_supervisor": sup, "mcp_gateway": None})
+ assert body == {
+ "state": "down", "attempts": 2,
+ "last_failed_at": "2026-10-13T08:00:00+00:00", "up_since": None,
+ "next_retry_at": "2026-10-13T08:05:00+00:00", "email_poller": False,
+ }
+
+
+def test_health_without_a_supervisor() -> None:
+ assert _health({"mcp_gateway": None}, mcp_enabled=False)["state"] == "off"
+ assert _health({"mcp_gateway": None}, mcp_enabled=True)["state"] == "no_servers"
+ assert _health({"mcp_gateway": MagicMock(pinned_tools=None)})["state"] == "up"
+
+
+def test_status_serializes_to_json() -> None:
+ sup = _supervisor()
+ json.dumps(sup.status().as_dict())