Skip to content

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

feat(ui): add a setup status page that tests each part of the install (#219)

Rufusa95f924dd548
diff --git a/.env.example b/.env.example
index ba4e9e20..8b5df366 100644
--- a/.env.example
+++ b/.env.example
@@ -211,7 +211,8 @@ EMAIL_POLL_INTERVAL_SECONDS=60
# Telegram integration (optional)
# Setup: docs/telegram_setup.md
-TELEGRAM_BOT_TOKEN= # from @BotFather
+# Bot token from @BotFather
+TELEGRAM_BOT_TOKEN=
# Must equal the secret_token passed to setWebhook, or every update is rejected
# with 401. 1-256 chars of A-Z a-z 0-9 _ - (e.g. `openssl rand -hex 32`).
TELEGRAM_WEBHOOK_SECRET=
@@ -233,10 +234,13 @@ DISCORD_NOTIFY_CHANNEL_ID=
DISCORD_THREAD_RESPONSE_GATE_ENABLED=true # in bot-owned threads, ask Haiku whether each non-mention message warrants a reply (filters side chatter in multi-party threads); set to false to reply to every thread message
# Google Chat integration (optional)
-GOOGLE_CHAT_PROJECT_NUMBER= # numeric project number (not project ID) — see docs/google_chat_setup.md
+# Numeric project number (not the project ID) — see docs/google_chat_setup.md
+GOOGLE_CHAT_PROJECT_NUMBER=
# Auth — set ONE of the following (see docs/google_chat_setup.md for which to use):
-GOOGLE_CHAT_SERVICE_ACCOUNT_FILE= # Option A: absolute path to SA JSON key (blocked by some org policies)
-GOOGLE_CHAT_SERVICE_ACCOUNT_EMAIL= # Option B: SA email for impersonation via ADC (gcloud auth application-default login)
+# Option A: absolute path to SA JSON key (blocked by some org policies)
+GOOGLE_CHAT_SERVICE_ACCOUNT_FILE=
+# Option B: SA email for impersonation via ADC (gcloud auth application-default login)
+GOOGLE_CHAT_SERVICE_ACCOUNT_EMAIL=
# Google Workspace MCP (optional — enables Gmail, Calendar, Drive access)
# Outbound email is sent via Gmail MCP using the account authenticated below.
diff --git a/README.md b/README.md
index 19071298..cfa1c6ea 100644
--- a/README.md
+++ b/README.md
@@ -133,6 +133,10 @@ in both files the root `.env` takes precedence.
Open http://localhost:3000 to start chatting with your executive. The API runs on port 8000 and the UI on 3000.
+To check everything is working, open **Settings → Setup status**. It tests
+the AI key and each chat app's token, then shows a green, amber or red light
+for each part of your setup, with what to do about anything that isn't green.
+
> **First run:** requires Python 3.11+ and Node 22.6+. The initial `uv sync` pulls heavy
> ML dependencies (ChromaDB + sentence-transformers/PyTorch), and the first boot
> downloads a small embedding model (~90 MB) to build the local vector index — so the
diff --git a/docs/architecture.md b/docs/architecture.md
index 857b9778..e99e7fcf 100644
--- a/docs/architecture.md
+++ b/docs/architecture.md
@@ -511,7 +511,7 @@ Optional: `EMAIL_POLL_INTERVAL_SECONDS`
### Telegram Bot
`integrations/telegram_bot.py`
-Webhook-based bot registered via FastAPI (`POST /webhook/telegram`). When `TELEGRAM_WEBHOOK_SECRET` is set, rejects (401) any request whose `X-Telegram-Bot-Api-Secret-Token` header doesn't match it (constant-time comparison). Splits long responses at paragraph boundaries to stay within Telegram's 4096-char limit.
+Webhook-based bot registered via FastAPI (`POST /webhook/telegram`). When `TELEGRAM_WEBHOOK_SECRET` is set, rejects (401) any request whose `X-Telegram-Bot-Api-Secret-Token` header doesn't match it (constant-time comparison) — and every request while the secret has characters Telegram can't send (only 1–256 of `A-Z a-z 0-9 _ -`), since only a guess could match it. Splits long responses at paragraph boundaries to stay within Telegram's 4096-char limit.
Required env vars: `TELEGRAM_BOT_TOKEN`, `TELEGRAM_WEBHOOK_SECRET`
diff --git a/docs/auth.md b/docs/auth.md
index 58afe494..3a444188 100644
--- a/docs/auth.md
+++ b/docs/auth.md
@@ -90,7 +90,8 @@ There is no password, so the protection is *where* a request can come from:
rebinding). Both also refuse writes that another page makes your browser
send, such as a form posted from another site or another `localhost` port.
A Telegram webhook arriving through a tunnel is accepted only when
- `TELEGRAM_WEBHOOK_SECRET` is set, so Telegram can prove it sent it.
+ `TELEGRAM_WEBHOOK_SECRET` is set to a value Telegram can send, so Telegram
+ can prove it sent it.
The session has no email. The UI proxy then sends no `x-caller-email`, and the
API treats the request as the principal's, the same way it treats the CLI. If
diff --git a/docs/google_chat_setup.md b/docs/google_chat_setup.md
index 85879fd6..87a04e31 100644
--- a/docs/google_chat_setup.md
+++ b/docs/google_chat_setup.md
@@ -141,6 +141,7 @@ The webhook endpoint is now active at `POST /webhook/google-chat`. Google Chat w
1. In Google Chat, find your app (search by name in the **+ New chat** dialog).
2. Send it a direct message.
3. It should reply within a few seconds.
+ If it doesn't, open **Settings → Setup status** in the web app: the Google Chat light checks the project number and the service-account settings.
4. To watch logs:
```bash
# Docker
diff --git a/docs/telegram_setup.md b/docs/telegram_setup.md
index 4b9ef6ec..dcdc23ac 100644
--- a/docs/telegram_setup.md
+++ b/docs/telegram_setup.md
@@ -90,6 +90,8 @@ The same rejection is recorded in the audit log as an `integration_inbound` even
Send the bot a direct message. It should reply within a few seconds. `/start`, `/help` and `/ask` prefixes are stripped before the text reaches the Executive; photos and documents are passed along as attachments.
+If it doesn't reply, open **Settings → Setup status** in the web app. The Telegram light says whether the token works, whether the webhook is registered at this app's address, what went wrong with Telegram's last delivery, and whether anyone on the team list has a Telegram chat ID.
+
---
## Troubleshooting
@@ -97,6 +99,7 @@ Send the bot a direct message. It should reply within a few seconds. `/start`, `
| Symptom | Cause | Fix |
|---|---|---|
| `getWebhookInfo` shows `401 Unauthorized` | `secret_token` missing from `setWebhook`, or it differs from `TELEGRAM_WEBHOOK_SECRET` | Re-run Step 5 with the current secret |
+| Every update gets `401` and the API log says `TELEGRAM_WEBHOOK_SECRET is not a value Telegram can send` | The secret has characters `setWebhook` won't accept, such as a note left after the `=` | Use only letters, digits, `_` and `-` (Step 2), restart, then re-run Step 5 |
| `503 Telegram integration not configured` | `TELEGRAM_BOT_TOKEN` unset or API not restarted | Set the var and restart |
| No reply, `rejected message from chat_id=…` in logs | Chat not on the People roster | Add the chat ID to a Person in /people (Step 6) |
| No reply, nothing in logs | Webhook URL unreachable | Check `getWebhookInfo`; for local dev, confirm ngrok is still running and re-register if its URL changed |
diff --git a/packages/core/openexecutive/api/main.py b/packages/core/openexecutive/api/main.py
index 7c5db10b..12daa207 100644
--- a/packages/core/openexecutive/api/main.py
+++ b/packages/core/openexecutive/api/main.py
@@ -41,6 +41,7 @@ from openexecutive.api.routes import (
review,
scheduled,
sessions,
+ setup_status,
skill_drafts,
skills,
today,
@@ -539,6 +540,11 @@ async def lifespan(app: FastAPI) -> AsyncIterator[None]:
discord_bot_task: asyncio.Task[None] | None = None
slack_handler: Any = None
slack_connect_task: asyncio.Task[None] | None = None
+ # Read by the Setup status page (api/setup_checks.py) to tell a
+ # connected bot from one that is still trying or has given up.
+ app.state.discord_bot = None
+ app.state.discord_bot_task = None
+ app.state.slack_handler = None
email_poller_task = await _start_mcp_gateway(app, settings)
@@ -588,6 +594,8 @@ async def lifespan(app: FastAPI) -> AsyncIterator[None]:
)
discord_bot_task.add_done_callback(_on_discord_done)
+ app.state.discord_bot = discord_bot
+ app.state.discord_bot_task = discord_bot_task
except Exception:
_discord_log.exception(
"Failed to start Discord bot; continuing without it"
@@ -639,6 +647,7 @@ async def lifespan(app: FastAPI) -> AsyncIterator[None]:
_slack_log.info("Slack socket mode listener connected")
slack_connect_task.add_done_callback(_on_slack_connect_done)
+ app.state.slack_handler = slack_handler
except Exception:
# Covers a missing slack_bolt, a malformed token, and any
# failure building the app. Nothing to release here: the
@@ -787,13 +796,14 @@ _READ_ONLY_METHODS = frozenset({"GET", "HEAD", "OPTIONS"})
def _webhook_verifies_its_caller(path: str) -> bool:
"""Whether this webhook authenticates its caller by itself. Google Chat
always checks the signed JWT; Telegram only when TELEGRAM_WEBHOOK_SECRET is
- set — without it, it accepts anyone's update."""
+ set to a value Telegram can send — without it, it accepts anyone's
+ update."""
if path == "/webhook/google-chat":
return True
if path == "/webhook/telegram":
from openexecutive.config import get_settings
- return bool(get_settings().telegram_webhook_secret)
+ return get_settings().telegram_webhook_secret_valid
return False
@@ -913,6 +923,7 @@ def create_app() -> FastAPI:
app.include_router(architecture.router, tags=["architecture"])
app.include_router(guide.router, tags=["guide"])
app.include_router(health.router, tags=["health"])
+ app.include_router(setup_status.router, tags=["setup"])
# Expose Open Executive as an MCP server at /mcp (Streamable-HTTP). Gated
# by the same shared-secret middleware as every other route — clients pass
diff --git a/packages/core/openexecutive/api/routes/setup_status.py b/packages/core/openexecutive/api/routes/setup_status.py
new file mode 100644
index 00000000..711a4a7d
--- /dev/null
+++ b/packages/core/openexecutive/api/routes/setup_status.py
@@ -0,0 +1,73 @@
+"""``GET /setup/status`` — a green/amber/red light per part of the install.
+
+The checks live in ``api/setup_checks.py``; this module runs them and shares
+one run between requests that arrive close together.
+"""
+from __future__ import annotations
+
+import asyncio
+import time
+from typing import Any
+
+import httpx
+from fastapi import APIRouter, Request
+from pydantic import BaseModel
+
+from openexecutive.api.setup_checks import (
+ PROBE_TIMEOUT_S,
+ SetupCheck,
+ gather_snapshot,
+ run_checks,
+)
+
+router = APIRouter()
+
+# A run calls Anthropic, Slack, Discord and Telegram. Requests inside this
+# window get the last run's answer, and requests during a run wait for that
+# run, so a held-down "Check again" (or a script) can't turn into a stream of
+# calls to those services. Settings only change on a restart, so a few
+# seconds' reuse hides nothing.
+_REUSE_FOR_S = 5.0
+
+
+class SetupStatusResponse(BaseModel):
+ checked_at: str
+ checks: list[SetupCheck]
+
+
+class _Runs:
+ """Kept on ``app.state``: one app's last answer and its run in flight."""
+
+ def __init__(self) -> None:
+ self.last: tuple[float, SetupStatusResponse] | None = None
+ self.current: asyncio.Task[SetupStatusResponse] | None = None
+
+
+async def _run_all(app_state: Any) -> SetupStatusResponse:
+ # Imported here: api.main imports this module while it is being built.
+ from openexecutive.api.main import _is_local_login
+ from openexecutive.config import get_settings
+
+ snap = await asyncio.to_thread(
+ gather_snapshot, get_settings(), local_login=_is_local_login(), app_state=app_state
+ )
+ async with httpx.AsyncClient(timeout=PROBE_TIMEOUT_S) as http:
+ checks = await run_checks(snap, http)
+ return SetupStatusResponse(checked_at=snap.now.isoformat(), checks=checks)
+
+
[email protected]("/setup/status", response_model=SetupStatusResponse)
+async def setup_status(request: Request) -> SetupStatusResponse:
+ state = request.app.state
+ runs: _Runs | None = getattr(state, "setup_status_runs", None)
+ if runs is None:
+ runs = state.setup_status_runs = _Runs()
+ if runs.last is not None and time.monotonic() - runs.last[0] < _REUSE_FOR_S:
+ return runs.last[1]
+ current = runs.current
+ if current is None or current.done() or current.get_loop() is not asyncio.get_running_loop():
+ current = runs.current = asyncio.create_task(_run_all(state))
+ # Shielded: a caller that gives up must not cancel the run others await.
+ result = await asyncio.shield(current)
+ runs.last = (time.monotonic(), result)
+ return result
diff --git a/packages/core/openexecutive/api/setup_checks.py b/packages/core/openexecutive/api/setup_checks.py
new file mode 100644
index 00000000..7f4a33f0
--- /dev/null
+++ b/packages/core/openexecutive/api/setup_checks.py
@@ -0,0 +1,965 @@
+"""Setup status: one plain-language light per part of an install.
+
+Backs ``GET /setup/status`` (api/routes/setup_status.py), which the UI's
+Settings → Setup status page renders next to the sign-in light it works out
+itself. Each check answers "is this part working — and if not, what exactly
+do I do?" for someone who has never read this code.
+
+Every check keeps three rules:
+- No secret in a response or a log line. A probe that carries a token reports
+ a status code, a service's short error code or an exception's class name —
+ never the exception's text, which can quote the request URL.
+- At most one cheap, read-only call per service. Nothing here sends a
+ message, spends model tokens or changes state.
+- Every call is bounded by ``PROBE_TIMEOUT_S``: a slow service turns amber
+ instead of stalling the page.
+"""
+from __future__ import annotations
+
+import asyncio
+import json
+import logging
+import os
+import re
+from collections.abc import Awaitable, Callable, Sequence
+from dataclasses import dataclass
+from datetime import UTC, datetime
+from pathlib import Path
+from typing import TYPE_CHECKING, Any, Literal
+from urllib.parse import urlsplit
+
+import anthropic
+import httpx
+from pydantic import BaseModel
+
+if TYPE_CHECKING:
+ from openexecutive.audit import AuditEvent
+ from openexecutive.config import Settings
+ from openexecutive.people.models import Person
+
+logger = logging.getLogger(__name__)
+
+State = Literal["ok", "warn", "error", "off"]
+
+PROBE_TIMEOUT_S = 5.0
+
+# The scheduler records every tick. Three missed ticks, and never less than a
+# minute and a half, means it has stopped rather than being between ticks.
+_SCHEDULER_STALE_TICKS = 3
+_SCHEDULER_STALE_FLOOR_S = 90
+# Boot work before the first tick (seeding briefs, a rotation reconcile) takes
+# seconds; a scheduler with no tick this long after starting is stuck.
+_SCHEDULER_STARTUP_GRACE_S = 300
+# Telegram reports its last failed delivery until the next one fails. Older
+# than this, it says nothing about whether delivery works now. The same
+# window applies to a message turned away because its sender wasn't on the
+# team list: after a day it is history, not something to fix.
+_RECENT_FAILURE_S = 24 * 60 * 60
+# Longest service-supplied text (a Telegram error, a Slack workspace name)
+# echoed back. The UI renders it as plain text; this only keeps it one line.
+_ECHO_MAX_CHARS = 160
+_SERVICE_ACCOUNT_KEY_MAX_BYTES = 64 * 1024
+
+# Sample values .env.example ships. One still in place means the file was
+# copied and that line never filled in. tests/unit/test_setup_checks.py fails
+# if .env.example ships a sample this set doesn't know.
+EXAMPLE_VALUES: frozenset[str] = frozenset(
+ {"sk-ant-your-key-here", "xoxb-your-bot-token", "xapp-your-app-token"}
+)
+# RFC 2606 names reserved for examples; no real mailbox lives at them.
+_EXAMPLE_EMAIL_DOMAINS = frozenset({"example.com", "example.org", "example.net"})
+
+_TELEGRAM_TOKEN_RE = re.compile(r"\d+:[A-Za-z0-9_-]{30,}")
+_SLACK_ERROR_CODE_RE = re.compile(r"[a-z_]{1,40}")
+# The sender id in the "Rejected: …" audit summaries the channel adapters
+# write when someone off the team list messages the Executive.
+_REJECTED_SENDER_RE = re.compile(r"(?:user|chat_id)=([\w.-]{1,64})")
+
+_OFFLINE_FIX = "Check this computer's internet connection, then check again."
+_RESTART = "then restart the app."
+
+
+class SetupCheck(BaseModel):
+ id: str
+ label: str
+ state: State
+ summary: str
+ fix: str | None = None
+ # An in-app page that helps with the fix, e.g. "/people".
+ link: str | None = None
+ # When the channel last received a message (the audit log's ISO time).
+ last_activity: str | None = None
+
+
+# Every check, in display order: what the Executive needs to work at all, then
+# the channels people reach it through, then what runs in the background.
+LABELS: dict[str, str] = {
+ "ai_model": "AI model",
+ "company": "Company setup",
+ "owner": "Owner",
+ "exec_email": "The Executive's email address",
+ "api_secret": "API protection",
+ "gmail": "Email (Gmail)",
+ "slack": "Slack",
+ "discord": "Discord",
+ "telegram": "Telegram",
+ "google_chat": "Google Chat",
+ "scheduler": "Daily schedule",
+ "memory": "Long-term memory (Honcho)",
+}
+
+
+def _result(
+ check_id: str,
+ state: State,
+ summary: str,
+ fix: str | None = None,
+ *,
+ link: str | None = None,
+ last_activity: str | None = None,
+) -> SetupCheck:
+ return SetupCheck(
+ id=check_id,
+ label=LABELS[check_id],
+ state=state,
+ summary=summary,
+ fix=fix,
+ link=link,
+ last_activity=last_activity,
+ )
+
+
+@dataclass(frozen=True)
+class Snapshot:
+ """What the checks read, gathered once per run."""
+
+ settings: Settings
+ now: datetime
+ local_login: bool
+ people: Sequence[Person]
+ principal: Person | None
+ # Latest integration_inbound audit row per channel actor.
+ last_inbound: dict[str, AuditEvent | None]
+ discord_bot: Any = None
+ discord_bot_task: asyncio.Task[None] | None = None
+ slack_handler: Any = None
+ mcp_gateway: Any = None
+
+
+def _clip(text: str) -> str:
+ text = " ".join(text.split())
+ return text if len(text) <= _ECHO_MAX_CHARS else text[: _ECHO_MAX_CHARS - 1] + "…"
+
+
+def _ago(seconds: float) -> str:
+ minutes = int(seconds // 60)
+ if minutes < 1:
+ return "less than a minute ago"
+ if minutes < 120:
+ return f"{minutes} minute{'s' if minutes != 1 else ''} ago"
+ return f"{minutes // 60} hours ago"
+
+
+def is_example_email(address: str) -> bool:
+ domain = address.rpartition("@")[2].strip().lower()
+ return domain in _EXAMPLE_EMAIL_DOMAINS or domain.endswith(".example")
+
+
+# ---------------------------------------------------------------------------
+# AI model, company and the people running it
+# ---------------------------------------------------------------------------
+
+
+async def check_ai_model(snap: Snapshot) -> SetupCheck:
+ settings = snap.settings
+ key = (settings.anthropic_api_key or "").strip()
+ if not key:
+ # Settings refuses to load with no provider at all, so one of these is on.
+ using = " and ".join(
+ name
+ for name, on in (
+ ("OpenRouter", settings.openrouter_enabled),
+ ("local models", settings.local_models_enabled),
+ )
+ if on
+ )
+ return _result(
+ "ai_model", "ok", f"Using {using} instead of Anthropic. This page doesn't test that connection."
+ )
+ if key in EXAMPLE_VALUES:
+ return _result(
+ "ai_model",
+ "error",
+ "ANTHROPIC_API_KEY still has the sample value from .env.example, so the Executive can't answer.",
+ f"Paste your key from console.anthropic.com over it in the .env file, {_RESTART}",
+ )
+
+ from openexecutive.providers.anthropic_provider import configured_async_client
+
+ client = configured_async_client(timeout=PROBE_TIMEOUT_S).with_options(max_retries=0)
+ try:
+ # Listing models is free, and it goes through the same key and
+ # workspace header every chat turn uses.
+ await asyncio.wait_for(client.models.list(limit=1), PROBE_TIMEOUT_S)
+ except anthropic.AuthenticationError:
+ return _result(
+ "ai_model",
+ "error",
+ "Anthropic turned down the key in ANTHROPIC_API_KEY.",
+ f"Create a new key at console.anthropic.com, paste it into the .env file, {_RESTART}",
+ )
+ except (anthropic.BadRequestError, anthropic.PermissionDeniedError) as exc:
+ if not settings.anthropic_workspace_id:
+ return _result(
+ "ai_model",
+ "error",
+ f"Anthropic refused requests made with this key (HTTP {exc.status_code}).",
+ "If the key was created for your whole organisation rather than inside a workspace, set "
+ f"ANTHROPIC_WORKSPACE_ID in .env to the workspace to use, {_RESTART}",
+ )
+ return _result(
+ "ai_model",
+ "error",
+ "Anthropic refused requests made with this key and ANTHROPIC_WORKSPACE_ID "
+ f"(HTTP {exc.status_code}).",
+ f"Check in console.anthropic.com that the key belongs to that workspace, {_RESTART}",
+ )
+ except anthropic.RateLimitError:
+ return _result(
+ "ai_model",
+ "warn",
+ "The key works, but Anthropic says it is over its rate limit right now.",
+ "Wait a minute and check again. If it keeps happening, raise the limit in console.anthropic.com.",
+ )
+ except anthropic.APIStatusError as exc:
+ return _result(
+ "ai_model",
+ "warn",
+ f"Anthropic had a problem answering (HTTP {exc.status_code}). That is usually brief.",
+ "Check again in a few minutes.",
+ )
+ except (anthropic.APIConnectionError, TimeoutError):
+ return _result("ai_model", "warn", "Couldn't reach Anthropic to test the key.", _OFFLINE_FIX)
+ finally:
+ await client.close()
+ return _result("ai_model", "ok", "Connected to Anthropic.")
+
+
+def check_company(snap: Snapshot) -> SetupCheck:
+ from openexecutive.onboarding.profile_builder import load_or_create_profile
+
+ profile = load_or_create_profile(snap.settings.company_profile_path)
+ if profile.is_empty():
+ return _result(
+ "company",
+ "warn",
+ "Not done yet: the Executive doesn't know your company.",
+ "Run the setup interview: describe your business, then check what the Executive drafts.",
+ link="/onboard",
+ )
+ return _result("company", "ok", f"Set up for {_clip(profile.name)}.")
+
+
+def check_owner(snap: Snapshot) -> SetupCheck:
+ owner = snap.principal
+ if owner is None:
+ return _result(
+ "owner",
+ "warn",
+ "Nobody on the team list is marked as the owner.",
+ "Finish the setup interview — it asks who the owner is.",
+ link="/onboard",
+ )
+ if snap.local_login:
+ return _result("owner", "ok", f"{owner.full_name} is the owner. Local login signs you in as them.")
+ if not owner.email:
+ return _result(
+ "owner",
+ "warn",
+ f"{owner.full_name} is the owner, but has no email on the team list, so the app won't recognise "
+ "them when they sign in — owner-only actions will be refused.",
+ "Add the Google address they sign in with to their entry on the People page.",
+ link="/people",
+ )
+ return _result("owner", "ok", f"{owner.full_name} ({owner.email}) is the owner.")
+
+
+def check_exec_email(snap: Snapshot) -> SetupCheck:
+ address = snap.settings.exec_email_address.strip()
+ fix = f"Set EXEC_EMAIL_ADDRESS in .env to the Gmail address the Executive sends from, {_RESTART}"
+ if "@" not in address:
+ return _result("exec_email", "error", "EXEC_EMAIL_ADDRESS isn't an email address.", fix)
+ if is_example_email(address):
+ return _result(
+ "exec_email",
+ "warn",
+ f"EXEC_EMAIL_ADDRESS is still the sample address {address}. Chat works without a real "
+ "one; email doesn't.",
+ fix,
+ )
+ return _result("exec_email", "ok", f"The Executive sends email as {address}.")
+
+
+def check_api_protection(snap: Snapshot) -> SetupCheck:
+ if os.environ.get("BACKEND_SHARED_SECRET", "").strip():
+ return _result("api_secret", "ok", "Only the web app can use the API: BACKEND_SHARED_SECRET is set.")
+ if snap.local_login:
+ return _result(
+ "api_secret",
+ "ok",
+ "Not needed: with local login the API only answers requests addressed to this computer.",
+ )
+ return _result(
+ "api_secret",
+ "warn",
+ "The API has no shared secret, so anything that can reach it can use it.",
+ "Fine on your own computer. On a server, set BACKEND_SHARED_SECRET to the same random value for both "
+ "apps (openssl rand -hex 32), then restart them.",
+ )
+
+
+# ---------------------------------------------------------------------------
+# Channels
+# ---------------------------------------------------------------------------
+
+
+async def _fetch(
+ http: httpx.AsyncClient, method: str, url: str, **kwargs: Any
+) -> tuple[int, dict[str, Any]] | None:
+ """``(status, JSON object or {})``, or ``None`` when the service couldn't
+ be reached. Never raises, and never logs the URL, which can hold a token
+ (Telegram's does). httpx's own per-request log line would print it at
+ INFO; api.main._configure_logging holds the ``httpx`` logger at WARNING."""
+ try:
+ response = await asyncio.wait_for(http.request(method, url, **kwargs), PROBE_TIMEOUT_S)
+ except (httpx.HTTPError, TimeoutError) as exc:
+ logger.info("setup status: %s probe failed (%s)", urlsplit(url).hostname, type(exc).__name__)
+ return None
+ try:
+ body = response.json()
+ except ValueError:
+ body = {}
+ return response.status_code, body if isinstance(body, dict) else {}
+
+
+@dataclass(frozen=True)
+class _Roster:
+ """Which Person field a channel matches senders on, and what to call it."""
+
+ field: str
+ id_name: str
+
+
+def _turned_away_sender(snap: Snapshot, last: AuditEvent | None, roster: _Roster) -> str | None:
+ """The sender of a message the channel turned away in the last day, when
+ they still aren't on the team list — ``""`` when the audit row doesn't
+ name them. ``None`` when there is nothing left to fix."""
+ if last is None or not last.summary.startswith("Rejected"):
+ return None
+ try:
+ at = datetime.fromisoformat(last.ts)
+ except ValueError:
+ return None
+ if at.tzinfo is None:
+ at = at.replace(tzinfo=UTC)
+ if (snap.now - at).total_seconds() >= _RECENT_FAILURE_S:
+ return None
+ match = _REJECTED_SENDER_RE.search(last.summary)
+ if match is None:
+ return ""
+ sender = match.group(1)
+ rostered = any(str(getattr(person, roster.field) or "") == sender for person in snap.people)
+ return None if rostered else sender
+
+
+def _channel_ready(
+ snap: Snapshot, check_id: str, summary: str, *, actor: str, roster: _Roster | None
+) -> SetupCheck:
+ """The last word on a channel that is connected: can anyone reach the
+ Executive through it? Slack, Discord and Telegram answer only people on
+ the team list whose entry carries their id on that service."""
+ last = snap.last_inbound.get(actor)
+ last_at = last.ts if last is not None else None
+ if roster is not None:
+ if not any(getattr(person, roster.field) for person in snap.people):
+ return _result(
+ check_id,
+ "warn",
+ f"{summary} But nobody on the team list has a {roster.id_name}, so every message is ignored.",
+ f"Add your {roster.id_name} to your entry on the People page.",
+ link="/people",
+ last_activity=last_at,
+ )
+ sender = _turned_away_sender(snap, last, roster)
+ if sender is not None:
+ named = f" (from {roster.id_name} {sender})" if sender else ""
+ return _result(
+ check_id,
+ "warn",
+ f"{summary} The last message{named} was ignored because its sender isn't on the team list.",
+ f"If that was you, add that {roster.id_name} to your entry on the People page.",
+ link="/people",
+ last_activity=last_at,
+ )
+ return _result(check_id, "ok", summary, last_activity=last_at)
+
+
+async def check_slack(snap: Snapshot, http: httpx.AsyncClient) -> SetupCheck:
+ bot = (snap.settings.slack_bot_token or "").strip()
+ app_token = (snap.settings.slack_app_token or "").strip()
+ if not bot and not app_token:
+ return _result(
+ "slack",
+ "off",
+ "Not set up.",
+ f"To use Slack, add SLACK_BOT_TOKEN and SLACK_APP_TOKEN to .env, {_RESTART}",
+ )
+ if bot in EXAMPLE_VALUES or app_token in EXAMPLE_VALUES:
+ return _result(
+ "slack",
+ "error",
+ "Slack still has the sample tokens from .env.example.",
+ "Put your Slack app's tokens in SLACK_BOT_TOKEN and SLACK_APP_TOKEN, or delete both lines if you "
+ f"don't use Slack, {_RESTART}",
+ )
+ if not bot.startswith("xoxb-"):
+ return _result(
+ "slack",
+ "error",
+ "SLACK_BOT_TOKEN is missing or isn't a bot token — those start with xoxb-.",
+ "Copy the Bot User OAuth Token from your Slack app's OAuth & Permissions page into .env, "
+ f"{_RESTART}",
+ )
+ if app_token and not app_token.startswith("xapp-"):
+ return _result(
+ "slack",
+ "error",
+ "SLACK_APP_TOKEN isn't an app-level token — those start with xapp-.",
+ "Create an app-level token with the connections:write scope on your Slack app's Basic "
+ f"Information page, put it in .env, {_RESTART}",
+ )
+
+ probe = await _fetch(
+ http, "POST", "https://slack.com/api/auth.test", headers={"Authorization": f"Bearer {bot}"}
+ )
+ if probe is None:
+ return _result("slack", "warn", "Couldn't reach Slack to test the tokens.", _OFFLINE_FIX)
+ body = probe[1]
+ if body.get("ok") is not True:
+ code = str(body.get("error", ""))
+ shown = f" ({code})" if _SLACK_ERROR_CODE_RE.fullmatch(code) else ""
+ return _result(
+ "slack",
+ "error",
+ f"Slack turned down SLACK_BOT_TOKEN{shown}.",
+ f"Copy the Bot User OAuth Token again from your Slack app's settings into .env, {_RESTART}",
+ )
+ workspace = _clip(str(body.get("team") or "your Slack workspace"))
+ if not app_token:
+ return _result(
+ "slack",
+ "warn",
+ f"Can send to {workspace}, but won't hear messages: SLACK_APP_TOKEN isn't set.",
+ "Turn on Socket Mode in your Slack app, add its app-level token (starts with xapp-) to .env, "
+ f"{_RESTART}",
+ )
+ if snap.slack_handler is None:
+ return _result(
+ "slack",
+ "error",
+ f"The tokens work for {workspace}, but the Slack listener didn't start.",
+ f'The API log says why — look for "Failed to start Slack bot". Fix that, {_RESTART}',
+ )
+ try:
+ listening = bool(
+ await asyncio.wait_for(snap.slack_handler.client.is_connected(), PROBE_TIMEOUT_S)
+ )
+ except Exception as exc: # a client state we can't read counts as not listening
+ logger.info("setup status: Slack connection check failed (%s)", type(exc).__name__)
+ listening = False
+ if not listening:
+ return _result(
+ "slack",
+ "warn",
+ f"The tokens work for {workspace}, but Slack isn't delivering messages to the app yet.",
+ "If this lasts more than a minute, check SLACK_APP_TOKEN and that Socket Mode is on in "
+ "your Slack app's settings.",
+ )
+ return _channel_ready(
+ snap,
+ "slack",
+ f"Connected to {workspace} and listening.",
+ actor="slack",
+ roster=_Roster("slack_user_id", "Slack member ID"),
+ )
+
+
+# How a stopped discord.py client names what went wrong, and what to do.
+_DISCORD_STOP_FIXES: dict[str, tuple[str, str]] = {
+ "LoginFailure": (
+ "Discord turned down DISCORD_BOT_TOKEN.",
+ f"Reset the token on the Bot tab of the Discord developer portal, paste it into .env, {_RESTART}",
+ ),
+ "PrivilegedIntentsRequired": (
+ "Discord refused the bot: it needs the Message Content intent.",
+ f"Turn on Message Content Intent on the Bot tab of the Discord developer portal, {_RESTART}",
+ ),
+}
+
+
+async def check_discord(snap: Snapshot, http: httpx.AsyncClient) -> SetupCheck:
+ token = (snap.settings.discord_bot_token or "").strip()
+ if not token:
+ return _result(
+ "discord",
+ "off",
+ "Not set up.",
+ f"To use Discord, add DISCORD_BOT_TOKEN and DISCORD_APP_ID to .env, {_RESTART}",
+ )
+
+ bot, task = snap.discord_bot, snap.discord_bot_task
+ if task is not None and task.done():
+ stopped_by = None if task.cancelled() else task.exception()
+ kind = type(stopped_by).__name__ if stopped_by is not None else ""
+ if kind in _DISCORD_STOP_FIXES:
+ return _result("discord", "error", *_DISCORD_STOP_FIXES[kind])
+ return _result(
+ "discord",
+ "error",
+ f"The Discord bot stopped{f' ({kind})' if kind else ''}.",
+ f"The API log has the details. Fix that, {_RESTART}",
+ )
+ if bot is None:
+ return _result(
+ "discord",
+ "error",
+ "The Discord bot didn't start.",
+ f'The API log says why — look for "Discord bot". Fix that, {_RESTART}',
+ )
+ if bot.is_ready():
+ # discord.py stays "ready" through a dropped connection while it
+ # reconnects; only the gateway socket says whether messages arrive.
+ name = _clip(str(bot.user)) if bot.user is not None else "the bot"
+ if not getattr(bot.ws, "open", False):
+ return _result(
+ "discord",
+ "warn",
+ f"Signed in as {name}, but the connection to Discord dropped and the bot is "
+ "reconnecting.",
+ "Check again in a minute. If it stays like this, check this computer's internet connection "
+ "and the API log.",
+ )
+ return _channel_ready(
+ snap,
+ "discord",
+ f"Connected as {name}.",
+ actor="discord",
+ roster=_Roster("discord_user_id", "Discord user ID"),
+ )
+
+ # Still connecting: test the token, so a bad one is named now rather than
+ # whenever discord.py gives up.
+ probe = await _fetch(
+ http, "GET", "https://discord.com/api/v10/users/@me", headers={"Authorization": f"Bot {token}"}
+ )
+ if probe is None:
+ return _result("discord", "warn", "Couldn't reach Discord to test the token.", _OFFLINE_FIX)
+ if probe[0] == 401:
+ return _result("discord", "error", *_DISCORD_STOP_FIXES["LoginFailure"])
+ return _result(
+ "discord",
+ "warn",
+ "Still connecting to Discord.",
+ "Check again in a minute. If it stays like this, restart the app and read the API log.",
+ )
+
+
+_TELEGRAM_REREGISTER = (
+ "Set TELEGRAM_WEBHOOK_SECRET, restart the app, and register the webhook again with the same secret "
+ "(docs/telegram_setup.md)."
+)
+
+
+async def check_telegram(snap: Snapshot, http: httpx.AsyncClient) -> SetupCheck:
+ settings = snap.settings
+ token = (settings.telegram_bot_token or "").strip()
+ if not token:
+ return _result("telegram", "off", "Not set up.", "To use Telegram, follow docs/telegram_setup.md.")
+ # Checked before the token goes into a URL, so it can't reshape one.
+ if not _TELEGRAM_TOKEN_RE.fullmatch(token):
+ return _result(
+ "telegram",
+ "error",
+ "TELEGRAM_BOT_TOKEN isn't a Telegram bot token — those are digits, a colon, then letters.",
+ f"Copy the token @BotFather gave you into .env, {_RESTART}",
+ )
+ secret = settings.telegram_webhook_secret
+ if secret and not settings.telegram_webhook_secret_valid:
+ return _result(
+ "telegram",
+ "error",
+ "TELEGRAM_WEBHOOK_SECRET has characters Telegram won't accept, so the app turns "
+ "away every message.",
+ "Use 1–256 letters, digits, _ or - (openssl rand -hex 32 makes one), restart the app, "
+ "and register the webhook again with it (docs/telegram_setup.md).",
+ )
+ if snap.local_login and not secret:
+ return _result(
+ "telegram",
+ "error",
+ "Local login turns away Telegram messages unless TELEGRAM_WEBHOOK_SECRET is set.",
+ _TELEGRAM_REREGISTER,
+ )
+
+ base = f"https://api.telegram.org/bot{token}"
+ me = await _fetch(http, "GET", f"{base}/getMe")
+ if me is None:
+ return _result("telegram", "warn", "Couldn't reach Telegram to test the token.", _OFFLINE_FIX)
+ if me[1].get("ok") is not True:
+ return _result(
+ "telegram",
+ "error",
+ "Telegram turned down TELEGRAM_BOT_TOKEN.",
+ f"Ask @BotFather for the token again (/token), paste it into .env, {_RESTART}",
+ )
+ me_result = me[1].get("result")
+ username = me_result.get("username") if isinstance(me_result, dict) else None
+ bot_name = f"@{_clip(str(username))}" if username else "The bot"
+
+ hook = await _fetch(http, "GET", f"{base}/getWebhookInfo")
+ if hook is None:
+ return _result(
+ "telegram",
+ "warn",
+ f"{bot_name} works, but Telegram didn't say where it delivers messages.",
+ _OFFLINE_FIX,
+ )
+ info = hook[1].get("result")
+ if not isinstance(info, dict):
+ info = {}
+ url = str(info.get("url") or "")
+ if not url:
+ return _result(
+ "telegram",
+ "warn",
+ f"{bot_name} works, but Telegram doesn't know where to deliver its messages.",
+ "Register this app's /webhook/telegram address with setWebhook — see docs/telegram_setup.md.",
+ )
+ if not urlsplit(url).path.endswith("/webhook/telegram"):
+ return _result(
+ "telegram",
+ "warn",
+ f"Telegram delivers {bot_name}'s messages to an address that isn't this app's /webhook/telegram.",
+ "Register the webhook again with this app's address — see docs/telegram_setup.md.",
+ )
+ error_at = info.get("last_error_date")
+ if isinstance(error_at, int) and snap.now.timestamp() - error_at < _RECENT_FAILURE_S:
+ reason = _clip(str(info.get("last_error_message") or "no reason given"))
+ return _result(
+ "telegram",
+ "warn",
+ f"Telegram couldn't deliver {bot_name}'s last message: {reason}.",
+ "A 401 means the secret registered with setWebhook doesn't match "
+ "TELEGRAM_WEBHOOK_SECRET — register the webhook again (docs/telegram_setup.md). "
+ "Otherwise, check this app can be reached at that address.",
+ )
+ if not secret:
+ return _result(
+ "telegram",
+ "warn",
+ f"{bot_name} is receiving messages, but anyone who finds the webhook address can send fake ones: "
+ "TELEGRAM_WEBHOOK_SECRET isn't set.",
+ _TELEGRAM_REREGISTER,
+ )
+ return _channel_ready(
+ snap,
+ "telegram",
+ f"{bot_name} is receiving messages.",
+ actor="telegram",
+ roster=_Roster("telegram_chat_id", "Telegram chat ID"),
+ )
+
+
+def _readable_service_account(path: str) -> bool:
+ try:
+ with Path(path).expanduser().open("rb") as handle:
+ raw = handle.read(_SERVICE_ACCOUNT_KEY_MAX_BYTES + 1)
+ if len(raw) > _SERVICE_ACCOUNT_KEY_MAX_BYTES:
+ return False
+ key = json.loads(raw)
+ except (OSError, ValueError):
+ return False
+ return isinstance(key, dict) and bool(key.get("client_email"))
+
+
+def check_google_chat(snap: Snapshot) -> SetupCheck:
+ settings = snap.settings
+ project = (settings.google_chat_project_number or "").strip()
+ key_file = (settings.google_chat_service_account_file or "").strip()
+ key_email = (settings.google_chat_service_account_email or "").strip()
+ if not (project or key_file or key_email):
+ return _result(
+ "google_chat", "off", "Not set up.", "To use Google Chat, follow docs/google_chat_setup.md."
+ )
+ if not re.fullmatch(r"[0-9]+", project):
+ return _result(
+ "google_chat",
+ "error",
+ "GOOGLE_CHAT_PROJECT_NUMBER needs your Google Cloud project's number — digits only, "
+ "not the project ID.",
+ f"Copy the project number from the Google Cloud console's dashboard into .env, {_RESTART}",
+ )
+ if not (key_file or key_email):
+ return _result(
+ "google_chat",
+ "error",
+ "Google Chat has no service account to reply with.",
+ "Set GOOGLE_CHAT_SERVICE_ACCOUNT_FILE or GOOGLE_CHAT_SERVICE_ACCOUNT_EMAIL in .env — "
+ f"docs/google_chat_setup.md says which — {_RESTART}",
+ )
+ if key_file and not _readable_service_account(key_file):
+ return _result(
+ "google_chat",
+ "error",
+ "Can't read a service-account key from the file GOOGLE_CHAT_SERVICE_ACCOUNT_FILE names.",
+ f"Point it at the full path of the JSON key you downloaded from Google Cloud, {_RESTART}",
+ )
+ return _channel_ready(
+ snap,
+ "google_chat",
+ "Set up. Google Chat delivers messages to this app's /webhook/google-chat address "
+ "(this page can't test that part).",
+ actor="google_chat",
+ roster=None,
+ )
+
+
+def _google_sign_in_missing() -> str | None:
+ """The Google credentials the workspace-mcp child can't sign in without,
+ named for the fix, or None. Read from this process's environment because
+ that is what the MCP gateway forwards to it."""
+ def have(key: str) -> bool:
+ return bool(os.environ.get(key, "").strip())
+
+ if (os.environ.get("GWORKSPACE_AUTH_MODE", "").strip() or "oauth") == "service_account":
+ if have("GOOGLE_SERVICE_ACCOUNT_KEY_JSON") or have("GOOGLE_SERVICE_ACCOUNT_KEY_FILE"):
+ return None
+ return "GOOGLE_SERVICE_ACCOUNT_KEY_JSON or GOOGLE_SERVICE_ACCOUNT_KEY_FILE"
+ if have("GOOGLE_OAUTH_CLIENT_ID") and have("GOOGLE_OAUTH_CLIENT_SECRET"):
+ return None
+ return "GOOGLE_OAUTH_CLIENT_ID and GOOGLE_OAUTH_CLIENT_SECRET"
+
+
+def check_gmail(snap: Snapshot) -> SetupCheck:
+ from openexecutive.orchestrator.mcp_gateway import configured_server_names
+
+ settings = snap.settings
+ servers = configured_server_names(settings.mcp_servers_config_path) if settings.mcp_enabled else []
+ if "google_workspace" not in servers:
+ return _result(
+ "gmail",
+ "off",
+ "Not set up: the Executive can't read or send email.",
+ "To connect Gmail, follow the Google Workspace steps in .env.example.",
+ )
+ if snap.mcp_gateway is None:
+ 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}',
+ )
+ missing = _google_sign_in_missing()
+ if missing:
+ return _result(
+ "gmail",
+ "error",
+ f"Google can't sign the Executive in: {missing} isn't set.",
+ f"Set it in .env (the Google Workspace steps there explain how), {_RESTART}",
+ )
+ summary = (
+ f"Connected. The Executive checks {settings.exec_email_address}'s inbox every "
+ f"{settings.email_poll_interval_seconds} seconds."
+ )
+ if snap.last_inbound.get("email") is None:
+ summary += (
+ " No email has come in yet — if you've sent one, sign Google in once as that address "
+ "(scripts/mint-google-token.py)."
+ )
+ return _channel_ready(snap, "gmail", summary, actor="email", roster=None)
+
+
+# ---------------------------------------------------------------------------
+# What runs in the background
+# ---------------------------------------------------------------------------
+
+
+def check_scheduler(snap: Snapshot) -> SetupCheck:
+ from openexecutive.scheduler.pause import get_pause_state
+ from openexecutive.scheduler.runner import scheduler_heartbeat
+
+ settings = snap.settings
+ if not settings.scheduler_enabled:
+ return _result(
+ "scheduler",
+ "off",
+ "Turned off, so no briefs, reminders or follow-ups go out.",
+ f"Set SCHEDULER_ENABLED=true in .env, {_RESTART}",
+ )
+ # Liveness first: a paused scheduler still ticks, so one that has
+ # stopped needs a restart, not the Resume button.
+ started_at, last_tick = scheduler_heartbeat()
+ restart_fix = 'Restart the app, and look in the API log for lines from "scheduler".'
+ if started_at is None:
+ return _result(
+ "scheduler",
+ "error",
+ "The scheduler isn't running, so briefs and follow-ups won't go out.",
+ restart_fix,
+ )
+ if last_tick is None:
+ waited = (snap.now - started_at).total_seconds()
+ if waited < _SCHEDULER_STARTUP_GRACE_S:
+ return _result("scheduler", "warn", "Starting up.", "Check again in a minute.")
+ return _result(
+ "scheduler",
+ "error",
+ f"The scheduler started {_ago(waited)} but hasn't finished a check since.",
+ restart_fix,
+ )
+ ticked_at, outcome = last_tick
+ silent_for = (snap.now - ticked_at).total_seconds()
+ stale_after = max(
+ _SCHEDULER_STALE_TICKS * settings.scheduler_poll_interval_seconds, _SCHEDULER_STALE_FLOOR_S
+ )
+ if silent_for > stale_after:
+ return _result(
+ "scheduler",
+ "error",
+ f"The scheduler has stopped: its last check was {_ago(silent_for)}.",
+ restart_fix,
+ )
+ if outcome == "failed":
+ return _result(
+ "scheduler",
+ "error",
+ "The scheduler's last check hit an error.",
+ 'Look in the API log for "scheduler tick failed" to see why.',
+ )
+ if get_pause_state().paused:
+ return _result(
+ "scheduler",
+ "warn",
+ "Paused: briefs, reminders and email checks wait until you resume.",
+ "Press Resume in the banner at the top of the page.",
+ )
+ if outcome == "waiting_for_company":
+ return _result(
+ "scheduler",
+ "warn",
+ "Waiting for company setup: nothing scheduled runs until the setup interview is done.",
+ "Finish the setup interview.",
+ link="/onboard",
+ )
+ return _result("scheduler", "ok", "Running.")
+
+
+async def check_memory(snap: Snapshot) -> SetupCheck:
+ from openexecutive.api.routes.health import honcho_health
+
+ probe = await honcho_health()
+ status = probe.get("status")
+ if status == "disabled":
+ return _result(
+ "memory",
+ "off",
+ "Off. This optional service remembers people across conversations.",
+ f"To turn it on, set HONCHO_ENABLED=true and HONCHO_API_KEY in .env, {_RESTART}",
+ )
+ if status == "ok":
+ return _result("memory", "ok", "Connected to Honcho.")
+ return _result(
+ "memory",
+ "error",
+ f"Can't reach Honcho ({probe.get('error_type', 'unknown error')}).",
+ f"Check HONCHO_API_KEY and HONCHO_BASE_URL in .env, {_RESTART}",
+ )
+
+
+# ---------------------------------------------------------------------------
+# Running them all
+# ---------------------------------------------------------------------------
+
+_INBOUND_ACTORS = ("slack", "discord", "telegram", "google_chat", "email")
+
+
+def _latest_inbound() -> dict[str, AuditEvent | None]:
+ from openexecutive.audit import get_audit_logger
+
+ audit = get_audit_logger()
+ latest: dict[str, AuditEvent | None] = {}
+ for actor in _INBOUND_ACTORS:
+ rows = audit.query(event_type="integration_inbound", actor=actor, limit=1)
+ latest[actor] = rows[0] if rows else None
+ return latest
+
+
+def gather_snapshot(settings: Settings, *, local_login: bool, app_state: Any) -> Snapshot:
+ """Read everything the checks need. Blocking (SQLite): run it off the loop."""
+ from openexecutive.people.store import find_principal_person, list_people
+
+ return Snapshot(
+ settings=settings,
+ now=datetime.now(UTC),
+ local_login=local_login,
+ people=list_people(),
+ principal=find_principal_person(),
+ last_inbound=_latest_inbound(),
+ discord_bot=getattr(app_state, "discord_bot", None),
+ discord_bot_task=getattr(app_state, "discord_bot_task", None),
+ slack_handler=getattr(app_state, "slack_handler", None),
+ mcp_gateway=getattr(app_state, "mcp_gateway", None),
+ )
+
+
+def _check_runners(
+ snap: Snapshot, http: httpx.AsyncClient
+) -> dict[str, Callable[[], Awaitable[SetupCheck]]]:
+ def off_loop(check: Callable[[Snapshot], SetupCheck]) -> Callable[[], Awaitable[SetupCheck]]:
+ # The synchronous checks read files and SQLite.
+ return lambda: asyncio.to_thread(check, snap)
+
+ return {
+ "ai_model": lambda: check_ai_model(snap),
+ "company": off_loop(check_company),
+ "owner": off_loop(check_owner),
+ "exec_email": off_loop(check_exec_email),
+ "api_secret": off_loop(check_api_protection),
+ "gmail": off_loop(check_gmail),
+ "slack": lambda: check_slack(snap, http),
+ "discord": lambda: check_discord(snap, http),
+ "telegram": lambda: check_telegram(snap, http),
+ "google_chat": off_loop(check_google_chat),
+ "scheduler": off_loop(check_scheduler),
+ "memory": lambda: check_memory(snap),
+ }
+
+
+async def run_checks(snap: Snapshot, http: httpx.AsyncClient) -> list[SetupCheck]:
+ """Every check at once, in ``LABELS`` order. A check that crashes turns
+ red on its own instead of taking the page down."""
+ runners = _check_runners(snap, http)
+
+ async def guarded(check_id: str) -> SetupCheck:
+ try:
+ return await runners[check_id]()
+ except Exception as exc:
+ logger.warning("setup status: the %s check crashed (%s)", check_id, type(exc).__name__)
+ return _result(
+ check_id,
+ "error",
+ "This check couldn't run.",
+ 'The API log has the details — look for "setup status".',
+ )
+
+ return list(await asyncio.gather(*(guarded(check_id) for check_id in LABELS)))
diff --git a/packages/core/openexecutive/architecture/architecture-facts.yaml b/packages/core/openexecutive/architecture/architecture-facts.yaml
index 13731679..d36a836c 100644
--- a/packages/core/openexecutive/architecture/architecture-facts.yaml
+++ b/packages/core/openexecutive/architecture/architecture-facts.yaml
@@ -627,7 +627,8 @@ routing:
(`Session.from_web_chat`, the signed-in Google account) or the
principal's own Slack / Discord (`origin_channel`, the platform's user
id over an authenticated connection), or a PRIVATE Telegram chat only
- when TELEGRAM_WEBHOOK_SECRET is set — Telegram identifies the chat, not
+ when TELEGRAM_WEBHOOK_SECRET is set to a value Telegram can send
+ (Settings.telegram_webhook_secret_valid) — Telegram identifies the chat, not
the sender (a group is all its members), and /webhook/telegram is
exempt from the shared secret, so without the webhook secret anyone
can post an update naming the principal's chat id
@@ -2087,7 +2088,8 @@ people:
UI via the `list_people` / `upsert_person` / `archive_person` /
`set_department_head` tools (openexecutive.orchestrator.people_tools) —
but only when the principal asks from the web chat, their own Slack or
- Discord, or a private Telegram chat with TELEGRAM_WEBHOOK_SECRET set;
+ Discord, or a private Telegram chat with a TELEGRAM_WEBHOOK_SECRET
+ Telegram can send;
anyone and anything else is refused.
See `routing.people_tools` for details.
brief_insights: |
@@ -2112,6 +2114,24 @@ scheduler:
cross-client digest via _deliver_to_principal after the original
client is restored, then chains the next nightly occurrence via
seed_client_rotation (idempotent).
+ heartbeat: |
+ Liveness for Settings → Setup status. run_scheduler stamps
+ runner._started_at on entry, and every tick ends with _beat(outcome)
+ storing (finished_at, outcome) in runner._last_tick — outcome is ran,
+ paused, waiting_for_company, rotating, or failed (the tick raised;
+ the beat is in the except branch, after the log). In process memory
+ only: scheduler_heartbeat() returns (started_at, last_tick), None for
+ what hasn't happened. api/setup_checks.check_scheduler reads it: no
+ start = the task isn't running (red); no tick
+ _SCHEDULER_STARTUP_GRACE_S (300 s) after start = stuck (red, amber
+ before that); last tick older than max(3 × poll interval, 90 s) =
+ stopped (red); failed = red; waiting_for_company = amber with a link
+ to /onboard. The pause switch is checked AFTER liveness, from its own
+ row: a paused loop still beats, so a dead one reads as stopped (red),
+ not paused. run_scheduler also clears _last_tick on entry, so a
+ restart in one process never reports the previous run's last tick.
+ Due actions run as their own tasks (_inflight), so a slow action
+ never ages the heartbeat — only a stuck or dead loop does.
module: openexecutive.scheduler
pause: |
Operator pause switch — openexecutive.scheduler.pause. One row
@@ -4103,8 +4123,9 @@ auth:
The API receives the same flag and then adds `_local_login_gate`
(api/main.py), a 403 for (a) a raw Host that is not loopback, unless
the path is a webhook that verifies its caller (Google Chat always;
- Telegram only with TELEGRAM_WEBHOOK_SECRET, since without it the
- webhook accepts anyone's update), and (b) a write whose Sec-Fetch-Site
+ Telegram only with a TELEGRAM_WEBHOOK_SECRET Telegram can send, since
+ without it the webhook accepts anyone's update), and (b) a write whose
+ Sec-Fetch-Site
is present and not same-origin/none. Without it the owner's browser
could drive :8000 as the principal (usually no shared secret; no
x-caller-email = principal): a DNS-rebinding page calls it
@@ -4370,6 +4391,75 @@ integrations:
naturally small blast radius).
telegram: Webhook gating + per-chat conversation history. Roster-gated per `channel_access`.
google_chat: Webhook + service-account auth.
+ setup_status: |
+ GET /setup/status (api/routes/setup_status.py; checks in
+ api/setup_checks.py) backs the UI's Settings → Setup status page:
+ one light per part of the install, state ok | warn | error | off,
+ with a plain-language summary and fix, an optional in-app link
+ (/people, /onboard) and last_activity (latest integration_inbound
+ audit ts for the channel's actor). Order = setup_checks.LABELS. The
+ UI adds its own sign-in light (lib/setupStatus.ts signInCheck, from
+ the UI's env) and sorts worst-first.
+ Probes — at most one free read-only call per service, each bounded
+ by PROBE_TIMEOUT_S (5 s), via one shared httpx client per run:
+ Anthropic models.list(limit=1) through configured_async_client
+ (max_retries=0; so a missing ANTHROPIC_WORKSPACE_ID on an org key
+ surfaces as a 400/403); Slack POST auth.test (Bearer bot token);
+ Telegram getMe then getWebhookInfo (empty url, a url whose path isn't
+ …/webhook/telegram, or a last_error_date within 24 h = amber);
+ Discord GET /users/@me only while the bot is not ready and its task
+ hasn't died. Liveness from app.state, which the lifespan sets:
+ slack_handler (client.is_connected()), discord_bot (is_ready() AND
+ ws.open — discord.py keeps _ready set through a dropped connection
+ while it reconnects; only close() clears it) + discord_bot_task (a
+ finished task is red; LoginFailure / PrivilegedIntentsRequired map to
+ their own fixes), mcp_gateway.
+ Roster: a connected Slack/Discord/Telegram is amber while no
+ non-archived Person has its id field, or when the latest inbound row
+ is a "Rejected: …" from the last 24 h whose sender id (extracted from
+ the summary) is still not on the roster — so the light clears as soon
+ as the fix is made, and one stranger can't leave it amber for good.
+ Message text from inbound summaries is never echoed. Local login without
+ TELEGRAM_WEBHOOK_SECRET is red (the local-login gate refuses the
+ webhook). Google Chat: numeric project number, one of the SA
+ settings, and a readable SA key file (≤64 KiB JSON with
+ client_email). Gmail: google_workspace in configured_server_names,
+ gateway up, and the workspace-mcp credentials present in this
+ process's env (GOOGLE_OAUTH_CLIENT_ID + _SECRET, or a
+ GOOGLE_SERVICE_ACCOUNT_KEY_* with GWORKSPACE_AUTH_MODE=
+ service_account) — that env is what the gateway forwards.
+ Secrets: no token in a response or log line — probes report a status
+ code, a Slack error code matching [a-z_]{1,40}, or an exception class
+ name; _fetch never logs a URL (Telegram's carries the token), and the
+ Telegram token must match \d+:[A-Za-z0-9_-]{30,} before it is put in
+ one. Sample values from .env.example (setup_checks.EXAMPLE_VALUES,
+ RFC 2606 example domains for emails) are named as samples and never
+ sent; test_setup_checks.py fails if .env.example ships a sample the
+ set doesn't know, and scripts/setupStatus.test.mjs keeps the UI's
+ example-domain set equal to the API's.
+ Each check runs guarded: one that raises becomes a red "couldn't
+ run" light (class name logged), not a 500. Runs are shared: a
+ request within _REUSE_FOR_S (5 s) of the last run gets its answer,
+ and concurrent requests await one shielded task — so "Check again"
+ can't become a stream of calls to those services. Both live on
+ app.state (setup_status_runs), not module globals, and a task from
+ another event loop is never awaited. Same auth as
+ every route (shared secret; local-login host gate).
+ Comment-as-value: python-dotenv reads `KEY= # note` as "# note"
+ (it strips only a comment that follows a value). Settings maps such
+ values to None for the Slack, Telegram, Discord and Google Chat
+ credentials (config._unset_if_comment → _blank_or_comment), so a
+ copied .env.example no longer switches Telegram and Google Chat on
+ with their comments as tokens; the example's notes now sit on their
+ own lines. TELEGRAM_WEBHOOK_SECRET is deliberately NOT covered: None
+ would skip the webhook's header check. Instead a secret outside
+ setWebhook's charset ([A-Za-z0-9_-]{1,256} — the only values Telegram
+ can send back) is treated as proving nothing: the webhook answers 401
+ to every update without comparing (a forger who guessed the junk text
+ would otherwise match it, and a non-ASCII value would make
+ hmac.compare_digest raise), people_tools and the local-login gate's
+ _webhook_verifies_its_caller return False, and Setup status shows it
+ red. One rule for all four: Settings.telegram_webhook_secret_valid.
attachments: |
openexecutive.integrations.attachments — cross-platform attachment
handling for the web chat, Discord, and Telegram. Inbound images are
diff --git a/packages/core/openexecutive/architecture/prebuilt/agents.json b/packages/core/openexecutive/architecture/prebuilt/agents.json
index 73cb9a38..1bb86f72 100644
--- a/packages/core/openexecutive/architecture/prebuilt/agents.json
+++ b/packages/core/openexecutive/architecture/prebuilt/agents.json
@@ -1,7 +1,7 @@
{
"section_id": "agents",
"title": "Agent Council",
- "markdown": "The Executive (`openexecutive.orchestrator.executive.Executive`) is a single coherent persona that fans out to specialist sub-agents via Anthropic tool use. Each specialist subclasses `openexecutive.agents.base.BaseAgent`, carrying a `name`, `domain`, and `model`, and exposes `analyze(...)`, which wraps the question in user-turn context and calls Claude through the per-call provider.\n\nRouting uses one `consult_specialist` tool. Beside it the Executive carries its skill tools (`search_skills`, `load_skill`, `create_skill`, `update_skill`, `delete_skill` — shown to users as **playbooks**; `create_skill` / `update_skill` / `delete_skill` never change the library — they save a draft (`knowledge/skill_drafts.py`) that a person approves on the Playbooks tab, and the reply links to it; `update_skill` / `delete_skill` (and `create_skill`, for a name a workflow still follows) refuse any built-in name (including a company's customized copy) and any company playbook a workflow (even a switched-off custom one) follows — workflows read playbooks at run time, approved scheduled ones included, and this loop also runs on inbound email and chat, so only a person on the Playbooks tab can change what a workflow follows; a hidden built-in is invisible to search and load; each `search_skills` hit lists the `workflows` that follow it, and the persona routes \"the finished deliverable\" to that workflow and quick or partial asks to the playbook inline); Tool calls made while proactive work is tagged (scheduler dispatch, reflection, research, alert review) feed the Attunement outcome ledger. Attunement adds `list_open_loops` (what a person owes — everyone's for the principal only in a private conversation, otherwise the caller's own) and `close_open_loop`, which only closes a loop when the turn's resolved speaker is the principal or the loop's owner — an unrostered sender, a signed-in web user not on the roster, and unattended sessions are refused. The roster write tools (`upsert_person`, `archive_person`, `set_department_head`) are the principal's alone, and only on a surface that verified the speaker — the web chat, the principal's own Slack or Discord, or a private Telegram chat when `TELEGRAM_WEBHOOK_SECRET` is set (Telegram identifies the chat rather than the sender, and without that secret its webhook accepts anyone's update). A teammate, an email (even from the principal's address), Google Chat, the CLI, the MCP server and unattended runs get `status: refused` (audited, and no action chip), because a People row is also the web sign-in and outbound-email allow-list. Multiple parallel `tool_use` blocks in a single assistant turn fan out concurrently through `router.route_parallel`, each running its own domain-filtered ChromaDB query before the specialist sees the question. The Executive then synthesizes the returned analyses into one reply.\n\nThe nine entries in `SPECIALIST_REGISTRY` (`openexecutive.orchestrator.router`):\n\n| Key | Agent | Domain |\n| --- | --- | --- |\n| `cso` | `StrategyAgent` | strategy |\n| `cfo` | `FinanceAgent` | finance |\n| `chro` | `HRAgent` | hr |\n| `gc` | `LegalAgent` | legal |\n| `coo` | `OperationsAgent` | operations |\n| `cmo` | `MarketingAgent` | marketing |\n| `cpo` | `ProductAgent` | product |\n| `board_comms` | `BoardCommsAgent` | board |\n| `triage` | `TriageAgent` | triage |\n\nModels: specialists default to `claude-sonnet-5`; a deep-reasoning tier uses `claude-opus-5` (adaptive thinking); routing/fast classification uses `claude-haiku-4-5`. The Council's **Deep reasoning** toggle is honoured on Claude Opus/Sonnet (direct or via OpenRouter) and on any OpenRouter model whose live catalog entry supports `reasoning` (today all OpenAI, Gemini, DeepSeek and Grok entries; not Llama) — the request translator turns Anthropic adaptive thinking + effort into OpenRouter's `reasoning` parameter. It is a silent no-op on models that can't reason, and disabled for Haiku, which rejects adaptive thinking. The Council picks a model in two steps: a **Provider** dropdown (Anthropic, OpenAI, Google, Meta, DeepSeek, xAI, Local, …), then a **Model** dropdown limited to that provider, with readable names (\"Claude Opus 5.5\") and the raw id and serving route shown underneath. The Anthropic group combines the direct Claude models (`claude-fable-5-1`, `claude-opus-5-5`, `claude-opus-5`, `claude-sonnet-5`, `claude-haiku-4-5`) with any Claude generation that exists only on OpenRouter, and never lists a model twice. With `OPENROUTER_ENABLED`, the non-Anthropic entries come from OpenRouter's live `/models` catalog (fetched at startup, refreshed in the background, filtered to tool-capable paid text models from an allowlisted vendor set), falling back to a built-in snapshot if the fetch fails. Eight Council-only agents are model/prompt-overridable in the UI but NOT callable via `consult_specialist`, because they are deliberately kept out of `SPECIALIST_REGISTRY`: `quality_judge` (committee review), `utility_fast` (gates, titles, decision parsing), `research` (the `executive_research` fan-out), `fixture_generator` (invents demo companies), `engagement_intake` (models a real client from intake material), `onboarding_interviewer` (interviews a new user about their own company and drafts its profile, people and departments), `workflow_designer` (runs the conversational New workflow wizard on `/jobs/new`: searches the available tools, asks clarifying questions, then drafts a validated dynamic-workflow definition for the user to review), and `workflow_actor` (runs a workflow's `action` steps: a bounded tool-use loop limited to the tools the user approved for that step). `fixture_generator`, `engagement_intake` and `onboarding_interviewer` share one shape — a forced tool call producing a whole company, validated for referential integrity, with a single repair retry — but opposite epistemics: the fixture author invents, the other two extract and leave unstated facts empty rather than guessing.\n\nOne more structured-output utility agent sits beside `triage`: `openexecutive.agents.alert_review.AlertReviewAgent` (routing model, one forced `emit_alert_reviews` tool call, never raises). The alert review job hands it a batch of open alerts with evidence and gets back, per alert, a verdict (relevant / changed / resolved / stale), a confidence, the evidence it relied on, a one-line note, why-now, an optional deadline, and a recommended move (none / route / nudge / escalate / draft / suggest_workflow / merge / close) with its parameters. Like `triage`, it never mutates state — `alerts.review.apply_verdict` executes the verdicts deterministically within authority, so the model's job is judgment, not action.\n\nEvery specialist *advises* — each returns domain analysis the Executive synthesizes into one voice. None of them act on the company's behalf; the side-effecting tools in the main loop (schedule, people, departments, broadcast, watchlist, workflows) belong to the Executive, not to a specialist.\n\nThe Executive can also launch *any* workflow conversationally: `orchestrator.workflow_run_tools` adds `list_workflows` (the launchable catalog with each workflow's inputs) and `run_workflow` (runs a built-in or custom workflow to completion and returns its artifact, checkpointing approval gates as `awaiting_human`). This makes the `/jobs` catalog reachable from chat — see the Workflows section.\n\nDeliverables are first-class too. `orchestrator.artifact_tools` gives the Executive three tools: `draft_artifact` publishes a memo, web page (`html`), Word document (`docx`), spreadsheet (`xlsx`, from structured `sheets`) or a `link` to something it created in one of the principal's connected apps through the generic MCP gateway (`search_tools` → `call_tool`, any server — no vendor is named), and returns the artifact's id and link; `list_artifacts` and `get_artifact` let it find and reread its own past work (drafts and workflow outputs alike, through the same `artifact_records` read model the API uses). Revising is `draft_artifact(supersedes=<id>)`, which archives the earlier version. When the principal asks for a deliverable the tool is always used; the \"quiet is the right default\" bar applies only to unprompted drafts. The format enum is a hard-coded sorted tuple so the cached tool schema stays byte-stable. Delivery: `message_person(person_id, text, artifact_id?)` appends the artifact's title and a `UI_BASE_URL/artifacts/<id>` link (through the same outbound guard as any DM; the link needs Open Executive access), and a Gmail send/draft can attach the file itself by `artifact_id` — see Integrations.\n\nThe Executive also backs the **Ask OE** panel's form-fill tier via `orchestrator.form_tools.propose_form_values`: when a chat turn arrives with a `<page_context>` block describing a form on the user's screen, the Executive can propose values for it. The proposal is delivered to the UI as a `form_patch` SSE event and placed into the form as highlighted suggestions — the tool never saves or submits anything; the user reviews and saves manually. The tool is **always** in the tool list (tool definitions sit at the top of the cached prompt prefix, so a conditionally-present tool would invalidate the prompt cache whenever panel and non-panel turns alternate); its description restricts usage to turns that carry a form descriptor.",
+ "markdown": "The Executive (`openexecutive.orchestrator.executive.Executive`) is a single coherent persona that fans out to specialist sub-agents via Anthropic tool use. Each specialist subclasses `openexecutive.agents.base.BaseAgent`, carrying a `name`, `domain`, and `model`, and exposes `analyze(...)`, which wraps the question in user-turn context and calls Claude through the per-call provider.\n\nRouting uses one `consult_specialist` tool. Beside it the Executive carries its skill tools (`search_skills`, `load_skill`, `create_skill`, `update_skill`, `delete_skill` — shown to users as **playbooks**; `create_skill` / `update_skill` / `delete_skill` never change the library — they save a draft (`knowledge/skill_drafts.py`) that a person approves on the Playbooks tab, and the reply links to it; `update_skill` / `delete_skill` (and `create_skill`, for a name a workflow still follows) refuse any built-in name (including a company's customized copy) and any company playbook a workflow (even a switched-off custom one) follows — workflows read playbooks at run time, approved scheduled ones included, and this loop also runs on inbound email and chat, so only a person on the Playbooks tab can change what a workflow follows; a hidden built-in is invisible to search and load; each `search_skills` hit lists the `workflows` that follow it, and the persona routes \"the finished deliverable\" to that workflow and quick or partial asks to the playbook inline); Tool calls made while proactive work is tagged (scheduler dispatch, reflection, research, alert review) feed the Attunement outcome ledger. Attunement adds `list_open_loops` (what a person owes — everyone's for the principal only in a private conversation, otherwise the caller's own) and `close_open_loop`, which only closes a loop when the turn's resolved speaker is the principal or the loop's owner — an unrostered sender, a signed-in web user not on the roster, and unattended sessions are refused. The roster write tools (`upsert_person`, `archive_person`, `set_department_head`) are the principal's alone, and only on a surface that verified the speaker — the web chat, the principal's own Slack or Discord, or a private Telegram chat when `TELEGRAM_WEBHOOK_SECRET` is set to a value Telegram can send (Telegram identifies the chat rather than the sender, and without that secret its webhook accepts anyone's update). A teammate, an email (even from the principal's address), Google Chat, the CLI, the MCP server and unattended runs get `status: refused` (audited, and no action chip), because a People row is also the web sign-in and outbound-email allow-list. Multiple parallel `tool_use` blocks in a single assistant turn fan out concurrently through `router.route_parallel`, each running its own domain-filtered ChromaDB query before the specialist sees the question. The Executive then synthesizes the returned analyses into one reply.\n\nThe nine entries in `SPECIALIST_REGISTRY` (`openexecutive.orchestrator.router`):\n\n| Key | Agent | Domain |\n| --- | --- | --- |\n| `cso` | `StrategyAgent` | strategy |\n| `cfo` | `FinanceAgent` | finance |\n| `chro` | `HRAgent` | hr |\n| `gc` | `LegalAgent` | legal |\n| `coo` | `OperationsAgent` | operations |\n| `cmo` | `MarketingAgent` | marketing |\n| `cpo` | `ProductAgent` | product |\n| `board_comms` | `BoardCommsAgent` | board |\n| `triage` | `TriageAgent` | triage |\n\nModels: specialists default to `claude-sonnet-5`; a deep-reasoning tier uses `claude-opus-5` (adaptive thinking); routing/fast classification uses `claude-haiku-4-5`. The Council's **Deep reasoning** toggle is honoured on Claude Opus/Sonnet (direct or via OpenRouter) and on any OpenRouter model whose live catalog entry supports `reasoning` (today all OpenAI, Gemini, DeepSeek and Grok entries; not Llama) — the request translator turns Anthropic adaptive thinking + effort into OpenRouter's `reasoning` parameter. It is a silent no-op on models that can't reason, and disabled for Haiku, which rejects adaptive thinking. The Council picks a model in two steps: a **Provider** dropdown (Anthropic, OpenAI, Google, Meta, DeepSeek, xAI, Local, …), then a **Model** dropdown limited to that provider, with readable names (\"Claude Opus 5.5\") and the raw id and serving route shown underneath. The Anthropic group combines the direct Claude models (`claude-fable-5-1`, `claude-opus-5-5`, `claude-opus-5`, `claude-sonnet-5`, `claude-haiku-4-5`) with any Claude generation that exists only on OpenRouter, and never lists a model twice. With `OPENROUTER_ENABLED`, the non-Anthropic entries come from OpenRouter's live `/models` catalog (fetched at startup, refreshed in the background, filtered to tool-capable paid text models from an allowlisted vendor set), falling back to a built-in snapshot if the fetch fails. Eight Council-only agents are model/prompt-overridable in the UI but NOT callable via `consult_specialist`, because they are deliberately kept out of `SPECIALIST_REGISTRY`: `quality_judge` (committee review), `utility_fast` (gates, titles, decision parsing), `research` (the `executive_research` fan-out), `fixture_generator` (invents demo companies), `engagement_intake` (models a real client from intake material), `onboarding_interviewer` (interviews a new user about their own company and drafts its profile, people and departments), `workflow_designer` (runs the conversational New workflow wizard on `/jobs/new`: searches the available tools, asks clarifying questions, then drafts a validated dynamic-workflow definition for the user to review), and `workflow_actor` (runs a workflow's `action` steps: a bounded tool-use loop limited to the tools the user approved for that step). `fixture_generator`, `engagement_intake` and `onboarding_interviewer` share one shape — a forced tool call producing a whole company, validated for referential integrity, with a single repair retry — but opposite epistemics: the fixture author invents, the other two extract and leave unstated facts empty rather than guessing.\n\nOne more structured-output utility agent sits beside `triage`: `openexecutive.agents.alert_review.AlertReviewAgent` (routing model, one forced `emit_alert_reviews` tool call, never raises). The alert review job hands it a batch of open alerts with evidence and gets back, per alert, a verdict (relevant / changed / resolved / stale), a confidence, the evidence it relied on, a one-line note, why-now, an optional deadline, and a recommended move (none / route / nudge / escalate / draft / suggest_workflow / merge / close) with its parameters. Like `triage`, it never mutates state — `alerts.review.apply_verdict` executes the verdicts deterministically within authority, so the model's job is judgment, not action.\n\nEvery specialist *advises* — each returns domain analysis the Executive synthesizes into one voice. None of them act on the company's behalf; the side-effecting tools in the main loop (schedule, people, departments, broadcast, watchlist, workflows) belong to the Executive, not to a specialist.\n\nThe Executive can also launch *any* workflow conversationally: `orchestrator.workflow_run_tools` adds `list_workflows` (the launchable catalog with each workflow's inputs) and `run_workflow` (runs a built-in or custom workflow to completion and returns its artifact, checkpointing approval gates as `awaiting_human`). This makes the `/jobs` catalog reachable from chat — see the Workflows section.\n\nDeliverables are first-class too. `orchestrator.artifact_tools` gives the Executive three tools: `draft_artifact` publishes a memo, web page (`html`), Word document (`docx`), spreadsheet (`xlsx`, from structured `sheets`) or a `link` to something it created in one of the principal's connected apps through the generic MCP gateway (`search_tools` → `call_tool`, any server — no vendor is named), and returns the artifact's id and link; `list_artifacts` and `get_artifact` let it find and reread its own past work (drafts and workflow outputs alike, through the same `artifact_records` read model the API uses). Revising is `draft_artifact(supersedes=<id>)`, which archives the earlier version. When the principal asks for a deliverable the tool is always used; the \"quiet is the right default\" bar applies only to unprompted drafts. The format enum is a hard-coded sorted tuple so the cached tool schema stays byte-stable. Delivery: `message_person(person_id, text, artifact_id?)` appends the artifact's title and a `UI_BASE_URL/artifacts/<id>` link (through the same outbound guard as any DM; the link needs Open Executive access), and a Gmail send/draft can attach the file itself by `artifact_id` — see Integrations.\n\nThe Executive also backs the **Ask OE** panel's form-fill tier via `orchestrator.form_tools.propose_form_values`: when a chat turn arrives with a `<page_context>` block describing a form on the user's screen, the Executive can propose values for it. The proposal is delivered to the UI as a `form_patch` SSE event and placed into the form as highlighted suggestions — the tool never saves or submits anything; the user reviews and saves manually. The tool is **always** in the tool list (tool definitions sit at the top of the cached prompt prefix, so a conditionally-present tool would invalidate the prompt cache whenever panel and non-panel turns alternate); its description restricts usage to turns that carry a form descriptor.",
"mermaid": "flowchart TD\n User([User message]) --> Exec[\"Executive<br/>orchestrator\"]\n Exec -->|consult_specialist| Cso[\"cso: StrategyAgent\"]\n Exec -->|consult_specialist| Cfo[\"cfo: FinanceAgent\"]\n Exec -->|consult_specialist| Gc[\"gc: LegalAgent\"]\n Exec -->|consult_specialist| More[\"chro / coo / cmo / cpo<br/>board_comms / triage\"]\n Cso --> Claude[\"Claude (Anthropic)\"]\n Cfo --> Claude\n Gc --> Claude\n More --> Claude\n Claude --> Exec\n class User entry\n class Exec compute\n class Cso compute\n class Cfo compute\n class Gc compute\n class More compute\n class Claude external",
- "generated_at": "2026-09-25T01:36:05.539643+00:00"
+ "generated_at": "2026-09-25T12:22:48.458924+00:00"
}
diff --git a/packages/core/openexecutive/architecture/prebuilt/api.json b/packages/core/openexecutive/architecture/prebuilt/api.json
index 0457bb40..ccff10bd 100644
--- a/packages/core/openexecutive/architecture/prebuilt/api.json
+++ b/packages/core/openexecutive/architecture/prebuilt/api.json
@@ -1,7 +1,7 @@
{
"section_id": "api",
"title": "API Reference",
- "markdown": "The FastAPI surface lives in `openexecutive.api.main`, which mounts one router per topic. A shared-secret middleware gates every request via an `x-api-key` header, except `/health` and the `/webhook/*` callbacks (which carry their own verification). With local login (`OE_LOCAL_LOGIN=1`, which only `make dev` sets, and only while Google sign-in is not set up) a second middleware answers 403 to any request whose raw `Host` is not `localhost`, `127.0.0.1` or `[::1]` (except a webhook that verifies its caller: Google Chat always, Telegram only with `TELEGRAM_WEBHOOK_SECRET`), and to any write whose `Sec-Fetch-Site` is present and not `same-origin`/`none`. The UI signs that owner in with no password and this API usually has no secret, so without it a web page in the owner's browser could drive the API as the principal — by DNS-rebinding its own hostname to 127.0.0.1, or by posting a plain form from another site or localhost port. CORS is restricted to configured UI origins. The gate is off when `BACKEND_SHARED_SECRET` is unset — intended for local development only — so any internet-reachable deployment sets `OE_PUBLIC_DEPLOYMENT`, and `create_app()` then refuses to boot without the secret rather than serving an unauthenticated API.\n\nEndpoints grouped by router:\n\n| Router | Key endpoints | Purpose |\n|---|---|---|\n| `chat` | `POST /chat`, `POST /chat/stop` | SSE stream of a live Executive turn. The request body optionally carries `page_context` (route, page title, guide section id, and a form descriptor with current values) — sent only by the Ask OE side panel so the Executive can explain the current page or propose form values. When the Executive calls its `propose_form_values` tool, the stream emits a `form_patch` event (`{type, form_id, fields, rationale, iteration}`) that the panel applies into the on-screen form as highlighted suggestions; the user reviews and saves through the form's normal submit path. Each round of tool calls also emits an `activity` event (`{type, label, tool, iteration}`) naming what is running — progress only, forwarded verbatim and never persisted with the message, unlike an `action_taken` chip. A `session_id` in the body must be a chat the caller may use (the same ownership rule as `sessions`). If it isn't, the turn runs in a fresh chat instead, so nothing is written into someone else's session and the reply looks the same as for an unknown id. An unknown namespaced id (`slack:…`, `telegram:…` and so on) is ignored and a fresh chat is started, because those ids belong to the channel adapters and claiming one first would make the caller its owner. The client mints a `client_turn_id` and sends it with the turn; `POST /chat/stop` takes that id and halts the turn mid-flight, so the button is live from the moment Send is pressed rather than only once the first SSE byte arrives. A stopped turn emits a `stopped` event and then the usual `done` over the same still-open stream — never an `error` — and whatever streamed so far is persisted and flagged. The endpoint returns 404 both for an unknown id and for another caller's turn, so it cannot be used to probe which turns are live. An optional `memory_text` (1–2000 chars) is what peer memory records as the caller's words instead of `message` — the briefing handoffs send it because their seed quotes the Executive's own card; `POST /chat/upload` derives it from the typed text and filenames. Since it never reaches the transcript, the `chat_turn` audit row keeps it beside `message`. |\n| `sessions` | `GET /sessions`, `GET /sessions/{id}`, `GET /sessions/{id}/messages`, `DELETE /sessions/{id}`, `POST /sessions/{id}/messages/{message_id}/feedback`, `GET /sessions/{id}/followup` | List, read and delete saved chat sessions (assistant messages carry their row `id` and any `feedback`). The list is scoped to the caller. Every per-session route checks ownership, because session ids are guessable (`slack:dm:<user id>`, `telegram:<chat id>`): only the session's owner or the principal gets through, and a legacy row with no owner is the principal's alone. Anyone else gets the same 404 as for an unknown id, so the routes can't be used to find out which chats exist. The one other way in is having started the chat in this process (matched by Person id or verified email, so it survives the caller being added to the roster), which is how a caller the roster can't resolve keeps using their own chat. That record is in memory, so after a restart such an ownerless chat is refused for reads. The principal can continue someone else's ownerless chat without becoming its owner. Deleting a session also drops its in-memory copy, so a later turn naming that id starts fresh. The feedback route records 👍/👎 (`{\"feedback\": \"up\"|\"down\"|null}`) on one assistant reply; only the session's own caller or the principal may rate it. The rater is stored (`feedback_by_person_id`), and a 👎 on a reply to the rater's own message triggers a working-style pass for them (paced; see attunement). The chat stream's `done` event carries `message_id` for the persisted reply. The followup route returns `{\"suggestion\": string|null}` — one suggested next user message, written by the utility-fast model from the last few turns, that the chat composer shows as its greyed placeholder (Tab / → or the inline chip fills it in without sending). It is null unless the session ends on a persisted assistant reply, and null (uncached) when the model fails. Same ownership check as feedback; successful suggestions are cached in-process per (session, reply id). |\n| `today` | `GET /today`, `GET /today/activity`, `GET /today/activity/daily` | Morning-brief aggregation, recent-action rail, and Pulse heartbeat heatmap (per-day activity counts). |\n| `people` | `GET\\|POST\\|PATCH /people`, `POST /people/{id}/archive`, `GET /people/{id}/open-loops`, `POST /open-loops/{loop_id}/close`, `GET /people/{id}/outreach`, `GET\\|PUT\\|DELETE /people/{id}/attunement` | Roster CRUD and scope lookups. Archiving a person closes their open loops. The open-loop routes list what a person owes (soonest due first) and close one (`reason`: done / not_needed / cancelled) — both the principal's or the owner's only (403 otherwise, via `people.store.is_principal_or_self`). `/outreach` returns, per kind of proactive outreach over 30 days, `sent` / `replied` / `acted` / `ignored` / `pending` (voided DMs are excluded) — same access rule, checked before the person lookup so it can't probe which ids exist. `/attunement` reads, replaces (`rules`: up to 4 strings, or omitted to only set `locked`) or resets the person's working-style rules — same access rule, 404 for an archived person; `PUT` rejects a rule that is not purely about style with 422. Archiving a person also drops their working style. |\n| `departments` | `GET\\|POST\\|PATCH\\|DELETE /departments`, `.../goals` | Department state and per-department goals. `PATCH /departments/{slug}` also takes `watched_entities` (≤50 names, `[]` clears) — the entities the research watch policy may add watches for and route to this department. A `cadences` spec that does not parse is rejected with a 422 (empty means no cadence). |\n| `agents` | `GET /agents`, `GET /agents/models`, `GET /agents/models/options`, `PATCH /agents/{id}`, `POST /agents/{id}/test` | Specialist metadata and Council overrides. `/agents/models` is the flat model allowlist the PATCH validator uses; `/agents/models/options` returns the same ids in the same order, each tagged with `provider`, `provider_label`, `route` (`direct` / `openrouter` / `local`) and a display `label`, for the Council's Provider → Model picker. |\n| `personas` | `GET\\|PUT\\|POST\\|DELETE /personas` | Executive persona definitions. |\n| `alerts` | `POST /alerts/{id}/ack`, `POST /alerts/bulk-ack`, `POST /alerts/{id}/reopen`, `POST /alerts/review` | Groom the briefing queue. `ack` (`read`/`ack`/`dismissed`, optional `mute_topic`) also teaches a watch-sourced alert's watch (`trust_score`); `bulk-ack` takes explicit `alert_ids` and/or `older_than_days` + `category` (exempt sources skipped); `reopen` is the Undo for a `resolved` / `expired` / `dismissed` alert (never `ack` or an artifact / decision row; back to `unread` with every review stamp cleared and its TTL anchor refreshed, so it is live again even if older than its TTL); `review` runs the Executive's relevance review on demand (ignores the interval; still honours `ALERT_REVIEW_ENABLED`, the per-pass caps, the single-flight lock and per-alert idempotency) and returns the move counts. `bulk-ack` caps ids at 500, needs `older_than_days >= 1`, and applies watch feedback per row; `mute_topic` must be one of the alert's tags or a scoped `external:` / `department:` pattern. Alerts still surface only through the briefing (`/today` reads the live view) — there is no list, prefs, mutes, or live-stream endpoint. |\n| `artifacts` | `GET /artifacts`, `GET /artifacts/{id}`, `GET /artifacts/{id}/download?as=`, `POST /artifacts/{id}/archive`, `POST /artifacts/{id}/restore`, `DELETE /artifacts/{id}` | Browsable deliverables in any format — Markdown, HTML, Word, Excel, or a link into a connected app — with `format`, `downloads`, `external_url` and `supersedes_id` on every summary. `download` renders the file (Word/Excel built at request time from the stored text; any Markdown artifact, workflow output included, can export `?as=docx`) and is always an attachment with `nosniff` and a sandbox CSP. |\n| `decisions` | `GET /decisions`, `POST /decisions/{id}/{approve,reject,cancel}`, `GET /audit/reliability` | Approval-gated decision instances (e.g. calendar bookings). A proposed booking is surfaced on the briefing as a companion alert; approve/reject/cancel here also clear that alert. Reviewed in the briefing — there is no separate proposals page. |\n| `audit` | `GET /audit/logs`, `GET /audit/logs/{id}`, `GET /audit/sessions/{id}`, `GET /audit/usage`, `POST /audit/log` | Durable audit trail of side effects. `/audit/sessions/{id}` adds a per-session token cost summary; `/audit/usage` aggregates token usage and OpenRouter cost across all sessions (totals, by day, by model, and by source — the part of the system that made the calls — including server-side web-search counts). |\n| `architecture` | `GET /architecture/sections`, `.../sections/{id}` | This documentation surface. |\n| `guide` | `GET /guide/sections`, `.../sections/{id}` | Plain-language user-guide content surface — mirrors `architecture` (static, version-controlled files; no LLM on the serving path). |\n| `health` | `GET /health`, `GET /health/honcho` | Liveness probes (unauthenticated). |\n| `documents` | `POST\\|GET\\|DELETE /documents`, `GET /documents/{filename}` | Upload, list, view extracted text, and delete indexed company docs. Upload is keyed on the filename, so re-uploading a document replaces its chunks rather than duplicating them, and `DELETE` removes the rows as well as the file. `domain` must be one of the eight specialist domains or `general`; anything else is a 400 rather than a 200 that indexes where no specialist can retrieve. |\n| `executive` | `GET /executive/status`, `POST /executive/pause`, `POST /executive/resume` | Operator pause switch for all autonomous work (scheduler, Gmail poller, workflow resumer); inbound chat and DMs stay live. Status returns `{paused, paused_at, paused_by, reason, held_actions, can_resume}` — `held_actions` counts due `pending` rows that fire on resume. `pause` takes an optional `reason` (≤200 chars) and is idempotent (re-pausing keeps the original start and reason); `paused_by` is the UI proxy's `x-caller-email`, else `api`. Behind the shared-secret middleware — not `SCHEDULED_ADMIN_TOKEN`, which the UI cannot send. Any caller may pause; `resume` is principal-only (`is_principal_or_self`, 403 otherwise; open while no principal is rostered; a header-less caller resolves to the principal as in `chat`), and status carries `can_resume` for the viewer so the UI hides Resume from everyone else. |\n| `scheduled` | `GET\\|DELETE` scheduled actions (`?status=…&order=asc\\|desc`) | Pending and fired scheduled actions; `order` flips the `run_at` sort (asc=soonest-first for the upcoming queue, desc=most-recent-first for terminal-status history). `DELETE /scheduled/{id}` cancels a `pending` row (409 otherwise). Like pause it only stops work, so any signed-in user may — the UI proxy's `x-caller-email` is trusted when the request also carries the `BACKEND_SHARED_SECRET` `x-api-key` — as may a matching `X-Admin-Token` (`SCHEDULED_ADMIN_TOKEN`) or a loopback caller with no token set; otherwise 401 (token set) or 503. Audited as `scheduled_action_cancelled`. |\n| `watchlist` | `GET\\|POST\\|PATCH\\|DELETE /watchlist`, `POST /watchlist/{slug}/approve`, `POST /watchlist/{slug}/decline` | External-monitoring watchlist + signals. Rows carry `origin` (`manual` \\| `executive` \\| `research` \\| `research_proposed`); `approve` turns a research suggestion (`research_proposed`, `dry_run`) into a live watch, `decline` `{reason: not_relevant \\| too_noisy \\| wrong_source}` removes it and records the decline (or, for `too_noisy`, keeps it live at a high floor), both 409 unless the row is a pending suggestion; `DELETE ?reason=` on a research-origin row records the decline too. |\n| `workflows` | `GET /workflows`, `POST /workflows/{name}/runs`, `GET\\|POST\\|PUT\\|DELETE /workflows/custom`, `GET\\|DELETE /workflows/custom/{name}/targets`, `POST /workflows/runs/{run_id}/decision`, `GET /workflows/tools/search?q=`, `GET /workflows/tools/describe?names=` | Workflow catalog, run management, and user-created (dynamic) workflow CRUD. Custom definitions come back with a server-managed `owner_person_id` (the creator — the web caller on `POST`, set on insert only; a client-sent value is ignored), who is asked to approve a workflow's first write to a new target. `GET /workflows/custom/{name}/targets` lists the targets its tool steps may write to without asking and `DELETE …/targets?value=` forgets one. `POST /workflows/runs/{run_id}/decision` with `{decision: \"approve\"|\"reject\"}` answers a run awaiting a yes/no sign-off from the web app — 403 unless the caller is the person it waits on or the principal, 409 if it isn't awaiting or needs a written reply — through the same `apply_resolution` a chat reply uses. Custom create/update also rejects (422) any action-step tool that does not resolve, and so does `POST /workflows/custom/{name}/activate` when turning a workflow **on** — that click is the approval for a tool workflow chat saved switched off (turning off is never checked). Turning on a workflow with action steps requires the body `{is_active: true, definition}` carrying the definition the user reviewed; if the stored one differs (ignoring `is_active` and timestamps) it returns 409, and the switch itself is a compare-and-set on the validated revision (`dynamic_store.activate_if_unchanged`, keyed on `updated_at`), so a save that lands while the tool check awaits the gateway — even from another process — is a 409 too, so only what was shown gets switched on. `GET /workflows/custom` lists inactive definitions too; `GET /workflows/{name}` 404s for them. The two `tools` endpoints return `{tools: [{name, description, read_only, source}]}` for the advanced editor's tool picker and the review card; `read_only` is true only when the name says it reads (a label, not a control). The run stream adds a `progress` event (`step_id`, `summary`) while an action step uses tools. Each catalog entry (`WorkflowMeta`) carries `is_custom` and `background` (true for the system-run built-ins the UI files under “System”). The run endpoint streams SSE; its `awaiting_human` event carries `delivery` (`self` \\| `sent` \\| `suppressed` \\| `alerted` \\| `failed`) alongside `person_id` / `question` / `awaiting_until`, because the outbound guard or an unreachable approver means the question may never have been asked — a client must not render “waiting on them” for those. A paused run ends the stream with neither `done` nor `error`, so that `awaiting_human` frame carries `terminal: true` to say so explicitly, plus `resumable` — whether the run continues by itself once answered or stops at the gate. `GET /workflows/runs/{run_id}` returns the run row with the resume payload replaced by a small `resume_progress` summary (`gate_step_id`, `completed_step_ids`, or `null`): the payload holds every completed step's full text, and the run-detail page polls this endpoint while a run is unfinished. |\n| `knowledge` | `/knowledge/builtin`, `/external`, `/search` | MBA knowledge base and external sources. `/search` is the introspection parallel of `retriever.retrieve` and mirrors its filters — including the `general` catch-all on the company collection — so the panel cannot report a specialist seeing nothing that it does retrieve in chat. It accepts `general` in `domain_filter` for the same reason. `/search` applies the same review gate as `retrieve()` — withheld (pending or rejected) built-in, external and failure rows are dropped, so the panel never advertises knowledge the Executive cannot use; it degrades to unfiltered rather than failing if review state is unreadable. `POST /knowledge/builtin` refuses a name already held by shipped content, and `POST|DELETE /knowledge/failures` now register and deregister for review — without that a user-authored failure case study had no review row, so no SME decision could block it. |\n| `skills` | `/skills`, `/skills/search`, `/skills/{name}/restore` | Skill registry (the UI's **Playbooks**) CRUD and search. `PUT` on a built-in saves a company customization that shadows it; `DELETE` returns `{name, outcome}` — `deleted`, `reverted` (customization removed, built-in back) or `hidden` (built-in hidden for this company); `restore` un-hides; `GET /skills?include_hidden=true` lists hidden built-ins. List and detail carry `used_by` — `[{name, title, is_custom}]` of the workflows that follow the playbook (switched-off custom ones included) (`WorkflowMeta.playbooks` is the other direction). |\n| `skill_drafts` | `/skill-drafts`, `/skill-drafts/{name}`, `/skill-drafts/{name}/approve` | Review queue for playbook changes the Executive proposed from chat. `GET` lists drafts (`action` create / update / delete, the proposed fields, an `id` version token, `current` — the playbook in effect now — and `followers`, the workflows that follow the name); `approve` (body `{id}`) applies exactly the reviewed version through the ordinary skills operations — 409 and the draft is kept if it was replaced since, on a conflict, or if its playbook vanished; `DELETE ?id=` discards that version only. |\n| `evals` | `/evals/scenarios`, `/evals/runs` | Eval scenarios and run results. |\n| `memories` | `/memories/{decisions,initiatives,advice}`, `GET /memories/people`, `GET /memories/people/{person_id}/conclusions` | Episodic-memory record management, plus the read-only peer-memory overview the Pulse People tab reads (`{status: ok|disabled|error, people: [...], conclusion_total}`; `?recent=` 1–50, default 5) and one person's full conclusion list, paged newest first (`{status, person_id, items, page, size, total, has_more}`; `?page=` ≥1, `?size=` 1–100, default 50; 404 when the person has no peer). |\n| `review` | `/review/items`, `/review/stats`, `/review/trusted-defaults`, `POST /review/curate`, `POST /review/bulk-approve` | Knowledge review queue and annotations. Shipped knowledge registers as a trusted default (`approved` with a NULL `reviewed_at`), so the queue starts empty; `curate` (`{domain, action: start|stop}`, domain required) opts one domain in or out, and `trusted-defaults` returns domain → unreviewed count. `bulk-approve` takes a non-empty `domain`, `item_ids` (max 500) or `all_pending: true`, and 400s with no selector; it returns `{approved_count, item_ids}`. |\n| `onboarding` | `/onboard/interview/start`, `/onboard/interview/message`, `/onboard/interview/draft`, `/onboard/interview/{id}`, `/onboard/interview/commit` | Conversational company setup. The `onboarding_interviewer` agent asks clarifying questions, then emits a draft profile + people + departments. **Nothing is persisted until `POST /onboard/interview/commit`** — the interview itself never writes. `start` is multipart (description + optional deck/one-pager uploads). `commit` answers 403 when the draft would make a different person the owner and the caller is not the current owner (setup demotes the old principal, and any signed-in user can open it). It also takes an optional `owner_email` — the principal's sign-in email, which the review screen pre-fills from the signed-in user — checked before anything is written (422 if it is malformed, already another person's, or would replace the principal's existing email — setup only fills in a missing one) and saved on the principal's People row, so the owner's chats resolve to them from the first turn. |\n| `workflow_designer` | `POST /workflows/designer/start`, `POST /workflows/designer/message`, `POST /workflows/designer/draft`, `GET /workflows/designer/{session_id}` | The conversational New workflow wizard. The `workflow_designer` agent asks clarifying questions (`phase: \"question\"`, with `hint` and up to four suggested `options`), then returns `phase: \"draft\"` with `draft.definition` (exactly the body `POST /workflows/custom` takes), `summary`, and `assumptions`; every response carries the `transcript`. **Nothing is persisted here** — sessions are in memory, and the UI saves through `POST /workflows/custom`. Errors are fixed strings (422 over the 8,000-char message cap or the transcript cap, 404 for an expired session, 409 while another turn on the same session is still running, 502/504 for model failure or timeout). Mounted ahead of the `workflows` router. |\n| `onboarding` (fallback) | `/onboard/start`, `/onboard/answer`, `/onboard/status/{id}` | The original 12-step form wizard, kept as a fallback (UI at `/onboard?mode=form`) and used by the `openexecutive onboard` CLI. |\n| `company-profile` | `GET\\|PATCH /company-profile` | Structured company profile. |\n| `auth` | `GET /auth/allowed-emails` | Non-archived people with an email, offered to the UI's sign-in gate. The gate takes the **union** of this roster and its own `ALLOWED_EMAILS` env list, so env entries always work (and are checked first, short-circuiting the fetch) and roster entries are additive — a roster change can never revoke a configured operator. With local login (`make dev` with Google sign-in not set up — the UI then listens on 127.0.0.1 only) the UI signs in without an email, sends no `x-caller-email`, and the backend resolves the caller to the principal, as it does for the CLI. |\n| `fixtures` | `/fixtures`, `/fixtures/{name}/load` | Demo-company fixture load/reset/snapshot. |\n| `clients` | `/clients`, `/clients/generate`, `/clients/cockpit`, `/clients/save`, `/clients/{slug}/activate` | Client-company slots — multi-client mode for fractional use; create from current/blank/AI-generated intake draft (pasted notes and/or file attachments, multipart on `/clients/generate`), save-back switching, engagement metadata (PATCH), cross-client cockpit, delete. See the Client Companies section. |\n| webhooks | `POST /webhook/telegram`, `POST /webhook/google-chat` | Inbound integration callbacks (self-verified). |\n| MCP server | `POST\\|GET /mcp` | Open Executive exposed as an MCP server (Streamable-HTTP). Not a router — a mounted FastMCP sub-app. Same shared-secret gate (`x-api-key`); exposes company context as resources and the specialist council as tools. See the MCP Server section. |",
+ "markdown": "The FastAPI surface lives in `openexecutive.api.main`, which mounts one router per topic. A shared-secret middleware gates every request via an `x-api-key` header, except `/health` and the `/webhook/*` callbacks (which carry their own verification). With local login (`OE_LOCAL_LOGIN=1`, which only `make dev` sets, and only while Google sign-in is not set up) a second middleware answers 403 to any request whose raw `Host` is not `localhost`, `127.0.0.1` or `[::1]` (except a webhook that verifies its caller: Google Chat always, Telegram only with a `TELEGRAM_WEBHOOK_SECRET` Telegram can send), and to any write whose `Sec-Fetch-Site` is present and not `same-origin`/`none`. The UI signs that owner in with no password and this API usually has no secret, so without it a web page in the owner's browser could drive the API as the principal — by DNS-rebinding its own hostname to 127.0.0.1, or by posting a plain form from another site or localhost port. CORS is restricted to configured UI origins. The gate is off when `BACKEND_SHARED_SECRET` is unset — intended for local development only — so any internet-reachable deployment sets `OE_PUBLIC_DEPLOYMENT`, and `create_app()` then refuses to boot without the secret rather than serving an unauthenticated API.\n\nEndpoints grouped by router:\n\n| Router | Key endpoints | Purpose |\n|---|---|---|\n| `chat` | `POST /chat`, `POST /chat/stop` | SSE stream of a live Executive turn. The request body optionally carries `page_context` (route, page title, guide section id, and a form descriptor with current values) — sent only by the Ask OE side panel so the Executive can explain the current page or propose form values. When the Executive calls its `propose_form_values` tool, the stream emits a `form_patch` event (`{type, form_id, fields, rationale, iteration}`) that the panel applies into the on-screen form as highlighted suggestions; the user reviews and saves through the form's normal submit path. Each round of tool calls also emits an `activity` event (`{type, label, tool, iteration}`) naming what is running — progress only, forwarded verbatim and never persisted with the message, unlike an `action_taken` chip. A `session_id` in the body must be a chat the caller may use (the same ownership rule as `sessions`). If it isn't, the turn runs in a fresh chat instead, so nothing is written into someone else's session and the reply looks the same as for an unknown id. An unknown namespaced id (`slack:…`, `telegram:…` and so on) is ignored and a fresh chat is started, because those ids belong to the channel adapters and claiming one first would make the caller its owner. The client mints a `client_turn_id` and sends it with the turn; `POST /chat/stop` takes that id and halts the turn mid-flight, so the button is live from the moment Send is pressed rather than only once the first SSE byte arrives. A stopped turn emits a `stopped` event and then the usual `done` over the same still-open stream — never an `error` — and whatever streamed so far is persisted and flagged. The endpoint returns 404 both for an unknown id and for another caller's turn, so it cannot be used to probe which turns are live. An optional `memory_text` (1–2000 chars) is what peer memory records as the caller's words instead of `message` — the briefing handoffs send it because their seed quotes the Executive's own card; `POST /chat/upload` derives it from the typed text and filenames. Since it never reaches the transcript, the `chat_turn` audit row keeps it beside `message`. |\n| `sessions` | `GET /sessions`, `GET /sessions/{id}`, `GET /sessions/{id}/messages`, `DELETE /sessions/{id}`, `POST /sessions/{id}/messages/{message_id}/feedback`, `GET /sessions/{id}/followup` | List, read and delete saved chat sessions (assistant messages carry their row `id` and any `feedback`). The list is scoped to the caller. Every per-session route checks ownership, because session ids are guessable (`slack:dm:<user id>`, `telegram:<chat id>`): only the session's owner or the principal gets through, and a legacy row with no owner is the principal's alone. Anyone else gets the same 404 as for an unknown id, so the routes can't be used to find out which chats exist. The one other way in is having started the chat in this process (matched by Person id or verified email, so it survives the caller being added to the roster), which is how a caller the roster can't resolve keeps using their own chat. That record is in memory, so after a restart such an ownerless chat is refused for reads. The principal can continue someone else's ownerless chat without becoming its owner. Deleting a session also drops its in-memory copy, so a later turn naming that id starts fresh. The feedback route records 👍/👎 (`{\"feedback\": \"up\"|\"down\"|null}`) on one assistant reply; only the session's own caller or the principal may rate it. The rater is stored (`feedback_by_person_id`), and a 👎 on a reply to the rater's own message triggers a working-style pass for them (paced; see attunement). The chat stream's `done` event carries `message_id` for the persisted reply. The followup route returns `{\"suggestion\": string|null}` — one suggested next user message, written by the utility-fast model from the last few turns, that the chat composer shows as its greyed placeholder (Tab / → or the inline chip fills it in without sending). It is null unless the session ends on a persisted assistant reply, and null (uncached) when the model fails. Same ownership check as feedback; successful suggestions are cached in-process per (session, reply id). |\n| `today` | `GET /today`, `GET /today/activity`, `GET /today/activity/daily` | Morning-brief aggregation, recent-action rail, and Pulse heartbeat heatmap (per-day activity counts). |\n| `people` | `GET\\|POST\\|PATCH /people`, `POST /people/{id}/archive`, `GET /people/{id}/open-loops`, `POST /open-loops/{loop_id}/close`, `GET /people/{id}/outreach`, `GET\\|PUT\\|DELETE /people/{id}/attunement` | Roster CRUD and scope lookups. Archiving a person closes their open loops. The open-loop routes list what a person owes (soonest due first) and close one (`reason`: done / not_needed / cancelled) — both the principal's or the owner's only (403 otherwise, via `people.store.is_principal_or_self`). `/outreach` returns, per kind of proactive outreach over 30 days, `sent` / `replied` / `acted` / `ignored` / `pending` (voided DMs are excluded) — same access rule, checked before the person lookup so it can't probe which ids exist. `/attunement` reads, replaces (`rules`: up to 4 strings, or omitted to only set `locked`) or resets the person's working-style rules — same access rule, 404 for an archived person; `PUT` rejects a rule that is not purely about style with 422. Archiving a person also drops their working style. |\n| `departments` | `GET\\|POST\\|PATCH\\|DELETE /departments`, `.../goals` | Department state and per-department goals. `PATCH /departments/{slug}` also takes `watched_entities` (≤50 names, `[]` clears) — the entities the research watch policy may add watches for and route to this department. A `cadences` spec that does not parse is rejected with a 422 (empty means no cadence). |\n| `agents` | `GET /agents`, `GET /agents/models`, `GET /agents/models/options`, `PATCH /agents/{id}`, `POST /agents/{id}/test` | Specialist metadata and Council overrides. `/agents/models` is the flat model allowlist the PATCH validator uses; `/agents/models/options` returns the same ids in the same order, each tagged with `provider`, `provider_label`, `route` (`direct` / `openrouter` / `local`) and a display `label`, for the Council's Provider → Model picker. |\n| `personas` | `GET\\|PUT\\|POST\\|DELETE /personas` | Executive persona definitions. |\n| `alerts` | `POST /alerts/{id}/ack`, `POST /alerts/bulk-ack`, `POST /alerts/{id}/reopen`, `POST /alerts/review` | Groom the briefing queue. `ack` (`read`/`ack`/`dismissed`, optional `mute_topic`) also teaches a watch-sourced alert's watch (`trust_score`); `bulk-ack` takes explicit `alert_ids` and/or `older_than_days` + `category` (exempt sources skipped); `reopen` is the Undo for a `resolved` / `expired` / `dismissed` alert (never `ack` or an artifact / decision row; back to `unread` with every review stamp cleared and its TTL anchor refreshed, so it is live again even if older than its TTL); `review` runs the Executive's relevance review on demand (ignores the interval; still honours `ALERT_REVIEW_ENABLED`, the per-pass caps, the single-flight lock and per-alert idempotency) and returns the move counts. `bulk-ack` caps ids at 500, needs `older_than_days >= 1`, and applies watch feedback per row; `mute_topic` must be one of the alert's tags or a scoped `external:` / `department:` pattern. Alerts still surface only through the briefing (`/today` reads the live view) — there is no list, prefs, mutes, or live-stream endpoint. |\n| `artifacts` | `GET /artifacts`, `GET /artifacts/{id}`, `GET /artifacts/{id}/download?as=`, `POST /artifacts/{id}/archive`, `POST /artifacts/{id}/restore`, `DELETE /artifacts/{id}` | Browsable deliverables in any format — Markdown, HTML, Word, Excel, or a link into a connected app — with `format`, `downloads`, `external_url` and `supersedes_id` on every summary. `download` renders the file (Word/Excel built at request time from the stored text; any Markdown artifact, workflow output included, can export `?as=docx`) and is always an attachment with `nosniff` and a sandbox CSP. |\n| `decisions` | `GET /decisions`, `POST /decisions/{id}/{approve,reject,cancel}`, `GET /audit/reliability` | Approval-gated decision instances (e.g. calendar bookings). A proposed booking is surfaced on the briefing as a companion alert; approve/reject/cancel here also clear that alert. Reviewed in the briefing — there is no separate proposals page. |\n| `audit` | `GET /audit/logs`, `GET /audit/logs/{id}`, `GET /audit/sessions/{id}`, `GET /audit/usage`, `POST /audit/log` | Durable audit trail of side effects. `/audit/sessions/{id}` adds a per-session token cost summary; `/audit/usage` aggregates token usage and OpenRouter cost across all sessions (totals, by day, by model, and by source — the part of the system that made the calls — including server-side web-search counts). |\n| `architecture` | `GET /architecture/sections`, `.../sections/{id}` | This documentation surface. |\n| `guide` | `GET /guide/sections`, `.../sections/{id}` | Plain-language user-guide content surface — mirrors `architecture` (static, version-controlled files; no LLM on the serving path). |\n| `health` | `GET /health`, `GET /health/honcho` | Liveness probes (unauthenticated). |\n| `setup_status` | `GET /setup/status` | Settings → Setup status: one light per part of the install — AI model, company setup, owner, the Executive's address, API protection, Gmail, Slack, Discord, Telegram, Google Chat, the scheduler and Honcho — as `{checked_at, checks: [{id, label, state, summary, fix, link, last_activity}]}`, where `state` is `ok`, `warn`, `error` or `off` (optional and not set up), `fix` says what to do in plain language, `link` is an in-app page that helps (`/people`, `/onboard`) and `last_activity` is the channel's latest `integration_inbound` audit time. It tests live, with at most one free read-only call per service, each bounded to 5 s: Anthropic `models.list` (so an organisation key missing `ANTHROPIC_WORKSPACE_ID` shows up), Slack `auth.test`, Telegram `getMe` and `getWebhookInfo`, and Discord `users/@me` only while the bot is still connecting. It also reads the listeners the lifespan leaves on `app.state` (Slack's socket, the Discord bot and its task, the MCP gateway), the scheduler heartbeat and the pause switch. Sample values copied from `.env.example` are named as such without being sent anywhere. No token reaches a response or a log line: probes report a status code, a service's short error code or an exception's class name. Requests within 5 s of a run get that run's answer and concurrent requests share one run (kept per app on `app.state`), so the button can't become a stream of calls to those services. Gated like every other route; the UI adds a sign-in light of its own, from its own settings. |\n| `documents` | `POST\\|GET\\|DELETE /documents`, `GET /documents/{filename}` | Upload, list, view extracted text, and delete indexed company docs. Upload is keyed on the filename, so re-uploading a document replaces its chunks rather than duplicating them, and `DELETE` removes the rows as well as the file. `domain` must be one of the eight specialist domains or `general`; anything else is a 400 rather than a 200 that indexes where no specialist can retrieve. |\n| `executive` | `GET /executive/status`, `POST /executive/pause`, `POST /executive/resume` | Operator pause switch for all autonomous work (scheduler, Gmail poller, workflow resumer); inbound chat and DMs stay live. Status returns `{paused, paused_at, paused_by, reason, held_actions, can_resume}` — `held_actions` counts due `pending` rows that fire on resume. `pause` takes an optional `reason` (≤200 chars) and is idempotent (re-pausing keeps the original start and reason); `paused_by` is the UI proxy's `x-caller-email`, else `api`. Behind the shared-secret middleware — not `SCHEDULED_ADMIN_TOKEN`, which the UI cannot send. Any caller may pause; `resume` is principal-only (`is_principal_or_self`, 403 otherwise; open while no principal is rostered; a header-less caller resolves to the principal as in `chat`), and status carries `can_resume` for the viewer so the UI hides Resume from everyone else. |\n| `scheduled` | `GET\\|DELETE` scheduled actions (`?status=…&order=asc\\|desc`) | Pending and fired scheduled actions; `order` flips the `run_at` sort (asc=soonest-first for the upcoming queue, desc=most-recent-first for terminal-status history). `DELETE /scheduled/{id}` cancels a `pending` row (409 otherwise). Like pause it only stops work, so any signed-in user may — the UI proxy's `x-caller-email` is trusted when the request also carries the `BACKEND_SHARED_SECRET` `x-api-key` — as may a matching `X-Admin-Token` (`SCHEDULED_ADMIN_TOKEN`) or a loopback caller with no token set; otherwise 401 (token set) or 503. Audited as `scheduled_action_cancelled`. |\n| `watchlist` | `GET\\|POST\\|PATCH\\|DELETE /watchlist`, `POST /watchlist/{slug}/approve`, `POST /watchlist/{slug}/decline` | External-monitoring watchlist + signals. Rows carry `origin` (`manual` \\| `executive` \\| `research` \\| `research_proposed`); `approve` turns a research suggestion (`research_proposed`, `dry_run`) into a live watch, `decline` `{reason: not_relevant \\| too_noisy \\| wrong_source}` removes it and records the decline (or, for `too_noisy`, keeps it live at a high floor), both 409 unless the row is a pending suggestion; `DELETE ?reason=` on a research-origin row records the decline too. |\n| `workflows` | `GET /workflows`, `POST /workflows/{name}/runs`, `GET\\|POST\\|PUT\\|DELETE /workflows/custom`, `GET\\|DELETE /workflows/custom/{name}/targets`, `POST /workflows/runs/{run_id}/decision`, `GET /workflows/tools/search?q=`, `GET /workflows/tools/describe?names=` | Workflow catalog, run management, and user-created (dynamic) workflow CRUD. Custom definitions come back with a server-managed `owner_person_id` (the creator — the web caller on `POST`, set on insert only; a client-sent value is ignored), who is asked to approve a workflow's first write to a new target. `GET /workflows/custom/{name}/targets` lists the targets its tool steps may write to without asking and `DELETE …/targets?value=` forgets one. `POST /workflows/runs/{run_id}/decision` with `{decision: \"approve\"|\"reject\"}` answers a run awaiting a yes/no sign-off from the web app — 403 unless the caller is the person it waits on or the principal, 409 if it isn't awaiting or needs a written reply — through the same `apply_resolution` a chat reply uses. Custom create/update also rejects (422) any action-step tool that does not resolve, and so does `POST /workflows/custom/{name}/activate` when turning a workflow **on** — that click is the approval for a tool workflow chat saved switched off (turning off is never checked). Turning on a workflow with action steps requires the body `{is_active: true, definition}` carrying the definition the user reviewed; if the stored one differs (ignoring `is_active` and timestamps) it returns 409, and the switch itself is a compare-and-set on the validated revision (`dynamic_store.activate_if_unchanged`, keyed on `updated_at`), so a save that lands while the tool check awaits the gateway — even from another process — is a 409 too, so only what was shown gets switched on. `GET /workflows/custom` lists inactive definitions too; `GET /workflows/{name}` 404s for them. The two `tools` endpoints return `{tools: [{name, description, read_only, source}]}` for the advanced editor's tool picker and the review card; `read_only` is true only when the name says it reads (a label, not a control). The run stream adds a `progress` event (`step_id`, `summary`) while an action step uses tools. Each catalog entry (`WorkflowMeta`) carries `is_custom` and `background` (true for the system-run built-ins the UI files under “System”). The run endpoint streams SSE; its `awaiting_human` event carries `delivery` (`self` \\| `sent` \\| `suppressed` \\| `alerted` \\| `failed`) alongside `person_id` / `question` / `awaiting_until`, because the outbound guard or an unreachable approver means the question may never have been asked — a client must not render “waiting on them” for those. A paused run ends the stream with neither `done` nor `error`, so that `awaiting_human` frame carries `terminal: true` to say so explicitly, plus `resumable` — whether the run continues by itself once answered or stops at the gate. `GET /workflows/runs/{run_id}` returns the run row with the resume payload replaced by a small `resume_progress` summary (`gate_step_id`, `completed_step_ids`, or `null`): the payload holds every completed step's full text, and the run-detail page polls this endpoint while a run is unfinished. |\n| `knowledge` | `/knowledge/builtin`, `/external`, `/search` | MBA knowledge base and external sources. `/search` is the introspection parallel of `retriever.retrieve` and mirrors its filters — including the `general` catch-all on the company collection — so the panel cannot report a specialist seeing nothing that it does retrieve in chat. It accepts `general` in `domain_filter` for the same reason. `/search` applies the same review gate as `retrieve()` — withheld (pending or rejected) built-in, external and failure rows are dropped, so the panel never advertises knowledge the Executive cannot use; it degrades to unfiltered rather than failing if review state is unreadable. `POST /knowledge/builtin` refuses a name already held by shipped content, and `POST|DELETE /knowledge/failures` now register and deregister for review — without that a user-authored failure case study had no review row, so no SME decision could block it. |\n| `skills` | `/skills`, `/skills/search`, `/skills/{name}/restore` | Skill registry (the UI's **Playbooks**) CRUD and search. `PUT` on a built-in saves a company customization that shadows it; `DELETE` returns `{name, outcome}` — `deleted`, `reverted` (customization removed, built-in back) or `hidden` (built-in hidden for this company); `restore` un-hides; `GET /skills?include_hidden=true` lists hidden built-ins. List and detail carry `used_by` — `[{name, title, is_custom}]` of the workflows that follow the playbook (switched-off custom ones included) (`WorkflowMeta.playbooks` is the other direction). |\n| `skill_drafts` | `/skill-drafts`, `/skill-drafts/{name}`, `/skill-drafts/{name}/approve` | Review queue for playbook changes the Executive proposed from chat. `GET` lists drafts (`action` create / update / delete, the proposed fields, an `id` version token, `current` — the playbook in effect now — and `followers`, the workflows that follow the name); `approve` (body `{id}`) applies exactly the reviewed version through the ordinary skills operations — 409 and the draft is kept if it was replaced since, on a conflict, or if its playbook vanished; `DELETE ?id=` discards that version only. |\n| `evals` | `/evals/scenarios`, `/evals/runs` | Eval scenarios and run results. |\n| `memories` | `/memories/{decisions,initiatives,advice}`, `GET /memories/people`, `GET /memories/people/{person_id}/conclusions` | Episodic-memory record management, plus the read-only peer-memory overview the Pulse People tab reads (`{status: ok|disabled|error, people: [...], conclusion_total}`; `?recent=` 1–50, default 5) and one person's full conclusion list, paged newest first (`{status, person_id, items, page, size, total, has_more}`; `?page=` ≥1, `?size=` 1–100, default 50; 404 when the person has no peer). |\n| `review` | `/review/items`, `/review/stats`, `/review/trusted-defaults`, `POST /review/curate`, `POST /review/bulk-approve` | Knowledge review queue and annotations. Shipped knowledge registers as a trusted default (`approved` with a NULL `reviewed_at`), so the queue starts empty; `curate` (`{domain, action: start|stop}`, domain required) opts one domain in or out, and `trusted-defaults` returns domain → unreviewed count. `bulk-approve` takes a non-empty `domain`, `item_ids` (max 500) or `all_pending: true`, and 400s with no selector; it returns `{approved_count, item_ids}`. |\n| `onboarding` | `/onboard/interview/start`, `/onboard/interview/message`, `/onboard/interview/draft`, `/onboard/interview/{id}`, `/onboard/interview/commit` | Conversational company setup. The `onboarding_interviewer` agent asks clarifying questions, then emits a draft profile + people + departments. **Nothing is persisted until `POST /onboard/interview/commit`** — the interview itself never writes. `start` is multipart (description + optional deck/one-pager uploads). `commit` answers 403 when the draft would make a different person the owner and the caller is not the current owner (setup demotes the old principal, and any signed-in user can open it). It also takes an optional `owner_email` — the principal's sign-in email, which the review screen pre-fills from the signed-in user — checked before anything is written (422 if it is malformed, already another person's, or would replace the principal's existing email — setup only fills in a missing one) and saved on the principal's People row, so the owner's chats resolve to them from the first turn. |\n| `workflow_designer` | `POST /workflows/designer/start`, `POST /workflows/designer/message`, `POST /workflows/designer/draft`, `GET /workflows/designer/{session_id}` | The conversational New workflow wizard. The `workflow_designer` agent asks clarifying questions (`phase: \"question\"`, with `hint` and up to four suggested `options`), then returns `phase: \"draft\"` with `draft.definition` (exactly the body `POST /workflows/custom` takes), `summary`, and `assumptions`; every response carries the `transcript`. **Nothing is persisted here** — sessions are in memory, and the UI saves through `POST /workflows/custom`. Errors are fixed strings (422 over the 8,000-char message cap or the transcript cap, 404 for an expired session, 409 while another turn on the same session is still running, 502/504 for model failure or timeout). Mounted ahead of the `workflows` router. |\n| `onboarding` (fallback) | `/onboard/start`, `/onboard/answer`, `/onboard/status/{id}` | The original 12-step form wizard, kept as a fallback (UI at `/onboard?mode=form`) and used by the `openexecutive onboard` CLI. |\n| `company-profile` | `GET\\|PATCH /company-profile` | Structured company profile. |\n| `auth` | `GET /auth/allowed-emails` | Non-archived people with an email, offered to the UI's sign-in gate. The gate takes the **union** of this roster and its own `ALLOWED_EMAILS` env list, so env entries always work (and are checked first, short-circuiting the fetch) and roster entries are additive — a roster change can never revoke a configured operator. With local login (`make dev` with Google sign-in not set up — the UI then listens on 127.0.0.1 only) the UI signs in without an email, sends no `x-caller-email`, and the backend resolves the caller to the principal, as it does for the CLI. |\n| `fixtures` | `/fixtures`, `/fixtures/{name}/load` | Demo-company fixture load/reset/snapshot. |\n| `clients` | `/clients`, `/clients/generate`, `/clients/cockpit`, `/clients/save`, `/clients/{slug}/activate` | Client-company slots — multi-client mode for fractional use; create from current/blank/AI-generated intake draft (pasted notes and/or file attachments, multipart on `/clients/generate`), save-back switching, engagement metadata (PATCH), cross-client cockpit, delete. See the Client Companies section. |\n| webhooks | `POST /webhook/telegram`, `POST /webhook/google-chat` | Inbound integration callbacks (self-verified). |\n| MCP server | `POST\\|GET /mcp` | Open Executive exposed as an MCP server (Streamable-HTTP). Not a router — a mounted FastMCP sub-app. Same shared-secret gate (`x-api-key`); exposes company context as resources and the specialist council as tools. See the MCP Server section. |",
"mermaid": null,
- "generated_at": "2026-09-25T01:22:23.080573+00:00"
+ "generated_at": "2026-09-25T12:22:48.458924+00:00"
}
diff --git a/packages/core/openexecutive/architecture/prebuilt/integrations.json b/packages/core/openexecutive/architecture/prebuilt/integrations.json
index 35d1d15d..c39b5967 100644
--- a/packages/core/openexecutive/architecture/prebuilt/integrations.json
+++ b/packages/core/openexecutive/architecture/prebuilt/integrations.json
@@ -1,7 +1,7 @@
{
"section_id": "integrations",
"title": "Integrations",
- "markdown": "External channels connect callers to the Executive. Each inbound adapter resolves the sender to a Person via `find_person_by_{slack,discord,telegram,email}_id` and threads `person_id` into `Executive.chat()`.\n\n### Inbound channels\n\n- **Slack** (`integrations.slack_bot`) — async Bolt socket-mode (`AsyncApp` + `AsyncSocketModeHandler`) embedded in the lifespan; responds to `@mention`s, DMs, and thread continuations, with per-conversation session memory (see **Conversation state** below). Text only: there is no interactivity endpoint and no Block Kit, so nothing Slack sends carries a button.\n- **Discord** (`integrations.discord_bot`) — discord.py gateway embedded in the lifespan; per-thread auto-titling, session-scoped memory, author attribution, configurable `@mention` thread promotion.\n- **Telegram** — webhook gating + per-chat history.\n- **Google Chat** — webhook + service-account auth. It resolves no approval gates and has no roster gate (the webhook authenticates Google, not the sender), and it never populates the session's trusted alert ids, so `ack_alert`'s trust check — which now runs on every session rather than only those declaring an `origin_channel` — refuses there by default, and its `<channel>` block says plainly that a sign-off cannot be answered from it.\n- **Email** (`integrations.email_poller`) — Gmail poll loop over the Google Workspace MCP (it starts only once the MCP gateway is up); strips Reply-To, filters auto-replies. While the Executive is paused (`scheduler.pause`) it skips each poll and leaves the inbox unread, so held mail is processed on the first poll after resume; the chat adapters above are not paused. The Executive sees the whole message; peer memory records only `_email_memory_text` — the subject, the sender's new text (cut at the first quoted or forwarded message) and the attachment filenames — parsed without backtracking-prone regexes, since the text is sender-controlled, and only for a rostered sender, the only kind with a peer to record into.\n\nSlack, Discord, and Telegram are roster-gated on inbound: an unrostered sender's message is silently dropped (`details.outcome=\"rejected_unknown_sender\"`). Email is not inbound-gated — non-roster mail flows through with a `[POLICY]` notice so triage can classify it. Slack/Discord thread continuations pass the shared `integrations.response_gate` (utility-fast model, biased toward replying).\n\n### Conversation state\n\nEvery adapter keys a deterministic `session_id` off the conversation surface and replays that session's stored turns into `Session.conversation_history`, so a follow-up (\"yes, go ahead\") lands with the question still in context. Slack's ids are `slack:dm:{user}`, `slack:thread:{channel}:{thread_ts}`, and `slack:channel:{channel}:{user}` for a mention that starts a thread; because the bot's reply roots a Slack thread at that message's `ts`, the turn is double-written to that thread's session too, so the first continuation inside it is not cold. A reply inside a thread THAT PERSON ROOTED also offers the parent `slack:channel:{channel}:{user}` id when matching an approval gate, since a gate raised on the mention recorded that session while the answer arrives under the thread's. The root-author check is load-bearing: widening on \"threaded and not a DM\" alone offered one person's channel session inside any thread in that channel, so a remark they made to a colleague could resolve their open gate and post the run's title into that colleague's thread. Discord has the same shape — its auto-thread router promotes a mention reply into a bot-owned thread — and the same alias. An @-mention inside a DM is handled once, by the DM path: Slack fires both events, and taking both forked the conversation across two session ids. The same id is the audit grouping key and the scope passed to `format_for_prompt`. A per-session `asyncio.Lock` serializes turns within one conversation — the inflight semaphore caps fan-out across the workspace, which does nothing to stop two messages in the same thread from both reading history before either writes it. Persistence happens after the reply is sent and its failure is logged, never surfaced: the user already has their answer.\n\nThis was absent on Slack until #136. Every message built a fresh `Session` and minted a per-*message* id (`thread_ts` falls back to the message's own `ts`, so a DM never repeated one), which meant a multi-turn confirmation could not work: the Executive asked whether to send a briefing to Slack, the user said yes, and the next turn had no record of the question.\n\n### What the model is told about the channel\n\nChat adapters pass a `<channel>` block (`integrations.channel_context`) in the **user turn** — never a cached system block. It names the surface, states that the person cannot see the app's cards or buttons, and draws the line the assistant kept crossing: briefing proposals and alerts are actioned on the briefing page; a proposal that books something can only be approved there; a workflow sign-off the Executive is explicitly waiting on *can* be answered in the conversation. The principal's DMs on Slack, Discord and Telegram also receive the open-alert digest (`briefing.context.format_open_alerts_for_prompt`) as the `<briefing>` block, gated to DMs because the board is company-wide and a shared channel must not pull it in. That digest is the ONLY trusted source of an `alert_id` for `ack_alert`. The briefing page's `[Discuss mode — alert_id=N]` primer is a pointer to which item is under discussion, not authority on its own: the server accepts that id only if it is also on the live board it derived itself. An id appearing anywhere else, including inside an alert's own body, is not trusted: alerts are minted from inbound email and chat, so their bodies are attacker-controlled. Two mechanisms enforce that rather than one prompt rule. Every field the digest interpolates is collapsed to a single line, because a newline in an attacker-written headline, suggested action, tag or review note would otherwise forge a whole extra `[N]` line — a fabricated instruction to clear somebody else's alert. And the live board the server derived is recorded on the session, so `ack_alert` refuses any id outside it — on EVERY session, web included; the web previously had no check at all. The recorded set is the whole live board (the cap `/today` renders as cards), not just the rows the digest printed, so a card past the digest's 30-row render cap is still ackable rather than sending the principal back to the page. Be precise about what this buys: it stops an id that is invented, closed, snoozed or expired, including one quoted out of an attacker-written alert body. It does NOT stop the model being argued into acking the wrong LIVE card — one alert's body can still make a case about another id that is genuinely open. Scoping trust to the single item under discussion would need the primer id carried server-side, which it is not.\n\n### Handler failures\n\nAn adapter's catch-all replies \"I encountered an error processing your request.\" On Slack that used to be the whole story — one uncorrelated log line, no audit row, and an unguarded error-send that could itself escape into Bolt. It now logs with the session, sender, channel, thread and mode, and writes an `integration_inbound` row with `details.outcome=\"handler_error\"`, joining the inbound row under the same `session_id`. Upstream, a single crashing tool handler no longer takes the turn down at all: the orchestrator's tool gathers use `return_exceptions=True`, hand the model an error `tool_result`, and audit it with `ok=false` (cancellation is re-raised, not swallowed).\n\n### Attachments\n\n`integrations.attachments` handles web chat, Discord, and Telegram. Images become Anthropic vision blocks; documents (PDF/DOCX/TXT/MD/CSV) are inlined into the turn that carried them and indexed into the ChromaDB `inbound_attachments` collection. 20 MB/file cap; web chat uses `POST /chat/upload`.\n\nIndexed chunks are keyed on `attachment:<bare filename>` and tagged `type=attachment`. An attachment's name is chosen by whoever sent the message and the name is the chunk-id namespace, so without the prefix an inbound `strategy-2026.md` would upsert over the curated company document of that name. The prefix separates inbound content from curated uploads and keeps provenance visible; it does not separate senders from one another.\n\nIsolation is the **collection**: `retriever.retrieve` never queries `inbound_attachments` at all, so an attachment cannot resurface as company knowledge in a later, unrelated turn. Attachment processing is roster-gated on Discord too — it previously ran before the gate, so an unrostered sender's file was downloaded and indexed before their message was dropped. These rows still have no operator surface: they are never written to `company/docs/`, so `GET /documents` does not list them.\n\nThis replaced a domain-based scheme that did not work. The chunks lived in `company_docs` under a domain outside the specialist set, on the premise that an unrecognised domain matched no filter. It matched every one — `ChromaDBStore.query` attaches a `where` clause only when a domain filter is present, and an Executive-level retrieval passes none — so attachments came back under “From your company documents”, top-ranked and indistinguishable from a curated upload. Legacy rows are migrated across on boot.\n\n### MCP gateway & outbound\n\nMCP runs in **both directions**. As a *client*, `orchestrator.mcp_gateway.MCPGateway` proxies MCP servers (Gmail, Calendar, Drive — whatever `mcp_servers.json` configures) as Executive tools, with egress gating on Gmail recipients, Calendar attendees, and Drive share grantees against the roster (and a refusal of public / whole-domain Drive sharing). The Google Workspace server (`workspace-mcp`) behind those Gmail/Calendar/Drive tools runs **co-located inside the API** as a stdio child of the gateway — fitting the single-tenant model (one install = one company = one exec Google account), so there's no separate service to operate. It's baked into the API image and launched by `docker/workspace-mcp-launch.sh`, which selects single-user OAuth (token persisted at `/data/google_credentials`) or service-account domain-wide delegation from `GWORKSPACE_AUTH_MODE`. The gateway forwards the Google secrets to the child via `_FORWARDED_ENV_VARS`. As a *server*, `openexecutive.mcp_server` exposes OE's own company context and specialist council to external MCP clients at `/mcp` — the inverse direction; see the dedicated **MCP Server** section. The gateway launches extensible-mcp as a `uvx` subprocess whose fastembed tool-search index uses an embedding model baked into the API image and loaded offline, so it no longer re-downloads that model from the Hugging Face Hub on every cold start. extensible-mcp is pinned twice over: to a commit, which fixes its own code, and with `--exclude-newer`, which fixes the resolution of its dependencies — without the cutoff uvx re-resolves them against PyPI on every networked start, so a new release of any of them would reach running deployments on restart. Both live in `_EXTENSIBLE_MCP_LAUNCH_ARGS` in `orchestrator/mcp_gateway.py`, the Dockerfile's pre-warm uses the same arguments (a unit test enforces the match), so an image whose pre-warm succeeded starts the gateway with no network. The pre-warm is best-effort (`|| true`): an image built while GitHub was unreachable fetches the pinned commit on its first start instead. Updating the gateway is a deliberate bump of the commit and cutoff; `uv` itself is not pinned. Because the MCP stdio client does not inherit the parent environment, `MCPGateway.start()` explicitly forwards the embedding-cache/offline env vars (`FASTEMBED_CACHE_PATH`, `HF_HUB_OFFLINE`, …) into the child.\n\n**Emailing an artifact.** A Gmail send or draft may carry `attachments=[{\"artifact_id\": \"alert:12\", \"as\"?: \"docx\"}]`. `call_tool` runs the recipient gate first; only if it passes does `_expand_artifact_attachments` replace each such entry with the rendered file (`content` base64 + `filename` + `mime_type`, workspace-mcp's own attachment shape), produced by `artifact_records.render_artifact_file` — the same renderer as `/artifacts/{id}/download`. Only artifact rows resolve (never an arbitrary alert), links have no file, and an entry mixing `artifact_id` with other keys is refused. A stringified or single-object `attachments` is normalised first, so an artifact entry can never reach workspace-mcp unexpanded (it would silently drop it). At most 5 distinct artifacts per email (repeats are dropped) and 15 MB rendered in total; rendering runs off the event loop via `asyncio.to_thread`. A refusal writes `artifact_attachment_refused`; a successful send writes `artifact_attached` — both carry the recipients. Other attachment entries pass through unchanged.\n\n**Enablement, and why it degrades instead of dying.** `MCP_ENABLED` left unset is inferred from the presence of `mcp_servers_config_path` — dropping an `mcp_servers.json` next to `profile.yaml` turns MCP on with no further configuration. An **explicit** setting always wins in both directions: `MCP_ENABLED=false` keeps MCP off with the file still in place. It did not: `_resolve_mcp` tested `not self.mcp_enabled`, which cannot tell \"never set\" from \"set to false\", so the file's presence silently overrode the operator. The file is probed through `config.mcp_config_file_present`, never `Path.exists` directly — that re-raises an EACCES on a parent directory, and from inside a validator that comes out of `Settings()` itself, which `api/main.py` calls at module level. The check now reads `model_fields_set` (the fields the env actually supplied) and stores that on a private attr behind the read-only `mcp_auto_enabled` property, because the validator's own assignment joins that set and would otherwise make every auto-enable look explicit downstream.\n\nStartup is **best-effort**, in `main._start_mcp_gateway`. Two checks come before the subprocess: MCP off is a no-op, and a config defining no servers under `mcpServers` is logged and skipped — extensible-mcp's own loader raises on that and exits, and because the child is already gone the only thing that surfaces is anyio's \"Attempted to exit cancel scope in a different task\" from `stdio_client` unwinding, a traceback naming nothing about configuration. The start is also bounded (120s, generous because that child may still clone extensible-mcp on a cold start if the image's pre-warm failed): `ClientSession` carries no `read_timeout_seconds`, so `initialize()` waits forever on a child that is *alive but silent*, and an unbounded wait is a lifespan that never yields — the same healthcheck-never-passes symptom, which no `except` can see. A gateway that fails anyway is logged at ERROR with the config path, the servers it named, and whether the config file or an explicit `MCP_ENABLED` turned MCP on, then torn down under its own timeout; the API boots **without MCP tools and without the email poller** rather than refusing to boot. The guard catches `BaseException`, not `Exception`, re-raising a bare `CancelledError` first: the original failure came from anyio, which wraps a task group's failures in `BaseExceptionGroup` as soon as one is a `BaseException` — and that group is not an `Exception`, so `except Exception` would miss the very shape this contains. The teardown is contained too, since it runs from inside that `except` and would otherwise replace the actionable log with the crash it prevents. `configured_server_names` never raises either, and deliberately catches broadly: it reads an operator-owned path during startup, where an exception is the crash loop rather than a bug report — `Path.is_file` re-raises an EACCES on a parent directory, and `json.loads` answers deeply-nested input with `RecursionError`, which is not a `ValueError`. It tests `is_file()` so a directory or a symlink to a FIFO is never opened, and caps the read at 1 MiB. That exception used to propagate out of the lifespan and kill the container — under `restart: unless-stopped`, a crash loop whose only outward symptom was a healthcheck that never passed. Outbound tools: per-Person DMs (`send_slack_dm`, `send_discord_dm`, `send_telegram_message`) plus room-targeted `send_department_message` and `send_company_broadcast`. The per-Person DMs are additionally rate-limited and de-duplicated by the outbound anti-spam guard (below).\n\n### Outbound anti-spam guard\n\nEvery per-Person DM passes a deterministic guard (`orchestrator.outbound_guard.check_outbound_allowed`) after the roster gate and recipient-id recovery but before the network send — the single chokepoint **all** proactive DM paths reach (ad-hoc chat sends, the scheduler's followup/nudge dispatch, principal-brief delivery, the reflection turn, and research-finding routing). On a violation it returns a human-readable reason and the handler **suppresses** the send (`{\"status\":\"suppressed\",\"reason\":…}`), writes a `tool_invocation` audit row with `suppressed=true`, and writes **no** `done` activity row — so a blocked attempt never counts toward its own rate cap, and the Executive can read the reason and hold or `schedule_followup` for the recipient's next window. Three controls: **content dedup** (a near-identical message — whitespace/case-normalized, first 160 chars — already sent to the same recipient within `OUTBOUND_DEDUP_WINDOW_MINUTES`, default 360); a **per-recipient rate cap** (`OUTBOUND_MAX_PER_RECIPIENT_PER_WINDOW`, default 5, over `OUTBOUND_RATE_WINDOW_MINUTES`, default 60); and **quiet hours / availability** (`OUTBOUND_RESPECT_QUIET_HOURS`, default on — refuse while the recipient is on leave or outside their `people.channel` availability windows, surfacing the next open window). Delivery history is read from the existing `status='done'` `scheduled_actions` rows (`episodic.recent_sends_for_channel_ref`), so there is no new table. The guard is **fail-open**: any internal lookup error returns \"allow\", so it can never turn a working send into a crash or a silently-dropped message. Principal briefs and the internal heartbeat kinds use the `__internal__` channel and never reach these handlers, so they are unaffected.\n\n### Calendar & Google Meet\n\nThe Executive books meetings through two typed tools over the Calendar MCP. `create_calendar_event` schedules a **future** meeting (propose→approve by default, or auto-execute once that decision class is promoted) and may be used proactively when a stalled goal warrants a sync. `create_instant_meeting` spins up an **impromptu call starting now**, auto-executing without the approval step and skipping the business-hours/horizon caps, so the Executive can hand back a join link immediately. Both attach a **Google Meet** link by default (`add_google_meet`; opt out for in-person), parsed from the created event's `conferenceData` and surfaced to the caller plus persisted on the decision ledger. Either way the caps that matter still hold — roster membership, principal-protection, max attendees, and a daily booking ceiling.\n\n**Around-the-meeting participation.** The Executive doesn't join the call as a live voice; instead, on every successful booking it schedules a best-effort post-meeting follow-up (~5 min after the end) that DMs a human attendee asking for a quick recap — key decisions and action items. The reply flows back through the same cross-session DM context linkage described below, so the Executive can act on it (summarize, follow up) in a later turn. No meeting-transcript or Drive integration is required.\n\n### Cross-session DM context\n\nWhen the principal says \"DM Alex about X\" in one session, OE sends the DM and — if a live conversation is active — records an `outbound_context` linkage row (recipient, full outbound text, originating session id). Email is covered too but recorded one layer deeper — there is no `send_email` tool, so the linkage is written in `orchestrator.mcp_gateway` after a successful `google_workspace__send_gmail_message`, one row per `to`/`cc` recipient keyed by the bare lowercased address (OE's own address skipped). When Alex later replies on the 1:1 DM path — or by email — the shared helper `integrations.inbound_hydration.hydrate_user_message` (called by the Discord, Telegram, and Slack handlers, and by the email poller keyed on the sender address) looks up the most-recent `open` linkage for that sender within 72h and prepends an `<outbound_reply_context>` block — the outbound text plus a backstory excerpt from the originating session — to the message handed to `Executive.chat()`. So OE knows what the reply is about instead of starting from an empty per-person session. The block is context for the LLM turn only: peer memory strips it before recording what the person said (`strip_outbound_reply_context`, applied in `sync_turn`, `sync_department_turn` and to the prefetch query), so the Executive's own DM is never attributed to the person who replied to it. The block lands in the user turn (caching rule) and is injected into a copy only — the pristine reply is persisted to history. The linkage is one-shot (consumed on first matched reply, race-safe) so an unrelated later DM isn't re-hydrated. This is deterministic and independent of the per-person `peer_memory` (Honcho) layer.\n\nEvery adapter that persists a turn (Slack, Discord, Telegram, and the web route) records the message's **resolved sender** on `chat_messages.sender_person_id` — the rostered Person the adapter matched, or NULL for an unrostered sender — independently of the session owner, which falls back to the principal on Discord and Telegram so those threads stay visible. Attunement's open loops and feedback rely on this so an outsider's words are never read as someone on the roster's.",
+ "markdown": "External channels connect callers to the Executive. Each inbound adapter resolves the sender to a Person via `find_person_by_{slack,discord,telegram,email}_id` and threads `person_id` into `Executive.chat()`.\n\n### Inbound channels\n\n- **Slack** (`integrations.slack_bot`) — async Bolt socket-mode (`AsyncApp` + `AsyncSocketModeHandler`) embedded in the lifespan; responds to `@mention`s, DMs, and thread continuations, with per-conversation session memory (see **Conversation state** below). Text only: there is no interactivity endpoint and no Block Kit, so nothing Slack sends carries a button.\n- **Discord** (`integrations.discord_bot`) — discord.py gateway embedded in the lifespan; per-thread auto-titling, session-scoped memory, author attribution, configurable `@mention` thread promotion.\n- **Telegram** — webhook gating + per-chat history.\n- **Google Chat** — webhook + service-account auth. It resolves no approval gates and has no roster gate (the webhook authenticates Google, not the sender), and it never populates the session's trusted alert ids, so `ack_alert`'s trust check — which now runs on every session rather than only those declaring an `origin_channel` — refuses there by default, and its `<channel>` block says plainly that a sign-off cannot be answered from it.\n- **Email** (`integrations.email_poller`) — Gmail poll loop over the Google Workspace MCP (it starts only once the MCP gateway is up); strips Reply-To, filters auto-replies. While the Executive is paused (`scheduler.pause`) it skips each poll and leaves the inbox unread, so held mail is processed on the first poll after resume; the chat adapters above are not paused. The Executive sees the whole message; peer memory records only `_email_memory_text` — the subject, the sender's new text (cut at the first quoted or forwarded message) and the attachment filenames — parsed without backtracking-prone regexes, since the text is sender-controlled, and only for a rostered sender, the only kind with a peer to record into.\n\nSlack, Discord, and Telegram are roster-gated on inbound: an unrostered sender's message is silently dropped (`details.outcome=\"rejected_unknown_sender\"`). Email is not inbound-gated — non-roster mail flows through with a `[POLICY]` notice so triage can classify it. Slack/Discord thread continuations pass the shared `integrations.response_gate` (utility-fast model, biased toward replying).\n\n### Checking a channel is set up\n\nSettings → Setup status (`GET /setup/status`, `api/setup_checks.py`) gives each channel a light and a plain-language fix. It tests the credentials with one free read-only call — Slack `auth.test`; Telegram `getMe`, then `getWebhookInfo` (is a webhook registered, is it this app's `/webhook/telegram`, did a delivery fail in the past day); Discord `users/@me`, only while the bot is still connecting — and reads what the lifespan left on `app.state`: the Slack socket's `is_connected()`, the Discord bot's `is_ready()` together with its gateway socket being open (discord.py stays ready while it reconnects after a drop), or the exception its task stopped with (`LoginFailure`, `PrivilegedIntentsRequired`), and the MCP gateway. Because inbound is roster-gated, a connected Slack, Discord or Telegram is amber while nobody on the roster has its id (`slack_user_id`, `discord_user_id`, `telegram_chat_id`), or when its latest `integration_inbound` row is a `Rejected: …` from the past day whose sender still isn't on the roster — the page shows the sender's id, never message text. Local login with no `TELEGRAM_WEBHOOK_SECRET` is red for Telegram, since the local-login gate turns its webhook away. Google Chat and Gmail are checked from configuration: a numeric project number and a readable service-account key; the OAuth client (or service-account key) the workspace-mcp child signs in with.\n\nA channel setting written `KEY= # note` in a `.env` file arrives as the note's text, because python-dotenv strips only a comment that follows a value. `Settings` reads such a value as unset for the Slack, Telegram, Discord and Google Chat credentials, so the line no longer switches a channel on with its own comment as the token. `TELEGRAM_WEBHOOK_SECRET` is the exception, because read as unset a junk secret would turn the webhook's check off. It is kept instead, and since Telegram can only ever send 1–256 of `A-Z a-z 0-9 _ -` (what `setWebhook` accepts), a secret outside that set — a leftover comment, a pasted `<value from Step 2>` — could only be matched by someone who guessed it: while it is set the webhook refuses every update, neither the local-login gate nor the roster tools count it as proof (`Settings.telegram_webhook_secret_valid`), and Setup status shows it red (`.env.example` shipped four such lines; the notes now sit on their own lines).\n\n### Conversation state\n\nEvery adapter keys a deterministic `session_id` off the conversation surface and replays that session's stored turns into `Session.conversation_history`, so a follow-up (\"yes, go ahead\") lands with the question still in context. Slack's ids are `slack:dm:{user}`, `slack:thread:{channel}:{thread_ts}`, and `slack:channel:{channel}:{user}` for a mention that starts a thread; because the bot's reply roots a Slack thread at that message's `ts`, the turn is double-written to that thread's session too, so the first continuation inside it is not cold. A reply inside a thread THAT PERSON ROOTED also offers the parent `slack:channel:{channel}:{user}` id when matching an approval gate, since a gate raised on the mention recorded that session while the answer arrives under the thread's. The root-author check is load-bearing: widening on \"threaded and not a DM\" alone offered one person's channel session inside any thread in that channel, so a remark they made to a colleague could resolve their open gate and post the run's title into that colleague's thread. Discord has the same shape — its auto-thread router promotes a mention reply into a bot-owned thread — and the same alias. An @-mention inside a DM is handled once, by the DM path: Slack fires both events, and taking both forked the conversation across two session ids. The same id is the audit grouping key and the scope passed to `format_for_prompt`. A per-session `asyncio.Lock` serializes turns within one conversation — the inflight semaphore caps fan-out across the workspace, which does nothing to stop two messages in the same thread from both reading history before either writes it. Persistence happens after the reply is sent and its failure is logged, never surfaced: the user already has their answer.\n\nThis was absent on Slack until #136. Every message built a fresh `Session` and minted a per-*message* id (`thread_ts` falls back to the message's own `ts`, so a DM never repeated one), which meant a multi-turn confirmation could not work: the Executive asked whether to send a briefing to Slack, the user said yes, and the next turn had no record of the question.\n\n### What the model is told about the channel\n\nChat adapters pass a `<channel>` block (`integrations.channel_context`) in the **user turn** — never a cached system block. It names the surface, states that the person cannot see the app's cards or buttons, and draws the line the assistant kept crossing: briefing proposals and alerts are actioned on the briefing page; a proposal that books something can only be approved there; a workflow sign-off the Executive is explicitly waiting on *can* be answered in the conversation. The principal's DMs on Slack, Discord and Telegram also receive the open-alert digest (`briefing.context.format_open_alerts_for_prompt`) as the `<briefing>` block, gated to DMs because the board is company-wide and a shared channel must not pull it in. That digest is the ONLY trusted source of an `alert_id` for `ack_alert`. The briefing page's `[Discuss mode — alert_id=N]` primer is a pointer to which item is under discussion, not authority on its own: the server accepts that id only if it is also on the live board it derived itself. An id appearing anywhere else, including inside an alert's own body, is not trusted: alerts are minted from inbound email and chat, so their bodies are attacker-controlled. Two mechanisms enforce that rather than one prompt rule. Every field the digest interpolates is collapsed to a single line, because a newline in an attacker-written headline, suggested action, tag or review note would otherwise forge a whole extra `[N]` line — a fabricated instruction to clear somebody else's alert. And the live board the server derived is recorded on the session, so `ack_alert` refuses any id outside it — on EVERY session, web included; the web previously had no check at all. The recorded set is the whole live board (the cap `/today` renders as cards), not just the rows the digest printed, so a card past the digest's 30-row render cap is still ackable rather than sending the principal back to the page. Be precise about what this buys: it stops an id that is invented, closed, snoozed or expired, including one quoted out of an attacker-written alert body. It does NOT stop the model being argued into acking the wrong LIVE card — one alert's body can still make a case about another id that is genuinely open. Scoping trust to the single item under discussion would need the primer id carried server-side, which it is not.\n\n### Handler failures\n\nAn adapter's catch-all replies \"I encountered an error processing your request.\" On Slack that used to be the whole story — one uncorrelated log line, no audit row, and an unguarded error-send that could itself escape into Bolt. It now logs with the session, sender, channel, thread and mode, and writes an `integration_inbound` row with `details.outcome=\"handler_error\"`, joining the inbound row under the same `session_id`. Upstream, a single crashing tool handler no longer takes the turn down at all: the orchestrator's tool gathers use `return_exceptions=True`, hand the model an error `tool_result`, and audit it with `ok=false` (cancellation is re-raised, not swallowed).\n\n### Attachments\n\n`integrations.attachments` handles web chat, Discord, and Telegram. Images become Anthropic vision blocks; documents (PDF/DOCX/TXT/MD/CSV) are inlined into the turn that carried them and indexed into the ChromaDB `inbound_attachments` collection. 20 MB/file cap; web chat uses `POST /chat/upload`.\n\nIndexed chunks are keyed on `attachment:<bare filename>` and tagged `type=attachment`. An attachment's name is chosen by whoever sent the message and the name is the chunk-id namespace, so without the prefix an inbound `strategy-2026.md` would upsert over the curated company document of that name. The prefix separates inbound content from curated uploads and keeps provenance visible; it does not separate senders from one another.\n\nIsolation is the **collection**: `retriever.retrieve` never queries `inbound_attachments` at all, so an attachment cannot resurface as company knowledge in a later, unrelated turn. Attachment processing is roster-gated on Discord too — it previously ran before the gate, so an unrostered sender's file was downloaded and indexed before their message was dropped. These rows still have no operator surface: they are never written to `company/docs/`, so `GET /documents` does not list them.\n\nThis replaced a domain-based scheme that did not work. The chunks lived in `company_docs` under a domain outside the specialist set, on the premise that an unrecognised domain matched no filter. It matched every one — `ChromaDBStore.query` attaches a `where` clause only when a domain filter is present, and an Executive-level retrieval passes none — so attachments came back under “From your company documents”, top-ranked and indistinguishable from a curated upload. Legacy rows are migrated across on boot.\n\n### MCP gateway & outbound\n\nMCP runs in **both directions**. As a *client*, `orchestrator.mcp_gateway.MCPGateway` proxies MCP servers (Gmail, Calendar, Drive — whatever `mcp_servers.json` configures) as Executive tools, with egress gating on Gmail recipients, Calendar attendees, and Drive share grantees against the roster (and a refusal of public / whole-domain Drive sharing). The Google Workspace server (`workspace-mcp`) behind those Gmail/Calendar/Drive tools runs **co-located inside the API** as a stdio child of the gateway — fitting the single-tenant model (one install = one company = one exec Google account), so there's no separate service to operate. It's baked into the API image and launched by `docker/workspace-mcp-launch.sh`, which selects single-user OAuth (token persisted at `/data/google_credentials`) or service-account domain-wide delegation from `GWORKSPACE_AUTH_MODE`. The gateway forwards the Google secrets to the child via `_FORWARDED_ENV_VARS`. As a *server*, `openexecutive.mcp_server` exposes OE's own company context and specialist council to external MCP clients at `/mcp` — the inverse direction; see the dedicated **MCP Server** section. The gateway launches extensible-mcp as a `uvx` subprocess whose fastembed tool-search index uses an embedding model baked into the API image and loaded offline, so it no longer re-downloads that model from the Hugging Face Hub on every cold start. extensible-mcp is pinned twice over: to a commit, which fixes its own code, and with `--exclude-newer`, which fixes the resolution of its dependencies — without the cutoff uvx re-resolves them against PyPI on every networked start, so a new release of any of them would reach running deployments on restart. Both live in `_EXTENSIBLE_MCP_LAUNCH_ARGS` in `orchestrator/mcp_gateway.py`, the Dockerfile's pre-warm uses the same arguments (a unit test enforces the match), so an image whose pre-warm succeeded starts the gateway with no network. The pre-warm is best-effort (`|| true`): an image built while GitHub was unreachable fetches the pinned commit on its first start instead. Updating the gateway is a deliberate bump of the commit and cutoff; `uv` itself is not pinned. Because the MCP stdio client does not inherit the parent environment, `MCPGateway.start()` explicitly forwards the embedding-cache/offline env vars (`FASTEMBED_CACHE_PATH`, `HF_HUB_OFFLINE`, …) into the child.\n\n**Emailing an artifact.** A Gmail send or draft may carry `attachments=[{\"artifact_id\": \"alert:12\", \"as\"?: \"docx\"}]`. `call_tool` runs the recipient gate first; only if it passes does `_expand_artifact_attachments` replace each such entry with the rendered file (`content` base64 + `filename` + `mime_type`, workspace-mcp's own attachment shape), produced by `artifact_records.render_artifact_file` — the same renderer as `/artifacts/{id}/download`. Only artifact rows resolve (never an arbitrary alert), links have no file, and an entry mixing `artifact_id` with other keys is refused. A stringified or single-object `attachments` is normalised first, so an artifact entry can never reach workspace-mcp unexpanded (it would silently drop it). At most 5 distinct artifacts per email (repeats are dropped) and 15 MB rendered in total; rendering runs off the event loop via `asyncio.to_thread`. A refusal writes `artifact_attachment_refused`; a successful send writes `artifact_attached` — both carry the recipients. Other attachment entries pass through unchanged.\n\n**Enablement, and why it degrades instead of dying.** `MCP_ENABLED` left unset is inferred from the presence of `mcp_servers_config_path` — dropping an `mcp_servers.json` next to `profile.yaml` turns MCP on with no further configuration. An **explicit** setting always wins in both directions: `MCP_ENABLED=false` keeps MCP off with the file still in place. It did not: `_resolve_mcp` tested `not self.mcp_enabled`, which cannot tell \"never set\" from \"set to false\", so the file's presence silently overrode the operator. The file is probed through `config.mcp_config_file_present`, never `Path.exists` directly — that re-raises an EACCES on a parent directory, and from inside a validator that comes out of `Settings()` itself, which `api/main.py` calls at module level. The check now reads `model_fields_set` (the fields the env actually supplied) and stores that on a private attr behind the read-only `mcp_auto_enabled` property, because the validator's own assignment joins that set and would otherwise make every auto-enable look explicit downstream.\n\nStartup is **best-effort**, in `main._start_mcp_gateway`. Two checks come before the subprocess: MCP off is a no-op, and a config defining no servers under `mcpServers` is logged and skipped — extensible-mcp's own loader raises on that and exits, and because the child is already gone the only thing that surfaces is anyio's \"Attempted to exit cancel scope in a different task\" from `stdio_client` unwinding, a traceback naming nothing about configuration. The start is also bounded (120s, generous because that child may still clone extensible-mcp on a cold start if the image's pre-warm failed): `ClientSession` carries no `read_timeout_seconds`, so `initialize()` waits forever on a child that is *alive but silent*, and an unbounded wait is a lifespan that never yields — the same healthcheck-never-passes symptom, which no `except` can see. A gateway that fails anyway is logged at ERROR with the config path, the servers it named, and whether the config file or an explicit `MCP_ENABLED` turned MCP on, then torn down under its own timeout; the API boots **without MCP tools and without the email poller** rather than refusing to boot. The guard catches `BaseException`, not `Exception`, re-raising a bare `CancelledError` first: the original failure came from anyio, which wraps a task group's failures in `BaseExceptionGroup` as soon as one is a `BaseException` — and that group is not an `Exception`, so `except Exception` would miss the very shape this contains. The teardown is contained too, since it runs from inside that `except` and would otherwise replace the actionable log with the crash it prevents. `configured_server_names` never raises either, and deliberately catches broadly: it reads an operator-owned path during startup, where an exception is the crash loop rather than a bug report — `Path.is_file` re-raises an EACCES on a parent directory, and `json.loads` answers deeply-nested input with `RecursionError`, which is not a `ValueError`. It tests `is_file()` so a directory or a symlink to a FIFO is never opened, and caps the read at 1 MiB. That exception used to propagate out of the lifespan and kill the container — under `restart: unless-stopped`, a crash loop whose only outward symptom was a healthcheck that never passed. Outbound tools: per-Person DMs (`send_slack_dm`, `send_discord_dm`, `send_telegram_message`) plus room-targeted `send_department_message` and `send_company_broadcast`. The per-Person DMs are additionally rate-limited and de-duplicated by the outbound anti-spam guard (below).\n\n### Outbound anti-spam guard\n\nEvery per-Person DM passes a deterministic guard (`orchestrator.outbound_guard.check_outbound_allowed`) after the roster gate and recipient-id recovery but before the network send — the single chokepoint **all** proactive DM paths reach (ad-hoc chat sends, the scheduler's followup/nudge dispatch, principal-brief delivery, the reflection turn, and research-finding routing). On a violation it returns a human-readable reason and the handler **suppresses** the send (`{\"status\":\"suppressed\",\"reason\":…}`), writes a `tool_invocation` audit row with `suppressed=true`, and writes **no** `done` activity row — so a blocked attempt never counts toward its own rate cap, and the Executive can read the reason and hold or `schedule_followup` for the recipient's next window. Three controls: **content dedup** (a near-identical message — whitespace/case-normalized, first 160 chars — already sent to the same recipient within `OUTBOUND_DEDUP_WINDOW_MINUTES`, default 360); a **per-recipient rate cap** (`OUTBOUND_MAX_PER_RECIPIENT_PER_WINDOW`, default 5, over `OUTBOUND_RATE_WINDOW_MINUTES`, default 60); and **quiet hours / availability** (`OUTBOUND_RESPECT_QUIET_HOURS`, default on — refuse while the recipient is on leave or outside their `people.channel` availability windows, surfacing the next open window). Delivery history is read from the existing `status='done'` `scheduled_actions` rows (`episodic.recent_sends_for_channel_ref`), so there is no new table. The guard is **fail-open**: any internal lookup error returns \"allow\", so it can never turn a working send into a crash or a silently-dropped message. Principal briefs and the internal heartbeat kinds use the `__internal__` channel and never reach these handlers, so they are unaffected.\n\n### Calendar & Google Meet\n\nThe Executive books meetings through two typed tools over the Calendar MCP. `create_calendar_event` schedules a **future** meeting (propose→approve by default, or auto-execute once that decision class is promoted) and may be used proactively when a stalled goal warrants a sync. `create_instant_meeting` spins up an **impromptu call starting now**, auto-executing without the approval step and skipping the business-hours/horizon caps, so the Executive can hand back a join link immediately. Both attach a **Google Meet** link by default (`add_google_meet`; opt out for in-person), parsed from the created event's `conferenceData` and surfaced to the caller plus persisted on the decision ledger. Either way the caps that matter still hold — roster membership, principal-protection, max attendees, and a daily booking ceiling.\n\n**Around-the-meeting participation.** The Executive doesn't join the call as a live voice; instead, on every successful booking it schedules a best-effort post-meeting follow-up (~5 min after the end) that DMs a human attendee asking for a quick recap — key decisions and action items. The reply flows back through the same cross-session DM context linkage described below, so the Executive can act on it (summarize, follow up) in a later turn. No meeting-transcript or Drive integration is required.\n\n### Cross-session DM context\n\nWhen the principal says \"DM Alex about X\" in one session, OE sends the DM and — if a live conversation is active — records an `outbound_context` linkage row (recipient, full outbound text, originating session id). Email is covered too but recorded one layer deeper — there is no `send_email` tool, so the linkage is written in `orchestrator.mcp_gateway` after a successful `google_workspace__send_gmail_message`, one row per `to`/`cc` recipient keyed by the bare lowercased address (OE's own address skipped). When Alex later replies on the 1:1 DM path — or by email — the shared helper `integrations.inbound_hydration.hydrate_user_message` (called by the Discord, Telegram, and Slack handlers, and by the email poller keyed on the sender address) looks up the most-recent `open` linkage for that sender within 72h and prepends an `<outbound_reply_context>` block — the outbound text plus a backstory excerpt from the originating session — to the message handed to `Executive.chat()`. So OE knows what the reply is about instead of starting from an empty per-person session. The block is context for the LLM turn only: peer memory strips it before recording what the person said (`strip_outbound_reply_context`, applied in `sync_turn`, `sync_department_turn` and to the prefetch query), so the Executive's own DM is never attributed to the person who replied to it. The block lands in the user turn (caching rule) and is injected into a copy only — the pristine reply is persisted to history. The linkage is one-shot (consumed on first matched reply, race-safe) so an unrelated later DM isn't re-hydrated. This is deterministic and independent of the per-person `peer_memory` (Honcho) layer.\n\nEvery adapter that persists a turn (Slack, Discord, Telegram, and the web route) records the message's **resolved sender** on `chat_messages.sender_person_id` — the rostered Person the adapter matched, or NULL for an unrostered sender — independently of the session owner, which falls back to the principal on Discord and Telegram so those threads stay visible. Attunement's open loops and feedback rely on this so an outsider's words are never read as someone on the roster's.",
"mermaid": "flowchart TD\n Channels[\"Slack / Discord<br/>Telegram / GChat / Email\"]\n Resolve[\"find_person_by_*_id\"]\n Gate[\"roster gate\"]\n Drop[\"drop unrostered\"]\n Exec[\"Executive.chat()\"]\n Attach[\"attachments<br/>(vision / inbound_attachments)\"]\n MCP[\"MCP gateway\"]\n Guard[\"outbound anti-spam guard<br/>(dedup / rate cap / quiet hours)\"]\n Out[\"DM / department<br/>/ broadcast tools\"]\n Channels --> Resolve\n Resolve --> Gate\n Gate -- \"unknown sender\" --> Drop\n Gate -- \"Person\" --> Exec\n Gate --> Attach\n Attach --> Exec\n Exec --> MCP\n Exec --> Guard\n Guard -- \"suppress\" --> Drop\n Guard -- \"allow\" --> Out\n Out --> Channels\n class Channels entry\n class Resolve compute\n class Gate compute\n class Drop external\n class Exec hot\n class Attach compute\n class MCP external\n class Guard compute\n class Out compute",
- "generated_at": "2026-09-24T17:40:22.177514+00:00"
+ "generated_at": "2026-09-25T12:22:48.458924+00:00"
}
diff --git a/packages/core/openexecutive/architecture/prebuilt/org.json b/packages/core/openexecutive/architecture/prebuilt/org.json
index 1aae5e43..f496ff43 100644
--- a/packages/core/openexecutive/architecture/prebuilt/org.json
+++ b/packages/core/openexecutive/architecture/prebuilt/org.json
@@ -1,7 +1,7 @@
{
"section_id": "org",
"title": "Org Structure (Departments & People)",
- "markdown": "The org model has two persistent registries backed by SQLite (both share `episodic_memory.db`): **departments** and **people**. Eight default departments are seeded exactly once per database on first boot, tracked by a `default_departments_seeded` sentinel in `departments_meta`; after that the user owns the list and deleted departments stay deleted across restarts.\n\n### Company setup (onboarding)\nBoth registries are first populated by **conversational onboarding** at\n`/onboard`. The user describes their business in their own words (optionally\nattaching a deck or one-pager); the `onboarding_interviewer` agent — Council-\nvisible but outside `SPECIALIST_REGISTRY`, so the Executive cannot reach it via\n`consult_specialist` — asks up to 8 clarifying questions, then emits a draft\ncompany profile, a leadership roster, and a department list. The user reviews\nand edits that draft inline (the same section editors `/company-profile` uses)\nbefore anything is written.\n\nTwo properties matter here. First, **the interview never writes**: the whole\nexchange lives in an in-memory, TTL'd session, and the single write happens at\n`POST /onboard/interview/commit`, so a rejected save leaves the draft editable\nand retryable. Second, **the department step is additive** — drafted\ndepartments are matched onto existing ones by slug or title and updated in\nplace, unmatched ones are created, and nothing is ever deleted. That is\ndeliberately unlike the fixture loader's `_seed_departments`, which DELETEs\nevery row first: doing that here would drop the eight defaults along with their\n`specialist_key` wiring, which `create_department` (always `specialist_key =\nNULL`) cannot restore. `profile.org_structure` is derived from the reviewed\npeople and department tables at commit time, so it cannot drift from them.\n\nExactly one person is marked `is_principal` and receives `WILDCARD` authority;\nno contact details are imported, even if the user volunteers them, because\nchannels and handles are a deliberate action on the People page. The one\nexception is the owner's own sign-in email: the review screen has a separate\nfield for it, pre-filled with the current owner's email on a re-run and with the\nsigned-in user's on a first setup. The commit checks it before writing anything\n(malformed, already another person's, or different from the owner's existing\nemail is a 422 — setup only fills in a missing one) and then saves it on the\nprincipal's row. Without it the signed-in owner matched no Person,\nso their chat history stayed empty until they found the People page. With\nlocal login (`make dev` without Google sign-in) the field is optional: that\nsession carries no email, which the backend already reads as the principal.\nBecause the save demotes the old principal, only the current owner may draft\nsomeone else as \"This is me\" when setup is re-run (403 otherwise); a re-run\nthat keeps the owner, or a first setup, is open to anyone who can sign in. The original\n12-step form wizard remains available at `/onboard?mode=form` and backs the\n`openexecutive onboard` CLI.\n\n### Departments\nEach department carries a charter, `Goal` rows, `ChecklistItem`s, and named cadences. Cadence specs (`daily@HH:MM`, `weekly@DOW@HH:MM`, `quarterly@DD-HH:MM`, UTC) enqueue a `department_check_in` workflow when due, then chain the next occurrence; `PATCH /departments/{slug}` rejects a spec that does not parse with a 422. A department may map to one of the 8 specialist agents via `specialist_key`, or stay informational. An assigned head gets a generated department-head voice persona.\n\nA department can also list **watched entities** (`watched_entities`, edited one per line on its page): vendors it is evaluating, competitors in its lane, tickers it tracks. The research watch policy treats them as strong grounding — a proposal about one can be added to the watch list on its own — and routes the resulting watch, its alerts and any suggestion cards to the department and its head rather than the principal (see External monitoring).\n\n### Authority gate\nEach department declares an `AuthorityLevel`, which `departments.authority.gate_action` checks whenever a department-scoped scheduled action comes due. `auto_execute` (autonomous) fires directly. `propose_only` turns the action into an approval card for an approver (`propose_via_alert`) and sends nothing, deferring the card to the approver's next availability window when they are outside it. `escalate` also sends nothing until someone approves: it raises an urgent `[ESCALATION]` card (severity high) right away, never deferred — filed unrouted when nobody holds the scope and no principal is set, since the Briefing lists every unread card — what the Departments page promises (\"the specialist will not act — it forwards everything to a human\"). It used to raise the card *and* dispatch, so approving the card sent the action a second time. Calendar bookings follow the same rule. The approver is chosen by `AuthorityScope` — a scheduled action's `required_scope` (e.g. `vendor_onboarding`, `spend_lt_10k`) feeds `find_approvers(scope)`, which ranks non-principal scope-holders ahead of `WILDCARD` holders. A null/unknown scope falls back to `WILDCARD` (the principal).\n\n### People & channels\nThe people registry resolves each `Person` to a `(channel, channel_ref)` pair via `prefer_channel_for()`, honoring `preferred_channel` (falling back email → slack → discord → telegram) and availability windows. Departments can also set `slack_channel_id` / `discord_channel_id` / `telegram_chat_id` to broadcast to a team room instead of DMing the head.\n\nEach person's page also lists their **open loops** (see Attunement) — what they committed to or were asked for in conversation — with a *Mark done* action; archiving a person closes their open loops, since an archived person can no longer be chased. The list is the principal's or that person's only; `people.store.is_principal_or_self` is the one check behind it, the close action and reply feedback.\n\nThe Executive can change the roster from a chat turn (`upsert_person`, `archive_person`, `set_department_head`) only when the principal asks, from the web chat, their own Slack or Discord, or a private Telegram chat when `TELEGRAM_WEBHOOK_SECRET` is set. A teammate, an email (even one from the principal's address), Google Chat, the CLI, the MCP server and unattended runs are refused, because a People row is also the web sign-in allow-list, the outbound-email allow-list and approval routing. The People page itself is unaffected.",
+ "markdown": "The org model has two persistent registries backed by SQLite (both share `episodic_memory.db`): **departments** and **people**. Eight default departments are seeded exactly once per database on first boot, tracked by a `default_departments_seeded` sentinel in `departments_meta`; after that the user owns the list and deleted departments stay deleted across restarts.\n\n### Company setup (onboarding)\nBoth registries are first populated by **conversational onboarding** at\n`/onboard`. The user describes their business in their own words (optionally\nattaching a deck or one-pager); the `onboarding_interviewer` agent — Council-\nvisible but outside `SPECIALIST_REGISTRY`, so the Executive cannot reach it via\n`consult_specialist` — asks up to 8 clarifying questions, then emits a draft\ncompany profile, a leadership roster, and a department list. The user reviews\nand edits that draft inline (the same section editors `/company-profile` uses)\nbefore anything is written.\n\nTwo properties matter here. First, **the interview never writes**: the whole\nexchange lives in an in-memory, TTL'd session, and the single write happens at\n`POST /onboard/interview/commit`, so a rejected save leaves the draft editable\nand retryable. Second, **the department step is additive** — drafted\ndepartments are matched onto existing ones by slug or title and updated in\nplace, unmatched ones are created, and nothing is ever deleted. That is\ndeliberately unlike the fixture loader's `_seed_departments`, which DELETEs\nevery row first: doing that here would drop the eight defaults along with their\n`specialist_key` wiring, which `create_department` (always `specialist_key =\nNULL`) cannot restore. `profile.org_structure` is derived from the reviewed\npeople and department tables at commit time, so it cannot drift from them.\n\nExactly one person is marked `is_principal` and receives `WILDCARD` authority;\nno contact details are imported, even if the user volunteers them, because\nchannels and handles are a deliberate action on the People page. The one\nexception is the owner's own sign-in email: the review screen has a separate\nfield for it, pre-filled with the current owner's email on a re-run and with the\nsigned-in user's on a first setup. The commit checks it before writing anything\n(malformed, already another person's, or different from the owner's existing\nemail is a 422 — setup only fills in a missing one) and then saves it on the\nprincipal's row. Without it the signed-in owner matched no Person,\nso their chat history stayed empty until they found the People page. With\nlocal login (`make dev` without Google sign-in) the field is optional: that\nsession carries no email, which the backend already reads as the principal.\nBecause the save demotes the old principal, only the current owner may draft\nsomeone else as \"This is me\" when setup is re-run (403 otherwise); a re-run\nthat keeps the owner, or a first setup, is open to anyone who can sign in. The original\n12-step form wizard remains available at `/onboard?mode=form` and backs the\n`openexecutive onboard` CLI.\n\n### Departments\nEach department carries a charter, `Goal` rows, `ChecklistItem`s, and named cadences. Cadence specs (`daily@HH:MM`, `weekly@DOW@HH:MM`, `quarterly@DD-HH:MM`, UTC) enqueue a `department_check_in` workflow when due, then chain the next occurrence; `PATCH /departments/{slug}` rejects a spec that does not parse with a 422. A department may map to one of the 8 specialist agents via `specialist_key`, or stay informational. An assigned head gets a generated department-head voice persona.\n\nA department can also list **watched entities** (`watched_entities`, edited one per line on its page): vendors it is evaluating, competitors in its lane, tickers it tracks. The research watch policy treats them as strong grounding — a proposal about one can be added to the watch list on its own — and routes the resulting watch, its alerts and any suggestion cards to the department and its head rather than the principal (see External monitoring).\n\n### Authority gate\nEach department declares an `AuthorityLevel`, which `departments.authority.gate_action` checks whenever a department-scoped scheduled action comes due. `auto_execute` (autonomous) fires directly. `propose_only` turns the action into an approval card for an approver (`propose_via_alert`) and sends nothing, deferring the card to the approver's next availability window when they are outside it. `escalate` also sends nothing until someone approves: it raises an urgent `[ESCALATION]` card (severity high) right away, never deferred — filed unrouted when nobody holds the scope and no principal is set, since the Briefing lists every unread card — what the Departments page promises (\"the specialist will not act — it forwards everything to a human\"). It used to raise the card *and* dispatch, so approving the card sent the action a second time. Calendar bookings follow the same rule. The approver is chosen by `AuthorityScope` — a scheduled action's `required_scope` (e.g. `vendor_onboarding`, `spend_lt_10k`) feeds `find_approvers(scope)`, which ranks non-principal scope-holders ahead of `WILDCARD` holders. A null/unknown scope falls back to `WILDCARD` (the principal).\n\n### People & channels\nThe people registry resolves each `Person` to a `(channel, channel_ref)` pair via `prefer_channel_for()`, honoring `preferred_channel` (falling back email → slack → discord → telegram) and availability windows. Departments can also set `slack_channel_id` / `discord_channel_id` / `telegram_chat_id` to broadcast to a team room instead of DMing the head.\n\nEach person's page also lists their **open loops** (see Attunement) — what they committed to or were asked for in conversation — with a *Mark done* action; archiving a person closes their open loops, since an archived person can no longer be chased. The list is the principal's or that person's only; `people.store.is_principal_or_self` is the one check behind it, the close action and reply feedback.\n\nThe Executive can change the roster from a chat turn (`upsert_person`, `archive_person`, `set_department_head`) only when the principal asks, from the web chat, their own Slack or Discord, or a private Telegram chat when `TELEGRAM_WEBHOOK_SECRET` is set to a value Telegram can send. A teammate, an email (even one from the principal's address), Google Chat, the CLI, the MCP server and unattended runs are refused, because a People row is also the web sign-in allow-list, the outbound-email allow-list and approval routing. The People page itself is unaffected.",
"mermaid": "flowchart TD\n People[\"People registry (Person, is_principal)\"]\n Dept[\"Departments (8 seeded once)\"]\n GC[\"Goals / checklists / cadences\"]\n Head[\"Head + voice persona\"]\n Gate[\"Authority gate (propose_only vs autonomous)\"]\n Scope[\"AuthorityScope to find_approvers\"]\n Chan[\"Channel resolution (Discord / Telegram / email)\"]\n Dept --> GC\n Dept --> Head\n Dept -->|proposes action| Gate\n Gate -->|required_scope| Scope\n Scope -->|ranks approvers| People\n People --> Chan\n Dept -->|team room| Chan\n class People storage\n class Dept storage\n class GC storage\n class Gate compute\n class Scope compute\n class Chan compute\n class Head compute",
- "generated_at": "2026-09-25T01:36:05.539643+00:00"
+ "generated_at": "2026-09-25T12:22:48.458924+00:00"
}
diff --git a/packages/core/openexecutive/architecture/prebuilt/scheduler.json b/packages/core/openexecutive/architecture/prebuilt/scheduler.json
index 06992b8a..aefe3e8c 100644
--- a/packages/core/openexecutive/architecture/prebuilt/scheduler.json
+++ b/packages/core/openexecutive/architecture/prebuilt/scheduler.json
@@ -1,7 +1,7 @@
{
"section_id": "scheduler",
"title": "Scheduler & Cadences",
- "markdown": "The scheduler is an asyncio task started in the FastAPI lifespan (`openexecutive.scheduler.runner.run_scheduler`). It polls every 30s and reads due rows from `scheduled_actions` (in `episodic_memory.db`). The due query uses `claim_due_actions`, an UPDATE…RETURNING claim, so each row fires at most once per process — this assumes a single scheduler instance per database. Polls are gated on an active company profile via `_company_profile_active()`; before onboarding, due rows stay `pending`.\n\n### Operator pause\n\nA global pause switch (`openexecutive.scheduler.pause`, one row in the `executive_control` table) stops everything the Executive starts on its own. It is the first check of every scheduler tick: while paused the tick does nothing — no alert/watchlist sweep, no claim — so due rows stay `pending` and fire on the first tick after resume. Actions already claimed when the pause lands run to completion; pausing holds work, it never cancels it. The same check gates the Gmail poller (the inbox is left unread) and the workflow resumer (no `wait_for_human` timeouts or resumes, and `apply_resolution` records a reply without kicking the run). Inbound conversations — web chat, Slack, Discord, Telegram, Google Chat — are deliberately not gated. The switch is set from the sidebar, the paused banner or Settings in the UI, or via `POST /executive/pause` / `POST /executive/resume`; each flip writes an `executive_paused` / `executive_resumed` audit row. Any signed-in caller may pause (it only holds work); resuming releases every held action at once, so it is the principal's alone (open only while no principal is on the roster). The state persists across restarts (boot logs a warning while paused) and across client-slot switches. `is_paused()` is read-only: a DB file or table that does not exist yet reads as \"running\", but a read error on an existing DB reads as \"paused\" — the brake fails closed, so a storage fault holds work rather than silently releasing it while the UI still shows \"paused\" (the UI shows \"status unknown\" when it cannot read the state).\n\n### Cadence DSL\n\n`openexecutive.departments.cadence` supports, all in UTC:\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()`. Deleting a department cancels its pending `dept_cadence` rows, and `cancel_orphaned_cadences()` sweeps orphans on boot.\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 gated `dept_cadence` row becomes a card and does not chain its next occurrence until the next startup bootstrap. 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\nThe stale-commitment source also chases **open loops** (see Attunement): `scheduled_actions` rows with `kind='open_loop'`, recorded `done` on the `__internal__` channel so the runner never dispatches them, whose `awaiting_response_since` is the loop's *due time*. They are chased as soon as they are overdue — not after `NUDGE_COMMITMENT_STALE_DAYS` — with a check-in intent addressed to the loop's owner (which quotes only the owner's own verbatim words and tells the dispatching turn to treat them as data), through the same `prefer_channel_for` routing, availability windows and outbound guard. Until open loops existed nothing in production set `awaiting_response_since`, so this source had nothing to chase. Each scan first closes loops older than `ATTUNEMENT_LOOP_TTL_DAYS` (21) as `expired`, then marks proactive outreach nobody answered within `ATTUNEMENT_IGNORE_AFTER_HOURS` as `ignored` in the outcome ledger. Ranking uses that ledger: a candidate whose person left their last five resolved nudges of that kind unanswered ranks after all others and waits three times its cooldown; a single answer lifts it. Approving a stalled run (however it's approved) and updating an initiative count as acting on the nudges that chased them. The generic dispatch path tags each send with its source (`_outreach_source`) so the ledger can attribute it.\n\n### Alert lifecycle: expiry sweep and the review heartbeat\n\nTwo alert-maintenance jobs live here. The **expiry sweep** is loop-level, not a heartbeat row: `_maybe_sweep_alerts` runs `alerts.lifecycle.expire_stale_alerts` (and, on the same 15-minute throttle, `monitoring.research.watch_policy.sweep` — expiring unreviewed research watch suggestions, auto-disabling research-added watches that proved noisy or dead, and filing one `watchlist_suggestions` nudge when ≥3 suggestions have waited ≥7 days; see External monitoring) once at boot and every 15 minutes at the top of the tick — before the company-profile and rotation gates, so an old backlog expires even before onboarding completes, flipping `unread` alerts past their category TTL to `expired` and auditing `alert_sweep`. Pure DB hygiene, no model call, reversible via `POST /alerts/{id}/reopen`.\n\nThe **Executive alert review** is a real heartbeat — kind `alert_review_scan`, `__internal__` channel, bootstrapped idempotently at startup when `ALERT_REVIEW_ENABLED` and chained every `ALERT_REVIEW_INTERVAL_HOURS` (6) with the same crash-resilient run → mark-done → chain shape as `nudge_scan`. `_run_principal_brief` also runs a `pre_brief` pass right before the morning brief (a review failure never blocks the brief). Each pass re-examines open alerts with evidence and, within department authority and the privacy rule, routes, nudges, escalates, drafts, merges or resolves them — see the Today section for the policy. The moves go through the real handlers (`message_person`, `draft_artifact`), so the outbound anti-spam guard applies, and `ALERT_REVIEW_MAX_MOVES_PER_SCAN` bounds side effects per pass.\n\n## Client rotation claim pause\n\nThe `client_rotation` kind (multi-client practice mode, opt-in via `CLIENT_ROTATION_ENABLED`) adds one loop-level behavior: while a rotation's `.rotation_in_progress` marker exists, the scheduler **skips claiming entirely** for that tick. Rotation switches the live company context between parked clients; claiming during the window would fire the just-activated client's overdue outbound follow-ups from a context nobody is watching. Everything due fires on the first tick after the original client is restored. Stale markers (crash mid-rotation) are reconciled at scheduler startup, and the rotation row is idempotently re-seeded both at boot and after every slot activation (scheduled rows swap with the client). See the Client Companies section for the rotation's full design.\n\nAn optional `notion_sync_scan` heartbeat (`NOTION_SYNC_ENABLED`, off by default) incrementally re-indexes Notion pages the workspace integration can see into the isolated `notion_wiki` collection (not COMPANY), reconciles un-shared pages, then chains the next tick.",
+ "markdown": "The scheduler is an asyncio task started in the FastAPI lifespan (`openexecutive.scheduler.runner.run_scheduler`). It polls every 30s and reads due rows from `scheduled_actions` (in `episodic_memory.db`). The due query uses `claim_due_actions`, an UPDATE…RETURNING claim, so each row fires at most once per process — this assumes a single scheduler instance per database. Polls are gated on an active company profile via `_company_profile_active()`; before onboarding, due rows stay `pending`.\n\n### Operator pause\n\nA global pause switch (`openexecutive.scheduler.pause`, one row in the `executive_control` table) stops everything the Executive starts on its own. It is the first check of every scheduler tick: while paused the tick does nothing — no alert/watchlist sweep, no claim — so due rows stay `pending` and fire on the first tick after resume. Actions already claimed when the pause lands run to completion; pausing holds work, it never cancels it. The same check gates the Gmail poller (the inbox is left unread) and the workflow resumer (no `wait_for_human` timeouts or resumes, and `apply_resolution` records a reply without kicking the run). Inbound conversations — web chat, Slack, Discord, Telegram, Google Chat — are deliberately not gated. The switch is set from the sidebar, the paused banner or Settings in the UI, or via `POST /executive/pause` / `POST /executive/resume`; each flip writes an `executive_paused` / `executive_resumed` audit row. Any signed-in caller may pause (it only holds work); resuming releases every held action at once, so it is the principal's alone (open only while no principal is on the roster). The state persists across restarts (boot logs a warning while paused) and across client-slot switches. `is_paused()` is read-only: a DB file or table that does not exist yet reads as \"running\", but a read error on an existing DB reads as \"paused\" — the brake fails closed, so a storage fault holds work rather than silently releasing it while the UI still shows \"paused\" (the UI shows \"status unknown\" when it cannot read the state).\n\n### Liveness heartbeat\n\nEvery tick ends by recording when it finished and what it did — `ran`, `paused`, `waiting_for_company`, `rotating`, or `failed` when the tick raised — and `run_scheduler` notes when it started. `scheduler_heartbeat()` returns both; they live in process memory, not the database. Settings → Setup status (`GET /setup/status`) reads them: no start means the task isn't running; no tick five minutes after starting, or none for three poll intervals (at least 90 s), means the loop has stopped; `failed` and `waiting_for_company` get their own light. Liveness is judged before the pause switch, because a paused scheduler still ticks: one that has stopped shows as stopped, where the Resume button wouldn't help. A restart clears the previous run's last tick. Due actions run as their own tasks, so a slow brief never ages the heartbeat.\n\n### Cadence DSL\n\n`openexecutive.departments.cadence` supports, all in UTC:\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()`. Deleting a department cancels its pending `dept_cadence` rows, and `cancel_orphaned_cadences()` sweeps orphans on boot.\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 gated `dept_cadence` row becomes a card and does not chain its next occurrence until the next startup bootstrap. 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\nThe stale-commitment source also chases **open loops** (see Attunement): `scheduled_actions` rows with `kind='open_loop'`, recorded `done` on the `__internal__` channel so the runner never dispatches them, whose `awaiting_response_since` is the loop's *due time*. They are chased as soon as they are overdue — not after `NUDGE_COMMITMENT_STALE_DAYS` — with a check-in intent addressed to the loop's owner (which quotes only the owner's own verbatim words and tells the dispatching turn to treat them as data), through the same `prefer_channel_for` routing, availability windows and outbound guard. Until open loops existed nothing in production set `awaiting_response_since`, so this source had nothing to chase. Each scan first closes loops older than `ATTUNEMENT_LOOP_TTL_DAYS` (21) as `expired`, then marks proactive outreach nobody answered within `ATTUNEMENT_IGNORE_AFTER_HOURS` as `ignored` in the outcome ledger. Ranking uses that ledger: a candidate whose person left their last five resolved nudges of that kind unanswered ranks after all others and waits three times its cooldown; a single answer lifts it. Approving a stalled run (however it's approved) and updating an initiative count as acting on the nudges that chased them. The generic dispatch path tags each send with its source (`_outreach_source`) so the ledger can attribute it.\n\n### Alert lifecycle: expiry sweep and the review heartbeat\n\nTwo alert-maintenance jobs live here. The **expiry sweep** is loop-level, not a heartbeat row: `_maybe_sweep_alerts` runs `alerts.lifecycle.expire_stale_alerts` (and, on the same 15-minute throttle, `monitoring.research.watch_policy.sweep` — expiring unreviewed research watch suggestions, auto-disabling research-added watches that proved noisy or dead, and filing one `watchlist_suggestions` nudge when ≥3 suggestions have waited ≥7 days; see External monitoring) once at boot and every 15 minutes at the top of the tick — before the company-profile and rotation gates, so an old backlog expires even before onboarding completes, flipping `unread` alerts past their category TTL to `expired` and auditing `alert_sweep`. Pure DB hygiene, no model call, reversible via `POST /alerts/{id}/reopen`.\n\nThe **Executive alert review** is a real heartbeat — kind `alert_review_scan`, `__internal__` channel, bootstrapped idempotently at startup when `ALERT_REVIEW_ENABLED` and chained every `ALERT_REVIEW_INTERVAL_HOURS` (6) with the same crash-resilient run → mark-done → chain shape as `nudge_scan`. `_run_principal_brief` also runs a `pre_brief` pass right before the morning brief (a review failure never blocks the brief). Each pass re-examines open alerts with evidence and, within department authority and the privacy rule, routes, nudges, escalates, drafts, merges or resolves them — see the Today section for the policy. The moves go through the real handlers (`message_person`, `draft_artifact`), so the outbound anti-spam guard applies, and `ALERT_REVIEW_MAX_MOVES_PER_SCAN` bounds side effects per pass.\n\n## Client rotation claim pause\n\nThe `client_rotation` kind (multi-client practice mode, opt-in via `CLIENT_ROTATION_ENABLED`) adds one loop-level behavior: while a rotation's `.rotation_in_progress` marker exists, the scheduler **skips claiming entirely** for that tick. Rotation switches the live company context between parked clients; claiming during the window would fire the just-activated client's overdue outbound follow-ups from a context nobody is watching. Everything due fires on the first tick after the original client is restored. Stale markers (crash mid-rotation) are reconciled at scheduler startup, and the rotation row is idempotently re-seeded both at boot and after every slot activation (scheduled rows swap with the client). See the Client Companies section for the rotation's full design.\n\nAn optional `notion_sync_scan` heartbeat (`NOTION_SYNC_ENABLED`, off by default) incrementally re-indexes Notion pages the workspace integration can see into the isolated `notion_wiki` collection (not COMPANY), reconciles un-shared pages, then chains the next tick.",
"mermaid": "flowchart TD\n Loop[\"run_scheduler<br/>poll every 30s\"]\n Pause{\"is_paused()?<br/>(executive_control)\"}\n Claim[\"claim_due_actions<br/>(status=pending, by kind)\"]\n Table[(\"scheduled_actions\")]\n Dispatch[\"dispatch via row channel<br/>(ad_hoc / proactive_nudge)\"]\n Dept[\"dept_cadence →<br/>department_check_in\"]\n Nudge[\"nudge_scan →<br/>nudge_engine scan\"]\n Brief[\"principal_brief_morning / _eod →<br/>morning_brief / end_of_day_digest\"]\n Reflect[\"executive_reflection →<br/>reflection (artifact only)\"]\n ExtMon[\"external_monitor_scan →<br/>monitoring pipeline\"]\n Research[\"watchlist_research_scan →<br/>executive_research (skip-if-unchanged)\"]\n Notion[\"notion_sync_scan →<br/>isolated wiki ingest\"]\n Chain[\"enqueue_next<br/>(re-arm recurring tick)\"]\n Prefer[\"prefer_channel_for<br/>(availability + last-used)\"]\n Channels[\"Slack / Discord<br/>Telegram / Email\"]\n Principal[\"DM 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 -- \"nudge_scan\" --> Nudge\n Claim -- \"principal_brief_*\" --> Brief\n Claim -- \"executive_reflection\" --> Reflect\n Claim -- \"external_monitor_scan\" --> ExtMon\n Claim -- \"watchlist_research_scan\" --> Research\n Claim -- \"notion_sync_scan\" --> Notion\n Nudge -- \"prefer_channel_for\" --> Prefer\n Prefer -- \"emits proactive_nudge\" --> Table\n Dispatch --> Channels\n Brief --> Principal\n ExtMon --> Alerts\n Dept --> Chain\n Nudge --> Chain\n Brief --> Chain\n Reflect --> Chain\n ExtMon --> Chain\n Research --> Chain\n Notion --> Chain\n Chain --> Table\n class Loop entry\n class Claim compute\n class Table storage\n class Dispatch compute\n class Dept compute\n class Nudge compute\n class Brief compute\n class Reflect compute\n class ExtMon compute\n class Research compute\n class Notion compute\n class Chain compute\n class Prefer compute\n class Channels external\n class Principal external\n class Alerts hot",
- "generated_at": "2026-09-25T01:40:36.243753+00:00"
+ "generated_at": "2026-09-25T12:12:11.102620+00:00"
}
diff --git a/packages/core/openexecutive/config.py b/packages/core/openexecutive/config.py
index 206dd0f7..400754aa 100644
--- a/packages/core/openexecutive/config.py
+++ b/packages/core/openexecutive/config.py
@@ -30,6 +30,10 @@ _ENV_FILE = _ROOT / ".env"
# two silent retries later, and nowhere near the setting that caused it.
_WORKSPACE_ID_RE = re.compile(r"^[A-Za-z0-9._-]+$")
+# What Telegram's setWebhook accepts as a secret_token — and so the only
+# header values its servers can ever send back.
+_TELEGRAM_SECRET_RE = re.compile(r"[A-Za-z0-9_-]{1,256}")
+
def _blank_or_comment(v: Any) -> bool:
"""True for unset, '', or a dotenv inline-comment captured as the value.
@@ -500,6 +504,22 @@ class Settings(BaseSettings):
)
google_chat_project_number: str | None = Field(None, alias="GOOGLE_CHAT_PROJECT_NUMBER")
+ @field_validator(
+ "slack_bot_token", "slack_app_token", "telegram_bot_token",
+ "discord_bot_token", "discord_app_id", "google_chat_project_number",
+ "google_chat_service_account_file", "google_chat_service_account_email",
+ mode="before",
+ )
+ @classmethod
+ def _unset_if_comment(cls, v: Any) -> Any:
+ # `KEY= # note` reaches us as "# note": python-dotenv only strips a
+ # comment that follows a value. Left alone, that note would count as
+ # a token and switch the channel on with it. TELEGRAM_WEBHOOK_SECRET
+ # is deliberately not here: read as unset, a junk secret would switch
+ # the webhook's check off; kept, it makes the webhook refuse every
+ # update (see telegram_webhook_secret_valid).
+ return None if _blank_or_comment(v) else v
+
# ---- Tool results ----
# Upper bound on a single tool result's characters before it enters the
# prompt. A circuit breaker against an unbounded result (a large document
@@ -921,6 +941,19 @@ class Settings(BaseSettings):
self.mcp_enabled = True
return self
+ @property
+ def telegram_webhook_secret_valid(self) -> bool:
+ """Whether TELEGRAM_WEBHOOK_SECRET is set to a value Telegram can send.
+
+ setWebhook only accepts 1–256 of ``A-Z a-z 0-9 _ -``, so any other
+ value — a leftover ``# note``, a pasted ``<value from Step 2>`` — can
+ only ever be matched by someone who guessed it. Such a secret proves
+ nothing: the webhook refuses every update while it is set, and
+ nothing counts a Telegram message as verified.
+ """
+ secret = self.telegram_webhook_secret
+ return bool(secret) and _TELEGRAM_SECRET_RE.fullmatch(secret or "") is not None
+
@property
def mcp_auto_enabled(self) -> bool:
"""True when MCP is on ONLY because the config file exists.
diff --git a/packages/core/openexecutive/guide/prebuilt/integrations.json b/packages/core/openexecutive/guide/prebuilt/integrations.json
index e84f530a..431f11d7 100644
--- a/packages/core/openexecutive/guide/prebuilt/integrations.json
+++ b/packages/core/openexecutive/guide/prebuilt/integrations.json
@@ -1,7 +1,7 @@
{
"section_id": "integrations",
"title": "Integrations",
- "markdown": "**What it is:** The channels that connect the Executive to where your team already works — so proposals, updates, and replies flow through familiar tools instead of just the web app.\n\n**What it does:**\n\n- **Slack / Google Chat:** receive messages and thread replies, send proposals and alerts.\n- **Discord / Telegram:** direct-message conversations for proposals and approvals.\n- **Email:** poll for inbound mail and send outbound replies.\n- **Google Workspace:** the Executive can send and draft Gmail (recipients limited to your People roster) and manage Calendar events, including Google Meet links.\n- **MCP:** expose the Executive's specialist council and company context to external AI tools.\n\n**How to use:**\n\n*Before anyone can use a channel,* an administrator turns it on (see *Setup* below) and restarts the app. Then add each person's channel ID under **People → Contact & routing** — Slack, Discord and Telegram only answer people on your roster.\n\n*Talking to the Executive*\n\n- **Slack** — DM the app, or @mention it in a channel; it replies in a thread. Keep replying in that thread without mentioning it again.\n- **Discord** — DM the bot or @mention it (it usually answers in a new thread). Or use the slash commands `/ask` and `/today`.\n- **Telegram** — message the bot directly; text, documents and photos all work.\n- **Google Chat** — DM the app, or add it to a space and @mention it.\n- **Email** — send mail to the Executive's address; it picks up unread inbox mail on a regular poll.\n- **Signing off a paused workflow** — reply in the thread on Slack, Discord or Telegram: \"yes\", \"LGTM\", \"no\", \"not now\".\n\n**Example (Slack):** *\"@Executive what's blocking the Q3 hiring plan?\"* — the answer arrives in a thread, and you can follow up there.\n\n*Setup (administrators)* — each channel is switched on with environment settings:\n\n| Channel | Settings |\n|---|---|\n| Slack | `SLACK_BOT_TOKEN`, `SLACK_APP_TOKEN` (Socket Mode) |\n| Discord | `DISCORD_BOT_TOKEN`, `DISCORD_APP_ID`; enable the bot's Message Content intent (see the README) |\n| Telegram | `TELEGRAM_BOT_TOKEN`, `TELEGRAM_WEBHOOK_SECRET`; webhook at `/webhook/telegram` |\n| Google Chat | `GOOGLE_CHAT_PROJECT_NUMBER` plus a service account — see `docs/google_chat_setup.md` |\n| Email, Gmail & Calendar | `EXEC_EMAIL_ADDRESS` plus the Google Workspace connection — see `docs/deployment.md` |\n\n*Use the Executive from other AI tools (MCP)* — the API serves an MCP endpoint at `/mcp`; clients authenticate with the backend shared secret. In Claude Code:\n\n```bash\nclaude mcp add --transport http open-executive http://localhost:8000/mcp \\\n --header \"x-api-key: YOUR_BACKEND_SHARED_SECRET\"\n```\n\nOther MCP clients take the same URL and `x-api-key` header. They get `ask_executive`, `consult_specialist`, `search_knowledge` and `list_workflows`, plus read-only company context.\n\n*Note: every channel is recorded in the Audit Log. Replying to approve a paused workflow works on Slack, Discord and Telegram only — not email or Google Chat. Channels are turned on with environment configuration, not from this screen.*",
+ "markdown": "**What it is:** The channels that connect the Executive to where your team already works — so proposals, updates, and replies flow through familiar tools instead of just the web app.\n\n**What it does:**\n\n- **Slack / Google Chat:** receive messages and thread replies, send proposals and alerts.\n- **Discord / Telegram:** direct-message conversations for proposals and approvals.\n- **Email:** poll for inbound mail and send outbound replies.\n- **Google Workspace:** the Executive can send and draft Gmail (recipients limited to your People roster) and manage Calendar events, including Google Meet links.\n- **MCP:** expose the Executive's specialist council and company context to external AI tools.\n\n**How to use:**\n\n*Before anyone can use a channel,* an administrator turns it on (see *Setup* below) and restarts the app. Then add each person's channel ID under **People → Contact & routing** — Slack, Discord and Telegram only answer people on your roster. **Settings → Setup status** then shows whether each channel is working, and what to do if it isn't.\n\n*Talking to the Executive*\n\n- **Slack** — DM the app, or @mention it in a channel; it replies in a thread. Keep replying in that thread without mentioning it again.\n- **Discord** — DM the bot or @mention it (it usually answers in a new thread). Or use the slash commands `/ask` and `/today`.\n- **Telegram** — message the bot directly; text, documents and photos all work.\n- **Google Chat** — DM the app, or add it to a space and @mention it.\n- **Email** — send mail to the Executive's address; it picks up unread inbox mail on a regular poll.\n- **Signing off a paused workflow** — reply in the thread on Slack, Discord or Telegram: \"yes\", \"LGTM\", \"no\", \"not now\".\n\n**Example (Slack):** *\"@Executive what's blocking the Q3 hiring plan?\"* — the answer arrives in a thread, and you can follow up there.\n\n*Setup (administrators)* — each channel is switched on with environment settings:\n\n| Channel | Settings |\n|---|---|\n| Slack | `SLACK_BOT_TOKEN`, `SLACK_APP_TOKEN` (Socket Mode) |\n| Discord | `DISCORD_BOT_TOKEN`, `DISCORD_APP_ID`; enable the bot's Message Content intent (see the README) |\n| Telegram | `TELEGRAM_BOT_TOKEN`, `TELEGRAM_WEBHOOK_SECRET`; webhook at `/webhook/telegram` |\n| Google Chat | `GOOGLE_CHAT_PROJECT_NUMBER` plus a service account — see `docs/google_chat_setup.md` |\n| Email, Gmail & Calendar | `EXEC_EMAIL_ADDRESS` plus the Google Workspace connection — see `docs/deployment.md` |\n\n*Use the Executive from other AI tools (MCP)* — the API serves an MCP endpoint at `/mcp`; clients authenticate with the backend shared secret. In Claude Code:\n\n```bash\nclaude mcp add --transport http open-executive http://localhost:8000/mcp \\\n --header \"x-api-key: YOUR_BACKEND_SHARED_SECRET\"\n```\n\nOther MCP clients take the same URL and `x-api-key` header. They get `ask_executive`, `consult_specialist`, `search_knowledge` and `list_workflows`, plus read-only company context.\n\n*Note: every channel is recorded in the Audit Log. Replying to approve a paused workflow works on Slack, Discord and Telegram only — not email or Google Chat. Channels are turned on with environment configuration, not from this screen.*",
"mermaid": null,
- "generated_at": "2026-09-23T00:00:00+00:00"
+ "generated_at": "2026-09-25T11:58:29.878938+00:00"
}
diff --git a/packages/core/openexecutive/guide/prebuilt/settings.json b/packages/core/openexecutive/guide/prebuilt/settings.json
index 40cb6530..800c58c6 100644
--- a/packages/core/openexecutive/guide/prebuilt/settings.json
+++ b/packages/core/openexecutive/guide/prebuilt/settings.json
@@ -1,7 +1,7 @@
{
"section_id": "settings",
"title": "Settings & Advanced",
- "markdown": "**What it is:** The hub for power-user and admin tools that were pulled out of the day-to-day nav to keep it focused.\n\n**What it does:**\n\n- Links to the Agent Council, Audit Log, Token Usage, this User Guide, the Architecture reference, Company Simulator, and Client Companies.\n- Acts as a directory — each tile opens a dedicated screen.\n- Keeps advanced configuration one click away without cluttering the main workspace.\n- Shows whether the Executive is **running** or **paused**, with a switch to pause or resume it.\n\n**How to use:**\n\n1. Click **Settings** at the bottom of the sidebar.\n2. Click the tile for what you want to do:\n - **Agent Council** — change a specialist's model or prompt, or the Executive's voice.\n - **Audit log** — find out what the Executive did, and why.\n - **Token usage** — see what you're spending and where.\n - **User Guide** — this guide.\n - **Architecture** — the technical reference for how the system is built.\n - **Company Simulator** — try the Executive on a test company.\n - **Client Companies** — switch between clients if you do fractional work.\n\n**Pausing the Executive:**\n\n- Click **Executive running** at the bottom of the sidebar (or use the card at the top of Settings), add a reason if you like, and click **Pause Executive**.\n- While paused, the Executive starts nothing on its own: no briefs, nudges, monitoring, inbox processing or workflow timers. An amber banner appears on every page.\n- Chat and direct messages (Slack, Telegram, Discord, Google Chat) still get answers.\n- Nothing is lost. Work that falls due during the pause waits, and runs when you click **Resume**. The switch shows how many actions are waiting.\n- Anyone who can sign in can pause the Executive, but only the principal can resume it.\n\n*Tip: if you're looking for a feature that isn't in the sidebar, it's probably here. This guide is also pinned next to Settings at the bottom of the nav.*",
+ "markdown": "**What it is:** The hub for power-user and admin tools that were pulled out of the day-to-day nav to keep it focused.\n\n**What it does:**\n\n- Links to Setup status, the Agent Council, Audit Log, Token Usage, this User Guide, the Architecture reference, Company Simulator, and Client Companies.\n- Acts as a directory — each tile opens a dedicated screen.\n- Keeps advanced configuration one click away without cluttering the main workspace.\n- Shows whether the Executive is **running** or **paused**, with a switch to pause or resume it.\n\n**How to use:**\n\n1. Click **Settings** at the bottom of the sidebar.\n2. Click the tile for what you want to do:\n - **Setup status** — check that every part of your setup is working, and see what to do about anything that isn't.\n - **Agent Council** — change a specialist's model or prompt, or the Executive's voice.\n - **Audit log** — find out what the Executive did, and why.\n - **Token usage** — see what you're spending and where.\n - **User Guide** — this guide.\n - **Architecture** — the technical reference for how the system is built.\n - **Company Simulator** — try the Executive on a test company.\n - **Client Companies** — switch between clients if you do fractional work.\n\n**Checking your setup:**\n\n- Open **Settings → Setup status**. Each part of your setup gets a light: green is working, amber needs attention, red isn't working, grey isn't set up (and is optional).\n- It tests things for real: the AI key, and each chat app's token, with a quick call that sends nothing. It also checks the Executive's email address, the company setup, the daily schedule and whether anyone on your team list can reach each chat app.\n- Anything that isn't green says what to do in plain words, with a button when the fix is on another page. After you change a setting and restart the app, click **Check again**.\n\n**Pausing the Executive:**\n\n- Click **Executive running** at the bottom of the sidebar (or use the card at the top of Settings), add a reason if you like, and click **Pause Executive**.\n- While paused, the Executive starts nothing on its own: no briefs, nudges, monitoring, inbox processing or workflow timers. An amber banner appears on every page.\n- Chat and direct messages (Slack, Telegram, Discord, Google Chat) still get answers.\n- Nothing is lost. Work that falls due during the pause waits, and runs when you click **Resume**. The switch shows how many actions are waiting.\n- Anyone who can sign in can pause the Executive, but only the principal can resume it.\n\n*Tip: if you're looking for a feature that isn't in the sidebar, it's probably here. This guide is also pinned next to Settings at the bottom of the nav.*",
"mermaid": null,
- "generated_at": "2026-09-24T14:59:39.568371+00:00"
+ "generated_at": "2026-09-25T11:58:29.878938+00:00"
}
diff --git a/packages/core/openexecutive/integrations/telegram_bot.py b/packages/core/openexecutive/integrations/telegram_bot.py
index 93cd0a5e..18ed2175 100644
--- a/packages/core/openexecutive/integrations/telegram_bot.py
+++ b/packages/core/openexecutive/integrations/telegram_bot.py
@@ -365,6 +365,14 @@ async def telegram_webhook(request: Request, background_tasks: BackgroundTasks)
# Verify the secret token Telegram sends in the header (set when registering the webhook).
if settings.telegram_webhook_secret:
+ if not settings.telegram_webhook_secret_valid:
+ # Telegram can never send such a value (setWebhook refuses it), so
+ # the only request that could match it is a forged one.
+ logger.warning(
+ "Telegram: TELEGRAM_WEBHOOK_SECRET is not a value Telegram can send "
+ "(1-256 of A-Z a-z 0-9 _ -); refusing every update until it is fixed"
+ )
+ raise HTTPException(status_code=401, detail="Invalid webhook secret")
sent = request.headers.get("X-Telegram-Bot-Api-Secret-Token", "")
if not hmac.compare_digest(sent, settings.telegram_webhook_secret):
logger.warning("Telegram: webhook secret mismatch")
diff --git a/packages/core/openexecutive/orchestrator/people_tools.py b/packages/core/openexecutive/orchestrator/people_tools.py
index e9e29f42..f165426a 100644
--- a/packages/core/openexecutive/orchestrator/people_tools.py
+++ b/packages/core/openexecutive/orchestrator/people_tools.py
@@ -257,12 +257,13 @@ def _is_verified_speaker_surface(session: Any) -> bool:
return False
# Telegram identifies the chat, not the sender, and its webhook is exempt
# from the shared secret: an update is only proven to come from Telegram
- # when TELEGRAM_WEBHOOK_SECRET is set (otherwise anyone can post one naming
- # the principal's chat id). A group (negative id) is everyone in it.
+ # when TELEGRAM_WEBHOOK_SECRET is set to a value Telegram can send
+ # (otherwise anyone can post one naming the principal's chat id). A group
+ # (negative id) is everyone in it.
from openexecutive.config import get_settings
chat_ref = str(getattr(session, "origin_channel_ref", "") or "")
- return bool(get_settings().telegram_webhook_secret) and chat_ref.isdigit()
+ return get_settings().telegram_webhook_secret_valid and chat_ref.isdigit()
def _roster_refusal_reason(session: Any) -> str | None:
diff --git a/packages/core/openexecutive/scheduler/runner.py b/packages/core/openexecutive/scheduler/runner.py
index bd923270..295d3e35 100644
--- a/packages/core/openexecutive/scheduler/runner.py
+++ b/packages/core/openexecutive/scheduler/runner.py
@@ -30,6 +30,24 @@ logger = logging.getLogger(__name__)
# Strong refs so GC cannot cancel in-flight tasks mid-execution.
_inflight: set[asyncio.Task[None]] = set()
+# Liveness for the Setup status page (api/setup_checks.py): when this
+# loop started, and when its last tick finished and how. Every tick ends by
+# recording itself, so an old value means the loop has stopped or is stuck.
+_started_at: datetime | None = None
+_last_tick: tuple[datetime, str] | None = None
+
+
+def scheduler_heartbeat() -> tuple[datetime | None, tuple[datetime, str] | None]:
+ """``(started_at, (finished_at, outcome))`` — ``None`` for what hasn't
+ happened yet. Outcomes: ``ran``, ``paused``, ``waiting_for_company``,
+ ``rotating``, ``failed``."""
+ return _started_at, _last_tick
+
+
+def _beat(outcome: str) -> None:
+ global _last_tick
+ _last_tick = (datetime.now(UTC), outcome)
+
def _company_profile_active() -> bool:
"""True when a company profile with a name is configured.
@@ -98,6 +116,9 @@ async def run_scheduler(
poll_interval_seconds: int = 30,
) -> None:
"""Poll for due scheduled actions and dispatch them through the Executive."""
+ global _started_at, _last_tick
+ _started_at = datetime.now(UTC)
+ _last_tick = None
# Sweep any rows left in 'running' by a previous crash back to 'pending'
# so they can be re-tried. Without this they would stay stuck forever.
try:
@@ -168,6 +189,7 @@ async def run_scheduler(
"scheduler: executive paused — holding all scheduled work"
)
holding_for_pause = True
+ _beat("paused")
await asyncio.sleep(poll_interval_seconds)
continue
if holding_for_pause:
@@ -185,6 +207,7 @@ async def run_scheduler(
"scheduled actions until one is configured"
)
holding_for_profile = True
+ _beat("waiting_for_company")
await asyncio.sleep(poll_interval_seconds)
continue
if holding_for_profile:
@@ -197,6 +220,7 @@ async def run_scheduler(
# context — claiming now would fire the just-activated
# client's overdue outbound backlog at 3am. Everything due
# fires on the first tick after the original client is back.
+ _beat("rotating")
await asyncio.sleep(poll_interval_seconds)
continue
due = claim_due_actions(now)
@@ -206,10 +230,12 @@ async def run_scheduler(
task = asyncio.create_task(_execute_action(row, gateway))
_inflight.add(task)
task.add_done_callback(_inflight.discard)
+ _beat("ran")
except asyncio.CancelledError:
raise
except Exception:
logger.exception("scheduler tick failed")
+ _beat("failed")
try:
await asyncio.sleep(poll_interval_seconds)
except asyncio.CancelledError:
diff --git a/packages/core/tests/unit/test_people_tools.py b/packages/core/tests/unit/test_people_tools.py
index 925845a3..738f2049 100644
--- a/packages/core/tests/unit/test_people_tools.py
+++ b/packages/core/tests/unit/test_people_tools.py
@@ -392,7 +392,10 @@ def test_owner_in_a_private_telegram_chat_can_change_the_roster(
(None, "424242"),
# A group chat (negative id) is every member of the group.
("hook-secret", "-100424242"),
-], ids=["no_webhook_secret", "group_chat"])
+ # A secret Telegram can't send (a comment left in .env) proves only that
+ # the sender guessed it.
+ ("# from step 2", "424242"),
+], ids=["no_webhook_secret", "group_chat", "secret_telegram_cannot_send"])
def test_unverifiable_telegram_cannot_change_the_roster(
owner_id: int, monkeypatch: pytest.MonkeyPatch, secret: str | None, chat_ref: str
) -> None:
diff --git a/packages/core/tests/unit/test_setup_checks.py b/packages/core/tests/unit/test_setup_checks.py
new file mode 100644
index 00000000..a59030a2
--- /dev/null
+++ b/packages/core/tests/unit/test_setup_checks.py
@@ -0,0 +1,1030 @@
+"""Settings → Setup status: the checks behind GET /setup/status.
+
+Every probe runs against a mocked transport; nothing here reaches a real
+service. The recurring assertion besides the verdict itself: no token ever
+comes back in a check's text.
+"""
+from __future__ import annotations
+
+import asyncio
+import json
+import logging
+from collections.abc import Callable, Iterator
+from datetime import UTC, datetime, timedelta
+from pathlib import Path
+from types import SimpleNamespace
+from typing import Any
+
+import anthropic
+import httpx
+import pytest
+from dotenv import dotenv_values
+from fastapi.testclient import TestClient
+
+from openexecutive.api import setup_checks
+from openexecutive.api.routes import setup_status as setup_route
+from openexecutive.api.setup_checks import (
+ EXAMPLE_VALUES,
+ LABELS,
+ SetupCheck,
+ Snapshot,
+ check_ai_model,
+ check_api_protection,
+ check_company,
+ check_discord,
+ check_exec_email,
+ check_gmail,
+ check_google_chat,
+ check_memory,
+ check_owner,
+ check_scheduler,
+ check_slack,
+ check_telegram,
+ is_example_email,
+ run_checks,
+)
+from openexecutive.audit import AuditEvent
+from openexecutive.config import Settings
+from openexecutive.people.models import Person
+
+NOW = datetime(2026, 9, 25, 12, 0, tzinfo=UTC)
+REPO_ROOT = Path(__file__).resolve().parents[4]
+
+SLACK_BOT = "xoxb-111-222-realistic"
+SLACK_APP = "xapp-1-A1-realistic"
+TELEGRAM = "123456789:AAH" + "x" * 32
+DISCORD = "discord-token-realistic"
+
+# Every integration off, so a value in the developer's shell or .env can't
+# leak into a check; each test turns on what it exercises.
+_ALL_OFF: dict[str, Any] = {
+ "ANTHROPIC_API_KEY": "sk-ant-api03-realistic",
+ "ANTHROPIC_WORKSPACE_ID": None,
+ "EXEC_EMAIL_ADDRESS": "[email protected]",
+ "OPENROUTER_ENABLED": False,
+ "LOCAL_MODELS_ENABLED": False,
+ "SLACK_BOT_TOKEN": None,
+ "SLACK_APP_TOKEN": None,
+ "TELEGRAM_BOT_TOKEN": None,
+ "TELEGRAM_WEBHOOK_SECRET": None,
+ "DISCORD_BOT_TOKEN": None,
+ "DISCORD_APP_ID": None,
+ "GOOGLE_CHAT_PROJECT_NUMBER": None,
+ "GOOGLE_CHAT_SERVICE_ACCOUNT_FILE": None,
+ "GOOGLE_CHAT_SERVICE_ACCOUNT_EMAIL": None,
+ "MCP_ENABLED": False,
+ "HONCHO_ENABLED": False,
+ "SCHEDULER_ENABLED": True,
+ "SCHEDULER_POLL_INTERVAL_SECONDS": 30,
+}
+
+
+def make_settings(**overrides: Any) -> Settings:
+ return Settings(**{**_ALL_OFF, **overrides})
+
+
+def make_snap(settings: Settings | None = None, **fields: Any) -> Snapshot:
+ values: dict[str, Any] = {
+ "settings": settings or make_settings(),
+ "now": NOW,
+ "local_login": False,
+ "people": [],
+ "principal": None,
+ "last_inbound": {},
+ }
+ values.update(fields)
+ return Snapshot(**values)
+
+
+def inbound(actor: str, summary: str, ts: str = "2026-09-25T11:50:00.000000Z") -> AuditEvent:
+ return AuditEvent(
+ id=1,
+ ts=ts,
+ event_type="integration_inbound",
+ session_id=None,
+ turn_id=None,
+ actor=actor,
+ summary=summary,
+ )
+
+
+class Recorder:
+ """An httpx transport that answers from a routing function and keeps
+ every request it saw."""
+
+ def __init__(self, route: Callable[[httpx.Request], httpx.Response]) -> None:
+ self.requests: list[httpx.Request] = []
+ self._route = route
+
+ def __call__(self, request: httpx.Request) -> httpx.Response:
+ self.requests.append(request)
+ return self._route(request)
+
+ def client(self) -> httpx.AsyncClient:
+ return httpx.AsyncClient(transport=httpx.MockTransport(self))
+
+
+def unreachable(request: httpx.Request) -> httpx.Response:
+ raise httpx.ConnectError("no route to host", request=request)
+
+
+def never_called(request: httpx.Request) -> httpx.Response:
+ raise AssertionError(f"unexpected request to {request.url.host}")
+
+
+def assert_no_secret(check: SetupCheck, *secrets: str) -> None:
+ text = check.model_dump_json()
+ for secret in secrets:
+ assert secret not in text
+
+
+# ---------------------------------------------------------------------------
+# AI model
+# ---------------------------------------------------------------------------
+
+
+class FakeAnthropic:
+ def __init__(self, error: BaseException | None = None) -> None:
+ self.error = error
+ self.closed = False
+ self.models = self
+
+ def with_options(self, **_: Any) -> FakeAnthropic:
+ return self
+
+ async def list(self, **_: Any) -> list[Any]:
+ if self.error is not None:
+ raise self.error
+ return []
+
+ async def close(self) -> None:
+ self.closed = True
+
+
+def _status_error(cls: type[anthropic.APIStatusError], status: int) -> anthropic.APIStatusError:
+ request = httpx.Request("GET", "https://api.anthropic.com/v1/models")
+ return cls(message="refused", response=httpx.Response(status, request=request), body=None)
+
+
+def fake_anthropic(monkeypatch: pytest.MonkeyPatch) -> Callable[[BaseException | None], FakeAnthropic]:
+ def install(error: BaseException | None = None) -> FakeAnthropic:
+ client = FakeAnthropic(error)
+ monkeypatch.setattr(
+ "openexecutive.providers.anthropic_provider.configured_async_client",
+ lambda **_: client,
+ )
+ return client
+
+ return install
+
+
+async def test_ai_model_connected(fake_anthropic: Callable[..., FakeAnthropic]) -> None:
+ client = fake_anthropic()
+ check = await check_ai_model(make_snap())
+ assert (check.state, check.summary) == ("ok", "Connected to Anthropic.")
+ assert client.closed
+
+
+async def test_ai_model_sample_key_is_red_without_a_call(monkeypatch: pytest.MonkeyPatch) -> None:
+ def boom(**_: Any) -> None:
+ raise AssertionError("the sample key must not be sent anywhere")
+
+ monkeypatch.setattr("openexecutive.providers.anthropic_provider.configured_async_client", boom)
+ check = await check_ai_model(make_snap(make_settings(ANTHROPIC_API_KEY="sk-ant-your-key-here")))
+ assert check.state == "error"
+ assert "sample value" in check.summary
+
+
+ ("error", "state", "phrase"),
+ [
+ (_status_error(anthropic.AuthenticationError, 401), "error", "turned down the key"),
+ (_status_error(anthropic.BadRequestError, 400), "error", "ANTHROPIC_WORKSPACE_ID"),
+ (_status_error(anthropic.PermissionDeniedError, 403), "error", "ANTHROPIC_WORKSPACE_ID"),
+ (_status_error(anthropic.RateLimitError, 429), "warn", "rate limit"),
+ (_status_error(anthropic.InternalServerError, 529), "warn", "HTTP 529"),
+ (
+ anthropic.APIConnectionError(request=httpx.Request("GET", "https://api.anthropic.com")),
+ "warn",
+ "Couldn't reach Anthropic",
+ ),
+ (TimeoutError(), "warn", "Couldn't reach Anthropic"),
+ ],
+)
+async def test_ai_model_failures(
+ fake_anthropic: Callable[..., FakeAnthropic], error: BaseException, state: str, phrase: str
+) -> None:
+ client = fake_anthropic(error)
+ check = await check_ai_model(make_snap())
+ assert check.state == state
+ assert phrase in f"{check.summary} {check.fix}"
+ assert client.closed
+ assert_no_secret(check, "sk-ant-api03-realistic")
+
+
+async def test_ai_model_bad_request_with_a_workspace_set_points_at_the_workspace(
+ fake_anthropic: Callable[..., FakeAnthropic],
+) -> None:
+ fake_anthropic(_status_error(anthropic.BadRequestError, 400))
+ check = await check_ai_model(make_snap(make_settings(ANTHROPIC_WORKSPACE_ID="wrk_1")))
+ assert check.state == "error"
+ assert "belongs to that workspace" in (check.fix or "")
+
+
+async def test_ai_model_without_anthropic_names_the_provider_in_use() -> None:
+ settings = make_settings(
+ ANTHROPIC_API_KEY=None, OPENROUTER_ENABLED=True, OPENROUTER_API_KEY="sk-or-realistic"
+ )
+ check = await check_ai_model(make_snap(settings))
+ assert check.state == "ok"
+ assert "OpenRouter" in check.summary
+
+
+# ---------------------------------------------------------------------------
+# Company, owner, the Executive's address, API protection
+# ---------------------------------------------------------------------------
+
+
+def test_exec_email() -> None:
+ assert check_exec_email(make_snap(make_settings(EXEC_EMAIL_ADDRESS="nobody"))).state == "error"
+ sample = check_exec_email(make_snap(make_settings(EXEC_EMAIL_ADDRESS="[email protected]")))
+ assert sample.state == "warn" and "sample address" in sample.summary
+ real = check_exec_email(make_snap())
+ assert (real.state, real.summary) == ("ok", "The Executive sends email as [email protected].")
+
+
+def test_is_example_email() -> None:
+ assert is_example_email("[email protected]")
+ assert is_example_email("[email protected]")
+ assert is_example_email("[email protected]")
+ assert not is_example_email("[email protected]")
+ assert not is_example_email("[email protected]")
+
+
+def test_company(tmp_path: Path) -> None:
+ profile = tmp_path / "profile.yaml"
+ missing = check_company(make_snap(make_settings(COMPANY_PROFILE_PATH=str(profile))))
+ assert (missing.state, missing.link) == ("warn", "/onboard")
+
+ profile.write_text("company:\n name: Acme Robotics\n", encoding="utf-8")
+ done = check_company(make_snap(make_settings(COMPANY_PROFILE_PATH=str(profile))))
+ assert (done.state, done.summary) == ("ok", "Set up for Acme Robotics.")
+
+
+def test_owner() -> None:
+ assert check_owner(make_snap()).link == "/onboard"
+
+ unlinked = Person(id=1, full_name="Ada Park", is_principal=True)
+ warn = check_owner(make_snap(principal=unlinked))
+ assert (warn.state, warn.link) == ("warn", "/people")
+ assert "owner-only actions will be refused" in warn.summary
+
+ # Local login signs in as the owner, so no email is needed.
+ assert check_owner(make_snap(principal=unlinked, local_login=True)).state == "ok"
+
+ linked = Person(id=1, full_name="Ada Park", is_principal=True, email="[email protected]")
+ assert check_owner(make_snap(principal=linked)).summary == "Ada Park ([email protected]) is the owner."
+
+
+def test_api_protection(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setenv("BACKEND_SHARED_SECRET", "s3cret-value")
+ protected = check_api_protection(make_snap())
+ assert protected.state == "ok"
+ assert_no_secret(protected, "s3cret-value")
+
+ monkeypatch.delenv("BACKEND_SHARED_SECRET")
+ assert check_api_protection(make_snap(local_login=True)).state == "ok"
+ assert check_api_protection(make_snap()).state == "warn"
+
+
+# ---------------------------------------------------------------------------
+# Slack
+# ---------------------------------------------------------------------------
+
+
+def slack_ok(request: httpx.Request) -> httpx.Response:
+ return httpx.Response(200, json={"ok": True, "team": "Acme HQ", "user": "exec"})
+
+
+def listening_handler(connected: bool = True) -> Any:
+ async def is_connected() -> bool:
+ return connected
+
+ return SimpleNamespace(client=SimpleNamespace(is_connected=is_connected))
+
+
+def slack_settings(**overrides: Any) -> Settings:
+ return make_settings(**{"SLACK_BOT_TOKEN": SLACK_BOT, "SLACK_APP_TOKEN": SLACK_APP, **overrides})
+
+
+async def test_slack_off_and_sample_tokens_make_no_call() -> None:
+ http = Recorder(never_called)
+ async with http.client() as client:
+ off = await check_slack(make_snap(), client)
+ sample = await check_slack(
+ make_snap(make_settings(SLACK_BOT_TOKEN="xoxb-your-bot-token", SLACK_APP_TOKEN="xapp-your-app-token")),
+ client,
+ )
+ wrong_kind = await check_slack(make_snap(slack_settings(SLACK_BOT_TOKEN="xoxp-user-token")), client)
+ wrong_app = await check_slack(make_snap(slack_settings(SLACK_APP_TOKEN="xoxb-not-an-app-token")), client)
+ assert off.state == "off"
+ assert sample.state == "error" and "sample tokens" in sample.summary
+ assert wrong_kind.state == "error" and "xoxb-" in wrong_kind.summary
+ assert wrong_app.state == "error" and "xapp-" in wrong_app.summary
+ assert http.requests == []
+
+
+async def test_slack_connected_and_listening() -> None:
+ http = Recorder(slack_ok)
+ ada = Person(id=1, full_name="Ada", slack_user_id="U1")
+ snap = make_snap(
+ slack_settings(),
+ slack_handler=listening_handler(),
+ people=[ada],
+ last_inbound={"slack": inbound("slack", "Inbound slack from user=U1 channel=D1: hello there")},
+ )
+ async with http.client() as client:
+ check = await check_slack(snap, client)
+ assert (check.state, check.summary) == ("ok", "Connected to Acme HQ and listening.")
+ assert check.last_activity == "2026-09-25T11:50:00.000000Z"
+ # Message content from the audit row never reaches the page.
+ assert "hello there" not in check.model_dump_json()
+ [request] = http.requests
+ assert request.url == "https://slack.com/api/auth.test"
+ assert request.headers["authorization"] == f"Bearer {SLACK_BOT}"
+ assert_no_secret(check, SLACK_BOT, SLACK_APP)
+
+
+async def test_slack_rejected_token_shows_only_a_clean_error_code() -> None:
+ async with Recorder(lambda r: httpx.Response(200, json={"ok": False, "error": "invalid_auth"})).client() as c:
+ check = await check_slack(make_snap(slack_settings()), c)
+ assert check.state == "error"
+ assert check.summary == "Slack turned down SLACK_BOT_TOKEN (invalid_auth)."
+
+ odd = {"ok": False, "error": "<script>alert(1)</script>"}
+ async with Recorder(lambda r: httpx.Response(200, json=odd)).client() as c:
+ check = await check_slack(make_snap(slack_settings()), c)
+ assert check.summary == "Slack turned down SLACK_BOT_TOKEN."
+
+
+async def test_slack_states_after_the_token_works() -> None:
+ async with Recorder(unreachable).client() as c:
+ assert (await check_slack(make_snap(slack_settings()), c)).state == "warn"
+ async with Recorder(slack_ok).client() as c:
+ send_only = await check_slack(make_snap(make_settings(SLACK_BOT_TOKEN=SLACK_BOT)), c)
+ not_started = await check_slack(make_snap(slack_settings()), c)
+ not_listening = await check_slack(
+ make_snap(slack_settings(), slack_handler=listening_handler(False)), c
+ )
+ assert send_only.state == "warn" and "won't hear messages" in send_only.summary
+ assert not_started.state == "error" and "didn't start" in not_started.summary
+ assert not_listening.state == "warn"
+
+
+async def test_slack_nobody_on_the_team_list_can_reach_it() -> None:
+ snap = make_snap(slack_settings(), slack_handler=listening_handler(), people=[Person(id=1, full_name="Ada")])
+ async with Recorder(slack_ok).client() as c:
+ check = await check_slack(snap, c)
+ assert (check.state, check.link) == ("warn", "/people")
+ assert "nobody on the team list has a Slack member ID" in check.summary
+
+
+async def test_slack_last_message_was_turned_away() -> None:
+ snap = make_snap(
+ slack_settings(),
+ slack_handler=listening_handler(),
+ people=[Person(id=1, full_name="Ada", slack_user_id="U1")],
+ last_inbound={"slack": inbound("slack", "Rejected: slack user=U999 not in People roster")},
+ )
+ async with Recorder(slack_ok).client() as c:
+ check = await check_slack(snap, c)
+ assert check.state == "warn"
+ assert "(from Slack member ID U999) was ignored" in check.summary
+
+
+ ("people_ids", "rejected_at"),
+ [
+ (["U1", "U999"], "2026-09-25T11:50:00.000000Z"), # the sender has since been added
+ (["U1"], "2026-09-23T11:50:00.000000Z"), # turned away days ago
+ ],
+)
+async def test_slack_turned_away_message_stops_warning(people_ids: list[str], rejected_at: str) -> None:
+ snap = make_snap(
+ slack_settings(),
+ slack_handler=listening_handler(),
+ people=[Person(id=i, full_name=f"P{i}", slack_user_id=uid) for i, uid in enumerate(people_ids, 1)],
+ last_inbound={"slack": inbound("slack", "Rejected: slack user=U999 not in People roster", rejected_at)},
+ )
+ async with Recorder(slack_ok).client() as c:
+ check = await check_slack(snap, c)
+ assert check.state == "ok"
+
+
+# ---------------------------------------------------------------------------
+# Discord
+# ---------------------------------------------------------------------------
+
+
+def failed_task(exc_name: str) -> asyncio.Future[None]:
+ future: asyncio.Future[None] = asyncio.get_running_loop().create_future()
+ future.set_exception(type(exc_name, (Exception,), {})())
+ return future
+
+
+async def test_discord_connected() -> None:
+ bot = SimpleNamespace(is_ready=lambda: True, user="exec-bot#0001", ws=SimpleNamespace(open=True))
+ snap = make_snap(
+ make_settings(DISCORD_BOT_TOKEN=DISCORD),
+ discord_bot=bot,
+ people=[Person(id=1, full_name="Ada", discord_user_id="42")],
+ )
+ async with Recorder(never_called).client() as c:
+ check = await check_discord(snap, c)
+ assert (check.state, check.summary) == ("ok", "Connected as exec-bot#0001.")
+
+
+async def test_discord_ready_but_reconnecting_is_not_green() -> None:
+ # discord.py keeps is_ready() through a dropped connection; the closed
+ # gateway socket is what says no messages can arrive.
+ bot = SimpleNamespace(is_ready=lambda: True, user="exec-bot#0001", ws=SimpleNamespace(open=False))
+ snap = make_snap(make_settings(DISCORD_BOT_TOKEN=DISCORD), discord_bot=bot)
+ async with Recorder(never_called).client() as c:
+ check = await check_discord(snap, c)
+ assert check.state == "warn" and "reconnecting" in check.summary
+
+
+ ("exc_name", "phrase"),
+ [
+ ("LoginFailure", "turned down DISCORD_BOT_TOKEN"),
+ ("PrivilegedIntentsRequired", "Message Content intent"),
+ ("GatewayNotFound", "stopped (GatewayNotFound)"),
+ ],
+)
+async def test_discord_stopped(exc_name: str, phrase: str) -> None:
+ bot = SimpleNamespace(is_ready=lambda: False, user=None)
+ snap = make_snap(
+ make_settings(DISCORD_BOT_TOKEN=DISCORD), discord_bot=bot, discord_bot_task=failed_task(exc_name)
+ )
+ async with Recorder(never_called).client() as c:
+ check = await check_discord(snap, c)
+ assert check.state == "error"
+ assert phrase in check.summary
+
+
+async def test_discord_stopped_task_wins_over_a_stale_ready_flag() -> None:
+ bot = SimpleNamespace(is_ready=lambda: True, user="exec-bot#0001", ws=SimpleNamespace(open=True))
+ snap = make_snap(
+ make_settings(DISCORD_BOT_TOKEN=DISCORD), discord_bot=bot, discord_bot_task=failed_task("LoginFailure")
+ )
+ async with Recorder(never_called).client() as c:
+ check = await check_discord(snap, c)
+ assert check.state == "error" and "turned down DISCORD_BOT_TOKEN" in check.summary
+
+
+async def test_discord_task_that_ended_without_an_error_is_stopped() -> None:
+ finished: asyncio.Future[None] = asyncio.get_running_loop().create_future()
+ finished.set_result(None)
+ bot = SimpleNamespace(is_ready=lambda: False, user=None)
+ snap = make_snap(make_settings(DISCORD_BOT_TOKEN=DISCORD), discord_bot=bot, discord_bot_task=finished)
+ async with Recorder(never_called).client() as c:
+ check = await check_discord(snap, c)
+ assert (check.state, check.summary) == ("error", "The Discord bot stopped.")
+
+
+async def test_discord_still_connecting_tests_the_token() -> None:
+ settings = make_settings(DISCORD_BOT_TOKEN=DISCORD)
+ bot = SimpleNamespace(is_ready=lambda: False, user=None)
+ rejected = Recorder(lambda r: httpx.Response(401, json={"message": "401: Unauthorized"}))
+ async with rejected.client() as c:
+ check = await check_discord(make_snap(settings, discord_bot=bot), c)
+ assert check.state == "error" and "turned down" in check.summary
+ assert rejected.requests[0].headers["authorization"] == f"Bot {DISCORD}"
+ assert_no_secret(check, DISCORD)
+
+ async with Recorder(lambda r: httpx.Response(200, json={"id": "1"})).client() as c:
+ assert (await check_discord(make_snap(settings, discord_bot=bot), c)).state == "warn"
+ async with Recorder(unreachable).client() as c:
+ assert (await check_discord(make_snap(settings, discord_bot=bot), c)).state == "warn"
+
+
+async def test_discord_off_or_never_started() -> None:
+ async with Recorder(never_called).client() as c:
+ assert (await check_discord(make_snap(), c)).state == "off"
+ never = await check_discord(make_snap(make_settings(DISCORD_BOT_TOKEN=DISCORD)), c)
+ assert never.state == "error" and "didn't start" in never.summary
+
+
+# ---------------------------------------------------------------------------
+# Telegram
+# ---------------------------------------------------------------------------
+
+
+def telegram(webhook: dict[str, Any], me: dict[str, Any] | None = None) -> Recorder:
+ def route(request: httpx.Request) -> httpx.Response:
+ if request.url.path.endswith("/getMe"):
+ return httpx.Response(200, json=me or {"ok": True, "result": {"username": "acme_exec_bot"}})
+ return httpx.Response(200, json={"ok": True, "result": webhook})
+
+ return Recorder(route)
+
+
+GOOD_HOOK = {"url": "https://exec.acme.io/webhook/telegram", "pending_update_count": 0}
+
+
+def telegram_settings(**overrides: Any) -> Settings:
+ return make_settings(
+ **{"TELEGRAM_BOT_TOKEN": TELEGRAM, "TELEGRAM_WEBHOOK_SECRET": "hook-secret", **overrides}
+ )
+
+
+async def test_telegram_receiving() -> None:
+ http = telegram(GOOD_HOOK)
+ snap = make_snap(telegram_settings(), people=[Person(id=1, full_name="Ada", telegram_chat_id="7")])
+ async with http.client() as c:
+ check = await check_telegram(snap, c)
+ assert (check.state, check.summary) == ("ok", "@acme_exec_bot is receiving messages.")
+ assert [r.url.path for r in http.requests] == [f"/bot{TELEGRAM}/getMe", f"/bot{TELEGRAM}/getWebhookInfo"]
+ assert_no_secret(check, TELEGRAM, "hook-secret")
+
+
+async def test_telegram_bad_token_is_never_put_in_a_url() -> None:
+ http = Recorder(never_called)
+ async with http.client() as c:
+ malformed = await check_telegram(make_snap(make_settings(TELEGRAM_BOT_TOKEN="1:abc/../x")), c)
+ assert malformed.state == "error" and "isn't a Telegram bot token" in malformed.summary
+ assert http.requests == []
+
+
+async def test_telegram_local_login_needs_the_secret() -> None:
+ async with Recorder(never_called).client() as c:
+ check = await check_telegram(
+ make_snap(make_settings(TELEGRAM_BOT_TOKEN=TELEGRAM), local_login=True), c
+ )
+ assert check.state == "error" and "Local login" in check.summary
+
+
+ ("hook", "state", "phrase"),
+ [
+ ({"url": ""}, "warn", "doesn't know where to deliver"),
+ ({"url": "https://other.example/bot"}, "warn", "isn't this app's /webhook/telegram"),
+ (
+ {**GOOD_HOOK, "last_error_date": int(NOW.timestamp()) - 60, "last_error_message": "Wrong response from the webhook: 401 Unauthorized"},
+ "warn",
+ "couldn't deliver @acme_exec_bot's last message: Wrong response from the webhook: 401 Unauthorized",
+ ),
+ ],
+)
+async def test_telegram_delivery_problems(hook: dict[str, Any], state: str, phrase: str) -> None:
+ snap = make_snap(telegram_settings(), people=[Person(id=1, full_name="Ada", telegram_chat_id="7")])
+ async with telegram(hook).client() as c:
+ check = await check_telegram(snap, c)
+ assert check.state == state
+ assert phrase in check.summary
+
+
+async def test_telegram_odd_answers_do_not_crash_the_check() -> None:
+ odd = Recorder(lambda r: httpx.Response(200, json={"ok": True, "result": "not an object"}))
+ async with odd.client() as c:
+ check = await check_telegram(make_snap(telegram_settings()), c)
+ assert check.state == "warn" and "The bot works" in check.summary
+
+
+async def test_telegram_old_delivery_error_is_ignored() -> None:
+ old = {**GOOD_HOOK, "last_error_date": int((NOW - timedelta(days=3)).timestamp()), "last_error_message": "old"}
+ snap = make_snap(telegram_settings(), people=[Person(id=1, full_name="Ada", telegram_chat_id="7")])
+ async with telegram(old).client() as c:
+ assert (await check_telegram(snap, c)).state == "ok"
+
+
+async def test_telegram_rejected_token_and_missing_secret() -> None:
+ async with telegram(GOOD_HOOK, me={"ok": False, "error_code": 401}).client() as c:
+ rejected = await check_telegram(make_snap(telegram_settings()), c)
+ assert rejected.state == "error" and "turned down" in rejected.summary
+
+ snap = make_snap(make_settings(TELEGRAM_BOT_TOKEN=TELEGRAM))
+ async with telegram(GOOD_HOOK).client() as c:
+ open_hook = await check_telegram(snap, c)
+ assert open_hook.state == "warn" and "fake ones" in open_hook.summary
+
+
+# ---------------------------------------------------------------------------
+# Google Chat and Gmail
+# ---------------------------------------------------------------------------
+
+
+def test_google_chat(tmp_path: Path) -> None:
+ assert check_google_chat(make_snap()).state == "off"
+
+ def chat(**overrides: Any) -> SetupCheck:
+ return check_google_chat(make_snap(make_settings(**overrides)))
+
+ assert "digits only" in chat(GOOGLE_CHAT_PROJECT_NUMBER="my-project").summary
+ assert "no service account" in chat(GOOGLE_CHAT_PROJECT_NUMBER="1234").summary
+ missing = chat(GOOGLE_CHAT_PROJECT_NUMBER="1234", GOOGLE_CHAT_SERVICE_ACCOUNT_FILE=str(tmp_path / "nope.json"))
+ assert missing.state == "error"
+
+ key = tmp_path / "sa.json"
+ key.write_text(json.dumps({"type": "service_account", "client_email": "[email protected]"}))
+ assert chat(GOOGLE_CHAT_PROJECT_NUMBER="1234", GOOGLE_CHAT_SERVICE_ACCOUNT_FILE=str(key)).state == "ok"
+ assert chat(GOOGLE_CHAT_PROJECT_NUMBER="1234", GOOGLE_CHAT_SERVICE_ACCOUNT_EMAIL="[email protected]").state == "ok"
+
+ key.write_text("not json")
+ assert chat(GOOGLE_CHAT_PROJECT_NUMBER="1234", GOOGLE_CHAT_SERVICE_ACCOUNT_FILE=str(key)).state == "error"
+
+
+def gmail_settings(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Settings:
+ config = tmp_path / "mcp_servers.json"
+ config.write_text(json.dumps({"mcpServers": {"google_workspace": {"command": "true"}}}))
+ for var in ("GWORKSPACE_AUTH_MODE", "GOOGLE_SERVICE_ACCOUNT_KEY_JSON", "GOOGLE_SERVICE_ACCOUNT_KEY_FILE"):
+ monkeypatch.delenv(var, raising=False)
+ monkeypatch.setenv("GOOGLE_OAUTH_CLIENT_ID", "id.apps.googleusercontent.com")
+ monkeypatch.setenv("GOOGLE_OAUTH_CLIENT_SECRET", "oauth-secret")
+ return make_settings(MCP_ENABLED=True, MCP_SERVERS_CONFIG_PATH=str(config))
+
+
+def test_gmail_connected(gmail_settings: Settings) -> None:
+ fresh = check_gmail(make_snap(gmail_settings, mcp_gateway=object()))
+ assert fresh.state == "ok"
+ assert "[email protected]'s inbox" in fresh.summary and "No email has come in yet" in fresh.summary
+
+ seen = check_gmail(
+ make_snap(gmail_settings, mcp_gateway=object(), last_inbound={"email": inbound("email", "Inbound email")})
+ )
+ assert "No email has come in yet" not in seen.summary
+ assert seen.last_activity is not None
+ assert_no_secret(seen, "oauth-secret")
+
+
+def test_gmail_problems(gmail_settings: Settings, monkeypatch: pytest.MonkeyPatch) -> None:
+ assert check_gmail(make_snap()).state == "off"
+ assert "didn't start" in check_gmail(make_snap(gmail_settings)).summary
+
+ monkeypatch.delenv("GOOGLE_OAUTH_CLIENT_SECRET")
+ no_oauth = check_gmail(make_snap(gmail_settings, mcp_gateway=object()))
+ assert no_oauth.state == "error" and "GOOGLE_OAUTH_CLIENT_SECRET" in no_oauth.summary
+
+ monkeypatch.setenv("GWORKSPACE_AUTH_MODE", "service_account")
+ assert "GOOGLE_SERVICE_ACCOUNT_KEY_JSON" in check_gmail(make_snap(gmail_settings, mcp_gateway=object())).summary
+ monkeypatch.setenv("GOOGLE_SERVICE_ACCOUNT_KEY_FILE", "/keys/sa.json")
+ assert check_gmail(make_snap(gmail_settings, mcp_gateway=object())).state == "ok"
+
+
+# ---------------------------------------------------------------------------
+# Scheduler and memory
+# ---------------------------------------------------------------------------
+
+
+def heartbeat(monkeypatch: pytest.MonkeyPatch) -> Callable[..., None]:
+ monkeypatch.setattr(
+ "openexecutive.scheduler.pause.get_pause_state", lambda: SimpleNamespace(paused=False)
+ )
+
+ def set_beat(started: datetime | None, tick: tuple[datetime, str] | None = None) -> None:
+ monkeypatch.setattr("openexecutive.scheduler.runner.scheduler_heartbeat", lambda: (started, tick))
+
+ return set_beat
+
+
+ ("started", "tick", "state", "phrase"),
+ [
+ (None, None, "error", "isn't running"),
+ (NOW - timedelta(seconds=20), None, "warn", "Starting up"),
+ (NOW - timedelta(minutes=10), None, "error", "10 minutes ago but hasn't finished"),
+ (NOW - timedelta(hours=1), (NOW - timedelta(minutes=5), "ran"), "error", "last check was 5 minutes ago"),
+ (NOW - timedelta(hours=1), (NOW - timedelta(seconds=10), "failed"), "error", "hit an error"),
+ (NOW - timedelta(hours=1), (NOW - timedelta(seconds=10), "waiting_for_company"), "warn", "Waiting for company"),
+ (NOW - timedelta(hours=1), (NOW - timedelta(seconds=10), "ran"), "ok", "Running."),
+ (NOW - timedelta(hours=1), (NOW - timedelta(seconds=10), "rotating"), "ok", "Running."),
+ ],
+)
+def test_scheduler(
+ heartbeat: Callable[..., None],
+ started: datetime | None,
+ tick: tuple[datetime, str] | None,
+ state: str,
+ phrase: str,
+) -> None:
+ heartbeat(started, tick)
+ check = check_scheduler(make_snap())
+ assert check.state == state
+ assert phrase in check.summary
+
+
+def test_scheduler_off_and_paused(heartbeat: Callable[..., None], monkeypatch: pytest.MonkeyPatch) -> None:
+ heartbeat(NOW, (NOW, "paused"))
+ assert check_scheduler(make_snap(make_settings(SCHEDULER_ENABLED=False))).state == "off"
+ monkeypatch.setattr("openexecutive.scheduler.pause.get_pause_state", lambda: SimpleNamespace(paused=True))
+ paused = check_scheduler(make_snap())
+ assert paused.state == "warn" and "Resume" in (paused.fix or "")
+
+ # Paused and dead: Resume wouldn't help, so say it has stopped.
+ heartbeat(NOW - timedelta(hours=1), (NOW - timedelta(minutes=30), "paused"))
+ dead = check_scheduler(make_snap())
+ assert dead.state == "error" and "has stopped" in dead.summary
+
+
+def test_scheduler_stale_window_follows_the_poll_interval(heartbeat: Callable[..., None]) -> None:
+ # A 5-minute poll interval: four minutes of silence is just between ticks.
+ heartbeat(NOW - timedelta(hours=1), (NOW - timedelta(minutes=4), "ran"))
+ slow = make_settings(SCHEDULER_POLL_INTERVAL_SECONDS=300)
+ assert check_scheduler(make_snap(slow)).state == "ok"
+
+
+ ("probe", "state"),
+ [
+ ({"status": "disabled"}, "off"),
+ ({"status": "ok", "latency_ms": 12}, "ok"),
+ ({"status": "error", "error_type": "TimeoutError", "error_msg": "key=hk-secret expired"}, "error"),
+ ],
+)
+async def test_memory(monkeypatch: pytest.MonkeyPatch, probe: dict[str, Any], state: str) -> None:
+ async def honcho_health() -> dict[str, Any]:
+ return probe
+
+ monkeypatch.setattr("openexecutive.api.routes.health.honcho_health", honcho_health)
+ check = await check_memory(make_snap())
+ assert check.state == state
+ # Only the error's class name is shown, never its message.
+ assert_no_secret(check, "hk-secret")
+
+
+# ---------------------------------------------------------------------------
+# Running them all, and the route
+# ---------------------------------------------------------------------------
+
+
+def check_logs() -> Iterator[list[str]]:
+ """Messages logged by api/setup_checks.py. ``caplog`` listens on the
+ root logger and would miss them once another test has run
+ ``main._configure_logging``, which stops the ``openexecutive`` tree
+ propagating — so this attaches to the module's logger directly."""
+ messages: list[str] = []
+
+ class Collect(logging.Handler):
+ def emit(self, record: logging.LogRecord) -> None:
+ messages.append(record.getMessage())
+
+ handler = Collect(level=logging.INFO)
+ setup_logger = logging.getLogger(setup_checks.__name__)
+ setup_logger.addHandler(handler)
+ try:
+ yield messages
+ finally:
+ setup_logger.removeHandler(handler)
+
+
+async def test_run_checks_keeps_order_and_contains_a_crash(
+ monkeypatch: pytest.MonkeyPatch,
+ fake_anthropic: Callable[..., FakeAnthropic],
+ heartbeat: Callable[..., None],
+ check_logs: list[str],
+) -> None:
+ fake_anthropic()
+ heartbeat(NOW - timedelta(minutes=5), (NOW, "ran"))
+
+ async def honcho_health() -> dict[str, Any]:
+ return {"status": "disabled"}
+
+ monkeypatch.setattr("openexecutive.api.routes.health.honcho_health", honcho_health)
+
+ def explode(snap: Snapshot) -> SetupCheck:
+ raise RuntimeError("token=abc123 leaked into a message")
+
+ monkeypatch.setattr(setup_checks, "check_company", explode)
+ async with Recorder(never_called).client() as c:
+ checks = await run_checks(make_snap(), c)
+ assert [c.id for c in checks] == list(LABELS)
+ company = checks[list(LABELS).index("company")]
+ assert (company.state, company.summary) == ("error", "This check couldn't run.")
+ assert check_logs == ["setup status: the company check crashed (RuntimeError)"]
+ assert all(c.label == LABELS[c.id] for c in checks)
+
+
+def route_calls(monkeypatch: pytest.MonkeyPatch) -> list[Snapshot]:
+ for var in ("OE_LOCAL_LOGIN", "OE_PUBLIC_DEPLOYMENT", "BACKEND_SHARED_SECRET"):
+ monkeypatch.delenv(var, raising=False)
+ calls: list[Snapshot] = []
+
+ def gather(settings: Settings, *, local_login: bool, app_state: Any) -> Snapshot:
+ return make_snap(settings, local_login=local_login)
+
+ async def run(snap: Snapshot, http: httpx.AsyncClient) -> list[SetupCheck]:
+ calls.append(snap)
+ return [SetupCheck(id="ai_model", label="AI model", state="ok", summary="Connected to Anthropic.")]
+
+ monkeypatch.setattr(setup_route, "gather_snapshot", gather)
+ monkeypatch.setattr(setup_route, "run_checks", run)
+ return calls
+
+
+def test_route_answers_and_reuses_a_recent_run(
+ route_calls: list[Snapshot], monkeypatch: pytest.MonkeyPatch
+) -> None:
+ from openexecutive.api.main import create_app
+
+ client = TestClient(create_app())
+ first = client.get("/setup/status")
+ assert first.status_code == 200
+ body = first.json()
+ assert body["checks"] == [
+ {
+ "id": "ai_model",
+ "label": "AI model",
+ "state": "ok",
+ "summary": "Connected to Anthropic.",
+ "fix": None,
+ "link": None,
+ "last_activity": None,
+ }
+ ]
+ assert datetime.fromisoformat(body["checked_at"]) == NOW
+ assert client.get("/setup/status").json() == body
+ assert len(route_calls) == 1
+
+ monkeypatch.setattr(setup_route, "_REUSE_FOR_S", 0.0)
+ client.get("/setup/status")
+ assert len(route_calls) == 2
+
+
+def test_route_runs_are_kept_per_app(route_calls: list[Snapshot]) -> None:
+ from openexecutive.api.main import create_app
+
+ TestClient(create_app()).get("/setup/status")
+ TestClient(create_app()).get("/setup/status")
+ assert len(route_calls) == 2
+
+
+def test_route_needs_the_shared_secret_when_one_is_set(
+ route_calls: list[Snapshot], monkeypatch: pytest.MonkeyPatch
+) -> None:
+ from openexecutive.api.main import create_app
+
+ monkeypatch.setenv("BACKEND_SHARED_SECRET", "s3cret")
+ client = TestClient(create_app())
+ assert client.get("/setup/status").status_code == 401
+ assert client.get("/setup/status", headers={"x-api-key": "s3cret"}).status_code == 200
+ assert len(route_calls) == 1
+
+
+def test_route_passes_local_login_through(route_calls: list[Snapshot], monkeypatch: pytest.MonkeyPatch) -> None:
+ from openexecutive.api.main import create_app
+
+ monkeypatch.setenv("OE_LOCAL_LOGIN", "1")
+ TestClient(create_app()).get("/setup/status", headers={"host": "localhost:8000"})
+ assert route_calls[0].local_login is True
+
+
+# ---------------------------------------------------------------------------
+# .env.example and the settings that read it
+# ---------------------------------------------------------------------------
+
+
+def test_env_example_has_no_value_that_is_really_a_comment() -> None:
+ values = dotenv_values(REPO_ROOT / ".env.example")
+ assert values, ".env.example not found"
+ comments = {key: value for key, value in values.items() if value and value.lstrip().startswith("#")}
+ assert comments == {}
+
+
+def test_env_example_samples_are_recognised() -> None:
+ values = dotenv_values(REPO_ROOT / ".env.example")
+ for key in ("ANTHROPIC_API_KEY", "SLACK_BOT_TOKEN", "SLACK_APP_TOKEN"):
+ sample = values.get(key)
+ assert not sample or sample in EXAMPLE_VALUES, f"{key}={sample!r} is a sample the checks don't know"
+ assert is_example_email(values["EXEC_EMAIL_ADDRESS"] or "")
+
+
+ "field",
+ [
+ "TELEGRAM_BOT_TOKEN",
+ "SLACK_BOT_TOKEN",
+ "SLACK_APP_TOKEN",
+ "DISCORD_BOT_TOKEN",
+ "DISCORD_APP_ID",
+ "GOOGLE_CHAT_PROJECT_NUMBER",
+ "GOOGLE_CHAT_SERVICE_ACCOUNT_FILE",
+ "GOOGLE_CHAT_SERVICE_ACCOUNT_EMAIL",
+ ],
+)
+def test_a_comment_left_as_a_value_means_unset(field: str) -> None:
+ settings = make_settings(**{field: "# from @BotFather"})
+ assert getattr(settings, field.lower()) is None
+ assert getattr(make_settings(**{field: "real-value"}), field.lower()) == "real-value"
+
+
+async def test_telegram_secret_telegram_would_refuse_is_red() -> None:
+ settings = make_settings(TELEGRAM_BOT_TOKEN=TELEGRAM, TELEGRAM_WEBHOOK_SECRET="# from step 2")
+ async with Recorder(never_called).client() as c:
+ check = await check_telegram(make_snap(settings), c)
+ assert check.state == "error" and "characters Telegram won't accept" in check.summary
+ assert_no_secret(check, "# from step 2")
+
+
+def test_a_comment_value_read_from_a_dotenv_file_means_unset(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ monkeypatch.delenv("TELEGRAM_BOT_TOKEN", raising=False)
+ env_file = tmp_path / ".env"
+ env_file.write_text("TELEGRAM_BOT_TOKEN= # from @BotFather\n", encoding="utf-8")
+ others = {k: v for k, v in _ALL_OFF.items() if k != "TELEGRAM_BOT_TOKEN"}
+ settings = Settings(_env_file=str(env_file), **others) # type: ignore[call-arg]
+ assert settings.telegram_bot_token is None
+
+
+# ---------------------------------------------------------------------------
+# The scheduler's heartbeat
+# ---------------------------------------------------------------------------
+
+
+def scheduler_loop(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> dict[str, Any]:
+ """run_scheduler against a throwaway DB, with its tick reduced to the
+ parts the heartbeat reports on. Returns knobs the test can turn."""
+ from openexecutive.memory import episodic
+ from openexecutive.scheduler import pause, runner
+
+ db = tmp_path / "episodic.db"
+ monkeypatch.setattr(episodic, "DB_PATH", db)
+ episodic.initialize_db(db)
+ monkeypatch.setattr("openexecutive.audit.log_event", lambda *a, **k: None)
+ monkeypatch.setattr(pause, "_read_failing", False)
+ monkeypatch.setattr(runner, "_started_at", None)
+ monkeypatch.setattr(runner, "_last_tick", None)
+ knobs: dict[str, Any] = {"company": True, "claim_error": None}
+
+ def claim(now: datetime) -> list[Any]:
+ if knobs["claim_error"] is not None:
+ raise knobs["claim_error"]
+ return []
+
+ monkeypatch.setattr(runner, "claim_due_actions", claim)
+ monkeypatch.setattr(runner, "_maybe_sweep_alerts", lambda now: 0)
+ monkeypatch.setattr(runner, "_company_profile_active", lambda: knobs["company"])
+ monkeypatch.setattr(runner, "seed_principal_briefs", lambda: 0)
+ return knobs
+
+
+async def _one_tick() -> tuple[datetime | None, tuple[datetime, str] | None]:
+ from openexecutive.scheduler.runner import run_scheduler, scheduler_heartbeat
+
+ task = asyncio.create_task(run_scheduler(gateway=None, poll_interval_seconds=60))
+ await asyncio.sleep(0.1)
+ task.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await task
+ return scheduler_heartbeat()
+
+
+ ("knob", "value", "outcome"),
+ [
+ (None, None, "ran"),
+ ("company", False, "waiting_for_company"),
+ ("claim_error", RuntimeError("db locked"), "failed"),
+ ],
+)
+async def test_every_tick_records_itself(
+ scheduler_loop: dict[str, Any], knob: str | None, value: Any, outcome: str
+) -> None:
+ if knob is not None:
+ scheduler_loop[knob] = value
+ started, tick = await _one_tick()
+ assert started is not None
+ assert tick is not None and tick[1] == outcome
+ assert started <= tick[0] <= datetime.now(UTC)
+
+
+async def test_a_restart_forgets_the_last_run_s_tick(
+ scheduler_loop: dict[str, Any], monkeypatch: pytest.MonkeyPatch
+) -> None:
+ from openexecutive.scheduler import runner
+
+ monkeypatch.setattr(runner, "_last_tick", (datetime(2020, 1, 1, tzinfo=UTC), "ran"))
+ seen_at_boot: list[Any] = []
+
+ def requeue() -> int:
+ seen_at_boot.append(runner.scheduler_heartbeat()[1])
+ return 0
+
+ monkeypatch.setattr(runner, "requeue_orphaned_running", requeue)
+ await _one_tick()
+ assert seen_at_boot == [None]
+
+
+async def test_a_paused_tick_records_itself(scheduler_loop: dict[str, Any]) -> None:
+ from openexecutive.scheduler import pause
+
+ pause.pause("[email protected]")
+ _, tick = await _one_tick()
+ assert tick is not None and tick[1] == "paused"
diff --git a/packages/core/tests/unit/test_telegram_webhook_secret.py b/packages/core/tests/unit/test_telegram_webhook_secret.py
new file mode 100644
index 00000000..cd5b3879
--- /dev/null
+++ b/packages/core/tests/unit/test_telegram_webhook_secret.py
@@ -0,0 +1,77 @@
+"""TELEGRAM_WEBHOOK_SECRET verifies an update only when Telegram could send it.
+
+setWebhook accepts a secret of 1–256 ``A-Z a-z 0-9 _ -``, so any other value
+— a ``# note`` left in .env, a pasted ``<value from Step 2>`` — can only be
+matched by someone who guessed it. With such a secret the webhook refuses
+every update, and nothing treats a Telegram message as verified.
+"""
+
+from __future__ import annotations
+
+import pytest
+from fastapi.testclient import TestClient
+
+from openexecutive.api.main import _webhook_verifies_its_caller, create_app
+from openexecutive.config import get_settings
+
+TOKEN = "123456789:AAH" + "x" * 32
+HEADER = "X-Telegram-Bot-Api-Secret-Token"
+
+
[email protected](autouse=True)
+def _telegram_on(monkeypatch: pytest.MonkeyPatch) -> None:
+ for var in ("OE_LOCAL_LOGIN", "OE_PUBLIC_DEPLOYMENT", "BACKEND_SHARED_SECRET"):
+ monkeypatch.delenv(var, raising=False)
+ monkeypatch.setenv("TELEGRAM_BOT_TOKEN", TOKEN)
+
+
+def _post(secret: str, header: str | None) -> int:
+ headers = {HEADER: header} if header is not None else {}
+ # An empty update: past the secret check it is ignored with a 200.
+ return TestClient(create_app()).post("/webhook/telegram", json={}, headers=headers).status_code
+
+
+ ("secret", "valid"),
+ [
+ ("", False),
+ ("hook-secret_42", True),
+ ("x" * 256, True),
+ ("x" * 257, False),
+ ("# from step 2", False),
+ ("<value from Step 2>", False),
+ ("sécret", False),
+ ],
+)
+def test_only_a_secret_telegram_can_send_is_valid(
+ monkeypatch: pytest.MonkeyPatch, secret: str, valid: bool
+) -> None:
+ monkeypatch.setenv("TELEGRAM_WEBHOOK_SECRET", secret)
+ assert get_settings().telegram_webhook_secret_valid is valid
+ assert _webhook_verifies_its_caller("/webhook/telegram") is valid
+
+
+def test_a_valid_secret_admits_only_the_matching_header(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setenv("TELEGRAM_WEBHOOK_SECRET", "hook-secret")
+ assert _post("hook-secret", "hook-secret") == 200
+ assert _post("hook-secret", "guess") == 401
+ assert _post("hook-secret", None) == 401
+
+
[email protected]("secret", ["# from step 2", "<value from Step 2>", "sécret"])
+def test_a_secret_telegram_cannot_send_refuses_even_a_matching_header(
+ monkeypatch: pytest.MonkeyPatch, secret: str
+) -> None:
+ # A comment left as the value is kept rather than read as unset (which
+ # would switch the check off), and matching it proves only a guess.
+ monkeypatch.setenv("TELEGRAM_WEBHOOK_SECRET", secret)
+ assert get_settings().telegram_webhook_secret == secret
+ header = secret if secret.isascii() else "guess"
+ assert _post(secret, header) == 401
+
+
+def test_no_secret_still_accepts_updates(monkeypatch: pytest.MonkeyPatch) -> None:
+ # Unchanged: without a secret the webhook can't tell Telegram from anyone
+ # else, which Setup status reports amber.
+ monkeypatch.setenv("TELEGRAM_WEBHOOK_SECRET", "")
+ assert _post("", None) == 200
diff --git a/packages/ui/scripts/setupStatus.test.mjs b/packages/ui/scripts/setupStatus.test.mjs
new file mode 100644
index 00000000..c5f0e2d3
--- /dev/null
+++ b/packages/ui/scripts/setupStatus.test.mjs
@@ -0,0 +1,97 @@
+import assert from "node:assert/strict";
+import { readFileSync } from "node:fs";
+import test from "node:test";
+import { parseAllowedEmails } from "../src/lib/allowlist.ts";
+import {
+ EXAMPLE_EMAIL_DOMAINS,
+ formatAgo,
+ isExampleEmail,
+ safeInAppLink,
+ signInCheck,
+ sortChecks,
+} from "../src/lib/setupStatus.ts";
+
+const GOOGLE = {
+ localLogin: false,
+ googleClientId: "id.apps.googleusercontent.com",
+ googleClientSecret: "google-secret",
+ allowedEmails: parseAllowedEmails("[email protected], [email protected]"),
+ authUrl: "https://exec.acme.io",
+ publicDeployment: true,
+};
+
+test("local login needs nothing else", () => {
+ const check = signInCheck({ ...GOOGLE, localLogin: true, googleClientId: undefined, googleClientSecret: undefined });
+ assert.equal(check.state, "ok");
+ assert.match(check.summary, /Local login/);
+});
+
+test("Google sign-in with a real allow-list is green", () => {
+ const check = signInCheck(GOOGLE);
+ assert.equal(check.state, "ok");
+ assert.match(check.summary, /the 2 addresses in ALLOWED_EMAILS/);
+ assert.ok(!JSON.stringify(check).includes("google-secret"));
+ const rosterOnly = signInCheck({ ...GOOGLE, allowedEmails: new Set() });
+ assert.equal(rosterOnly.summary, "Google sign-in, for anyone with an email on the team list.");
+});
+
+test("half-configured Google sign-in is red", () => {
+ assert.equal(signInCheck({ ...GOOGLE, googleClientSecret: " " }).state, "error");
+ assert.equal(signInCheck({ ...GOOGLE, googleClientId: undefined }).state, "error");
+});
+
+test("sample addresses left in ALLOWED_EMAILS are named", () => {
+ const check = signInCheck({ ...GOOGLE, allowedEmails: parseAllowedEmails("[email protected],[email protected]") });
+ assert.equal(check.state, "warn");
+ assert.equal(check.summary, "ALLOWED_EMAILS still lists sample addresses: [email protected].");
+});
+
+test("a public deployment without AUTH_URL is amber", () => {
+ assert.equal(signInCheck({ ...GOOGLE, authUrl: "" }).state, "warn");
+ assert.equal(signInCheck({ ...GOOGLE, authUrl: "", publicDeployment: false }).state, "ok");
+});
+
+test("a fresh copy of .env.example is caught", () => {
+ const example = readFileSync(new URL("../../../.env.example", import.meta.url), "utf8");
+ const line = /^ALLOWED_EMAILS=(.*)$/m.exec(example);
+ assert.ok(line, "ALLOWED_EMAILS not found in .env.example");
+ const samples = parseAllowedEmails(line[1]);
+ assert.ok(samples.size > 0);
+ for (const email of samples) assert.ok(isExampleEmail(email), email);
+});
+
+test("the API flags exactly the same sample email domains", () => {
+ const py = readFileSync(new URL("../../core/openexecutive/api/setup_checks.py", import.meta.url), "utf8");
+ const literal = /_EXAMPLE_EMAIL_DOMAINS = frozenset\(\{([^}]*)\}\)/.exec(py);
+ assert.ok(literal, "_EXAMPLE_EMAIL_DOMAINS not found in api/setup_checks.py");
+ const apiValues = [...literal[1].matchAll(/"([^"]*)"/g)].map((m) => m[1]);
+ assert.deepEqual([...EXAMPLE_EMAIL_DOMAINS].sort(), apiValues.sort());
+});
+
+test("worst lights come first, otherwise in arrival order", () => {
+ const light = (id, state) => ({ id, label: id, state, summary: "", fix: null, link: null, last_activity: null });
+ const sorted = sortChecks([light("a", "ok"), light("b", "off"), light("c", "warn"), light("d", "error"), light("e", "ok")]);
+ assert.deepEqual(
+ sorted.map((c) => c.id),
+ ["d", "c", "a", "e", "b"],
+ );
+});
+
+test("formatAgo", () => {
+ const now = new Date("2026-09-25T12:00:00Z");
+ assert.equal(formatAgo("2026-09-25T11:59:30Z", now), "less than a minute ago");
+ assert.equal(formatAgo("2026-09-25T11:59:00Z", now), "1 minute ago");
+ assert.equal(formatAgo("2026-09-25T11:15:00Z", now), "45 minutes ago");
+ assert.equal(formatAgo("2026-09-25T10:00:00Z", now), "2 hours ago");
+ assert.equal(formatAgo("2026-09-21T12:00:00Z", now), "4 days ago");
+ assert.equal(formatAgo("2026-09-25T11:50:00.000000Z", now), "10 minutes ago");
+ assert.equal(formatAgo("not a time", now), "at an unknown time");
+});
+
+test("only in-app paths become links", () => {
+ assert.equal(safeInAppLink("/people"), "/people");
+ assert.equal(safeInAppLink("/onboard"), "/onboard");
+ for (const bad of [null, "", "//evil.example", "https://evil.example", "javascript:alert(1)", "/people?next=//x", "people"]) {
+ assert.equal(safeInAppLink(bad), null, String(bad));
+ }
+});
diff --git a/packages/ui/src/app/settings/status/page.tsx b/packages/ui/src/app/settings/status/page.tsx
new file mode 100644
index 00000000..e88ab4e0
--- /dev/null
+++ b/packages/ui/src/app/settings/status/page.tsx
@@ -0,0 +1,21 @@
+import { LOCAL_LOGIN } from "@/auth";
+import SetupStatusView from "@/components/settings/SetupStatusView";
+import { parseAllowedEmails } from "@/lib/allowlist";
+import { FALSEY_ENV } from "@/lib/localLogin";
+import { signInCheck } from "@/lib/setupStatus";
+
+// Read this server's settings on every request. Prerendered, the page would
+// show the settings of whichever machine ran `next build`.
+export const dynamic = "force-dynamic";
+
+export default function SetupStatusPage() {
+ const signIn = signInCheck({
+ localLogin: LOCAL_LOGIN,
+ googleClientId: process.env.AUTH_GOOGLE_ID,
+ googleClientSecret: process.env.AUTH_GOOGLE_SECRET,
+ allowedEmails: parseAllowedEmails(process.env.ALLOWED_EMAILS),
+ authUrl: process.env.AUTH_URL,
+ publicDeployment: !FALSEY_ENV.has((process.env.OE_PUBLIC_DEPLOYMENT ?? "").trim().toLowerCase()),
+ });
+ return <SetupStatusView signIn={signIn} />;
+}
diff --git a/packages/ui/src/components/settings/SetupStatusView.tsx b/packages/ui/src/components/settings/SetupStatusView.tsx
new file mode 100644
index 00000000..3559b423
--- /dev/null
+++ b/packages/ui/src/components/settings/SetupStatusView.tsx
@@ -0,0 +1,181 @@
+"use client";
+
+import Link from "next/link";
+import { useCallback, useEffect, useRef, useState } from "react";
+
+import Icon from "@/components/Icon";
+import { getSetupStatus } from "@/lib/api";
+import {
+ formatAgo,
+ safeInAppLink,
+ sortChecks,
+ type SetupCheck,
+ type SetupState,
+ type SetupStatus,
+} from "@/lib/setupStatus";
+
+const STATE_STYLE: Record<SetupState, { dot: string; word: string; wordClass: string }> = {
+ ok: { dot: "bg-emerald-400", word: "Working", wordClass: "text-emerald-300" },
+ warn: { dot: "bg-amber-400", word: "Needs attention", wordClass: "text-amber-300" },
+ error: { dot: "bg-rose-400", word: "Not working", wordClass: "text-rose-300" },
+ off: { dot: "bg-fg-subtle", word: "Not set up", wordClass: "text-fg-muted" },
+};
+
+const LINK_LABELS: Record<string, string> = {
+ "/people": "Open the People page",
+ "/onboard": "Open the setup interview",
+};
+
+function CheckRow({ check }: { check: SetupCheck }) {
+ const style = STATE_STYLE[check.state];
+ const link = safeInAppLink(check.link);
+ return (
+ <li className="rounded-xl border border-line bg-surface-elevated p-4">
+ <div className="flex items-start gap-3">
+ <span
+ className={`mt-1.5 inline-block w-2.5 h-2.5 rounded-full flex-shrink-0 ${style.dot}`}
+ aria-hidden="true"
+ />
+ <div className="min-w-0 flex-1">
+ <div className="flex flex-wrap items-baseline justify-between gap-x-3 gap-y-0.5">
+ <h2 className="text-sm font-medium text-fg">{check.label}</h2>
+ <span className={`text-xs ${style.wordClass}`}>{style.word}</span>
+ </div>
+ <p className="mt-1 text-sm text-fg-muted leading-relaxed break-words">{check.summary}</p>
+ {check.fix && check.state !== "ok" ? (
+ <p
+ className={`mt-2 text-sm leading-relaxed break-words ${
+ check.state === "off" ? "text-fg-subtle" : "text-fg"
+ }`}
+ >
+ <span className="font-medium">{check.state === "off" ? "To turn it on: " : "What to do: "}</span>
+ {check.fix}
+ </p>
+ ) : null}
+ {link ? (
+ <Link
+ href={link}
+ className="mt-2 inline-flex items-center gap-1 text-xs font-medium text-fg hover:underline"
+ >
+ {LINK_LABELS[link] ?? "Open"}
+ <Icon name="chevron-right" size="w-3.5 h-3.5" />
+ </Link>
+ ) : null}
+ {check.last_activity ? (
+ <p className="mt-2 text-xs text-fg-subtle">
+ Last message received {formatAgo(check.last_activity)}.
+ </p>
+ ) : null}
+ </div>
+ </div>
+ </li>
+ );
+}
+
+function Tally({ checks }: { checks: SetupCheck[] }) {
+ const count = (state: SetupState) => checks.filter((c) => c.state === state).length;
+ const parts = (["error", "warn", "ok", "off"] as const)
+ .map((state) => ({ state, n: count(state) }))
+ .filter(({ n }) => n > 0);
+ return (
+ <p className="mt-4 flex flex-wrap gap-x-4 gap-y-1 text-xs text-fg-muted" aria-live="polite">
+ {parts.map(({ state, n }) => (
+ <span key={state} className="inline-flex items-center gap-1.5">
+ <span className={`inline-block w-2 h-2 rounded-full ${STATE_STYLE[state].dot}`} aria-hidden="true" />
+ {n} {STATE_STYLE[state].word.toLowerCase()}
+ </span>
+ ))}
+ </p>
+ );
+}
+
+/**
+ * Settings → Setup status. `signIn` is worked out on the server from this
+ * app's own settings; everything else comes from the API, which tests each
+ * part live — so a run takes a few seconds.
+ */
+export default function SetupStatusView({ signIn }: { signIn: SetupCheck }) {
+ const [status, setStatus] = useState<SetupStatus | null>(null);
+ const [error, setError] = useState<string | null>(null);
+ const [loading, setLoading] = useState(true);
+ const inflight = useRef<AbortController | null>(null);
+
+ const check = useCallback(async () => {
+ inflight.current?.abort();
+ const controller = new AbortController();
+ inflight.current = controller;
+ setLoading(true);
+ setError(null);
+ try {
+ setStatus(await getSetupStatus(controller.signal));
+ } catch (e) {
+ if (controller.signal.aborted) return;
+ setError(e instanceof Error ? e.message : String(e));
+ } finally {
+ if (inflight.current === controller) setLoading(false);
+ }
+ }, []);
+
+ useEffect(() => {
+ void check();
+ return () => inflight.current?.abort();
+ }, [check]);
+
+ const checks = sortChecks([signIn, ...(status?.checks ?? [])]);
+
+ return (
+ <main className="flex-1 min-h-0 overflow-y-auto">
+ <div className="max-w-3xl mx-auto px-4 sm:px-6 py-8">
+ <Link
+ href="/settings"
+ className="inline-flex items-center gap-1 text-xs text-fg-muted hover:text-fg transition-colors"
+ >
+ <Icon name="arrow-left" size="w-3.5 h-3.5" />
+ Settings
+ </Link>
+ <div className="mt-3 flex flex-wrap items-start justify-between gap-3">
+ <div className="min-w-0">
+ <h1 className="text-xl font-semibold text-fg">Setup status</h1>
+ <p className="mt-1 text-sm text-fg-muted">
+ Each part of your setup, tested now. Anything that isn&apos;t green says what to do.
+ </p>
+ </div>
+ <button
+ type="button"
+ onClick={() => void check()}
+ disabled={loading}
+ className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-sm font-medium border border-line bg-surface-elevated text-fg hover:bg-surface-overlay transition-colors cursor-pointer disabled:opacity-50 disabled:cursor-not-allowed"
+ >
+ <Icon name="restore" size="w-4 h-4" />
+ {loading ? "Checking…" : "Check again"}
+ </button>
+ </div>
+
+ {status && !loading ? <Tally checks={checks} /> : null}
+ {status && !loading ? (
+ <p className="mt-1 text-xs text-fg-subtle">Checked {formatAgo(status.checked_at)}.</p>
+ ) : null}
+
+ {error ? (
+ <div className="mt-6 rounded-xl border border-rose-500/30 bg-rose-500/10 p-4 text-sm text-rose-200" role="alert">
+ <p className="font-medium">Couldn&apos;t run the checks: {error}.</p>
+ <p className="mt-1 text-rose-200/80">
+ The API may not be running. <code>make dev</code> starts it on port 8000; its log says what went wrong.
+ </p>
+ </div>
+ ) : null}
+
+ <ul className="mt-6 space-y-3" aria-busy={loading}>
+ {checks.map((c) => (
+ <CheckRow key={c.id} check={c} />
+ ))}
+ {loading && !status ? (
+ <li className="rounded-xl border border-line bg-surface-overlay/60 p-4 text-sm text-fg-muted animate-pulse motion-reduce:animate-none">
+ Testing the AI key, channels and schedule…
+ </li>
+ ) : null}
+ </ul>
+ </div>
+ </main>
+ );
+}
diff --git a/packages/ui/src/components/shell/AppShell.tsx b/packages/ui/src/components/shell/AppShell.tsx
index 4872a73f..04ee6374 100644
--- a/packages/ui/src/components/shell/AppShell.tsx
+++ b/packages/ui/src/components/shell/AppShell.tsx
@@ -43,6 +43,7 @@ const SEGMENT_LABELS: Record<string, string> = {
onboard: "Setup",
watchlist: "Watch list",
settings: "Settings",
+ status: "Setup status",
guide: "User Guide",
clients: "Client Companies",
};
diff --git a/packages/ui/src/components/shell/navConfig.ts b/packages/ui/src/components/shell/navConfig.ts
index b469b66b..a498fb91 100644
--- a/packages/ui/src/components/shell/navConfig.ts
+++ b/packages/ui/src/components/shell/navConfig.ts
@@ -146,6 +146,13 @@ export const BRIEFING_DESCRIPTION =
// Admin / power-user tools surfaced on the Settings hub page rather than
// in the primary nav — they aren't part of the day-to-day loop.
export const ADVANCED_ITEMS: NavItem[] = [
+ {
+ href: "/settings/status",
+ label: "Setup status",
+ icon: "check-circle",
+ description:
+ "A light for each part of your setup — AI key, sign-in, channels, schedule — and what to do about anything that isn't working.",
+ },
{
href: "/council",
label: "Agent Council",
diff --git a/packages/ui/src/lib/api.ts b/packages/ui/src/lib/api.ts
index c8119512..134f02c7 100644
--- a/packages/ui/src/lib/api.ts
+++ b/packages/ui/src/lib/api.ts
@@ -1,3 +1,5 @@
+import type { SetupStatus } from "@/lib/setupStatus";
+
const API_BASE = "/api/backend";
export type CommitteePhase = "drafting" | "reviewing" | "finalizing";
@@ -1224,6 +1226,14 @@ export async function getExecutiveStatus(signal?: AbortSignal): Promise<Executiv
return res.json();
}
+// Settings → Setup status. The API tests each part of the install live, so
+// this can take a few seconds; see api/setup_checks.py.
+export async function getSetupStatus(signal?: AbortSignal): Promise<SetupStatus> {
+ const res = await fetch(`${API_BASE}/setup/status`, { signal, cache: "no-store" });
+ if (!res.ok) throw new Error(`Setup status request failed (HTTP ${res.status})`);
+ return res.json();
+}
+
export async function pauseExecutive(reason?: string): Promise<ExecutiveStatus> {
const res = await fetch(`${API_BASE}/executive/pause`, {
method: "POST",
diff --git a/packages/ui/src/lib/setupStatus.ts b/packages/ui/src/lib/setupStatus.ts
new file mode 100644
index 00000000..1472c614
--- /dev/null
+++ b/packages/ui/src/lib/setupStatus.ts
@@ -0,0 +1,124 @@
+// Settings → Setup status (/settings/status): the shape of the API's
+// GET /setup/status answer, and the one light this app works out itself —
+// sign-in, whose settings live here rather than in the API.
+//
+// No imports, so `npm test` can exercise this under
+// `node --experimental-strip-types` (see scripts/setupStatus.test.mjs).
+
+export type SetupState = "ok" | "warn" | "error" | "off";
+
+/** One light. Mirrors `SetupCheck` in packages/core/openexecutive/api/setup_checks.py. */
+export interface SetupCheck {
+ id: string;
+ label: string;
+ state: SetupState;
+ summary: string;
+ fix: string | null;
+ /** An in-app page that helps with the fix, e.g. "/people". */
+ link: string | null;
+ /** When the channel last received a message (ISO time). */
+ last_activity: string | null;
+}
+
+export interface SetupStatus {
+ checked_at: string;
+ checks: SetupCheck[];
+}
+
+export interface SignInEnv {
+ localLogin: boolean;
+ googleClientId: string | undefined;
+ googleClientSecret: string | undefined;
+ /** ALLOWED_EMAILS, parsed the way sign-in parses it. */
+ allowedEmails: ReadonlySet<string>;
+ authUrl: string | undefined;
+ publicDeployment: boolean;
+}
+
+// RFC 2606 names reserved for examples — the same set as
+// _EXAMPLE_EMAIL_DOMAINS in api/setup_checks.py, and
+// scripts/setupStatus.test.mjs fails if the two ever disagree.
+export const EXAMPLE_EMAIL_DOMAINS: ReadonlySet<string> = new Set([
+ "example.com",
+ "example.org",
+ "example.net",
+]);
+
+export function isExampleEmail(email: string): boolean {
+ const domain = email.slice(email.lastIndexOf("@") + 1).trim().toLowerCase();
+ return EXAMPLE_EMAIL_DOMAINS.has(domain) || domain.endsWith(".example");
+}
+
+export function signInCheck(env: SignInEnv): SetupCheck {
+ const check = (state: SetupState, summary: string, fix: string | null = null): SetupCheck => ({
+ id: "sign_in",
+ label: "Sign-in",
+ state,
+ summary,
+ fix,
+ link: null,
+ last_activity: null,
+ });
+
+ if (env.localLogin) {
+ return check("ok", "Local login: no sign-in needed, and only this computer can open the app.");
+ }
+ if (!env.googleClientId?.trim() || !env.googleClientSecret?.trim()) {
+ return check(
+ "error",
+ "Google sign-in isn't fully set up: it needs both AUTH_GOOGLE_ID and AUTH_GOOGLE_SECRET.",
+ "Set both from your Google Cloud OAuth client (docs/auth.md), then restart the app.",
+ );
+ }
+ const samples = [...env.allowedEmails].filter(isExampleEmail);
+ if (samples.length > 0) {
+ return check(
+ "warn",
+ `ALLOWED_EMAILS still lists sample addresses: ${samples.join(", ")}.`,
+ "Replace them in .env with the Google addresses of the people who should sign in, then restart the app.",
+ );
+ }
+ if (env.publicDeployment && !env.authUrl?.trim()) {
+ return check(
+ "warn",
+ "AUTH_URL isn't set, so Google can send people back to the wrong address after they sign in.",
+ "Set AUTH_URL to this app's public address (for example https://exec.example.com), then restart the app.",
+ );
+ }
+ const listed = env.allowedEmails.size;
+ return check(
+ "ok",
+ listed > 0
+ ? `Google sign-in, for the ${listed} address${listed === 1 ? "" : "es"} in ALLOWED_EMAILS and anyone with an email on the team list.`
+ : "Google sign-in, for anyone with an email on the team list.",
+ );
+}
+
+// Worst first, so what needs fixing is at the top of the page.
+const STATE_RANK: Record<SetupState, number> = { error: 0, warn: 1, ok: 2, off: 3 };
+
+/** The lights in the order the page shows them: worst first, and otherwise
+ * in the order they arrived. */
+export function sortChecks(checks: readonly SetupCheck[]): SetupCheck[] {
+ return checks
+ .map((check, index) => ({ check, index }))
+ .sort((a, b) => STATE_RANK[a.check.state] - STATE_RANK[b.check.state] || a.index - b.index)
+ .map(({ check }) => check);
+}
+
+/** "5 minutes ago" — how long before `now` an ISO time was. */
+export function formatAgo(iso: string, now: Date = new Date()): string {
+ const then = Date.parse(iso);
+ if (Number.isNaN(then)) return "at an unknown time";
+ const minutes = Math.floor((now.getTime() - then) / 60_000);
+ if (minutes < 1) return "less than a minute ago";
+ if (minutes < 60) return `${minutes} minute${minutes === 1 ? "" : "s"} ago`;
+ const hours = Math.floor(minutes / 60);
+ if (hours < 48) return `${hours} hour${hours === 1 ? "" : "s"} ago`;
+ return `${Math.floor(hours / 24)} days ago`;
+}
+
+/** Only an in-app path is ever rendered as a link. */
+export function safeInAppLink(link: string | null): string | null {
+ return link && /^\/(?!\/)[\w\-/]*$/.test(link) ? link : null;
+}