AI-powered virtual executive team — a single coherent executive persona backed by 8 specialist agents (FastAPI + Next.js).
feat(people): add quiet hours and a digest setting for the Executive's own messages (#457)
Rufus0545f356ffc4
diff --git a/packages/core/openexecutive/alerts/review.py b/packages/core/openexecutive/alerts/review.pyindex ad937e99..fe6f4d89 100644--- a/packages/core/openexecutive/alerts/review.py+++ b/packages/core/openexecutive/alerts/review.py@@ -24,6 +24,7 @@ Heartbeat plumbing (``alert_review_scan`` rows) mirrors ``scheduler/nudge_enginefrom __future__ import annotationsimport asyncio+import contextlibimport jsonimport loggingfrom dataclasses import asdict, dataclass, field@@ -530,6 +531,9 @@ def _bump_severity(current: str, requested: str | None) -> str:_DM_MAX_CHARS = 1200+# `_dm`'s detail for a DM held by the recipient's notification settings+# (people.held_messages): it goes later, so it is not yet a delivered nudge.+_HELD_DETAIL = "held for their quiet hours or brief"def _dm_text(headline: str, text: str) -> str:@@ -547,7 +551,9 @@ async def _dm(resolution + the outbound anti-spam guard). Returns (ok, detail).Tagged as alert-review outreach about ``alert_id``, so acknowledging or- dismissing that alert later resolves whether the DM landed."""+ dismissing that alert later resolves whether the DM landed. A caller+ about a critical alert wraps it in ``_urgent_if`` so it gets past the+ person's quiet hours and digest (``people.notifications``)."""import jsonfrom openexecutive.attunement.outcomes import SOURCE_ALERT_REVIEW, tag_proactive@@ -566,9 +572,21 @@ async def _dm(# review that would just mint another candidate to route next pass.if isinstance(parsed, dict) and "error" not in parsed and parsed.get("status") == "sent":return True, "sent"+ # Held by the person's own notification settings: it is saved and goes+ # when they asked to hear, so the move happened.+ if isinstance(parsed, dict) and parsed.get("status") == "held":+ return True, _HELD_DETAILreturn False, str(parsed.get("error") if isinstance(parsed, dict) else raw)[:200]+def _urgent_if(urgent: bool) -> contextlib.AbstractContextManager[None]:+ """Mark the DMs inside as urgent (a critical alert: severity ``urgent``)+ for the person's "Let urgent things through" (``people.notifications``)."""+ from openexecutive.people.notifications import urgent_send++ return urgent_send() if urgent else contextlib.nullcontext()++def _nudges_so_far(alert_id: int) -> int:try:from openexecutive.audit.logger import get_audit_logger@@ -815,10 +833,11 @@ async def _apply_route(ctx: _MoveContext) -> None:if alert.routed_to_person_id == target:return # already routed there (by any pass or producer) — never re-DMalert_store.update_alert_routing(ctx.alert_id, target, db_path=ctx.db_path)- ok, detail = await _dm(- target, v.message or f"Can you own this? {alert.headline}", headline=alert.headline,- alert_id=ctx.alert_id,- )+ with _urgent_if(alert.severity == "urgent"):+ ok, detail = await _dm(+ target, v.message or f"Can you own this? {alert.headline}", headline=alert.headline,+ alert_id=ctx.alert_id,+ )ctx.summary.moves_used += 1if ok:ctx.summary.routed += 1@@ -843,11 +862,21 @@ async def _apply_nudge(ctx: _MoveContext) -> None:_audit(EVENT_REVIEWED, f"Nudge cap reached for '{alert.headline[:80]}'",{**ctx.base_details, "target_person_id": target, "cap": ctx.settings.nudge_cap})return- ok, detail = await _dm(- target, v.message or f"Checking in on: {alert.headline}", headline=alert.headline,- alert_id=ctx.alert_id,- )+ from openexecutive.people.held_messages import waiting_for++ if waiting_for(target, f"alert:{ctx.alert_id}"):+ return # a DM about it already waits for their quiet hours or brief+ with _urgent_if(alert.severity == "urgent"):+ ok, detail = await _dm(+ target, v.message or f"Checking in on: {alert.headline}", headline=alert.headline,+ alert_id=ctx.alert_id,+ )ctx.summary.moves_used += 1+ if ok and detail == _HELD_DETAIL:+ # Not delivered yet: no nudge counted toward the cap.+ _audit(EVENT_REVIEWED, f"Nudge about '{alert.headline[:80]}' held for the recipient",+ {**ctx.base_details, "target_person_id": target, "held": True})+ returnif ok:ctx.summary.nudged += 1ctx.move_taken = "nudge"@@ -869,12 +898,13 @@ async def _apply_escalate(ctx: _MoveContext) -> None:_audit(EVENT_REVIEWED, f"Escalation requested for '{alert.headline[:80]}' but no principal on roster",{**ctx.base_details, "stored": "relevant"})return- ok, detail = await _dm(- ctx.principal_id,- v.message or f"Needs you today: {alert.headline}\n{v.why_now or ''}".strip(),- headline=alert.headline,- alert_id=ctx.alert_id,- )+ with _urgent_if(_bump_severity(alert.severity, v.severity) == "urgent"):+ ok, detail = await _dm(+ ctx.principal_id,+ v.message or f"Needs you today: {alert.headline}\n{v.why_now or ''}".strip(),+ headline=alert.headline,+ alert_id=ctx.alert_id,+ )ctx.summary.moves_used += 1if not ok:# Nothing reached the principal: leave the row untouched so the nextdiff --git a/packages/core/openexecutive/api/main.py b/packages/core/openexecutive/api/main.pyindex 4f87e6f5..4a9b7149 100644--- a/packages/core/openexecutive/api/main.py+++ b/packages/core/openexecutive/api/main.py@@ -38,6 +38,7 @@ from openexecutive.api.routes import (health,history,knowledge,+ notifications,onboarding,people,personas,@@ -976,6 +977,7 @@ def create_app() -> FastAPI:app.include_router(scheduled.router, tags=["scheduled"])app.include_router(executive.router, tags=["executive"])app.include_router(workspace.router, tags=["workspace"])+ app.include_router(notifications.router, tags=["notifications"])app.include_router(watchlist.router, tags=["watchlist"])app.include_router(google_chat_router, tags=["google-chat"])app.include_router(telegram_router, tags=["telegram"])diff --git a/packages/core/openexecutive/api/routes/notifications.py b/packages/core/openexecutive/api/routes/notifications.pynew file mode 100644index 00000000..098277b2--- /dev/null+++ b/packages/core/openexecutive/api/routes/notifications.py@@ -0,0 +1,162 @@+"""Settings → Notifications: the caller's own quiet hours, digest or instant,+and whether urgent things get through (``people.notifications``).++Every route is about the CALLER'S OWN settings: each person sets theirs, and+nobody sets anyone else's (the principal included). The caller is resolved+as for the notes (``api.routes.history._caller``'s rule): a signed-in person+on the People list; a request with no caller only under local login, as the+principal. Anyone else gets 403.++Routes:+ GET /notifications/settings — the caller's settings, the zone they are+ read in, how many messages are waiting for+ them, and whether they get the briefs+ PUT /notifications/settings — replace them: {quiet_hours: {enabled, start,+ end, days}, delivery, urgent_through,+ timezone}+"""+from __future__ import annotations++import logging++from fastapi import APIRouter, HTTPException, Request+from pydantic import BaseModel, ConfigDict, Field++from openexecutive.api import caller as api_caller+from openexecutive.people.models import Person+from openexecutive.people.notifications import (+ Delivery,+ NotificationSettings,+ QuietHours,+ get_notification_settings,+ save_notification_settings,+ zone_for,+)++router = APIRouter()+logger = logging.getLogger(__name__)+++class NotificationsOut(BaseModel):+ quiet_hours: QuietHours+ delivery: Delivery+ urgent_through: bool+ # The zone they chose ("" for the workspace's), and the one in effect.+ timezone: str+ effective_timezone: str+ # Messages waiting for their quiet hours to end or their next brief.+ held_count: int+ # Whether the morning and end-of-day briefs go to them (the principal);+ # anyone else's held messages go out on their own when the briefs do.+ gets_briefs: bool+ updated_at: str+++class NotificationsUpdate(BaseModel):+ model_config = ConfigDict(extra="forbid")++ quiet_hours: QuietHours+ delivery: Delivery+ urgent_through: bool+ timezone: str = Field(default="", max_length=64)+++def _refuse(status_code: int, code: str, message: str) -> HTTPException:+ return HTTPException(status_code=status_code, detail={"code": code, "message": message})+++def _caller(request: Request) -> Person:+ """The caller on the People list; else 403."""+ from openexecutive.delegation.settings import local_login+ from openexecutive.people.store import find_person_by_email, find_principal_person++ who = api_caller.caller(request)+ try:+ if who.email:+ person = find_person_by_email(who.email)+ elif who.defaults_to_principal and local_login():+ person = find_principal_person()+ else:+ raise _refuse(403, "sign_in_required", "Sign in to change your notifications.")+ except HTTPException:+ raise+ except Exception as exc:+ logger.exception("notifications: caller lookup failed")+ raise _refuse(503, "roster_unavailable", "Couldn't read the People list.") from exc+ if person is None or person.id is None or person.archived:+ raise _refuse(+ 403, "not_on_roster", "Notification settings are for people on the People list."+ )+ return person+++def _out(person: Person, settings: NotificationSettings) -> NotificationsOut:+ from openexecutive.people.held_messages import held_count++ assert person.id is not None+ return NotificationsOut(+ quiet_hours=settings.quiet_hours,+ delivery=settings.delivery,+ urgent_through=settings.urgent_through,+ timezone=settings.timezone,+ effective_timezone=str(zone_for(settings)),+ held_count=held_count(person.id),+ gets_briefs=person.is_principal,+ updated_at=settings.updated_at,+ )++[email protected]("/notifications/settings", response_model=NotificationsOut)+def get_notifications(request: Request) -> NotificationsOut:+ person = _caller(request)+ return _out(person, get_notification_settings(person.id))++[email protected]("/notifications/settings", response_model=NotificationsOut)+def update_notifications(request: Request, body: NotificationsUpdate) -> NotificationsOut:+ person = _caller(request)+ assert person.id is not None+ try:+ settings = NotificationSettings(+ quiet_hours=body.quiet_hours,+ delivery=body.delivery,+ urgent_through=body.urgent_through,+ timezone=body.timezone,+ )+ except ValueError as exc:+ raise _refuse(422, "invalid_settings", "That time zone isn't one we know.") from exc+ before = get_notification_settings(person.id)+ try:+ saved = save_notification_settings(person.id, settings)+ except Exception as exc:+ logger.exception("notifications: couldn't save person %s's settings", person.id)+ raise _refuse(503, "save_failed", "Couldn't save your notification settings.") from exc+ from datetime import UTC, datetime++ from openexecutive.people.held_messages import release_digest_now, release_quiet_now++ now = datetime.now(UTC)+ try:+ if before.delivery == "digest" and saved.delivery == "instant":+ # Back to "As they happen": what waited for their brief goes now.+ release_digest_now(person.id, now=now)+ if before.quiet_hours != saved.quiet_hours or before.timezone != saved.timezone:+ # Quiet hours (or their zone) changed: what waited for the old end time is due now,+ # and the release pass holds it again if the new ones are quiet.+ release_quiet_now(person.id, now=now)+ except Exception:+ logger.warning("notifications: couldn't release person %s's held messages", person.id, exc_info=True)+ from openexecutive.audit import log_event++ log_event(+ "notification_settings_changed",+ f"Person {person.id} changed their notification settings",+ actor=api_caller.actor(request),+ details={+ "person_id": person.id,+ "quiet_hours": saved.quiet_hours.enabled,+ "delivery": saved.delivery,+ "urgent_through": saved.urgent_through,+ },+ )+ return _out(person, saved)diff --git a/packages/core/openexecutive/architecture/architecture-facts.yaml b/packages/core/openexecutive/architecture/architecture-facts.yamlindex 48d0d41a..d4fa043d 100644--- a/packages/core/openexecutive/architecture/architecture-facts.yaml+++ b/packages/core/openexecutive/architecture/architecture-facts.yaml@@ -1395,6 +1395,11 @@ routing:and the `max_pending_*` caps on `schedule_followup`. Principal briefs andthe internal heartbeat kinds (`__internal__` channel) never reach thesehandlers, so they are unaffected (see the `scheduler:` kinds note).+ After the guard allows a send, the handlers apply the recipient's own+ notification settings to the Executive's own (tagged) outreach:+ `_hold_outbound` → `outbound_guard.check_hold` stores the DM in+ `held_messages` and returns {"status":"held"} when they are in quiet+ hours or chose "In my briefs" (people.notification_settings).reflection_then_decide: |Shift 5 introduces a new routing pattern: ``executive_reflection``is the first workflow that lets OE consume structured signal data@@ -4262,6 +4267,76 @@ people:`prefer_channel_for()` also enforces availability windows (returnsNone if the person is on leave or outside all configured windows;no windows means always-on).+ notification_settings: |+ Each team member sets their own on Settings → Notifications+ (GET/PUT /notifications/settings, api.routes.notifications; caller+ resolved like the notes routes: a signed-in person on the People list,+ or the principal under local login, else 403). One row per person in+ `person_notification_settings` (people.notifications): quiet hours+ (enabled, start/end HH:MM in their zone, may cross midnight, start !=+ end; days every_day or weekdays — weekdays keeps the nightly window and+ makes Saturday and Sunday quiet all day), delivery instant | digest+ ("As they happen" / "In my briefs"), urgent_through (default true), and+ an IANA timezone ("" = the workspace zone). No row = defaults = nothing+ held, so existing installs behave as before.+ Scope: only the Executive's OWN outreach — a DM sent while a proactive+ source is tagged (attunement.outcomes.tag_proactive: scheduler dispatch+ of nudges, reflection, research, alert review). A reply+ in a conversation, a send someone asked for in chat, a scheduled+ follow-up (source followup, asked for at a time), the briefs, the+ cross-client digest, workflow artifacts and Act as me / note reminders+ are untagged and never held. Why not fold quiet hours into+ is_within_availability for everyone: the outbound guard's availability+ check runs on every DM, briefs included, and would refuse the brief the+ person scheduled inside their own quiet hours.+ Two mechanisms: (1) nudge routing — people.channel's+ is_within_availability / is_reachable_now / next_window_for /+ prefer_channel_for / next_available_window take `quiet_hours=True,+ urgent=` and then also treat quiet hours as unavailable; the nudge+ engine's _route_candidate and the runner's proactive_nudge re-check pass+ it, so a nudge row is deferred to the end of quiet hours (no model run+ at 3am, fresh text); (2) the send handlers' `_hold_outbound` after the+ anti-spam guard allows a send: outbound_guard.check_hold → if the+ recipient is in quiet hours or chose digest, the text is stored in+ `held_messages` (people.held_messages) and the tool returns+ {"status":"held"}; message_person returns it instead of trying the next+ channel (which would hold it twice), alert review counts it as a move+ made for a route but does not count a nudge toward the cap (and no+ second nudge is held while one about that alert waits, by `ref`). A+ store failure sends instead (fail-open, never lost). A scheduler+ dispatch whose turn held its message is audited phase `held`, not+ `delivered` (held_messages.track_holds).+ Release: rows with release_at (quiet hours) go once due, per person as+ one "While you were away" message via scheduler.runner.deliver_to_person+ (scheduler tick hook _maybe_release_held, once a minute). Every sender+ claims rows first (claimed_at compare-and-set, stale after 10 min), so a+ release pass and a brief never both send one; marked sent only after+ delivery, else the claim is freed. Postponed if quiet again, or to the+ leave end / next availability window when the guard would refuse them;+ any other failed delivery backs off 2, 4, 8 … min, capped at an hour.+ Dropped after 7 days or when the person is archived, and the oldest past+ the cap — each drop audited `held_messages_dropped`, private to the+ person, a count and reason only. Digest rows (release_at null) ride the+ principal's next morning brief / EoD digest as one block appended to the+ delivered text (not the stored run artifact), marked sent only when the+ brief went; everyone else's are made due when those briefs run+ (only the principal gets briefs); a digest row unclaimed for 36 h goes+ on its own. Switching back to instant releases what waited. Cap 50 open+ rows per person (oldest dropped).+ Urgent: source nudge_stalled (approval nudges) and alert-review DMs+ about an alert whose severity is or becomes `urgent`+ (notifications.urgent_send) are let through when urgent_through. A+ workflow approval question (gate_delivery wraps message_person in+ notifications.approval_send) is never held, whatever the setting: only+ a reply to it resolves the gate. If quiet hours cover every+ availability window in the 14-day horizon, next_window_for falls back+ to the next window rather than dropping the nudge.+ Not covered: nudges on the email channel (the MCP mail tool bypasses the+ send handlers — routing still defers them for quiet hours, but they are+ never digest-held); department channel broadcasts (rooms, not a person);+ alerts.dispatcher channels (web SSE, a self-addressed email, and a Slack+ DM stub); Act as me approval cards (untagged, and approvals anyway).+ Department check-ins send no DM: their proposals become approval cards.scope_tokens: |People can be queried by scope token viaGET /people/by-scope/{token} — e.g. "ceo", "head-of-marketing",@@ -4468,6 +4543,18 @@ scheduler:503. Each cancel is audited `scheduled_action_cancelled` with thecaller's email, "admin-token" or "local" as actor. Before this the UIcould never send the admin token, so Cancel failed on every deploy.+ held_messages: |+ Loop-level hook `_maybe_release_held` (like the reminders): at most once+ a minute it starts people.held_messages.maybe_release, which sends each+ person their due held messages (quiet hours ended, or a digest made due+ when the briefs ran) as one "While you were away" message through+ deliver_to_person, private audit rows (`held_messages_released`). The+ principal-brief handler appends the principal's digest rows to the+ morning brief / EoD digest it delivers (_with_held_messages), marks them+ sent only on delivery (_mark_held_sent), then _release_others_digests+ makes everyone else's due. The proactive_nudge re-check calls+ prefer_channel_for / next_available_window with quiet_hours=True+ (urgent for `nudge:stalled:` scope keys). See people.notification_settings.nudge_engine: |openexecutive.scheduler.nudge_engine — periodic heartbeat (kind=`nudge_scan`, default every 15 min via NUDGE_SCAN_INTERVAL_MINUTES)diff --git a/packages/core/openexecutive/architecture/prebuilt/api.json b/packages/core/openexecutive/architecture/prebuilt/api.jsonindex bef9bd03..f13c34ab 100644--- a/packages/core/openexecutive/architecture/prebuilt/api.json+++ b/packages/core/openexecutive/architecture/prebuilt/api.json@@ -1,7 +1,7 @@{"section_id": "api","title": "API Reference",- "markdown": "The FastAPI surface lives in `openexecutive.api.main`, which mounts one router per topic. A shared-secret middleware gates every request via an `x-api-key` header, except `/health` and the `/webhook/*` callbacks (which carry their own verification). With local login (`OE_LOCAL_LOGIN=1`, which only `make dev` sets, and only while neither Google nor SSO sign-in is set up) a second middleware answers 403 to any request whose raw `Host` is not `localhost`, `127.0.0.1` or `[::1]` (except a webhook that verifies its caller: Google Chat and Slack always, Telegram only with a `TELEGRAM_WEBHOOK_SECRET` Telegram can send), and to any write whose `Sec-Fetch-Site` is present and not `same-origin`/`none`. The UI signs that owner in with no password and this API usually has no secret, so without it a web page in the owner's browser could drive the API as the principal — by DNS-rebinding its own hostname to 127.0.0.1, or by posting a plain form from another site or localhost port. CORS is restricted to the UI origins in `BACKEND_ALLOWED_ORIGINS`, plus the `make dev` UI on `localhost:3000` only when `OE_PUBLIC_DEPLOYMENT` is unset, so a public instance never answers a localhost page with credentials. The gate is off when `BACKEND_SHARED_SECRET` is unset — intended for local development only — so any internet-reachable deployment sets `OE_PUBLIC_DEPLOYMENT`, and `create_app()` then refuses to boot without the secret rather than serving an unauthenticated API.\n\n**Who is calling** is read in one place, `api/caller.py`, which answers with a `Caller` kind and email; a test fails on any other read of an `x-caller-*` header. By default (`open`) it is the `x-caller-email` the UI proxy stamps from the sign-in, trusted because whoever holds the shared secret is trusted as the proxy, and a request with none runs as the principal. **Signed callers** remove that trust. With `CALLER_ASSERTION_PUBLIC_KEYS` set, the proxy signs every request with an Ed25519 key only the UI holds, and a third middleware checks the `x-caller-assertion` header:\n\n- **What it covers.** It is good for one method, the exact path and query, at most 120 seconds, and one use. The API keeps used ids in memory.\n- **What it names.** A `user`, by email, or the `operator`: local login, which runs as the principal.\n- **No caller header at all** is a `service`, for scripts or MCP clients holding only the secret. It is never the principal, not even on an install with no owner yet, so it can't save a first setup.\n- **Anything else is a 401.** That includes an `x-caller-email` without an assertion (`caller_assertion_required`), and a bad, expired, reused or mismatched assertion (`caller_assertion_invalid`).\n\nPublic keys that can't be read stop the boot, rather than fall back to trusting the header. `scripts/make-caller-keys.py` makes the pair, and `scripts/mint-caller-assertion.py` signs one request for curl. The API holds only public keys. Setup's API-protection check warns while a shared secret is set without them.\n\nEndpoints grouped by router:\n\n| Router | Key endpoints | Purpose |\n|---|---|---|\n| `chat` | `POST /chat`, `POST /chat/stop`, `POST /chat/add`, `POST /chat/background` | SSE stream of a live Executive turn. `POST /chat/background` starts a new chat that the server answers to the end with nobody connected (a phone approving a card, then closing the app): it answers `202` with the new `session_id` once the same caller, access and quota checks as `/chat` pass, the turn saves itself as a `/chat` turn does, and one caller may have three running at once (`429` beyond that). `POST /chat/add` hands the running turn a message the person typed while it works; the turn takes it at its next step and the stream names it in a `message_added` event, and a second `POST /chat` on the same conversation waits for the first to finish. The request body optionally carries `page_context` (route, page title, guide section id, and a form descriptor with current values) — sent only by the Ask OE side panel so the Executive can explain the current page or propose form values. When the Executive calls its `propose_form_values` tool, the stream emits a `form_patch` event (`{type, form_id, fields, rationale, iteration}`) that the panel applies into the on-screen form as highlighted suggestions; the user reviews and saves through the form's normal submit path. Each round of tool calls also emits an `activity` event (`{type, label, tool, iteration}`) naming what is running — progress only, forwarded verbatim and never persisted with the message, unlike an `action_taken` chip. A `session_id` in the body must be a chat the caller may use (the same ownership rule as `sessions`). If it isn't, the turn runs in a fresh chat instead, so nothing is written into someone else's session and the reply looks the same as for an unknown id. An unknown namespaced id (`slack:…`, `telegram:…` and so on) is ignored and a fresh chat is started, because those ids belong to the channel adapters and claiming one first would make the caller its owner. The client mints a `client_turn_id` and sends it with the turn; `POST /chat/stop` takes that id and halts the turn mid-flight, so the button is live from the moment Send is pressed rather than only once the first SSE byte arrives. A stopped turn emits a `stopped` event and then the usual `done` over the same still-open stream — never an `error` — and whatever streamed so far is persisted and flagged. The endpoint returns 404 both for an unknown id and for another caller's turn, so it cannot be used to probe which turns are live. An optional `memory_text` (1–2000 chars) is what peer memory records as the caller's words instead of `message` — the briefing handoffs send it because their seed quotes the Executive's own card; `POST /chat/upload` derives it from the typed text and filenames. Since it never reaches the transcript, the `chat_turn` audit row keeps it beside `message`. After the reply — a stopped or timed-out one too, before the `stopped` / `error` / `done` frames — a turn that looked at anything sends one `sources` event, `{type, session_id, sources: [{kind, title, url}], unavailable: [area]}`: `kind` is `company`, `knowledge`, `notion`, `research`, `document` or `web`, `url` is only ever an http(s) link or, for an earlier document, `/artifacts/<id>`, at most 12 sources (6 from the web, pages the reply cites first), and `unavailable` names parts of the analysis (\"finance\") whose specialist failed or said nothing every time it was asked. It is persisted with the reply as `chat_messages.sources`. A request that carries `x-caller-email` marks its turn signed in (`Session.web_caller_signed_in`), which Act as me needs on a deployment without local login. |\n| `sessions` | `GET /sessions`, `GET /sessions/{id}`, `GET /sessions/{id}/messages`, `DELETE /sessions/{id}`, `POST /sessions/{id}/messages/{message_id}/feedback`, `GET /sessions/{id}/followup` | List, read and delete saved chat sessions (assistant messages carry their row `id` and any `feedback`). The list is scoped to the caller, and each chat carries `preview`: its last message as one plain line, Markdown marks stripped and cut at a word near 120 characters, with `You:` before the person's own words. With `?q=` it is a search: the caller's own chats whose title or message text contains the words (case-insensitive, `LIKE` with wildcards escaped), each with `match_count` (messages that contain them; 0 for a title-only match) and `snippet` (the newest matching message, around the match, prefixed `You:` or `Executive:`). Scoped exactly like the list, so nobody else's conversation can match. The Chats page searches this way and opens a result with `?find=`, so the chat starts on that message and steps through the others. A chat-app conversation started with /new is left off the list until its first turn (`memory.conversations`). Every per-session route checks ownership, because session ids are guessable (`slack:dm:<user id>`, `telegram:<chat id>`): only the session's owner or the principal gets through, and a legacy row with no owner is the principal's alone. A teammate's own chat (a web chat, a DM, a private Telegram chat; not a channel or group conversation, `chat._shared_space`) is theirs alone, the principal included, as their mail with the Executive is. Anyone else gets the same 404 as for an unknown id, so the routes can't be used to find out which chats exist. The one other way in is having started the chat in this process (matched by Person id or verified email, so it survives the caller being added to the roster), which is how a caller the roster can't resolve keeps using their own chat. That record is in memory, so after a restart such an ownerless chat is refused for reads. The principal can continue someone else's ownerless chat without becoming its owner. Deleting a session also drops its in-memory copy, so a later turn naming that id starts fresh. The feedback route records 👍/👎 (`{\"feedback\": \"up\"|\"down\"|null}`) on one assistant reply; only the session's own caller or the principal may rate it. The rater is stored (`feedback_by_person_id`), and a 👎 on a reply to the rater's own message triggers a working-style pass for them (paced; see attunement). The chat stream's `done` event carries `message_id` for the persisted reply. The followup route returns `{\"suggestion\": string|null}` — one suggested next user message, written by the utility-fast model from the last few turns, that the chat composer shows as its greyed placeholder (Tab / → or the inline chip fills it in without sending). It is null unless the session ends on a persisted assistant reply, and null (uncached) when the model fails. Same ownership check as feedback; successful suggestions are cached in-process per (session, reply id). Messages from `GET /sessions/{id}/messages` carry each assistant reply's saved `sources` (the same shape as the chat stream's `sources` event, without `type`), so a reloaded chat shows them again. |\n| `today` | `GET /today`, `GET /today/activity`, `GET /today/activity/daily`, `GET /today/brief-delivery`, `GET /today/top-three`, `GET /today/weekly-review` | Morning-brief aggregation, recent-action rail, and Pulse heartbeat heatmap (per-day activity counts). `GET /today` carries the viewer's cached \"What's going on\" `narrative` with `narrative_generated_at` (when it was written) and `narrative_stale` (a fresher one is being written — the page re-polls; see Today). A proposal backed by a roster request carries `roster_request` (the new sender's server-derived details and held-message previews; the principal's only) and is answered through the `people` routes below. `brief-delivery` returns the latest morning brief or end-of-day digest that didn't reach the owner, as `{brief, at, problem, fix, readable}` in plain language (`readable` is false when it couldn't be written, so there is nothing to read), or null — null while briefs go out, once the cause is fixed, while the scheduler is off, and for anyone but the owner (`chat._caller_is_principal_or_unclaimed`); it carries no address or channel id. `top-three` and `weekly-review` feed the solo Briefing's own cards and answer only in solo mode and only to the principal (`workflows._caller_is_the_principal`: a principal match or no caller header, never an unclaimed roster); anyone else, and team mode, get null. `top-three` returns `{items: [{key, kind, text, why, slot}]}` — the morning brief's top three from the same code (`build_top_three(principal_due_soon())`), `slot` a free block like `10:00–11:00`, `\"\"` when none is left, null when no calendar was read — and is kept off `GET /today` because its calendar read may take up to 4 s. `weekly-review` returns the latest completed `weekly_review` run as `{run_id, completed_at, period, top_three, excerpt}` (next week's top three as plain text; `excerpt` when that list is empty), or null when none has completed. |\n| `people` | `GET\\|POST\\|PATCH /people`, `POST /people/{id}/archive`, `GET /people/requests`, `GET /people/requests/{id}`, `POST /people/requests/{id}/approve`, `POST /people/requests/{id}/decline`, `GET\\|POST /people/{id}/open-loops`, `POST /open-loops/{loop_id}/close`, `GET /people/{id}/outreach`, `GET\\|PUT\\|DELETE /people/{id}/attunement` | Roster CRUD and scope lookups. Every `Person` carries `kind` (`team` / `contact`). `GET /people` lists team members only unless `?include_contacts=true` (the People page asks for both; the department-head and workflow pickers keep the default); `POST` / `PATCH` accept `kind`, and a principal contact is a 422 either way. They also take `email_aliases` (other addresses the person writes from, at most 10; on `PATCH` the full list replaces the current one, omitted leaves it): an alias matches their mail and may be emailed but never signs in; a malformed one is a 422, and an alias — or a new primary `email` — that is already someone else's address or alias is a 409. Every `POST` / `PATCH` then closes any pending roster request whose sender now matches someone and replays its held messages. Adding, editing and archiving (`POST`, `PATCH`, `/archive`) are the principal's only, or anyone's while no one is principal yet so a first setup can add its owner (`chat._caller_is_principal_or_unclaimed`, the check behind `PUT /workspace`; a request with no `x-caller-email`, such as the CLI or local login, counts as the principal). Anyone else, a person editing their own row included, gets 403 before the person lookup, so it can't probe which ids exist. Contacts are private to the principal (`caller_is_principal`: the signed-in email is the principal's, or no `x-caller-email`; stricter than the owner rule above, so while no one is principal nobody is): for anyone else `include_contacts` is ignored, a contact's id is a 404 on `GET /people/{id}` and open-loops (exactly as for a missing id; `PATCH` and archive are already a 403 for them), and creating a contact or turning someone into one is a 403, even on a first setup with no principal yet. `GET /people/me` returns `{person_id, is_principal}` so the UI offers contacts to the principal only. `GET /people/by-scope/{token}` never returns a contact. Archiving a person closes their open loops. The open-loop routes list what a person owes (soonest due first) and close one (`reason`: done / not_needed / cancelled) — both the principal's or the owner's only (403 otherwise, via `people.store.is_principal_or_self`). `POST /people/{id}/open-loops` `{task, due_date?}` assigns that person a task (201 with the loop; `due_date` is a local date, due 17:00 in the user's timezone, clamped to 60 days, default 2 days): any active team member may assign anyone on the team, 403 for anyone else; 409 for an archived person, a contact (as seen by the principal), a person at the open-loop cap, a duplicate or open loops turned off; 422 for an empty task. Nobody is messaged at assignment — the owner is chased once it is due. `/outreach` returns, per kind of proactive outreach over 30 days, `sent` / `replied` / `acted` / `ignored` / `pending` (voided DMs are excluded) — same access rule, checked before the person lookup so it can't probe which ids exist. `/attunement` reads, replaces (`rules`: up to 4 strings, or omitted to only set `locked`) or resets the person's working-style rules — same access rule, 404 for an archived person; `PUT` rejects a rule that is not purely about style with 422. Archiving a person also drops their working style and frees their aliases. The **roster-request** routes (declared before `/people/{person_id}`) are the principal's alone (`caller_is_principal`; anyone else gets 404, as for a missing id): `GET /people/requests?status=pending|approved|linked|declined|expired|superseded|all` lists up to 100 (`id`, `channel`, `channel_ref`, sanitised `display_name`, `profile_email`, `on_company_domain`, `suggested_kind`, `suggested_person_id` / `_name`, `status`, `resolved_person_id` / `_kind`, `message_count`, timestamps, `ack_sent`, and `previews` of the held messages while pending — shown to the principal, never to a model); `approve` takes either `link_person_id` (+ `replace_channel_id`) or `full_name` + `kind` (no default: 422 without both) + optional `role`; `decline` takes no body. An answered request is a 409, a chat id or address already on someone else is a 409; the held messages are replayed (or dropped) in the background. |\n| `departments` | `GET\\|POST\\|PATCH\\|DELETE /departments`, `.../goals` | Department state and per-department goals. `PATCH /departments/{slug}` also takes `watched_entities` (≤50 names, `[]` clears) — the entities the research watch policy may add watches for and route to this department. A `cadences` spec that does not parse is rejected with a 422 (empty means no cadence, i.e. the check-in is off); a changed `check_in` cancels the pending check-in and queues the next one on the new schedule. `GET` and `PATCH /departments/{slug}` return the department state plus `next_check_in_at` (ISO UTC of the pending check-in, `null` when it is off, the workspace is solo or none is queued); the list route does not carry it. A new `head_person_id` must be a team member: an unknown id and one of the principal's contacts get the same name-free 422 (`person_id N is not on the team.`), so the route — open to any signed-in user — never reveals that a contact exists; an unchanged head is not re-checked. `POST .../goals` requires only `key_result`: a missing or blank `period_value` is filled with the current period for `period_type` in the user's zone (the same label `create_goal` uses), and `target` defaults to empty. `PATCH .../goals/{id}` rejects a blank `key_result` or `period_value` with a 422; `target` may be cleared. |\n| `agents` | `GET /agents`, `GET /agents/models`, `GET /agents/models/options`, `GET /agents/presets`, `POST /agents/presets/{id}`, `PATCH /agents/{id}`, `POST /agents/{id}/test` | Specialist metadata and Council overrides. `/agents/models` is the flat model allowlist the PATCH validator uses; `/agents/models/options` returns the same ids in the same order, each tagged with `provider`, `provider_label`, `route` (`direct` / `openrouter` / `local`) and a display `label`, for the Council's Provider → Model picker. `AgentDetail` carries `instructions` (additional instructions, appended after `prompt`, which stays the built-in prompt or its replacement); `PATCH` and `/test` accept `instructions` (max 4,000 chars, blank clears it). `GET /agents/presets` lists the Fast, Balanced and Thorough quality presets (each with `available` and the resolved `model` for this install) plus `active` (null when the council is Custom), `base` and `custom_agents`; `POST /agents/presets/{id}` applies one by writing per-agent model and deep-reasoning overrides and returns the same shape (404 unknown preset, 409 when the install allows none of its models). Each `AgentMeta` carries `visibility` (`core` or `internal`) so the Council's simple view can list core agents first. |\n| `personas` | `GET\\|PUT\\|POST\\|DELETE /personas` | Executive persona definitions. |\n| `alerts` | `POST /alerts/{id}/ack`, `POST /alerts/bulk-ack`, `POST /alerts/{id}/reopen`, `POST /alerts/review` | Groom the briefing queue. `ack` (`read`/`ack`/`dismissed`, optional `mute_topic`) also teaches a watch-sourced alert's watch (`trust_score`); `bulk-ack` takes explicit `alert_ids` and/or `older_than_days` + `category` (exempt sources skipped); `reopen` is the Undo for a `resolved` / `expired` / `dismissed` alert (never `ack` or an artifact / decision row; back to `unread` with every review stamp cleared and its TTL anchor refreshed, so it is live again even if older than its TTL); `review` runs the Executive's relevance review on demand (ignores the interval; still honours `ALERT_REVIEW_ENABLED`, the per-pass caps, the single-flight lock and per-alert idempotency) and returns the move counts. `bulk-ack` caps ids at 500, needs `older_than_days >= 1`, and applies watch feedback per row; `mute_topic` must be one of the alert's tags or a scoped `external:` / `department:` pattern. Alerts still surface only through the briefing (`/today` reads the live view) — there is no list, prefs, mutes, or live-stream endpoint. |\n| `artifacts` | `GET /artifacts`, `GET /artifacts/{id}`, `GET /artifacts/{id}/download?as=`, `POST /artifacts/{id}/archive`, `POST /artifacts/{id}/restore`, `DELETE /artifacts/{id}` | Browsable deliverables in any format — Markdown, HTML, Word, Excel, or a link into a connected app — with `format`, `downloads`, `external_url`, `supersedes_id` and, for an extension's kind of document, `collection` / `collection_label` on every summary (`orchestrator.extensions`; archive, restore and delete tell the collection first and answer 502 if it refuses). `download` renders the file (Word/Excel built at request time from the stored text; any Markdown artifact, workflow output included, can export `?as=docx`) and is always an attachment with `nosniff` and a sandbox CSP. Every route answers for the signed-in caller (`artifact_records.Viewer`): a drafted artifact is its owner's alone (`alerts.owner_person_id`, the person whose conversation published it; none = the principal's), a workflow output follows its run (`persistence.run_visible_to`), and anything the caller may not see is a 404 like a missing id, the principal included. `POST /alerts/{id}/ack` and `/reopen` answer 404 for someone else's drafted artifact the same way. |\n| `decisions` | `GET /decisions`, `POST /decisions/{id}/{approve,reject,cancel}`, `GET`/`PUT /decisions/classes/meeting_scheduling`, `GET /audit/reliability` | Approval-gated decision instances (e.g. calendar bookings). What approve/reject/cancel do is per class (`DECISION_CLASSES`, one `DecisionClassSpec` each; meeting booking books on approve and deletes on cancel; `delegation_reply`, an inbox reply card, is its approver's alone (`approver_only`) — hidden from everyone else, the principal included when it is a team member's — sends its Gmail draft on approve and, after a reject, deletes the draft unless it was edited), and an instance of a class with no spec gets 409 instead of being carried out as another. Only the principal, or the person the decision went to for approval (`approver_person_id`), may approve, reject or cancel it. Anyone else gets 403, and a decision nobody was asked about, or one private to the principal, is the principal's alone. The resolver is recorded as `resolver_person_id`, and a reject that loses the race to another answer is a 409. `GET /audit/reliability` is the principal's alone (403 otherwise), because it counts private decisions too. A proposed booking is surfaced on the briefing as a companion alert; approve/reject/cancel here also clear that alert. An approval whose caller resolves to the principal runs the booking inside `grant_contact_egress()`, so a meeting the principal proposed with a contact can be created. Such a booking's payload is marked `private`: it is proposed to the principal, left out of anyone else's `GET /decisions`, and a 404 for them on `GET /decisions/{id}` and every action route. Reviewed in the briefing — there is no separate proposals page. The class routes read and set how meetings are handled: both return `{decision_class: \"meeting_scheduling\", mode: \"propose\" \\| \"auto_execute\"}` (default `propose`); the `PUT` body is `{mode}`, principal-only (403 otherwise, open before a principal exists — but then only `propose` can be set: `auto_execute` is a 409 until a non-archived principal is on the roster), 422 on any other mode, and a change writes a `decision_class_mode_changed` audit row. In solo mode the class mode decides a booking, and `auto_execute` applies only to a turn the principal started on a verified surface — any other turn gets a proposal. |\n| `delegation` | `GET`/`PUT /delegation`, `GET`/`PUT`/`DELETE /delegation/voice`, `POST /delegation/voice/learn`, `POST /delegation/voice/describe`, `POST /delegation/voice/signature`, `PUT /delegation/inbox`, `POST /delegation/inbox/check`, `GET /delegation/replies`, `PUT /delegation/replies/{id}/text`, `GET /delegation/actions`, `PUT /delegation/handle-it`, `PUT /delegation/disclosure`, `PUT /delegation/training`, `DELETE /delegation/learned/{id}`, `GET /delegation/handled`, `PUT /delegation/team` | Act as me — the **caller's own** delegation only; nobody sets it for anyone else. It answers the principal, and a team member once the owner lets them; anyone else gets 403 `not_available_yet`. `GET /delegation` returns `{enabled, gmail: {status, message, email, connect_command, outlook_connect_command, provider}, inbox: {enabled, status, message, watch_since, last_poll_at, checking}, handle_it: {enabled, mode, available, sent_today, lead, lead_available}, training: {replies, follow_ups, actions, drafts, learned}, disclosure: {enabled, handle_it, approved_sends, line}, team}`, where `team` is the owner's switch for the principal while `DELEGATION_TEAM_MEMBERS` allows it — `{enabled, members: [{person_id, name, enabled, inbox, drafts_30d, sent_30d}]}`, counts only — and `null` otherwise. `PUT /delegation/handle-it` takes `{enabled?, mode?}` (`mode` is `careful`, `balanced` or `bold`; anything else is a 422 `bad_mode`) from a caller the API knows is that person — 403 `not_yours`, 409 `caller_signing_required` with only the shared secret — and turning it on needs Act as me and Draft replies to my inbox on (409 `act_as_me_off` / `inbox_off`); `GET /delegation/handled` returns `{replies: [{decision_id, sent_at, to_name, to_email, subject, body, open_questions, gmail_link, source}]}`, the caller's replies and follow-ups (`source` `follow_up`) sent on its own in the last 7 days; a card on `GET /delegation/replies` carries `source` the same way, `can_allow` while Replies (Follow-ups, on a follow-up) is in training, and `learns_style` while Drafts is. `PUT /delegation/disclosure` takes `{handle_it?, approved_sends?}` (any other field is a 422), the caller's own switches for the AI line on replies sent as them (`disclosure.enabled` is the install's `AI_DISCLOSURE`); turning one on needs no signed sign-in, turning one off does (409 `caller_signing_required`), and a change is audited as `delegation_disclosure_changed`. `PUT /delegation/training` takes `{replies?, follow_ups?, actions?, drafts?}` (any other field is a 422) and returns the `GET /delegation` shape; putting Replies or Follow-ups in, or Suggested actions out, needs no signed sign-in, anything else does (409 `caller_signing_required`), and putting Replies or Follow-ups in turns Take the lead as you off (`PUT /delegation/take-the-lead` on answers 409 `in_training` while they are). `training.learned` is `[{id, label, setting, example, uses, created_at}]`, what the caller allowed or kept in training (`setting` `replies`, `follow_ups`, `actions` or `drafts`; the kept example, or \"\"); `DELETE /delegation/learned/{id}` removes one of the caller's own (404 for anyone else's). `PUT /delegation/team` takes `{enabled}` from the principal alone (403 `principal_only`; 409 `not_available` when the install doesn't allow it). The Gmail `status` is `connected`, `not_configured`, `needs_reconnect`, `mismatch`, `no_email`, `shared_mailbox` or `error`, checked live with Google on each call. `PUT` takes `{enabled}` (any other field is a 422); turning it on needs the caller's own Gmail connected, otherwise a 409 whose code says why (`gmail_not_connected`, `gmail_needs_reconnect`, `gmail_mismatch`, `no_email`, `shared_mailbox`, `gmail_error`). The voice routes show, learn (from the caller's sent mail, one pass at a time — a 409 `in_progress`, `locked`, `too_soon`, `not_enough_mail`, `no_profile` or `changed` when it was locked or edited while learning, or a Gmail code), write it from the caller's own description (`POST /delegation/voice/describe` with `{description}`: one model call applies their words to the profile they have and returns it with a short `sample_reply`, saving nothing, so they review it and save it with `PUT`; a 409 `empty`, `too_long`, `in_progress`, `too_many` past 10 an hour or `no_profile`; no mailbox needed), edit and lock, and reset \"How I write\": a typed field that fails validation is a 422 `invalid_voice` listing each `rejected` field, and `clear_exemplars` / `clear_signature` drop those. `POST /delegation/voice/signature` reads the signature from the caller's Gmail settings again and changes nothing else (a locked profile stays locked), with the same Gmail codes as learning: a 409 when their mailbox isn't connected, it refuses the sign-in or the check itself fails (`gmail_error`), and a 502 `gmail_error` when reading the signature fails. On an Outlook mailbox it is a 409 `signature_unavailable`, since Outlook gives apps no signature to read, and the stored one is left alone. A caller `can_delegate` refuses — anyone but the principal, for now — gets 403 `not_available_yet`, which hides the Settings card. A request with no `x-caller-email` is a 403 `sign_in_required` unless the API runs under local login — a header-less call is not a sign-in (the caller is read through `api/caller.py`, as on every principal-only route). `PUT /delegation/inbox` takes `{enabled}` and turns **Draft replies to my inbox** on or off, returning the same shape as `GET /delegation`: on needs Act as me on (409 `act_as_me_off`) and the mailbox connected (the Gmail codes above, which keep their names for an Outlook mailbox too), and turning Act as me off turns it off too. `POST /delegation/inbox/check` starts a scan now in the background and answers 202 with the `inbox` state (409 `inbox_off` or `in_progress`). `GET /delegation/replies` returns `{cards: [...]}`, the caller's open reply cards from the database alone (no Gmail call): the decision id, the sender's name, address, relation and whether it was verified, the subject, when it arrived, what they wrote, the draft's recipients, subject and body, `open_questions`, `flags` and a Gmail link built from a fixed prefix. **Send** is `POST /decisions/{id}/approve`: it sends the card's draft exactly as it is in Gmail, after checking again that the caller is its owner — which on a server needs signed callers (409 `caller_signing_required` otherwise) — that both switches are on (`inbox_off`), no client slot is active (`client_slot`), the Gmail is connected (the Gmail codes), the draft is still there and unanswered (`draft_gone`, `you_replied`) and its recipients are allowed (`no_recipients`, `too_many_recipients`, `executive_recipient`, `not_from_you`). Recipients that changed, or a newer message in the thread, answer 409 `{code: \"confirm\", message, reasons, recipients}`; approving again with `edits: {recipients: <the list shown>, thread_moved_on: true}` is the second yes. **Send + allow** adds `edits.allow: true`: 422 `cant_allow` unless Replies (Follow-ups, on a follow-up card) is in training, 409 `learned_full` when their list is full, both before anything is sent; `edits.example: true` keeps a draft edited in the mailbox as how they write to that person while Drafts is in training. A draft edited in Gmail between those checks and the send is not sent (`draft_changed`). A double tap sends once (`already_handled`); Gmail refusing answers 429 `rate_limited` or 502 `gmail_error` with nothing sent, and a send Gmail didn't confirm answers 502 `send_unconfirmed` and is settled by the next inbox scan. Dismiss is `POST /decisions/{id}/reject`. `GET /delegation/actions` returns `{cards: [...]}`, the caller's own approval cards (`delegation_actions`): the decision id, when it was made, a one-line `why`, and each action's `index`, `kind` (`invite`, `message`, `add_contact`), `summary` and `text` (a message as it will be sent, or a meeting's description). **Approve** is `POST /decisions/{id}/approve` with `edits: {only: [indexes]}` (and `allow: true` for Approve + allow while Suggested actions is in training: 422 `cant_allow` otherwise or when nothing on it can be allowed, 409 `learned_full`; a card carries `can_allow`); it needs the card's own person signed in (403 `not_yours`, 409 `caller_signing_required`), Act as me on (409 `act_as_me_off`) and a card under a week old (409 `expired`), runs once (409 `already_handled`), and returns the decision with `final_payload_json.results`: per action `done`, `waiting` (sent to whoever approves meetings), `failed` with why, or `skipped`. Every change writes a private audit row. |\n| `history` | `GET /memories/history` (`?q=`), `PUT /memories/history/settings`, `PATCH`/`DELETE /memories/history/{id}`, `POST /memories/history/{id}/forget-conversation` | Always in the loop: the **caller's own** notes and switches only, resolved as for Act as me (a signed-in person on the roster, or the principal under local login; otherwise 403 `sign_in_required` / `not_on_roster`). `GET` returns `{notes, reply_notes, retention_days, effective_retention_days, company_retention_days, retention_choices, can_keep_notes, can_note_replies, can_set_company_retention, share_work_style, can_share_work_style}` (`can_keep_notes`: a team member on the People list may turn notes on; `can_note_replies`: they can use Act as me, so email replies are noted too; `share_work_style`: their own \"Share my work style with the team\" switch, `can_share_work_style`: a team member in a team workspace). `PUT` turns notes on only for someone who may keep them, and `share_work_style` on only for someone who may share it (403 `not_available` for either; turning either off always works), takes a person's retention only when shorter than the company's (422 `invalid_setting`), and the company retention only from the principal (403 `principal_only`). `PATCH` pins or corrects a note; `DELETE` forgets it; `forget-conversation` is \"Don't remember this\". A note that isn't the caller's is 404. Every change is audited privately to its person. |\n| `audit` | `GET /audit/logs`, `GET /audit/logs/{id}`, `GET /audit/sessions/{id}`, `GET /audit/usage`, `POST /audit/log` | Durable audit trail of side effects. `/audit/sessions/{id}` adds a per-session token cost summary; `/audit/usage` aggregates token usage and OpenRouter cost across all sessions (totals, by day, by model, and by source — the part of the system that made the calls — including server-side web-search counts), plus `scripts`: how many `run_script` scripts ran (and worked, and in workflows), the tool calls they made, their time, and `turns_avoided` — an upper bound on the model turns those calls would otherwise have needed (each call past a script's first) — and `python_jobs`: how many Python jobs ran (and worked, ran a kept Custom tool, took a chat attachment), their time, CPU, largest peak memory and bytes in and out, and the tokens and charge of the turns that ran one. The Token usage page shows it as a Scripts section. Rows private to the principal (`private_to_principal`: a turn about their private mail, or a row naming one of their contacts on their own turn) are theirs alone: for any other caller, resolved as for `/alerts`, the usage totals leave them out. Once a principal is on the roster, anyone else reads only their own rows (a teammate's own turns, their Act as me work) in the list, by id and in a session, and the principal reads those as actions only — what was done, when and in whose conversation, with the text, details and `full` left out, and no text search over them; any other row's id is a 404, and a session shows only the rows the caller reads. |\n| `architecture` | `GET /architecture/sections`, `.../sections/{id}` | This documentation surface. |\n| `guide` | `GET /guide/sections`, `.../sections/{id}` | Plain-language user-guide content surface — mirrors `architecture` (static, version-controlled files; no LLM on the serving path). |\n| `health` | `GET /health`, `GET /health/honcho` | Liveness probes. Only `/health` is unauthenticated; `/health/honcho` sits behind the gate like everything else, because the exemption is an exact-path set. `/health` also carries `google_tools_missing`, the pinned Google tools startup priming could not find: `[]` once it has checked and they are all there, a list of names when a workspace-mcp rename or the configured services and tool tier left one out, and `null` for no answer — Google Workspace is not configured, or the probe has not finished or it failed. Only `[]` asserts they are present. It also carries `gateway`, the MCP gateway's state from its supervisor (`orchestrator.gateway_boot`): `state` is `off` (MCP not enabled), `no_servers` (enabled, the config names none), `starting` (an attempt is running), `up` or `down` (every attempt so far failed; `next_retry_at` is the next one), with `attempts`, `up_since` and `email_poller` (whether the poller that rides on the gateway runs); the failure's own text stays out, since the route is open to anyone, and goes to the log and the owner's notice on Home. A hosted instance whose gateway never came up used to answer `ok` here with no email going out or in. Only `[]` asserts the tools are present, so a probe that died cannot read as healthy; Setup status says which of the three `null` means. |\n| `version` | `GET /version` | The running version, the latest release on GitHub and `update_available`, for Settings → About. The GitHub answer is cached 6h, only a semver `tag_name` is used and the release link is built from it; `UPDATE_CHECK_ENABLED=false` skips the call and still returns the running version. No in-app updater: upgrading is host-side (`docs/deployment.md#upgrading`). |\n| `setup_status` | `GET /setup/status` | Settings → Setup status: one light per part of the install — AI model, company setup, owner, the Executive's address, API protection, Gmail, your own mailbox (Act as me), Slack, Discord, Telegram, Google Chat, the scheduler, the daily brief (when and where it goes) and Honcho — as `{checked_at, checks: [{id, label, state, summary, fix, link, last_activity}]}`, where `state` is `ok`, `warn`, `error` or `off` (optional and not set up), `fix` says what to do in plain language, `link` is an in-app page that helps (`/people`, `/onboard`) and `last_activity` is the channel's latest `integration_inbound` audit time. It tests live, with at most one free read-only call per service, each bounded to 5 s: Anthropic `models.list` (so an organisation key missing `ANTHROPIC_WORKSPACE_ID` shows up), Slack `auth.test`, Telegram `getMe` and `getWebhookInfo`, Discord `users/@me` only while the bot is still connecting, and — once the owner's own Gmail credential exists — Google's token refresh and Gmail `users/me/profile`. It also reads the listeners the lifespan leaves on `app.state` (Slack's socket, the Discord bot and its task, the MCP gateway), the scheduler heartbeat and the pause switch. When `google_workspace` is configured, the lifespan also starts `MCPGateway.prime_pinned_tools()` in the background (held on `app.state.mcp_prime_task`, cancelled at shutdown), so the pinned Google tools named in the prompt are callable without a search. With `DRIVE_SYNC_ENABLED` the lifespan also bootstraps the `drive_sync_scan` heartbeat beside Notion's (see Scheduler); the Drive folder sync has no HTTP route, only the `openexecutive sync-drive` / `purge-drive` CLI. With `CONFLUENCE_SYNC_ENABLED` it bootstraps the `confluence_sync_scan` heartbeat the same way; that sync is run by hand with `openexecutive sync-confluence` / `purge-confluence`. Sample values copied from `.env.example` are named as such without being sent anywhere. No token reaches a response or a log line: probes report a status code, a service's short error code or an exception's class name. Requests within 5 s of a run get that run's answer and concurrent requests share one run (kept per app on `app.state`), so the button can't become a stream of calls to those services. Gated like every other route; the UI adds a sign-in light of its own, from its own settings. |\n| `documents` | `POST\\|GET\\|DELETE /documents`, `GET /documents/{filename}`, `GET /documents/sources`, `POST /documents/sources/{drive\\|onedrive\\|notion}/sync`, `GET /documents/{drive\\|onedrive\\|notion}`, `GET /documents/{drive\\|onedrive\\|notion}/{id}` | Upload, list, view extracted text, and delete indexed company docs. `GET /documents` rows carry `source: \"upload\"` and the `domain` the upload was indexed under. The connected-source routes back the knowledge page's single Company documents list: `/documents/sources` gives each source's `{id, label, enabled, syncing, last_run, last_error, interval_minutes, file_count}`; `/documents/drive`, `/documents/onedrive` and `/documents/notion` list synced files from the sync state (`{enabled, last_run, last_error, files: [{id, name, url, modified_at, synced_at, indexed}]}`; a Drive row also carries `unreadable_reason`, why a file with `indexed: false` has no text — e.g. a scan OCR could not read — or null); `/documents/{drive\\|onedrive\\|notion}/{id}` returns the stored text (a OneDrive id is `<drive id>:<item id>`) for an id on record (the path comes from the state, never the caller). They are read-only — a synced file is removed where it lives. `POST …/sync` starts one tick of the same sync the scheduler runs as a background task (202); 409 when the source is not connected or a tick is already running (every sync holds a per-process run lock, so a manual run never overlaps the heartbeat; the route also keeps its own started task per source and re-checks just before starting one, so two simultaneous requests start one tick, not two), 429 with `Retry-After` within 60 s of the last successful run or of the end of the last tick in this process, failed ones included, so a failing or slow source can't be re-run back-to-back. The page's text view never loads images from synced content (a remote image would be a read beacon for whoever edits the shared folder). Upload is keyed on the filename, so re-uploading a document replaces its chunks rather than duplicating them, and `DELETE` removes the rows as well as the file. `domain` must be one of the nine specialist domains (including `sales`) or `general`; anything else is a 400 rather than a 200 that indexes where no specialist can retrieve. A scanned PDF is converted (`knowledge.pdf_reader`) before it is indexed and in the text view, as are scanned PDFs in `POST /chat/upload` and the client / onboarding intake uploads. The upload is streamed to disk 1 MB at a time and refused with a 413 once it passes 50 MB, and the file is parsed in a short-lived child process (see the RAG section), so a large document does not stay in the API process's memory. A Word or Excel file that cannot be parsed, or whose parse runs out of time, is a 422 with a readable reason. When every parser is busy, the response is a 503 with `Retry-After`. |\n| `executive` | `GET /executive/status`, `POST /executive/pause`, `POST /executive/resume` | Operator pause switch for all autonomous work (scheduler, Gmail poller, workflow resumer); inbound chat and DMs stay live. Status returns `{paused, paused_at, paused_by, reason, held_actions, can_resume}` — `held_actions` counts due `pending` rows that fire on resume. `pause` takes an optional `reason` (≤200 chars) and is idempotent (re-pausing keeps the original start and reason); `paused_by` is the UI proxy's `x-caller-email`, else `api`. Behind the shared-secret middleware — not `SCHEDULED_ADMIN_TOKEN`, which the UI cannot send. Any caller may pause; `resume` is principal-only (`is_principal_or_self`, 403 otherwise; open while no principal is rostered; a header-less caller resolves to the principal as in `chat`), and status carries `can_resume` for the viewer so the UI hides Resume from everyone else. |\n| `workspace` | `GET /workspace`, `PUT /workspace` | Solo/team mode, the user's time zone and the principal's role (`memory.workspace_settings`). Both return `{mode, timezone, effective_timezone, role_kind, role_title, reports_to, remit, measured_on, company_domains, company_domains_custom}` — `timezone` is what the user set (null when unset), `effective_timezone` the zone in effect (`timezone`, else `USER_TIMEZONE`, else UTC), and each role field is null until set. `PUT` is a partial update: only the fields sent change; `mode` is `solo` or `team` (not null), `timezone` an IANA zone, or null/blank to clear it; `role_kind` is `owner`, `in_house`, `independent` or `other`, and `role_title` / `reports_to` / `remit` / `measured_on` are free text (trimmed, at most 120 / 120 / 500 / 300 characters), each null or blank to clear it; an unknown zone, a bad mode or role kind, an over-long role field or an unknown field is a 422 and changes nothing. Switching to solo cancels every pending department check-in, switching to team re-schedules them, and a new zone re-times the pending briefs and reflection; a role change has no side effects (the next turn reads it). `company_domains` is the company's own email domains (a teammate matches by local part on them — see Org): `GET` returns the ones in effect (the stored list, or the domain of the principal's primary address, with `company_domains_custom` false) only to the same caller the role is shown to, `[]` for anyone else; `PUT` takes a list (at most 10 plain domain names, never a free-mail provider's — 422 otherwise, the value never quoted) or null / `[]` to go back to deriving them, and a change is audited with the new list. Each change writes a `workspace_settings_changed` audit row (a role change adds `details.role_fields_changed`, the names of the fields that changed — never their text). The role is the principal's: `GET` returns it only to a caller `PUT` would accept and reads it as nulls for anyone else. `PUT` is the principal's alone (`is_principal_or_self`, 403 otherwise; a header-less caller resolves to the principal as in `chat`) and open while no principal is rostered, so first-run setup can pick a mode. Both work before onboarding — unlike `company-profile`, nothing here needs a profile. |\n| `scheduled` | `GET\\|DELETE` scheduled actions (`?status=…&order=asc\\|desc`) | Pending and fired scheduled actions; `order` flips the `run_at` sort (asc=soonest-first for the upcoming queue, desc=most-recent-first for terminal-status history). `DELETE /scheduled/{id}` cancels a `pending` row (409 otherwise). Like pause it only stops work, so any signed-in user may — the UI proxy's `x-caller-email` is trusted when the request also carries the `BACKEND_SHARED_SECRET` `x-api-key` — as may a matching `X-Admin-Token` (`SCHEDULED_ADMIN_TOKEN`) or a loopback caller with no token set; otherwise 401 (token set) or 503. Audited as `scheduled_action_cancelled`. |\n| `watchlist` | `GET\\|POST\\|PATCH\\|DELETE /watchlist`, `POST /watchlist/{slug}/approve`, `POST /watchlist/{slug}/decline` | External-monitoring watchlist + signals. Rows carry `origin` (`manual` \\| `executive` \\| `research` \\| `research_proposed`); `approve` turns a research suggestion (`research_proposed`, `dry_run`) into a live watch, `decline` `{reason: not_relevant \\| too_noisy \\| wrong_source}` removes it and records the decline (or, for `too_noisy`, keeps it live at a high floor), both 409 unless the row is a pending suggestion; `DELETE ?reason=` on a research-origin row records the decline too. |\n| `workflows` | `GET /workflows`, `POST /workflows/{name}/runs`, `GET\\|POST\\|PUT\\|DELETE /workflows/custom`, `GET\\|DELETE /workflows/custom/{name}/targets`, `POST /workflows/runs/{run_id}/decision`, `GET /workflows/tools/search?q=`, `GET /workflows/tools/describe?names=` | Workflow catalog, run management, and user-created (dynamic) workflow CRUD. Custom definitions come back with a server-managed `owner_person_id` (the creator — the web caller on `POST`, set on insert only; a client-sent value is ignored), who is asked to approve a workflow's first write to a new target. `GET /workflows/custom/{name}/targets` lists the targets its tool steps may write to without asking and `DELETE …/targets?value=` forgets one. `POST /workflows/{name}/runs` is a 403 (\"Only the principal can run this workflow.\"), audited, before any run row exists, when the workflow is one only the principal may start in the workspace's mode (`weekly_review` always, `morning_brief` in solo) and the caller is not the principal. A request with no `x-caller-email` counts as the principal; with no principal on the roster, no signed-in caller does. This governs starting a run only. A run started by hand (this endpoint, or `run_workflow` / research in chat) records its starter as `owner_person_id` and is theirs alone: `GET /workflows/runs` lists the team's (scheduled, no owner) runs plus the caller's own and the ones waiting on them, and `GET` / `DELETE /workflows/runs/{run_id}` and `POST /workflows/runs/{run_id}/decision` are a 404 for anyone else's, the principal included. A signed-in email that is on nobody's People entry cannot start one (403), and a run whose starter can't be read is refused (503); its steps read and draft documents as the starter only. `POST /workflows/runs/{run_id}/decision` with `{decision: \"approve\"|\"reject\"}` answers a run awaiting a yes/no sign-off from the web app — 403 unless the caller is the person it waits on or the principal, 409 if it isn't awaiting or needs a written reply — through the same `apply_resolution` a chat reply uses. Custom create/update also rejects (422) any action-step tool that does not resolve, and so does `POST /workflows/custom/{name}/activate` when turning a workflow **on** — that click is the approval for a tool workflow chat saved switched off (turning off is never checked). Turning on a workflow with action steps requires the body `{is_active: true, definition}` carrying the definition the user reviewed; if the stored one differs (ignoring `is_active` and timestamps) it returns 409, and the switch itself is a compare-and-set on the validated revision (`dynamic_store.activate_if_unchanged`, keyed on `updated_at`), so a save that lands while the tool check awaits the gateway — even from another process — is a 409 too, so only what was shown gets switched on. `GET /workflows/custom` lists inactive definitions too; `GET /workflows/{name}` 404s for them. The two `tools` endpoints return `{tools: [{name, description, read_only, source}]}` for the advanced editor's tool picker and the review card; `read_only` is true only when the name says it reads (a label, not a control). The run stream adds a `progress` event (`step_id`, `summary`) while an action step uses tools. Each catalog entry (`WorkflowMeta`) carries `is_custom`, `background` (true for the system-run built-ins the UI files under “System”) and `quick` (true for a Quick workflow, one per playbook nothing else follows, named `quick_<playbook>`). The run endpoint streams SSE; its `awaiting_human` event carries `delivery` (`self` \\| `sent` \\| `suppressed` \\| `alerted` \\| `failed`) alongside `person_id` / `question` / `awaiting_until`, because the outbound guard or an unreachable approver means the question may never have been asked — a client must not render “waiting on them” for those. A paused run ends the stream with neither `done` nor `error`, so that `awaiting_human` frame carries `terminal: true` to say so explicitly, plus `resumable` — whether the run continues by itself once answered or stops at the gate. `GET /workflows/runs/{run_id}` returns the run row with the resume payload replaced by a small `resume_progress` summary (`gate_step_id`, `completed_step_ids`, or `null`): the payload holds every completed step's full text, and the run-detail page polls this endpoint while a run is unfinished. |\n| `knowledge` | `/knowledge/builtin`, `/external`, `/search` | MBA knowledge base and external sources. `/search` is the introspection parallel of `retriever.retrieve` and mirrors its filters — including the `general` catch-all on the company collection — so the panel cannot report a specialist seeing nothing that it does retrieve in chat. It accepts `general` in `domain_filter` for the same reason. `/search` applies the same review gate as `retrieve()` — withheld (pending or rejected) built-in, external and failure rows are dropped, so the panel never advertises knowledge the Executive cannot use; it degrades to unfiltered rather than failing if review state is unreadable. `POST /knowledge/builtin` refuses a name already held by shipped content, and `POST|DELETE /knowledge/failures` now register and deregister for review — without that a user-authored failure case study had no review row, so no SME decision could block it. |\n| `skills` | `/skills`, `/skills/search`, `/skills/{name}/restore` | Skill registry (the UI's **Playbooks**) CRUD and search. `PUT` on a built-in saves a company customization that shadows it; `DELETE` returns `{name, outcome}` — `deleted`, `reverted` (customization removed, built-in back) or `hidden` (built-in hidden for this company); `restore` un-hides; `GET /skills?include_hidden=true` lists hidden built-ins. List and detail carry `used_by` — `[{name, title, is_custom}]` of the workflows that follow the playbook (switched-off custom ones included) (`WorkflowMeta.playbooks` is the other direction). |\n| `evals` | `/evals/scenarios`, `/evals/runs` | Eval scenarios and run results. `POST /evals/runs` is a 403 when a workflow scenario names a workflow that only the principal may start in the mode it runs in (the weekly review; the morning brief in solo) and the caller is not the principal — the Jobs page's rule for starting a run; stored results are read under the existing `/evals/runs` rules. |\n| `memories` | `/memories/{decisions,initiatives,advice}`, `GET /memories/facts`, `POST /memories/facts/{fact_id}/{retire,approve,decline}`, `GET /memories/facts/approval`, `PUT /memories/facts/approval/{person_id}`, `GET /memories/people`, `GET /memories/people/{person_id}/conclusions` | Episodic-memory record management; the standing facts the Pulse Corrections tab reads (`{facts: [...], can_retire, retirable_ids, can_review}`; each fact carries `recorded_by_role` / `recorded_by_name`; `?include_inactive=` default true, honoured for the principal only; anyone else gets the active rows plus their own `proposed` ones, with the provenance (`session_id`, `turn_id`, `recorded_by_person_id`, `retired_reason`, and `source_quote` except on their own facts) blanked, never retired, replaced or declined text; `?limit=` 1–500) and their retire (the principal any fact, a teammate only one they recorded that the principal has not approved — else 403; the audit row names the teammate; 404 for an unknown or `profile` row, 409 when no longer active; writes a private `fact_retired` audit row); approve / decline a teammate's `proposed` fact (principal only, else 403; 409 when it is not proposed; private `fact_reviewed` row); and the per-teammate \"needs my approval\" switch (on by default; `GET` lists `[{person_id, full_name, needs_approval}]` for every active team member but the principal, `true` for anyone not yet set; `PUT` takes `{needs_approval}`, 404 for anyone else; both principal only; private `fact_approval_changed` row); plus the read-only peer-memory overview the Pulse People tab reads (`{status: ok|disabled|error, people: [...], conclusion_total}`; `?recent=` 1–50, default 5) and one person's full conclusion list, paged newest first (`{status, person_id, items, page, size, total, has_more}`; `?page=` ≥1, `?size=` 1–100, default 50; 404 when the person has no peer). Peer memory is each person's own: the overview holds only the caller's entry (none for a caller off the roster; `conclusion_total` counts only theirs), the principal included, and `/conclusions` for anyone but the caller is a 404. |\n| `review` | `/review/items`, `/review/stats`, `/review/trusted-defaults`, `POST /review/curate`, `POST /review/bulk-approve` | Knowledge review queue and annotations. Shipped knowledge registers as a trusted default (`approved` with a NULL `reviewed_at`), so the queue starts empty; `curate` (`{domain, action: start|stop}`, domain required) opts one domain in or out, and `trusted-defaults` returns domain → unreviewed count. `bulk-approve` takes a non-empty `domain`, `item_ids` (max 500) or `all_pending: true`, and 400s with no selector; it returns `{approved_count, item_ids}`. |\n| `onboarding` | `/onboard/interview/understand`, `/onboard/interview/start`, `/onboard/interview/message`, `/onboard/interview/draft`, `/onboard/interview/{id}`, `/onboard/interview/commit` | Conversational company setup. The `onboarding_interviewer` agent asks clarifying questions, then emits a draft profile + people + departments. **Nothing is persisted until `POST /onboard/interview/commit`** — the interview itself never writes. `start` is multipart (description + optional deck/one-pager uploads). `commit` answers 403 when the draft would make a different person the owner and the caller is not the current owner (setup demotes the old principal, and any signed-in user can open it). It also takes an optional `owner_email` — the principal's sign-in email, which the review screen pre-fills from the signed-in user — checked before anything is written (422 if it is malformed, already another person's, or would replace the principal's existing email — setup only fills in a missing one; 403 if the caller is not the owner and it is not the address they signed in with, since the roster is the sign-in allow-list) and saved on the principal's People row, so the owner's chats resolve to them from the first turn. |\n| `workflow_designer` | `POST /workflows/designer/start`, `POST /workflows/designer/edit`, `POST /workflows/designer/message`, `POST /workflows/designer/draft`, `GET /workflows/designer/{session_id}` | The conversational New workflow wizard, and editing a saved workflow by conversation. `/edit` (`{name}`) opens a session on a saved custom workflow with no model call: the stored definition is the starting draft, and every response then carries `editing` (its name) and `original` (the stored definition as the session opened on it); drafts keep that name and its on/off state whatever the model writes (404 for an unknown workflow). The UI saves one with `POST /workflows/custom/{name}/save-edit` (`{session_id, definition}`): the server saves the session's own draft, never a client-sent body, and only when it equals the `definition` the user reviewed (a later message is a 409, so the click saves only what was shown); it re-validates it, keeps the stored on/off state, and writes only if the stored workflow is still the version the conversation opened on — otherwise 409, as it is for a session about another workflow or one with nothing drafted yet. It sits under `/workflows/custom` so anything that limits writes to custom workflows covers it too. The `workflow_designer` agent asks clarifying questions (`phase: \"question\"`, with `hint` and up to four suggested `options`), then returns `phase: \"draft\"` with `draft.definition` (exactly the body `POST /workflows/custom` takes), `summary`, and `assumptions`; every response carries the `transcript`. **Nothing is persisted here** — sessions are in memory, and the UI saves through `POST /workflows/custom`. Errors are fixed strings (422 over the 8,000-char message cap or the transcript cap, 404 for an expired session, 409 while another turn on the same session is still running, 502/504 for model failure or timeout). Mounted ahead of the `workflows` router. |\n| `python_jobs` | `GET /python-jobs/{job_id}/{name}` | A result file a Python job (`run_python_job`) wrote, the principal's alone (403 otherwise), served as a download (`Content-Disposition: attachment`, `Content-Security-Policy: sandbox`, `nosniff`, `Cache-Control: no-store`); 404 for a bad id or name or a file past its 7 days. |\n| `saved_tools` | `GET /saved-tools`, `GET\\|PUT /saved-tools/{name}`, `POST /saved-tools/{name}/rollback` | The scripts the Executive saved as tools (Settings → Advanced → Saved tools), the owner's alone (403 otherwise). The list gives each tool's name, description, on/off, current version, `kind` (`script` or `python`, a kept Python job) and the tools it calls, plus whether `SAVED_TOOLS_ENABLED` is on; the detail adds the script, every version and the last 20 runs. `PUT {enabled?, workflows?, version?}` turns one on or off (off also turns it off for workflows, so turning it back on never re-arms unattended runs), and turns the named `version` — the one the owner looked at, never whatever is current by then — on for workflows (or workflows off); a Python tool never turns on for workflows (409) — turning workflows on lets more run unattended, so it needs a request tied to the owner (signed sign-ins or local login, as Take the lead's switches do; 409 otherwise); `rollback {version}` makes that version the one that runs. Both are audited as `saved_tool_changed`. The Executive saves tools itself through `run_script`; there is no create route. |\n| `onboarding` (fallback) | `/onboard/start`, `/onboard/answer`, `/onboard/status/{id}` | The original 12-step form wizard, kept as a fallback (UI at `/onboard?mode=form`) and used by the `openexecutive onboard` CLI. Its final answer saves the profile and adds people with their emails and a principal, so once there is an owner only they can send it (403, and the session rolls back so the owner can still finish it). `/onboard/start` reads the workspace mode once for the session: solo skips the Team Size, Team Members and Fractional Executives steps. Each status response's `current_step` / `total_steps` count only the steps that session asks, and `optional` says whether the current step can be skipped. |\n| `company-profile` | `GET\\|PATCH /company-profile` | Structured company profile. |\n| `alerts` (private cards) | `POST /alerts/{id}/ack`, `/reopen`, `/alerts/bulk-ack` | An alert tagged `private:principal` (see Today) is a 404 on ack and reopen for anyone but the principal, and their bulk sweep skips it. A roster-request card (source `roster_request`) is a 409 on `ack` even for the principal — it is answered at `/people/requests/{id}`, since acking would leave the sender waiting with nothing to show it — and, as an exempt source, `bulk-ack` and `reopen` skip it. |\n| `auth` | `GET /auth/allowed-emails` | Non-archived **team members** with an email, offered to the UI's sign-in gate — a contact is never on it, so adding a client to reach them by email no longer lets them sign in. The gate takes the **union** of this roster and its own `ALLOWED_EMAILS` env list, so env entries always work (and are checked first, short-circuiting the fetch) and roster entries are additive — a roster change can never revoke a configured operator. With local login (`make dev` with Google sign-in not set up — the UI then listens on 127.0.0.1 only) the UI signs in without an email, sends no `x-caller-email`, and the backend resolves the caller to the principal, as it does for the CLI. |\n| `fixtures` | `/fixtures`, `/fixtures/{name}/load` | Demo-company fixture load/reset/snapshot. `POST /fixtures/reset` leaves no departments, like a new install (`departments_seeded` is always 0). |\n| `clients` | `/clients`, `/clients/generate`, `/clients/cockpit`, `/clients/save`, `/clients/{slug}/activate` | Client-company slots — multi-client mode for fractional use; create from current/blank/AI-generated intake draft (pasted notes and/or file attachments, multipart on `/clients/generate`), save-back switching, engagement metadata (PATCH), cross-client cockpit, delete. See the Client Companies section. |\n| webhooks | `POST /webhook/telegram`, `POST /webhook/google-chat`, `POST /webhook/slack` | Inbound integration callbacks (self-verified). `/webhook/slack` answers 503 unless `SLACK_SIGNING_SECRET` is set. |\n| MCP server | `POST\\|GET /mcp` | Open Executive exposed as an MCP server (Streamable-HTTP). Not a router — a mounted FastMCP sub-app. Same shared-secret gate (`x-api-key`); exposes company context as resources and the specialist council as tools. See the MCP Server section. |\n\n**Take the lead** (`api/routes/take_the_lead.py`): `GET /take-the-lead` returns the As the Executive switch, its six Ask first switches (`{kind, label, hint, on}`, the hint a plain line on what each one catches), the company's rules, whether this server can tie a change to the owner (`available`), and whether the Executive is paused. `PUT /take-the-lead` takes `{enabled?, ask_first?}`, and `POST /take-the-lead/rules` / `DELETE /take-the-lead/rules/{id}` add or remove a company rule (`{kind: person|domain|words|amount, value}`, 422 on a bad one). All four are the principal's alone (403). Anything that lets more happen on its own (turning it on, turning an Ask first off, removing a rule) needs a caller the API can tie to them (`delegation.verified.caller_refusal`, else 409). `GET /today/activity` adds `took_the_lead` rows (what Take the lead did, named, not quoted) and, for the caller alone, `sent_as_you` rows for what Handle it for me sent as them. Under `/delegation`: `PUT /delegation/take-the-lead {enabled}` is Take the lead as you (the owner's only for now; turning it on turns Handle it for me on), and `GET|POST /delegation/take-the-lead/rules` and `DELETE …/rules/{id}` manage the caller's own rules. `HandleItOut` gains `lead` and `lead_available`. A `take_the_lead_action` decision is approved or rejected through the existing `/decisions/{id}/approve|reject`. Training: the response also carries `training` (In training: everything waits unless allowed), `learned` (`{id, label, feature, example, uses, created_at}`: what it was allowed, the edit kept as an example by field) and `suggested` (`{key, label, approvals}`); `PUT` takes `training?` too, and leaving training while on needs the same provable owner as turning it on. `POST /take-the-lead/learned {key}` allows a current suggestion (404 for anything else; provable owner), `DELETE /take-the-lead/learned/{id}` makes it ask first again. `learned` also lists the owner's own Act as me senders (`feature` `act_as_me`), never anyone else's, and Remove works on those too. On a `take_the_lead_action` card, `POST /decisions/{id}/approve` takes `edits.input` (the card's editable fields, 422 for any other; the principal's alone, 403 for an area approver) and `edits.allow: true` (a training card only, 422 otherwise; the principal from a provable request, 403 otherwise), finishing `approved_with_edit` when a field changed.",+ "markdown": "The FastAPI surface lives in `openexecutive.api.main`, which mounts one router per topic. A shared-secret middleware gates every request via an `x-api-key` header, except `/health` and the `/webhook/*` callbacks (which carry their own verification). With local login (`OE_LOCAL_LOGIN=1`, which only `make dev` sets, and only while neither Google nor SSO sign-in is set up) a second middleware answers 403 to any request whose raw `Host` is not `localhost`, `127.0.0.1` or `[::1]` (except a webhook that verifies its caller: Google Chat and Slack always, Telegram only with a `TELEGRAM_WEBHOOK_SECRET` Telegram can send), and to any write whose `Sec-Fetch-Site` is present and not `same-origin`/`none`. The UI signs that owner in with no password and this API usually has no secret, so without it a web page in the owner's browser could drive the API as the principal — by DNS-rebinding its own hostname to 127.0.0.1, or by posting a plain form from another site or localhost port. CORS is restricted to the UI origins in `BACKEND_ALLOWED_ORIGINS`, plus the `make dev` UI on `localhost:3000` only when `OE_PUBLIC_DEPLOYMENT` is unset, so a public instance never answers a localhost page with credentials. The gate is off when `BACKEND_SHARED_SECRET` is unset — intended for local development only — so any internet-reachable deployment sets `OE_PUBLIC_DEPLOYMENT`, and `create_app()` then refuses to boot without the secret rather than serving an unauthenticated API.\n\n**Who is calling** is read in one place, `api/caller.py`, which answers with a `Caller` kind and email; a test fails on any other read of an `x-caller-*` header. By default (`open`) it is the `x-caller-email` the UI proxy stamps from the sign-in, trusted because whoever holds the shared secret is trusted as the proxy, and a request with none runs as the principal. **Signed callers** remove that trust. With `CALLER_ASSERTION_PUBLIC_KEYS` set, the proxy signs every request with an Ed25519 key only the UI holds, and a third middleware checks the `x-caller-assertion` header:\n\n- **What it covers.** It is good for one method, the exact path and query, at most 120 seconds, and one use. The API keeps used ids in memory.\n- **What it names.** A `user`, by email, or the `operator`: local login, which runs as the principal.\n- **No caller header at all** is a `service`, for scripts or MCP clients holding only the secret. It is never the principal, not even on an install with no owner yet, so it can't save a first setup.\n- **Anything else is a 401.** That includes an `x-caller-email` without an assertion (`caller_assertion_required`), and a bad, expired, reused or mismatched assertion (`caller_assertion_invalid`).\n\nPublic keys that can't be read stop the boot, rather than fall back to trusting the header. `scripts/make-caller-keys.py` makes the pair, and `scripts/mint-caller-assertion.py` signs one request for curl. The API holds only public keys. Setup's API-protection check warns while a shared secret is set without them.\n\nEndpoints grouped by router:\n\n| Router | Key endpoints | Purpose |\n|---|---|---|\n| `chat` | `POST /chat`, `POST /chat/stop`, `POST /chat/add`, `POST /chat/background` | SSE stream of a live Executive turn. `POST /chat/background` starts a new chat that the server answers to the end with nobody connected (a phone approving a card, then closing the app): it answers `202` with the new `session_id` once the same caller, access and quota checks as `/chat` pass, the turn saves itself as a `/chat` turn does, and one caller may have three running at once (`429` beyond that). `POST /chat/add` hands the running turn a message the person typed while it works; the turn takes it at its next step and the stream names it in a `message_added` event, and a second `POST /chat` on the same conversation waits for the first to finish. The request body optionally carries `page_context` (route, page title, guide section id, and a form descriptor with current values) — sent only by the Ask OE side panel so the Executive can explain the current page or propose form values. When the Executive calls its `propose_form_values` tool, the stream emits a `form_patch` event (`{type, form_id, fields, rationale, iteration}`) that the panel applies into the on-screen form as highlighted suggestions; the user reviews and saves through the form's normal submit path. Each round of tool calls also emits an `activity` event (`{type, label, tool, iteration}`) naming what is running — progress only, forwarded verbatim and never persisted with the message, unlike an `action_taken` chip. A `session_id` in the body must be a chat the caller may use (the same ownership rule as `sessions`). If it isn't, the turn runs in a fresh chat instead, so nothing is written into someone else's session and the reply looks the same as for an unknown id. An unknown namespaced id (`slack:…`, `telegram:…` and so on) is ignored and a fresh chat is started, because those ids belong to the channel adapters and claiming one first would make the caller its owner. The client mints a `client_turn_id` and sends it with the turn; `POST /chat/stop` takes that id and halts the turn mid-flight, so the button is live from the moment Send is pressed rather than only once the first SSE byte arrives. A stopped turn emits a `stopped` event and then the usual `done` over the same still-open stream — never an `error` — and whatever streamed so far is persisted and flagged. The endpoint returns 404 both for an unknown id and for another caller's turn, so it cannot be used to probe which turns are live. An optional `memory_text` (1–2000 chars) is what peer memory records as the caller's words instead of `message` — the briefing handoffs send it because their seed quotes the Executive's own card; `POST /chat/upload` derives it from the typed text and filenames. Since it never reaches the transcript, the `chat_turn` audit row keeps it beside `message`. After the reply — a stopped or timed-out one too, before the `stopped` / `error` / `done` frames — a turn that looked at anything sends one `sources` event, `{type, session_id, sources: [{kind, title, url}], unavailable: [area]}`: `kind` is `company`, `knowledge`, `notion`, `research`, `document` or `web`, `url` is only ever an http(s) link or, for an earlier document, `/artifacts/<id>`, at most 12 sources (6 from the web, pages the reply cites first), and `unavailable` names parts of the analysis (\"finance\") whose specialist failed or said nothing every time it was asked. It is persisted with the reply as `chat_messages.sources`. A request that carries `x-caller-email` marks its turn signed in (`Session.web_caller_signed_in`), which Act as me needs on a deployment without local login. |\n| `sessions` | `GET /sessions`, `GET /sessions/{id}`, `GET /sessions/{id}/messages`, `DELETE /sessions/{id}`, `POST /sessions/{id}/messages/{message_id}/feedback`, `GET /sessions/{id}/followup` | List, read and delete saved chat sessions (assistant messages carry their row `id` and any `feedback`). The list is scoped to the caller, and each chat carries `preview`: its last message as one plain line, Markdown marks stripped and cut at a word near 120 characters, with `You:` before the person's own words. With `?q=` it is a search: the caller's own chats whose title or message text contains the words (case-insensitive, `LIKE` with wildcards escaped), each with `match_count` (messages that contain them; 0 for a title-only match) and `snippet` (the newest matching message, around the match, prefixed `You:` or `Executive:`). Scoped exactly like the list, so nobody else's conversation can match. The Chats page searches this way and opens a result with `?find=`, so the chat starts on that message and steps through the others. A chat-app conversation started with /new is left off the list until its first turn (`memory.conversations`). Every per-session route checks ownership, because session ids are guessable (`slack:dm:<user id>`, `telegram:<chat id>`): only the session's owner or the principal gets through, and a legacy row with no owner is the principal's alone. A teammate's own chat (a web chat, a DM, a private Telegram chat; not a channel or group conversation, `chat._shared_space`) is theirs alone, the principal included, as their mail with the Executive is. Anyone else gets the same 404 as for an unknown id, so the routes can't be used to find out which chats exist. The one other way in is having started the chat in this process (matched by Person id or verified email, so it survives the caller being added to the roster), which is how a caller the roster can't resolve keeps using their own chat. That record is in memory, so after a restart such an ownerless chat is refused for reads. The principal can continue someone else's ownerless chat without becoming its owner. Deleting a session also drops its in-memory copy, so a later turn naming that id starts fresh. The feedback route records 👍/👎 (`{\"feedback\": \"up\"|\"down\"|null}`) on one assistant reply; only the session's own caller or the principal may rate it. The rater is stored (`feedback_by_person_id`), and a 👎 on a reply to the rater's own message triggers a working-style pass for them (paced; see attunement). The chat stream's `done` event carries `message_id` for the persisted reply. The followup route returns `{\"suggestion\": string|null}` — one suggested next user message, written by the utility-fast model from the last few turns, that the chat composer shows as its greyed placeholder (Tab / → or the inline chip fills it in without sending). It is null unless the session ends on a persisted assistant reply, and null (uncached) when the model fails. Same ownership check as feedback; successful suggestions are cached in-process per (session, reply id). Messages from `GET /sessions/{id}/messages` carry each assistant reply's saved `sources` (the same shape as the chat stream's `sources` event, without `type`), so a reloaded chat shows them again. |\n| `today` | `GET /today`, `GET /today/activity`, `GET /today/activity/daily`, `GET /today/brief-delivery`, `GET /today/top-three`, `GET /today/weekly-review` | Morning-brief aggregation, recent-action rail, and Pulse heartbeat heatmap (per-day activity counts). `GET /today` carries the viewer's cached \"What's going on\" `narrative` with `narrative_generated_at` (when it was written) and `narrative_stale` (a fresher one is being written — the page re-polls; see Today). A proposal backed by a roster request carries `roster_request` (the new sender's server-derived details and held-message previews; the principal's only) and is answered through the `people` routes below. `brief-delivery` returns the latest morning brief or end-of-day digest that didn't reach the owner, as `{brief, at, problem, fix, readable}` in plain language (`readable` is false when it couldn't be written, so there is nothing to read), or null — null while briefs go out, once the cause is fixed, while the scheduler is off, and for anyone but the owner (`chat._caller_is_principal_or_unclaimed`); it carries no address or channel id. `top-three` and `weekly-review` feed the solo Briefing's own cards and answer only in solo mode and only to the principal (`workflows._caller_is_the_principal`: a principal match or no caller header, never an unclaimed roster); anyone else, and team mode, get null. `top-three` returns `{items: [{key, kind, text, why, slot}]}` — the morning brief's top three from the same code (`build_top_three(principal_due_soon())`), `slot` a free block like `10:00–11:00`, `\"\"` when none is left, null when no calendar was read — and is kept off `GET /today` because its calendar read may take up to 4 s. `weekly-review` returns the latest completed `weekly_review` run as `{run_id, completed_at, period, top_three, excerpt}` (next week's top three as plain text; `excerpt` when that list is empty), or null when none has completed. |\n| `people` | `GET\\|POST\\|PATCH /people`, `POST /people/{id}/archive`, `GET /people/requests`, `GET /people/requests/{id}`, `POST /people/requests/{id}/approve`, `POST /people/requests/{id}/decline`, `GET\\|POST /people/{id}/open-loops`, `POST /open-loops/{loop_id}/close`, `GET /people/{id}/outreach`, `GET\\|PUT\\|DELETE /people/{id}/attunement` | Roster CRUD and scope lookups. Every `Person` carries `kind` (`team` / `contact`). `GET /people` lists team members only unless `?include_contacts=true` (the People page asks for both; the department-head and workflow pickers keep the default); `POST` / `PATCH` accept `kind`, and a principal contact is a 422 either way. They also take `email_aliases` (other addresses the person writes from, at most 10; on `PATCH` the full list replaces the current one, omitted leaves it): an alias matches their mail and may be emailed but never signs in; a malformed one is a 422, and an alias — or a new primary `email` — that is already someone else's address or alias is a 409. Every `POST` / `PATCH` then closes any pending roster request whose sender now matches someone and replays its held messages. Adding, editing and archiving (`POST`, `PATCH`, `/archive`) are the principal's only, or anyone's while no one is principal yet so a first setup can add its owner (`chat._caller_is_principal_or_unclaimed`, the check behind `PUT /workspace`; a request with no `x-caller-email`, such as the CLI or local login, counts as the principal). Anyone else, a person editing their own row included, gets 403 before the person lookup, so it can't probe which ids exist. Contacts are private to the principal (`caller_is_principal`: the signed-in email is the principal's, or no `x-caller-email`; stricter than the owner rule above, so while no one is principal nobody is): for anyone else `include_contacts` is ignored, a contact's id is a 404 on `GET /people/{id}` and open-loops (exactly as for a missing id; `PATCH` and archive are already a 403 for them), and creating a contact or turning someone into one is a 403, even on a first setup with no principal yet. `GET /people/me` returns `{person_id, is_principal}` so the UI offers contacts to the principal only. `GET /people/by-scope/{token}` never returns a contact. Archiving a person closes their open loops. The open-loop routes list what a person owes (soonest due first) and close one (`reason`: done / not_needed / cancelled) — both the principal's or the owner's only (403 otherwise, via `people.store.is_principal_or_self`). `POST /people/{id}/open-loops` `{task, due_date?}` assigns that person a task (201 with the loop; `due_date` is a local date, due 17:00 in the user's timezone, clamped to 60 days, default 2 days): any active team member may assign anyone on the team, 403 for anyone else; 409 for an archived person, a contact (as seen by the principal), a person at the open-loop cap, a duplicate or open loops turned off; 422 for an empty task. Nobody is messaged at assignment — the owner is chased once it is due. `/outreach` returns, per kind of proactive outreach over 30 days, `sent` / `replied` / `acted` / `ignored` / `pending` (voided DMs are excluded) — same access rule, checked before the person lookup so it can't probe which ids exist. `/attunement` reads, replaces (`rules`: up to 4 strings, or omitted to only set `locked`) or resets the person's working-style rules — same access rule, 404 for an archived person; `PUT` rejects a rule that is not purely about style with 422. Archiving a person also drops their working style and frees their aliases. The **roster-request** routes (declared before `/people/{person_id}`) are the principal's alone (`caller_is_principal`; anyone else gets 404, as for a missing id): `GET /people/requests?status=pending|approved|linked|declined|expired|superseded|all` lists up to 100 (`id`, `channel`, `channel_ref`, sanitised `display_name`, `profile_email`, `on_company_domain`, `suggested_kind`, `suggested_person_id` / `_name`, `status`, `resolved_person_id` / `_kind`, `message_count`, timestamps, `ack_sent`, and `previews` of the held messages while pending — shown to the principal, never to a model); `approve` takes either `link_person_id` (+ `replace_channel_id`) or `full_name` + `kind` (no default: 422 without both) + optional `role`; `decline` takes no body. An answered request is a 409, a chat id or address already on someone else is a 409; the held messages are replayed (or dropped) in the background. |\n| `departments` | `GET\\|POST\\|PATCH\\|DELETE /departments`, `.../goals` | Department state and per-department goals. `PATCH /departments/{slug}` also takes `watched_entities` (≤50 names, `[]` clears) — the entities the research watch policy may add watches for and route to this department. A `cadences` spec that does not parse is rejected with a 422 (empty means no cadence, i.e. the check-in is off); a changed `check_in` cancels the pending check-in and queues the next one on the new schedule. `GET` and `PATCH /departments/{slug}` return the department state plus `next_check_in_at` (ISO UTC of the pending check-in, `null` when it is off, the workspace is solo or none is queued); the list route does not carry it. A new `head_person_id` must be a team member: an unknown id and one of the principal's contacts get the same name-free 422 (`person_id N is not on the team.`), so the route — open to any signed-in user — never reveals that a contact exists; an unchanged head is not re-checked. `POST .../goals` requires only `key_result`: a missing or blank `period_value` is filled with the current period for `period_type` in the user's zone (the same label `create_goal` uses), and `target` defaults to empty. `PATCH .../goals/{id}` rejects a blank `key_result` or `period_value` with a 422; `target` may be cleared. |\n| `agents` | `GET /agents`, `GET /agents/models`, `GET /agents/models/options`, `GET /agents/presets`, `POST /agents/presets/{id}`, `PATCH /agents/{id}`, `POST /agents/{id}/test` | Specialist metadata and Council overrides. `/agents/models` is the flat model allowlist the PATCH validator uses; `/agents/models/options` returns the same ids in the same order, each tagged with `provider`, `provider_label`, `route` (`direct` / `openrouter` / `local`) and a display `label`, for the Council's Provider → Model picker. `AgentDetail` carries `instructions` (additional instructions, appended after `prompt`, which stays the built-in prompt or its replacement); `PATCH` and `/test` accept `instructions` (max 4,000 chars, blank clears it). `GET /agents/presets` lists the Fast, Balanced and Thorough quality presets (each with `available` and the resolved `model` for this install) plus `active` (null when the council is Custom), `base` and `custom_agents`; `POST /agents/presets/{id}` applies one by writing per-agent model and deep-reasoning overrides and returns the same shape (404 unknown preset, 409 when the install allows none of its models). Each `AgentMeta` carries `visibility` (`core` or `internal`) so the Council's simple view can list core agents first. |\n| `personas` | `GET\\|PUT\\|POST\\|DELETE /personas` | Executive persona definitions. |\n| `alerts` | `POST /alerts/{id}/ack`, `POST /alerts/bulk-ack`, `POST /alerts/{id}/reopen`, `POST /alerts/review` | Groom the briefing queue. `ack` (`read`/`ack`/`dismissed`, optional `mute_topic`) also teaches a watch-sourced alert's watch (`trust_score`); `bulk-ack` takes explicit `alert_ids` and/or `older_than_days` + `category` (exempt sources skipped); `reopen` is the Undo for a `resolved` / `expired` / `dismissed` alert (never `ack` or an artifact / decision row; back to `unread` with every review stamp cleared and its TTL anchor refreshed, so it is live again even if older than its TTL); `review` runs the Executive's relevance review on demand (ignores the interval; still honours `ALERT_REVIEW_ENABLED`, the per-pass caps, the single-flight lock and per-alert idempotency) and returns the move counts. `bulk-ack` caps ids at 500, needs `older_than_days >= 1`, and applies watch feedback per row; `mute_topic` must be one of the alert's tags or a scoped `external:` / `department:` pattern. Alerts still surface only through the briefing (`/today` reads the live view) — there is no list, prefs, mutes, or live-stream endpoint. |\n| `artifacts` | `GET /artifacts`, `GET /artifacts/{id}`, `GET /artifacts/{id}/download?as=`, `POST /artifacts/{id}/archive`, `POST /artifacts/{id}/restore`, `DELETE /artifacts/{id}` | Browsable deliverables in any format — Markdown, HTML, Word, Excel, or a link into a connected app — with `format`, `downloads`, `external_url`, `supersedes_id` and, for an extension's kind of document, `collection` / `collection_label` on every summary (`orchestrator.extensions`; archive, restore and delete tell the collection first and answer 502 if it refuses). `download` renders the file (Word/Excel built at request time from the stored text; any Markdown artifact, workflow output included, can export `?as=docx`) and is always an attachment with `nosniff` and a sandbox CSP. Every route answers for the signed-in caller (`artifact_records.Viewer`): a drafted artifact is its owner's alone (`alerts.owner_person_id`, the person whose conversation published it; none = the principal's), a workflow output follows its run (`persistence.run_visible_to`), and anything the caller may not see is a 404 like a missing id, the principal included. `POST /alerts/{id}/ack` and `/reopen` answer 404 for someone else's drafted artifact the same way. |\n| `decisions` | `GET /decisions`, `POST /decisions/{id}/{approve,reject,cancel}`, `GET`/`PUT /decisions/classes/meeting_scheduling`, `GET /audit/reliability` | Approval-gated decision instances (e.g. calendar bookings). What approve/reject/cancel do is per class (`DECISION_CLASSES`, one `DecisionClassSpec` each; meeting booking books on approve and deletes on cancel; `delegation_reply`, an inbox reply card, is its approver's alone (`approver_only`) — hidden from everyone else, the principal included when it is a team member's — sends its Gmail draft on approve and, after a reject, deletes the draft unless it was edited), and an instance of a class with no spec gets 409 instead of being carried out as another. Only the principal, or the person the decision went to for approval (`approver_person_id`), may approve, reject or cancel it. Anyone else gets 403, and a decision nobody was asked about, or one private to the principal, is the principal's alone. The resolver is recorded as `resolver_person_id`, and a reject that loses the race to another answer is a 409. `GET /audit/reliability` is the principal's alone (403 otherwise), because it counts private decisions too. A proposed booking is surfaced on the briefing as a companion alert; approve/reject/cancel here also clear that alert. An approval whose caller resolves to the principal runs the booking inside `grant_contact_egress()`, so a meeting the principal proposed with a contact can be created. Such a booking's payload is marked `private`: it is proposed to the principal, left out of anyone else's `GET /decisions`, and a 404 for them on `GET /decisions/{id}` and every action route. Reviewed in the briefing — there is no separate proposals page. The class routes read and set how meetings are handled: both return `{decision_class: \"meeting_scheduling\", mode: \"propose\" \\| \"auto_execute\"}` (default `propose`); the `PUT` body is `{mode}`, principal-only (403 otherwise, open before a principal exists — but then only `propose` can be set: `auto_execute` is a 409 until a non-archived principal is on the roster), 422 on any other mode, and a change writes a `decision_class_mode_changed` audit row. In solo mode the class mode decides a booking, and `auto_execute` applies only to a turn the principal started on a verified surface — any other turn gets a proposal. |\n| `delegation` | `GET`/`PUT /delegation`, `GET`/`PUT`/`DELETE /delegation/voice`, `POST /delegation/voice/learn`, `POST /delegation/voice/describe`, `POST /delegation/voice/signature`, `PUT /delegation/inbox`, `POST /delegation/inbox/check`, `GET /delegation/replies`, `PUT /delegation/replies/{id}/text`, `GET /delegation/actions`, `PUT /delegation/handle-it`, `PUT /delegation/disclosure`, `PUT /delegation/training`, `DELETE /delegation/learned/{id}`, `GET /delegation/handled`, `PUT /delegation/team` | Act as me — the **caller's own** delegation only; nobody sets it for anyone else. It answers the principal, and a team member once the owner lets them; anyone else gets 403 `not_available_yet`. `GET /delegation` returns `{enabled, gmail: {status, message, email, connect_command, outlook_connect_command, provider}, inbox: {enabled, status, message, watch_since, last_poll_at, checking}, handle_it: {enabled, mode, available, sent_today, lead, lead_available}, training: {replies, follow_ups, actions, drafts, learned}, disclosure: {enabled, handle_it, approved_sends, line}, team}`, where `team` is the owner's switch for the principal while `DELEGATION_TEAM_MEMBERS` allows it — `{enabled, members: [{person_id, name, enabled, inbox, drafts_30d, sent_30d}]}`, counts only — and `null` otherwise. `PUT /delegation/handle-it` takes `{enabled?, mode?}` (`mode` is `careful`, `balanced` or `bold`; anything else is a 422 `bad_mode`) from a caller the API knows is that person — 403 `not_yours`, 409 `caller_signing_required` with only the shared secret — and turning it on needs Act as me and Draft replies to my inbox on (409 `act_as_me_off` / `inbox_off`); `GET /delegation/handled` returns `{replies: [{decision_id, sent_at, to_name, to_email, subject, body, open_questions, gmail_link, source}]}`, the caller's replies and follow-ups (`source` `follow_up`) sent on its own in the last 7 days; a card on `GET /delegation/replies` carries `source` the same way, `can_allow` while Replies (Follow-ups, on a follow-up) is in training, and `learns_style` while Drafts is. `PUT /delegation/disclosure` takes `{handle_it?, approved_sends?}` (any other field is a 422), the caller's own switches for the AI line on replies sent as them (`disclosure.enabled` is the install's `AI_DISCLOSURE`); turning one on needs no signed sign-in, turning one off does (409 `caller_signing_required`), and a change is audited as `delegation_disclosure_changed`. `PUT /delegation/training` takes `{replies?, follow_ups?, actions?, drafts?}` (any other field is a 422) and returns the `GET /delegation` shape; putting Replies or Follow-ups in, or Suggested actions out, needs no signed sign-in, anything else does (409 `caller_signing_required`), and putting Replies or Follow-ups in turns Take the lead as you off (`PUT /delegation/take-the-lead` on answers 409 `in_training` while they are). `training.learned` is `[{id, label, setting, example, uses, created_at}]`, what the caller allowed or kept in training (`setting` `replies`, `follow_ups`, `actions` or `drafts`; the kept example, or \"\"); `DELETE /delegation/learned/{id}` removes one of the caller's own (404 for anyone else's). `PUT /delegation/team` takes `{enabled}` from the principal alone (403 `principal_only`; 409 `not_available` when the install doesn't allow it). The Gmail `status` is `connected`, `not_configured`, `needs_reconnect`, `mismatch`, `no_email`, `shared_mailbox` or `error`, checked live with Google on each call. `PUT` takes `{enabled}` (any other field is a 422); turning it on needs the caller's own Gmail connected, otherwise a 409 whose code says why (`gmail_not_connected`, `gmail_needs_reconnect`, `gmail_mismatch`, `no_email`, `shared_mailbox`, `gmail_error`). The voice routes show, learn (from the caller's sent mail, one pass at a time — a 409 `in_progress`, `locked`, `too_soon`, `not_enough_mail`, `no_profile` or `changed` when it was locked or edited while learning, or a Gmail code), write it from the caller's own description (`POST /delegation/voice/describe` with `{description}`: one model call applies their words to the profile they have and returns it with a short `sample_reply`, saving nothing, so they review it and save it with `PUT`; a 409 `empty`, `too_long`, `in_progress`, `too_many` past 10 an hour or `no_profile`; no mailbox needed), edit and lock, and reset \"How I write\": a typed field that fails validation is a 422 `invalid_voice` listing each `rejected` field, and `clear_exemplars` / `clear_signature` drop those. `POST /delegation/voice/signature` reads the signature from the caller's Gmail settings again and changes nothing else (a locked profile stays locked), with the same Gmail codes as learning: a 409 when their mailbox isn't connected, it refuses the sign-in or the check itself fails (`gmail_error`), and a 502 `gmail_error` when reading the signature fails. On an Outlook mailbox it is a 409 `signature_unavailable`, since Outlook gives apps no signature to read, and the stored one is left alone. A caller `can_delegate` refuses — anyone but the principal, for now — gets 403 `not_available_yet`, which hides the Settings card. A request with no `x-caller-email` is a 403 `sign_in_required` unless the API runs under local login — a header-less call is not a sign-in (the caller is read through `api/caller.py`, as on every principal-only route). `PUT /delegation/inbox` takes `{enabled}` and turns **Draft replies to my inbox** on or off, returning the same shape as `GET /delegation`: on needs Act as me on (409 `act_as_me_off`) and the mailbox connected (the Gmail codes above, which keep their names for an Outlook mailbox too), and turning Act as me off turns it off too. `POST /delegation/inbox/check` starts a scan now in the background and answers 202 with the `inbox` state (409 `inbox_off` or `in_progress`). `GET /delegation/replies` returns `{cards: [...]}`, the caller's open reply cards from the database alone (no Gmail call): the decision id, the sender's name, address, relation and whether it was verified, the subject, when it arrived, what they wrote, the draft's recipients, subject and body, `open_questions`, `flags` and a Gmail link built from a fixed prefix. **Send** is `POST /decisions/{id}/approve`: it sends the card's draft exactly as it is in Gmail, after checking again that the caller is its owner — which on a server needs signed callers (409 `caller_signing_required` otherwise) — that both switches are on (`inbox_off`), no client slot is active (`client_slot`), the Gmail is connected (the Gmail codes), the draft is still there and unanswered (`draft_gone`, `you_replied`) and its recipients are allowed (`no_recipients`, `too_many_recipients`, `executive_recipient`, `not_from_you`). Recipients that changed, or a newer message in the thread, answer 409 `{code: \"confirm\", message, reasons, recipients}`; approving again with `edits: {recipients: <the list shown>, thread_moved_on: true}` is the second yes. **Send + allow** adds `edits.allow: true`: 422 `cant_allow` unless Replies (Follow-ups, on a follow-up card) is in training, 409 `learned_full` when their list is full, both before anything is sent; `edits.example: true` keeps a draft edited in the mailbox as how they write to that person while Drafts is in training. A draft edited in Gmail between those checks and the send is not sent (`draft_changed`). A double tap sends once (`already_handled`); Gmail refusing answers 429 `rate_limited` or 502 `gmail_error` with nothing sent, and a send Gmail didn't confirm answers 502 `send_unconfirmed` and is settled by the next inbox scan. Dismiss is `POST /decisions/{id}/reject`. `GET /delegation/actions` returns `{cards: [...]}`, the caller's own approval cards (`delegation_actions`): the decision id, when it was made, a one-line `why`, and each action's `index`, `kind` (`invite`, `message`, `add_contact`), `summary` and `text` (a message as it will be sent, or a meeting's description). **Approve** is `POST /decisions/{id}/approve` with `edits: {only: [indexes]}` (and `allow: true` for Approve + allow while Suggested actions is in training: 422 `cant_allow` otherwise or when nothing on it can be allowed, 409 `learned_full`; a card carries `can_allow`); it needs the card's own person signed in (403 `not_yours`, 409 `caller_signing_required`), Act as me on (409 `act_as_me_off`) and a card under a week old (409 `expired`), runs once (409 `already_handled`), and returns the decision with `final_payload_json.results`: per action `done`, `waiting` (sent to whoever approves meetings), `failed` with why, or `skipped`. Every change writes a private audit row. |\n| `history` | `GET /memories/history` (`?q=`), `PUT /memories/history/settings`, `PATCH`/`DELETE /memories/history/{id}`, `POST /memories/history/{id}/forget-conversation` | Always in the loop: the **caller's own** notes and switches only, resolved as for Act as me (a signed-in person on the roster, or the principal under local login; otherwise 403 `sign_in_required` / `not_on_roster`). `GET` returns `{notes, reply_notes, retention_days, effective_retention_days, company_retention_days, retention_choices, can_keep_notes, can_note_replies, can_set_company_retention, share_work_style, can_share_work_style}` (`can_keep_notes`: a team member on the People list may turn notes on; `can_note_replies`: they can use Act as me, so email replies are noted too; `share_work_style`: their own \"Share my work style with the team\" switch, `can_share_work_style`: a team member in a team workspace). `PUT` turns notes on only for someone who may keep them, and `share_work_style` on only for someone who may share it (403 `not_available` for either; turning either off always works), takes a person's retention only when shorter than the company's (422 `invalid_setting`), and the company retention only from the principal (403 `principal_only`). `PATCH` pins or corrects a note; `DELETE` forgets it; `forget-conversation` is \"Don't remember this\". A note that isn't the caller's is 404. Every change is audited privately to its person. |\n| `notifications` | `GET /notifications/settings`, `PUT /notifications/settings` | Settings → Notifications: the **caller's own** settings only, resolved as for the notes (a signed-in person on the People list, or the principal under local login; otherwise 403 `sign_in_required` / `not_on_roster`). `GET` returns `{quiet_hours: {enabled, start, end, days}, delivery, urgent_through, timezone, effective_timezone, held_count, gets_briefs, updated_at}` — `days` is `every_day` or `weekdays`, `delivery` `instant` or `digest`, `timezone` the zone they chose (`\"\"` for the workspace's), `held_count` how many messages wait for their quiet hours or brief (counted, never listed), `gets_briefs` whether they are the principal. `PUT` takes `{quiet_hours, delivery, urgent_through, timezone}` and replaces them (extra fields, equal start and end, a bad time or an unknown zone → 422); switching `digest` → `instant` makes what waited for the brief go now. Audited as `notification_settings_changed`. See Org. |\n| `audit` | `GET /audit/logs`, `GET /audit/logs/{id}`, `GET /audit/sessions/{id}`, `GET /audit/usage`, `POST /audit/log` | Durable audit trail of side effects. `/audit/sessions/{id}` adds a per-session token cost summary; `/audit/usage` aggregates token usage and OpenRouter cost across all sessions (totals, by day, by model, and by source — the part of the system that made the calls — including server-side web-search counts), plus `scripts`: how many `run_script` scripts ran (and worked, and in workflows), the tool calls they made, their time, and `turns_avoided` — an upper bound on the model turns those calls would otherwise have needed (each call past a script's first) — and `python_jobs`: how many Python jobs ran (and worked, ran a kept Custom tool, took a chat attachment), their time, CPU, largest peak memory and bytes in and out, and the tokens and charge of the turns that ran one. The Token usage page shows it as a Scripts section. Rows private to the principal (`private_to_principal`: a turn about their private mail, or a row naming one of their contacts on their own turn) are theirs alone: for any other caller, resolved as for `/alerts`, the usage totals leave them out. Once a principal is on the roster, anyone else reads only their own rows (a teammate's own turns, their Act as me work) in the list, by id and in a session, and the principal reads those as actions only — what was done, when and in whose conversation, with the text, details and `full` left out, and no text search over them; any other row's id is a 404, and a session shows only the rows the caller reads. |\n| `architecture` | `GET /architecture/sections`, `.../sections/{id}` | This documentation surface. |\n| `guide` | `GET /guide/sections`, `.../sections/{id}` | Plain-language user-guide content surface — mirrors `architecture` (static, version-controlled files; no LLM on the serving path). |\n| `health` | `GET /health`, `GET /health/honcho` | Liveness probes. Only `/health` is unauthenticated; `/health/honcho` sits behind the gate like everything else, because the exemption is an exact-path set. `/health` also carries `google_tools_missing`, the pinned Google tools startup priming could not find: `[]` once it has checked and they are all there, a list of names when a workspace-mcp rename or the configured services and tool tier left one out, and `null` for no answer — Google Workspace is not configured, or the probe has not finished or it failed. Only `[]` asserts they are present. It also carries `gateway`, the MCP gateway's state from its supervisor (`orchestrator.gateway_boot`): `state` is `off` (MCP not enabled), `no_servers` (enabled, the config names none), `starting` (an attempt is running), `up` or `down` (every attempt so far failed; `next_retry_at` is the next one), with `attempts`, `up_since` and `email_poller` (whether the poller that rides on the gateway runs); the failure's own text stays out, since the route is open to anyone, and goes to the log and the owner's notice on Home. A hosted instance whose gateway never came up used to answer `ok` here with no email going out or in. Only `[]` asserts the tools are present, so a probe that died cannot read as healthy; Setup status says which of the three `null` means. |\n| `version` | `GET /version` | The running version, the latest release on GitHub and `update_available`, for Settings → About. The GitHub answer is cached 6h, only a semver `tag_name` is used and the release link is built from it; `UPDATE_CHECK_ENABLED=false` skips the call and still returns the running version. No in-app updater: upgrading is host-side (`docs/deployment.md#upgrading`). |\n| `setup_status` | `GET /setup/status` | Settings → Setup status: one light per part of the install — AI model, company setup, owner, the Executive's address, API protection, Gmail, your own mailbox (Act as me), Slack, Discord, Telegram, Google Chat, the scheduler, the daily brief (when and where it goes) and Honcho — as `{checked_at, checks: [{id, label, state, summary, fix, link, last_activity}]}`, where `state` is `ok`, `warn`, `error` or `off` (optional and not set up), `fix` says what to do in plain language, `link` is an in-app page that helps (`/people`, `/onboard`) and `last_activity` is the channel's latest `integration_inbound` audit time. It tests live, with at most one free read-only call per service, each bounded to 5 s: Anthropic `models.list` (so an organisation key missing `ANTHROPIC_WORKSPACE_ID` shows up), Slack `auth.test`, Telegram `getMe` and `getWebhookInfo`, Discord `users/@me` only while the bot is still connecting, and — once the owner's own Gmail credential exists — Google's token refresh and Gmail `users/me/profile`. It also reads the listeners the lifespan leaves on `app.state` (Slack's socket, the Discord bot and its task, the MCP gateway), the scheduler heartbeat and the pause switch. When `google_workspace` is configured, the lifespan also starts `MCPGateway.prime_pinned_tools()` in the background (held on `app.state.mcp_prime_task`, cancelled at shutdown), so the pinned Google tools named in the prompt are callable without a search. With `DRIVE_SYNC_ENABLED` the lifespan also bootstraps the `drive_sync_scan` heartbeat beside Notion's (see Scheduler); the Drive folder sync has no HTTP route, only the `openexecutive sync-drive` / `purge-drive` CLI. With `CONFLUENCE_SYNC_ENABLED` it bootstraps the `confluence_sync_scan` heartbeat the same way; that sync is run by hand with `openexecutive sync-confluence` / `purge-confluence`. Sample values copied from `.env.example` are named as such without being sent anywhere. No token reaches a response or a log line: probes report a status code, a service's short error code or an exception's class name. Requests within 5 s of a run get that run's answer and concurrent requests share one run (kept per app on `app.state`), so the button can't become a stream of calls to those services. Gated like every other route; the UI adds a sign-in light of its own, from its own settings. |\n| `documents` | `POST\\|GET\\|DELETE /documents`, `GET /documents/{filename}`, `GET /documents/sources`, `POST /documents/sources/{drive\\|onedrive\\|notion}/sync`, `GET /documents/{drive\\|onedrive\\|notion}`, `GET /documents/{drive\\|onedrive\\|notion}/{id}` | Upload, list, view extracted text, and delete indexed company docs. `GET /documents` rows carry `source: \"upload\"` and the `domain` the upload was indexed under. The connected-source routes back the knowledge page's single Company documents list: `/documents/sources` gives each source's `{id, label, enabled, syncing, last_run, last_error, interval_minutes, file_count}`; `/documents/drive`, `/documents/onedrive` and `/documents/notion` list synced files from the sync state (`{enabled, last_run, last_error, files: [{id, name, url, modified_at, synced_at, indexed}]}`; a Drive row also carries `unreadable_reason`, why a file with `indexed: false` has no text — e.g. a scan OCR could not read — or null); `/documents/{drive\\|onedrive\\|notion}/{id}` returns the stored text (a OneDrive id is `<drive id>:<item id>`) for an id on record (the path comes from the state, never the caller). They are read-only — a synced file is removed where it lives. `POST …/sync` starts one tick of the same sync the scheduler runs as a background task (202); 409 when the source is not connected or a tick is already running (every sync holds a per-process run lock, so a manual run never overlaps the heartbeat; the route also keeps its own started task per source and re-checks just before starting one, so two simultaneous requests start one tick, not two), 429 with `Retry-After` within 60 s of the last successful run or of the end of the last tick in this process, failed ones included, so a failing or slow source can't be re-run back-to-back. The page's text view never loads images from synced content (a remote image would be a read beacon for whoever edits the shared folder). Upload is keyed on the filename, so re-uploading a document replaces its chunks rather than duplicating them, and `DELETE` removes the rows as well as the file. `domain` must be one of the nine specialist domains (including `sales`) or `general`; anything else is a 400 rather than a 200 that indexes where no specialist can retrieve. A scanned PDF is converted (`knowledge.pdf_reader`) before it is indexed and in the text view, as are scanned PDFs in `POST /chat/upload` and the client / onboarding intake uploads. The upload is streamed to disk 1 MB at a time and refused with a 413 once it passes 50 MB, and the file is parsed in a short-lived child process (see the RAG section), so a large document does not stay in the API process's memory. A Word or Excel file that cannot be parsed, or whose parse runs out of time, is a 422 with a readable reason. When every parser is busy, the response is a 503 with `Retry-After`. |\n| `executive` | `GET /executive/status`, `POST /executive/pause`, `POST /executive/resume` | Operator pause switch for all autonomous work (scheduler, Gmail poller, workflow resumer); inbound chat and DMs stay live. Status returns `{paused, paused_at, paused_by, reason, held_actions, can_resume}` — `held_actions` counts due `pending` rows that fire on resume. `pause` takes an optional `reason` (≤200 chars) and is idempotent (re-pausing keeps the original start and reason); `paused_by` is the UI proxy's `x-caller-email`, else `api`. Behind the shared-secret middleware — not `SCHEDULED_ADMIN_TOKEN`, which the UI cannot send. Any caller may pause; `resume` is principal-only (`is_principal_or_self`, 403 otherwise; open while no principal is rostered; a header-less caller resolves to the principal as in `chat`), and status carries `can_resume` for the viewer so the UI hides Resume from everyone else. |\n| `workspace` | `GET /workspace`, `PUT /workspace` | Solo/team mode, the user's time zone and the principal's role (`memory.workspace_settings`). Both return `{mode, timezone, effective_timezone, role_kind, role_title, reports_to, remit, measured_on, company_domains, company_domains_custom}` — `timezone` is what the user set (null when unset), `effective_timezone` the zone in effect (`timezone`, else `USER_TIMEZONE`, else UTC), and each role field is null until set. `PUT` is a partial update: only the fields sent change; `mode` is `solo` or `team` (not null), `timezone` an IANA zone, or null/blank to clear it; `role_kind` is `owner`, `in_house`, `independent` or `other`, and `role_title` / `reports_to` / `remit` / `measured_on` are free text (trimmed, at most 120 / 120 / 500 / 300 characters), each null or blank to clear it; an unknown zone, a bad mode or role kind, an over-long role field or an unknown field is a 422 and changes nothing. Switching to solo cancels every pending department check-in, switching to team re-schedules them, and a new zone re-times the pending briefs and reflection; a role change has no side effects (the next turn reads it). `company_domains` is the company's own email domains (a teammate matches by local part on them — see Org): `GET` returns the ones in effect (the stored list, or the domain of the principal's primary address, with `company_domains_custom` false) only to the same caller the role is shown to, `[]` for anyone else; `PUT` takes a list (at most 10 plain domain names, never a free-mail provider's — 422 otherwise, the value never quoted) or null / `[]` to go back to deriving them, and a change is audited with the new list. Each change writes a `workspace_settings_changed` audit row (a role change adds `details.role_fields_changed`, the names of the fields that changed — never their text). The role is the principal's: `GET` returns it only to a caller `PUT` would accept and reads it as nulls for anyone else. `PUT` is the principal's alone (`is_principal_or_self`, 403 otherwise; a header-less caller resolves to the principal as in `chat`) and open while no principal is rostered, so first-run setup can pick a mode. Both work before onboarding — unlike `company-profile`, nothing here needs a profile. |\n| `scheduled` | `GET\\|DELETE` scheduled actions (`?status=…&order=asc\\|desc`) | Pending and fired scheduled actions; `order` flips the `run_at` sort (asc=soonest-first for the upcoming queue, desc=most-recent-first for terminal-status history). `DELETE /scheduled/{id}` cancels a `pending` row (409 otherwise). Like pause it only stops work, so any signed-in user may — the UI proxy's `x-caller-email` is trusted when the request also carries the `BACKEND_SHARED_SECRET` `x-api-key` — as may a matching `X-Admin-Token` (`SCHEDULED_ADMIN_TOKEN`) or a loopback caller with no token set; otherwise 401 (token set) or 503. Audited as `scheduled_action_cancelled`. |\n| `watchlist` | `GET\\|POST\\|PATCH\\|DELETE /watchlist`, `POST /watchlist/{slug}/approve`, `POST /watchlist/{slug}/decline` | External-monitoring watchlist + signals. Rows carry `origin` (`manual` \\| `executive` \\| `research` \\| `research_proposed`); `approve` turns a research suggestion (`research_proposed`, `dry_run`) into a live watch, `decline` `{reason: not_relevant \\| too_noisy \\| wrong_source}` removes it and records the decline (or, for `too_noisy`, keeps it live at a high floor), both 409 unless the row is a pending suggestion; `DELETE ?reason=` on a research-origin row records the decline too. |\n| `workflows` | `GET /workflows`, `POST /workflows/{name}/runs`, `GET\\|POST\\|PUT\\|DELETE /workflows/custom`, `GET\\|DELETE /workflows/custom/{name}/targets`, `POST /workflows/runs/{run_id}/decision`, `GET /workflows/tools/search?q=`, `GET /workflows/tools/describe?names=` | Workflow catalog, run management, and user-created (dynamic) workflow CRUD. Custom definitions come back with a server-managed `owner_person_id` (the creator — the web caller on `POST`, set on insert only; a client-sent value is ignored), who is asked to approve a workflow's first write to a new target. `GET /workflows/custom/{name}/targets` lists the targets its tool steps may write to without asking and `DELETE …/targets?value=` forgets one. `POST /workflows/{name}/runs` is a 403 (\"Only the principal can run this workflow.\"), audited, before any run row exists, when the workflow is one only the principal may start in the workspace's mode (`weekly_review` always, `morning_brief` in solo) and the caller is not the principal. A request with no `x-caller-email` counts as the principal; with no principal on the roster, no signed-in caller does. This governs starting a run only. A run started by hand (this endpoint, or `run_workflow` / research in chat) records its starter as `owner_person_id` and is theirs alone: `GET /workflows/runs` lists the team's (scheduled, no owner) runs plus the caller's own and the ones waiting on them, and `GET` / `DELETE /workflows/runs/{run_id}` and `POST /workflows/runs/{run_id}/decision` are a 404 for anyone else's, the principal included. A signed-in email that is on nobody's People entry cannot start one (403), and a run whose starter can't be read is refused (503); its steps read and draft documents as the starter only. `POST /workflows/runs/{run_id}/decision` with `{decision: \"approve\"|\"reject\"}` answers a run awaiting a yes/no sign-off from the web app — 403 unless the caller is the person it waits on or the principal, 409 if it isn't awaiting or needs a written reply — through the same `apply_resolution` a chat reply uses. Custom create/update also rejects (422) any action-step tool that does not resolve, and so does `POST /workflows/custom/{name}/activate` when turning a workflow **on** — that click is the approval for a tool workflow chat saved switched off (turning off is never checked). Turning on a workflow with action steps requires the body `{is_active: true, definition}` carrying the definition the user reviewed; if the stored one differs (ignoring `is_active` and timestamps) it returns 409, and the switch itself is a compare-and-set on the validated revision (`dynamic_store.activate_if_unchanged`, keyed on `updated_at`), so a save that lands while the tool check awaits the gateway — even from another process — is a 409 too, so only what was shown gets switched on. `GET /workflows/custom` lists inactive definitions too; `GET /workflows/{name}` 404s for them. The two `tools` endpoints return `{tools: [{name, description, read_only, source}]}` for the advanced editor's tool picker and the review card; `read_only` is true only when the name says it reads (a label, not a control). The run stream adds a `progress` event (`step_id`, `summary`) while an action step uses tools. Each catalog entry (`WorkflowMeta`) carries `is_custom`, `background` (true for the system-run built-ins the UI files under “System”) and `quick` (true for a Quick workflow, one per playbook nothing else follows, named `quick_<playbook>`). The run endpoint streams SSE; its `awaiting_human` event carries `delivery` (`self` \\| `sent` \\| `suppressed` \\| `alerted` \\| `failed`) alongside `person_id` / `question` / `awaiting_until`, because the outbound guard or an unreachable approver means the question may never have been asked — a client must not render “waiting on them” for those. A paused run ends the stream with neither `done` nor `error`, so that `awaiting_human` frame carries `terminal: true` to say so explicitly, plus `resumable` — whether the run continues by itself once answered or stops at the gate. `GET /workflows/runs/{run_id}` returns the run row with the resume payload replaced by a small `resume_progress` summary (`gate_step_id`, `completed_step_ids`, or `null`): the payload holds every completed step's full text, and the run-detail page polls this endpoint while a run is unfinished. |\n| `knowledge` | `/knowledge/builtin`, `/external`, `/search` | MBA knowledge base and external sources. `/search` is the introspection parallel of `retriever.retrieve` and mirrors its filters — including the `general` catch-all on the company collection — so the panel cannot report a specialist seeing nothing that it does retrieve in chat. It accepts `general` in `domain_filter` for the same reason. `/search` applies the same review gate as `retrieve()` — withheld (pending or rejected) built-in, external and failure rows are dropped, so the panel never advertises knowledge the Executive cannot use; it degrades to unfiltered rather than failing if review state is unreadable. `POST /knowledge/builtin` refuses a name already held by shipped content, and `POST|DELETE /knowledge/failures` now register and deregister for review — without that a user-authored failure case study had no review row, so no SME decision could block it. |\n| `skills` | `/skills`, `/skills/search`, `/skills/{name}/restore` | Skill registry (the UI's **Playbooks**) CRUD and search. `PUT` on a built-in saves a company customization that shadows it; `DELETE` returns `{name, outcome}` — `deleted`, `reverted` (customization removed, built-in back) or `hidden` (built-in hidden for this company); `restore` un-hides; `GET /skills?include_hidden=true` lists hidden built-ins. List and detail carry `used_by` — `[{name, title, is_custom}]` of the workflows that follow the playbook (switched-off custom ones included) (`WorkflowMeta.playbooks` is the other direction). |\n| `evals` | `/evals/scenarios`, `/evals/runs` | Eval scenarios and run results. `POST /evals/runs` is a 403 when a workflow scenario names a workflow that only the principal may start in the mode it runs in (the weekly review; the morning brief in solo) and the caller is not the principal — the Jobs page's rule for starting a run; stored results are read under the existing `/evals/runs` rules. |\n| `memories` | `/memories/{decisions,initiatives,advice}`, `GET /memories/facts`, `POST /memories/facts/{fact_id}/{retire,approve,decline}`, `GET /memories/facts/approval`, `PUT /memories/facts/approval/{person_id}`, `GET /memories/people`, `GET /memories/people/{person_id}/conclusions` | Episodic-memory record management; the standing facts the Pulse Corrections tab reads (`{facts: [...], can_retire, retirable_ids, can_review}`; each fact carries `recorded_by_role` / `recorded_by_name`; `?include_inactive=` default true, honoured for the principal only; anyone else gets the active rows plus their own `proposed` ones, with the provenance (`session_id`, `turn_id`, `recorded_by_person_id`, `retired_reason`, and `source_quote` except on their own facts) blanked, never retired, replaced or declined text; `?limit=` 1–500) and their retire (the principal any fact, a teammate only one they recorded that the principal has not approved — else 403; the audit row names the teammate; 404 for an unknown or `profile` row, 409 when no longer active; writes a private `fact_retired` audit row); approve / decline a teammate's `proposed` fact (principal only, else 403; 409 when it is not proposed; private `fact_reviewed` row); and the per-teammate \"needs my approval\" switch (on by default; `GET` lists `[{person_id, full_name, needs_approval}]` for every active team member but the principal, `true` for anyone not yet set; `PUT` takes `{needs_approval}`, 404 for anyone else; both principal only; private `fact_approval_changed` row); plus the read-only peer-memory overview the Pulse People tab reads (`{status: ok|disabled|error, people: [...], conclusion_total}`; `?recent=` 1–50, default 5) and one person's full conclusion list, paged newest first (`{status, person_id, items, page, size, total, has_more}`; `?page=` ≥1, `?size=` 1–100, default 50; 404 when the person has no peer). Peer memory is each person's own: the overview holds only the caller's entry (none for a caller off the roster; `conclusion_total` counts only theirs), the principal included, and `/conclusions` for anyone but the caller is a 404. |\n| `review` | `/review/items`, `/review/stats`, `/review/trusted-defaults`, `POST /review/curate`, `POST /review/bulk-approve` | Knowledge review queue and annotations. Shipped knowledge registers as a trusted default (`approved` with a NULL `reviewed_at`), so the queue starts empty; `curate` (`{domain, action: start|stop}`, domain required) opts one domain in or out, and `trusted-defaults` returns domain → unreviewed count. `bulk-approve` takes a non-empty `domain`, `item_ids` (max 500) or `all_pending: true`, and 400s with no selector; it returns `{approved_count, item_ids}`. |\n| `onboarding` | `/onboard/interview/understand`, `/onboard/interview/start`, `/onboard/interview/message`, `/onboard/interview/draft`, `/onboard/interview/{id}`, `/onboard/interview/commit` | Conversational company setup. The `onboarding_interviewer` agent asks clarifying questions, then emits a draft profile + people + departments. **Nothing is persisted until `POST /onboard/interview/commit`** — the interview itself never writes. `start` is multipart (description + optional deck/one-pager uploads). `commit` answers 403 when the draft would make a different person the owner and the caller is not the current owner (setup demotes the old principal, and any signed-in user can open it). It also takes an optional `owner_email` — the principal's sign-in email, which the review screen pre-fills from the signed-in user — checked before anything is written (422 if it is malformed, already another person's, or would replace the principal's existing email — setup only fills in a missing one; 403 if the caller is not the owner and it is not the address they signed in with, since the roster is the sign-in allow-list) and saved on the principal's People row, so the owner's chats resolve to them from the first turn. |\n| `workflow_designer` | `POST /workflows/designer/start`, `POST /workflows/designer/edit`, `POST /workflows/designer/message`, `POST /workflows/designer/draft`, `GET /workflows/designer/{session_id}` | The conversational New workflow wizard, and editing a saved workflow by conversation. `/edit` (`{name}`) opens a session on a saved custom workflow with no model call: the stored definition is the starting draft, and every response then carries `editing` (its name) and `original` (the stored definition as the session opened on it); drafts keep that name and its on/off state whatever the model writes (404 for an unknown workflow). The UI saves one with `POST /workflows/custom/{name}/save-edit` (`{session_id, definition}`): the server saves the session's own draft, never a client-sent body, and only when it equals the `definition` the user reviewed (a later message is a 409, so the click saves only what was shown); it re-validates it, keeps the stored on/off state, and writes only if the stored workflow is still the version the conversation opened on — otherwise 409, as it is for a session about another workflow or one with nothing drafted yet. It sits under `/workflows/custom` so anything that limits writes to custom workflows covers it too. The `workflow_designer` agent asks clarifying questions (`phase: \"question\"`, with `hint` and up to four suggested `options`), then returns `phase: \"draft\"` with `draft.definition` (exactly the body `POST /workflows/custom` takes), `summary`, and `assumptions`; every response carries the `transcript`. **Nothing is persisted here** — sessions are in memory, and the UI saves through `POST /workflows/custom`. Errors are fixed strings (422 over the 8,000-char message cap or the transcript cap, 404 for an expired session, 409 while another turn on the same session is still running, 502/504 for model failure or timeout). Mounted ahead of the `workflows` router. |\n| `python_jobs` | `GET /python-jobs/{job_id}/{name}` | A result file a Python job (`run_python_job`) wrote, the principal's alone (403 otherwise), served as a download (`Content-Disposition: attachment`, `Content-Security-Policy: sandbox`, `nosniff`, `Cache-Control: no-store`); 404 for a bad id or name or a file past its 7 days. |\n| `saved_tools` | `GET /saved-tools`, `GET\\|PUT /saved-tools/{name}`, `POST /saved-tools/{name}/rollback` | The scripts the Executive saved as tools (Settings → Advanced → Saved tools), the owner's alone (403 otherwise). The list gives each tool's name, description, on/off, current version, `kind` (`script` or `python`, a kept Python job) and the tools it calls, plus whether `SAVED_TOOLS_ENABLED` is on; the detail adds the script, every version and the last 20 runs. `PUT {enabled?, workflows?, version?}` turns one on or off (off also turns it off for workflows, so turning it back on never re-arms unattended runs), and turns the named `version` — the one the owner looked at, never whatever is current by then — on for workflows (or workflows off); a Python tool never turns on for workflows (409) — turning workflows on lets more run unattended, so it needs a request tied to the owner (signed sign-ins or local login, as Take the lead's switches do; 409 otherwise); `rollback {version}` makes that version the one that runs. Both are audited as `saved_tool_changed`. The Executive saves tools itself through `run_script`; there is no create route. |\n| `onboarding` (fallback) | `/onboard/start`, `/onboard/answer`, `/onboard/status/{id}` | The original 12-step form wizard, kept as a fallback (UI at `/onboard?mode=form`) and used by the `openexecutive onboard` CLI. Its final answer saves the profile and adds people with their emails and a principal, so once there is an owner only they can send it (403, and the session rolls back so the owner can still finish it). `/onboard/start` reads the workspace mode once for the session: solo skips the Team Size, Team Members and Fractional Executives steps. Each status response's `current_step` / `total_steps` count only the steps that session asks, and `optional` says whether the current step can be skipped. |\n| `company-profile` | `GET\\|PATCH /company-profile` | Structured company profile. |\n| `alerts` (private cards) | `POST /alerts/{id}/ack`, `/reopen`, `/alerts/bulk-ack` | An alert tagged `private:principal` (see Today) is a 404 on ack and reopen for anyone but the principal, and their bulk sweep skips it. A roster-request card (source `roster_request`) is a 409 on `ack` even for the principal — it is answered at `/people/requests/{id}`, since acking would leave the sender waiting with nothing to show it — and, as an exempt source, `bulk-ack` and `reopen` skip it. |\n| `auth` | `GET /auth/allowed-emails` | Non-archived **team members** with an email, offered to the UI's sign-in gate — a contact is never on it, so adding a client to reach them by email no longer lets them sign in. The gate takes the **union** of this roster and its own `ALLOWED_EMAILS` env list, so env entries always work (and are checked first, short-circuiting the fetch) and roster entries are additive — a roster change can never revoke a configured operator. With local login (`make dev` with Google sign-in not set up — the UI then listens on 127.0.0.1 only) the UI signs in without an email, sends no `x-caller-email`, and the backend resolves the caller to the principal, as it does for the CLI. |\n| `fixtures` | `/fixtures`, `/fixtures/{name}/load` | Demo-company fixture load/reset/snapshot. `POST /fixtures/reset` leaves no departments, like a new install (`departments_seeded` is always 0). |\n| `clients` | `/clients`, `/clients/generate`, `/clients/cockpit`, `/clients/save`, `/clients/{slug}/activate` | Client-company slots — multi-client mode for fractional use; create from current/blank/AI-generated intake draft (pasted notes and/or file attachments, multipart on `/clients/generate`), save-back switching, engagement metadata (PATCH), cross-client cockpit, delete. See the Client Companies section. |\n| webhooks | `POST /webhook/telegram`, `POST /webhook/google-chat`, `POST /webhook/slack` | Inbound integration callbacks (self-verified). `/webhook/slack` answers 503 unless `SLACK_SIGNING_SECRET` is set. |\n| MCP server | `POST\\|GET /mcp` | Open Executive exposed as an MCP server (Streamable-HTTP). Not a router — a mounted FastMCP sub-app. Same shared-secret gate (`x-api-key`); exposes company context as resources and the specialist council as tools. See the MCP Server section. |\n\n**Take the lead** (`api/routes/take_the_lead.py`): `GET /take-the-lead` returns the As the Executive switch, its six Ask first switches (`{kind, label, hint, on}`, the hint a plain line on what each one catches), the company's rules, whether this server can tie a change to the owner (`available`), and whether the Executive is paused. `PUT /take-the-lead` takes `{enabled?, ask_first?}`, and `POST /take-the-lead/rules` / `DELETE /take-the-lead/rules/{id}` add or remove a company rule (`{kind: person|domain|words|amount, value}`, 422 on a bad one). All four are the principal's alone (403). Anything that lets more happen on its own (turning it on, turning an Ask first off, removing a rule) needs a caller the API can tie to them (`delegation.verified.caller_refusal`, else 409). `GET /today/activity` adds `took_the_lead` rows (what Take the lead did, named, not quoted) and, for the caller alone, `sent_as_you` rows for what Handle it for me sent as them. Under `/delegation`: `PUT /delegation/take-the-lead {enabled}` is Take the lead as you (the owner's only for now; turning it on turns Handle it for me on), and `GET|POST /delegation/take-the-lead/rules` and `DELETE …/rules/{id}` manage the caller's own rules. `HandleItOut` gains `lead` and `lead_available`. A `take_the_lead_action` decision is approved or rejected through the existing `/decisions/{id}/approve|reject`. Training: the response also carries `training` (In training: everything waits unless allowed), `learned` (`{id, label, feature, example, uses, created_at}`: what it was allowed, the edit kept as an example by field) and `suggested` (`{key, label, approvals}`); `PUT` takes `training?` too, and leaving training while on needs the same provable owner as turning it on. `POST /take-the-lead/learned {key}` allows a current suggestion (404 for anything else; provable owner), `DELETE /take-the-lead/learned/{id}` makes it ask first again. `learned` also lists the owner's own Act as me senders (`feature` `act_as_me`), never anyone else's, and Remove works on those too. On a `take_the_lead_action` card, `POST /decisions/{id}/approve` takes `edits.input` (the card's editable fields, 422 for any other; the principal's alone, 403 for an area approver) and `edits.allow: true` (a training card only, 422 otherwise; the principal from a provable request, 403 otherwise), finishing `approved_with_edit` when a field changed.","mermaid": null,"generated_at": "2026-10-13T18:00:00Z"}diff --git a/packages/core/openexecutive/architecture/prebuilt/integrations.json b/packages/core/openexecutive/architecture/prebuilt/integrations.jsonindex 5d3f45a7..6f28ce88 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 — the chat adapters via `find_person_by_{slack,discord,telegram}_id`, the email poller via `people.identity.resolve_email_sender` (a primary address or an alias, then the company-domain rule; see Org) — and threads `person_id` into `Executive.chat()`. A sender who resolves to nobody is no longer simply dropped: see **New senders (roster requests)** below.\n\n### Inbound channels\n\n- **Slack** (`integrations.slack_bot`) — async Bolt app (`AsyncApp`) embedded in the lifespan, hearing Slack one of two ways: socket mode (`AsyncSocketModeHandler`, with `SLACK_APP_TOKEN`) or, with only `SLACK_SIGNING_SECRET`, the Events API over HTTP at `POST /webhook/slack` (`integrations.slack_events`), where the route checks each request's signature and age (and a 1 MB cap) before Bolt sees it, so unsigned traffic never reaches Bolt's logging; it then takes each signed request once, answering an identical replay (same signature) or Slack's re-signed retry of an `event_id` it already took with an empty 200 that never reaches Bolt (an in-memory, per-process set kept for twice the signature window and capped in size; keys are forgotten if Bolt fails, so a retry of a failed delivery still runs), and Bolt acknowledges at once while the listener runs. Either way a repeated event id is dropped (Slack resends what it thinks went unacknowledged), as is an event delivered for another workspace. 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. Replies (and every outbound Telegram message) go out as Telegram's HTML subset (`utils.markdown_telegram`: markdown-it-py with raw HTML and images off, text escaped), so the Executive's Markdown shows as formatting; links show as their text and target in plain text and never become tags, so quoted text can't hide where one goes; a chunk Telegram refuses is sent again as plain text.\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`) — MCP poll loop over the Executive's own mailbox — Gmail via `workspace-mcp` or Outlook via `ms-365-mcp-server`, chosen by `EMAIL_PROVIDER` (see *Workspace providers* below); it starts only once the MCP gateway is up, never surfaces Reply-To redirects, filters auto-replies. Its sessions carry `origin_channel=\"email\"`: the untrusted-content policy (`orchestrator.content_trust`) reads that tag to tell mail from the principal's own surfaces — left empty, as it once was, every stranger's body reached the decision extractor as the principal's words. The mail goes into the turn inside an `<untrusted_content source=\"email\" author=\"<sender>\" author_verified=\"no\">` block that says it carries none of the principal's authority, with the framing line and any `[POLICY]` notice outside it; mail from the principal's primary address that Gmail authenticated (`dmarc=pass`) is their own words — but only their new text goes in unwrapped: when the mail quotes or forwards another message (`_new_text_lines` cut something), the message as received follows in an `<untrusted_content source=\"email_quoted\">` block, since a stranger's text they replied to or passed on is not theirs. 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 from the rendered message with any trailing `--- REPLY ---` block dropped first, 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. The poller's `integration_inbound` row keeps the mail's text for the audit log, the way the reply's `chat_turn` row keeps the Executive's answer: `full.message` is the sender's new text (what web chat keeps for a turn), `full.attachments` the attachment filenames, and `details.preview` the first 120 characters of the new text, so /audit shows what was asked next to what was answered (the summary still reads `Inbound email from <sender>: <subject>`). The whole body with its quoted chain (`full.body`) is kept only on a row private to the principal: the chain is other people's mail — a contact's, on the principal's reply to one — and every signed-in user reads a public row. Each field is cut by its escaped JSON length (20,000 characters of text, 8,000 of attachment names), the measure the logger's 64 KB cap uses, so a long mail in a non-Latin script loses its tail rather than the row's structure. Outbound, the principal briefs and the client-rotation digest are emailed through the same gateway with the configured backend's send tool (`google_workspace__send_gmail_message` or `microsoft_365__send-mail`, via `workspace.registry.send_from_executive`, from the Executive's own mailbox to the principal's address, subject `<brief title> — <date>`, the date in the user's zone) as formatted HTML — rendered from the brief's Markdown with raw HTML and images off, so text quoted from outside shows as text and opening the email loads nothing remote. Email is first when the principal prefers it, and otherwise the backup after every chat channel, tried only when Slack, Discord and Telegram are missing or fail; an in-band error from the tool counts as a failed send and the next channel is tried. An emailed brief is not a DM, so the per-Person outbound guard below does not apply — the gateway's roster egress gate does.\n\n Two senders get their own framing. Mail from one of the principal's **contacts** (a `kind=\"contact\"` People row — see Org) replaces the non-roster `[POLICY]` notice with a contact one: it names them (name and role/company), says not to reply unless the principal asks and not to tell anyone else, and asks for a summary for the principal instead. Both this turn and the forwarded-by-principal turn below are marked `Session.private_to_principal`: they can email, DM or invite only the principal, an alert they raise is private to the principal, and they are not offered the tools that reach anyone else or start work outside the turn (`schedule_tools.PRIVATE_TURN_WITHHELD_TOOLS`: broadcasts, meeting bookings, workflows, follow-ups, watches, artifacts, goal updates, skill drafts, connecting a new MCP server), and of the MCP tools only Google Workspace reads and the gated Gmail send (see MCP below). Every audit row about such mail is private to the principal (see Audit Log), the poller's two `integration_inbound` rows included (`_private_to_principal_mail`), so the audit log's other readers see none of it. The poller holds `audit.private_rows` for the whole handling of such a mail, because some rows are written before the turn binds its private session: the knowledge retrieval quotes the mail's From line, subject and opening. The rows themselves read exactly like an outside sender's: the `integration_inbound` row is the non-roster one (`accepted_non_roster`), and the notice opens with the non-roster notice's exact sentence. The poller handles each message with no session bound, so one message's private turn never marks the next message's rows. The turn stays unattributed (`person_id` None — no peer memory, no co-presence), and the gateway refuses mail to a contact on a poller turn anyway. Mail **forwarded by the principal** — the sender resolves to the principal and `_new_text_lines` reports a forwarded message — is wrapped in a `<forwarded_by_principal>` block: summarise it, draft a reply the principal could send (as text in the reply, never sent or saved as a Gmail draft), note any commitment or date, and offer to add the original sender as a contact (confirmed from the web app or the principal's Slack / Discord, since an ordinary email turn cannot change the People list — the one email that can is the principal's tokened reply to a roster-request email, which is parsed before any model turn; see below). The reply still goes to the principal only. The From header is unauthenticated, so this framing grants nothing: a spoofed \"forward\" just gets the real principal a summary.\n\nSlack, Discord, and Telegram are roster-gated on inbound: an unrostered sender's message never reaches the Executive (`details.outcome=\"rejected_unknown_sender\"`). The gates look up **team members only** — a contact's Slack, Discord or Telegram id is treated as unknown, so a contact can never talk to the bot (nor count as a co-present peer). What happens next is the roster request below — except for a contact, a thread continuation, a Telegram group or an unverified Telegram webhook, which stay silent. 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). Slack only continues a thread it has replied in: it reads the thread with `conversations_replies` (5 s bound) and looks for its own user id, which `auth_test` resolves at startup. If that lookup fails, mentions and DMs still work and thread continuations stop until a retry succeeds (`slack_bot._resolve_bot_user_id`, at most once a minute, from the channel `message` listener). When Slack doesn't return the thread in time, the thread's stored history (`slack:thread:{channel}:{thread_ts}`, written on every turn the bot answers there) stands in: with history, a rostered sender gets an ephemeral \"I couldn't read this thread just now… @-mention me\" and the drop is audited (`outcome=dropped_thread_unreadable`). A thread the bot never answered in stays silent. A message the gate skips is audited (`outcome=skipped_gate`, with the gate's reason) and gets an :eyes: reaction (`reactions_add`, which needs the bot's `reactions:write` scope; without it the reaction is skipped), so a sender the gate misjudged can see the message was read and @-mention the bot.\n\n**No link previews on replies.** The Executive's replies go out with previews off — Telegram `sendMessage` carries `link_preview_options.is_disabled`, Slack's reply `say` passes `unfurl_links=False` / `unfurl_media=False`, and every Discord reply send passes `suppress_embeds=True`. The direct messages the Executive starts are the same: `send_slack_dm` posts with `unfurl_links=False` / `unfurl_media=False`, and Discord's `send_dm` sets the `SUPPRESS_EMBEDS` flag on each chunk, so a reminder or a brief sent by DM carries no preview either. Otherwise the chat service fetches a link in the text on its own, so a reply that quotes someone's mail (Act as me reads it) could carry data to a sender's server with no click. The web chat does the same for images: `Message.tsx` loads only an image the app itself serves (`lib/markdownImages.loadsInline`) and shows any other as a link.\n\n### Alert triage of chat messages\n\nEvery chat-app message that passes the roster gate (Telegram, Slack, Discord, Google Chat) is also handed to alert triage through `alerts.pipeline.schedule_chat_message_evaluation`. The sender is named by their People record (`full_name`), not by the name they typed into the chat app, so a person whose account there is called something else is never read as a stranger; the chat app's own name (or raw user id) is used only when nobody on the roster matched. The principal's own messages to their Executive are a conversation, not news for their brief, so they are not triaged at all. Triage sees the sender as `sender:` and the room as `channel:`.\n\n### New senders (roster requests)\n\nSomeone who writes in and is not on the People list — and is not one of the principal's contacts — is **held, acknowledged and asked about** instead of dropped (`integrations.roster_intake.intake` over the `people.roster_requests` ledger; lifecycle in Org). Each adapter calls it after its gate:\n\n- **Slack** — a DM or an `@mention` (not a thread continuation: the bot was not addressed there). The name and profile email come from `users_info` (5 s timeout). The acknowledgement goes in the DM, or as an **ephemeral** message for a mention, so nobody else in the channel learns who is and is not on the roster. The held event keeps only a fixed set of keys (text, user, channel, ts, thread, files).\n- **Discord** — a DM or a mention (not a thread the bot merely follows). The acknowledgement goes in the DM, or by DM for a channel mention; `/ask` answers the interaction with an ephemeral acknowledgement first (Discord allows 3 s), then holds the prompt. Its old \"ask the admin to add you\" reply is gone.\n- **Telegram** — only a **private** chat, and only when `TELEGRAM_WEBHOOK_SECRET` is set and valid: Telegram identifies the chat rather than the sender, and without the secret anyone could forge an update. A group, or an unverified webhook, stays silent as before. Attachment file ids are held and downloaded only on replay.\n- **Email** — non-roster mail that is not private to the principal (so never a contact's) and does not look machine-sent (`looks_automated`: a no-reply / notifications / billing-style local part, a `List-Id` / `List-Unsubscribe` / `Auto-Submitted` / bulk `Precedence` header, or a DMARC failure). The mail is **still triaged** by the Executive on this pass; its `[POLICY]` notice now says the sender was already told their message is waiting and the principal was asked who they are, so the model raises no second alert just to add them, and that the email will come back once they are added.\n\nEvery path skips a contact first (`find_person_by_*_id(..., include_contacts=True)`, or the email poller's private-mail rule): a contact has no chat access and gets no request and no acknowledgement, and the team-visible `rejected_unknown_sender` / `accepted_non_roster` rows read the same for a contact as for a stranger.\n\n**The acknowledgement** is one fixed text (`roster_intake.ACK_TEXT` — \"your message arrived … waiting for confirmation\"), never the model and never an echo of what they wrote, so a forged sender gains nothing by triggering it. It is sent at most once per sender per `ROSTER_ACK_WINDOW_DAYS` (7) and at most `ROSTER_ACK_DAILY_CAP` (20) a day across all senders (`claim_ack`, one transaction; a failed send releases its claim). An email acknowledgement is the one send the MCP gateway lets reach an address off the roster: `send_email_ack` sets `mcp_gateway.roster_ack_grant`, a one-shot ContextVar grant that admits a single `send_gmail_message` with exactly the granted recipient (a plain string, no list), subject and body and no other key, then is spent (audited `integration_outbound`, `kind: roster_ack`, private). An email sender is acknowledged only when Gmail authenticated them: once `claim_ack` succeeds, the poller's `send_ack` re-reads the mail as raw MIME and needs Gmail's own topmost `Authentication-Results` reporting `dmarc=pass` for the From domain (`fact_confirmation.sender_authenticated`, fail-closed). The printed headers the poller reads never carry that header, so without the second read a forged From would draw the acknowledgement to whoever it names — backscatter from the Executive's mailbox. An unauthenticated sender makes `send_ack` raise `roster_intake.AckWithheld`: the claim is released, and they are held silently. `authenticated_by_gmail` strips quoted strings and comments before reading the verdict — Gmail copies the envelope sender and DKIM tags into its own stamp, and a quoted local part could otherwise carry a fake `dmarc=pass` — and needs exactly one `dmarc=` verdict reading exactly `dmarc=pass header.from=<domain>` (Gmail may follow it with its own `dara=` resinfo, so its position is not checked). Residual: when Gmail writes no verdict at all (a From domain without DMARC) and echoes an unsanitised `;dmarc=pass header.from=…` elsewhere in its stamp, that echo would read as the verdict; bounded by the acknowledgement caps. A withheld acknowledgement is audited `roster_ack_withheld`. `intake` acknowledges before surfacing the card and telling the principal, and both follow the request's `ack_sent_at`: a withheld, failed or capped acknowledgement reads \"haven't been told anything yet\" on the Today card, in the principal's prompt and in the email `[POLICY]` notice.\n\n**Telling the principal.** A new request puts a private card on the principal's `/today` (see Today) and pushes a prompt on their delivery plan — preferred chat DM, then the others, then email — for a chat sender or an email sender on the company's own domain; an outside email sender waits on the card, as does everything past `ROSTER_REQUEST_DAILY_CAP` (30) pushes a day (the same cap bounds how many requests open a day; a declined sender is not raised again for 30 days). A chat prompt can be answered in place (\"that's Annamarie, add her to the team\"). An email prompt carries a one-time token (`RR-` + 20 base32 characters, stored hashed); the poller checks every inbound mail for one **before** triage (`try_email_roster_answer`): the reply must come from the principal's primary address exactly (not an alias, not the company-domain rule), carry the token of a pending request, not be an automatic reply, and not fail DMARC where the header is visible; and is parsed by `parse_decision`'s `roster_identity` shape — anything else falls through to the ordinary path. The token is hidden (`RR-[hidden]`) in every other Google Workspace result the gateway returns — the confirmation sits in the Executive's Sent folder, and any turn could otherwise read it — except the poller's own fetch of an inbound message (`mcp_gateway.reveal_roster_tokens`); a token-bearing mail that is not an answer is scrubbed before triage.\n\n**Replay.** Once the principal answers (web card, chat tool, email reply) — or a People-page / `upsert_person` write makes the sender match someone (`after_roster_write`) — the held messages are replayed through the adapter that received them (`register_replayer`: Slack re-runs the held event, Discord and Telegram their held text, email re-fetches the message from Gmail and handles it as mail from a known sender), oldest first, now attributed to the new Person. A teammate gets every held message; a new contact only held email (it takes the private contact path; held chat is dropped); a decline drops everything. Replays run in a **fresh `contextvars.Context`**: the answer may have come from the principal's own verified turn, and a stranger's message must never be read with the principal's session — and their contacts — still bound.\n\n### Standing facts by email (confirm by reply)\n\nThe principal can ask for a standing fact, a retirement or a company-profile edit by email, and the fact tools check it exactly as in chat (the own-words gates run on `_email_memory_text`, the sender's new text, not the quoted chain or attachments). An email's From line proves nothing, though, and a standing fact is read by every later prompt as the principal's own account. So an emailed change is **held, never applied**, until the principal's own mailbox confirms it (`integrations.fact_confirmation`, `memory.facts.fact_confirmations`):\n\n- **Who may ask.** The poller stamps every email turn with `Session.email_from` (the bare lowercased From address) and `email_authenticated`. The text the poller reads never carries `Authentication-Results` (workspace-mcp prints a fixed set of headers), so for mail claiming the principal's primary address it reads the message again as raw MIME (`fact_confirmation.sender_authenticated`) and requires Gmail's own stamp: the **topmost** `Authentication-Results` header (Gmail adds it on receipt, above anything the sender wrote), authserv-id `mx.google.com`, reporting `dmarc=pass` for the From address's domain, with the raw From matching (`authenticated_by_gmail`). It fails closed: no header, `dmarc=none`, a temporary error or a failed read all leave the turn unauthenticated. Mail from a teammate other than the principal is read the same way, before its inbound audit row is written: authenticated, the whole handling of it is theirs alone in the audit log (`rows_for_person`, see Audit) and the turn reads their own mail as them (`Session.email_sender_authenticated`); unauthenticated, it keeps the ordinary rule. Mail from anyone else costs no second read and is never authenticated. `fact_tools._gate` admits an email turn only from the principal's **primary** address, exactly (no alias, no company-domain rule), authenticated, and not private to the principal (mail they forwarded stays refused, as do contacts, teammates and unknown senders).\n- **The hold.** The tool returns `awaiting_confirmation` (no action chip, and the model is told to say nothing has changed). `request_confirmation` stores the change with the SHA-256 of a fresh one-time token (`FC-` + 20 base32 characters, 100 bits; 7-day expiry; at most 10 waiting at once) and emails the token to the principal's roster address, outside any turn's outbound context. A profile edit is dry-run first, so one that cannot apply is reported in the turn, before any email goes out. If the email fails, nothing is held.\n- **Keeping the token from any model.** The tool result never carries it, and `mcp_gateway.hide_roster_tokens` now scrubs `FC-` tokens as well as `RR-` ones (`FC-[hidden]`) from every Google Workspace result except the poller's own fetch of an inbound message. Act as me's reads of the principal's own Gmail, where the confirmation email lands, hide them too (`delegation.gmail.parse_message` and the thread search), so the drafting model never sees a live token either.\n- **The reply.** `_handle_one_email` hands every message to `try_email_fact_confirmation` right after the roster-answer check, before any model turn. It acts only on a reply from the principal's primary address carrying the token of a **pending** confirmation. A made-up, spent, cancelled or expired reference matches nothing and falls through to the ordinary path with the token hidden, so no old or forged token can make the Executive email the principal. A reply with a live token is read again as raw MIME (`read_raw`) and must pass the same Gmail DMARC check as the request; one that doesn't (or whose raw read fails) is refused, the change keeps waiting, and the principal is told. Then an **automatic reply** is consumed quietly — no answer, no model turn, the change keeps waiting: the printed headers catch a Gmail vacation reply (`Precedence: bulk`), and the raw headers catch what they don't show (`automatic_reply`: `Auto-Submitted` other than `no`, `X-Auto-Response-Suppress` and similar, `Precedence: auto_reply`, an out-of-office subject), since an Exchange out-of-office echoes the token from the principal's own address and may well say \"I'll confirm on my return\". The raw message starts at the tool's exact separator line (`\\n\\n--- RAW MIME ---\\n`), so a sender-written Subject imitating it cannot supply the headers. CONFIRM (or yes / approve) applies the change through `fact_tools.apply_confirmed`, the same apply step chat uses. CANCEL (or no) drops it, and an unclear reply leaves it waiting. The principal gets a one-line result either way. A compare-and-set on the row means two replies can apply it only once.\n- **Audit.** Private `fact_confirmation` rows record held / applied / cancelled / refused. The applied change also writes the fact tools' usual private rows, with `source_channel=\"email\"` as its provenance.\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. A listening Slack is amber while the listener hasn't resolved its own user id (`slack_bot.bot_user_id()`), since thread continuations are off until it does. 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. Gmail is also amber when startup priming could not find every pinned Google tool (`MCPGateway.prime_pinned_tools`, whose result the gateway keeps on `pinned_tools`): the row names a few of the missing tools and counts the rest, and points at the `MCPGateway` log lines. It is amber too while that probe has not finished, and when the probe itself failed — the one check that reads green is the one that ran and found everything, so a crashed probe is never silently fine. The row speaks for the whole `google_workspace` server, so a missing Docs or Drive tool shows up under Email (Gmail).\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\n**Conversations within a chat app.** A Telegram chat, a Slack or Discord DM and a person's @mentions in one channel (`slack:channel:…`, `discord:channel:…`) are each one endless stream, so they are cut into conversations (`memory.conversations`, shared helpers in `integrations/conversations.py`). Each adapter computes the stream's base id as before and asks `conversation_for` which conversation a message belongs to: the newest, unless the stream has been quiet for two hours (`CONVERSATION_GAP`), when the next one starts. The first conversation keeps the bare base id; later ones add `~2`, `~3`, … (`memory.conversation_ids`). A whole message of `/new`, \"new chat\" or \"new conversation\" starts a fresh one instead of a turn and is answered with the name of the one it ended; the new row has no messages and stays off the Chats page until its first turn. After a conversation's first exchange `title_after_turn` names it in the background with `utils.session_title.generate_session_title` (the first words of the message if that fails), as a web chat's first turn does. Threads (`slack:thread:…`, `discord:thread:…`), email and every other id are left whole. What has to see the whole stream compares base ids: the inbound resolver, so an approval asked before a cut is answered after it, and the session-scoped decisions and advice `format_for_prompt` renders. At boot `split_existing_streams` cuts history saved before this by the same rule, once (`app_migrations`), titling each part from its first message and carrying a read-mail lock to every part. An adapter installed outside the package adds its streams with `conversation_ids.register_rolling` and cuts its own old history once, with its own migration name and an `only` filter for its base ids, because the built-in sweep may already have run without it.\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, Telegram, Slack and Google Chat. Images become Anthropic vision blocks; documents (PDF/DOCX/TXT/MD/CSV) are inlined into the turn that carried them — inside an `<untrusted_content source=\"attachment\" author=\"<name>\">` block (`content_trust.wrap_untrusted`, whose closing tag the text cannot forge), under an `[Attached: <name>]` label, which the open-loop pass reads as \"not the speaker's words\" and the decision extractor strips before it reads the turn — and indexed into the ChromaDB `inbound_attachments` collection. 20 MB/file cap; web chat uses `POST /chat/upload`.\n\n**Scanned PDFs** are read, not reported empty. A PDF with no text layer goes through `knowledge.pdf_reader`: with `PDF_PROVIDER_READING=true` (opt-in, off by default) the deployment's own model reads it through its provider's PDF support (Anthropic natively, OpenRouter's `file-parser`, a local server only with `LOCAL_PDF_INPUT`); otherwise, and as the fallback, local OCR (pypdfium2 + RapidOCR, offline, no key) — so every deployment converts them. The label then reads `(converted from scanned pages)`, and an unreadable one says why. The index takes the text already extracted for the turn, so a scan is converted once. A file a channel delivered (everything here except `POST /chat/upload`, where the signed-in user sends it) converts at most `PDF_INBOUND_MAX_PAGES` (30) pages and draws on a rolling `PDF_INBOUND_PAGES_PER_HOUR` (300) budget shared by all senders, so sending scans cannot run up unbounded model spend or CPU.\n\nPer channel:\n- **Slack** — a `file_share` message (previously dropped outright for its `subtype`) is handled like any message; files download only after the roster gate and the response gate, with the bot token sent only to `https://files.slack.com/` (needs the `files:read` scope). History and peer memory record the words plus `(Attached files: …)`, never a document's text.\n- **Google Chat** — uploaded attachments download through `media.download` with the reply credentials (`chat.bot`), checked against the 20 MB cap per chunk, 5 per message; an attachment-only message is no longer dropped. The webhook authenticates Google, not the sender, so files are read only when the event's `user.email` is on the People roster (a team member); anyone else's files are named to the Executive, never downloaded. A Drive file shared into a message is left to the Drive tools, with its id.\n- **Email** — the poller (`integrations.email_attachments`) downloads up to 5 readable attachments of the message itself via `get_gmail_attachment_content` — workspace-mcp in stdio mode saves the file and answers `Saved to: <path>`, which must start its line, be the last such line and end in the answer's `Saved filename:` (the answer echoes the sender-chosen attachment name first, and a name carrying `Saved to: /…` must not redirect the read), then resolve inside the tool download folders — and appends their text to the turn (15k chars each). Only for a sender the principal knows (team, contact, principal); a stranger's files stay a list. It runs outside the model loop, so it works on private turns without adding the attachment tool to `PRIVATE_TURN_MCP_TOOLS`.\n- Anything else (a Drive PDF, a skipped attachment) — the Executive's `read_document` tool.\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, Outlook mail and calendar — whatever `mcp_servers.json` configures) as Executive tools, with egress gating on Gmail recipients, Calendar attendees, Drive share grantees, and Microsoft 365 recipients/attendees against the roster (and a refusal of public / whole-domain Drive sharing). The Gmail gate also accepts only a fixed set of argument keys, so workspace-mcp's `reply_all` (recipients taken from the thread, never checked) and `forward_message_id` / `include_forwarded_attachments` (forwarding any inbox message) are refused; a reply is `thread_id` plus an explicit, roster-checked `to`. Three more refusals close paths around those gates: every Apps Script tool (code running as the Executive's account, outside the gates, and since workspace-mcp 1.29.0 schedulable to keep running); any argument that makes the server fetch a URL (`fileUrl` / `file_url` on the Drive and import tools, a Gmail attachment given as a `url`), since the fetch can carry data out in its query string before any recipient gate matters; and text Google would mail to someone the roster never checked (`rsvp_comment` to an event's organizer, an out-of-office `decline_message` to whoever invites the Executive). Every gate reads its arguments by normalized spelling: workspace-mcp 1.29.0 renames a camelCase key such as `Attendees`, `userGoogleEmail` or `rsvpComment` to the real parameter, so a gate matching the exact key would never see it. Arguments that are not a JSON object are refused for the same reason. Google-side fetches are refused too: any key ending in `url` / `uri` at any depth whose value has a URL scheme (a Slides image or page background, a Docs or Forms image; a document hyperlink and a meeting link are stored, not fetched, and pass, as does a Drive file id), (a value is a URL after the characters a URL parser strips are removed, and `//host` counts), and on every tool that can write cells — the Sheets tools and the Drive create / update / import tools, which turn CSV into a Sheet — any string anywhere holding a formula call that fetches (`IMPORTDATA`, `IMPORTXML`, `IMPORTHTML`, `IMPORTFEED`, `IMAGE`), JSON-encoded or mid-CSV included: a string argument that encodes JSON is read as the server decodes it (one too large to read is refused), text is also scanned with character references decoded and comments / CDATA removed, and an upload that would become a native Sheet may only be text `content` — a `base64_content` or server-side `file_path` upload there is refused, since an XLSX hides its formulas behind zip members and XML encodings; a PNG to Drive or a DOCX to Docs is untouched. Not covered, unverified: whether Drive's HTML / Markdown import fetches an `<img src>` when it converts `content` into a Doc. A `manage_event` call that names no attendees is sent with `send_updates=\"none\"`, so the event's existing guests are not emailed text the gate never checked. The allow-list (`_egress_sets`, built by `_roster_allow_set` as a `people.identity.RosterAllow`) is every team member's email and email aliases plus the Executive's own address, always, and — for a teammate — any address on one of the company's own domains whose local part (`+tag` dropped) matches theirs, the same rule inbound mail is matched by; a **contact's** email joins it only when `people_tools.contacts_reachable_now()` is true — a turn the principal started on a verified surface (web chat, their own Slack or Discord, a verified private Telegram chat), or inside `grant_contact_egress()` (the decisions approve route, when the approver is the principal). On any other turn — an inbound email, a teammate, the scheduler, a workflow, the alert review — a contact's address is refused exactly like a stranger's, so the refusal cannot reveal that it belongs to a contact (contacts are private to the principal). The single exception to the roster rule is the fixed roster-request acknowledgement above, under its one-shot `roster_ack_grant`. A turn about the principal's private mail (`Session.private_to_principal`) narrows the list to the principal's own address and the Executive's. Such a turn may call only the MCP tools in `schedule_tools.PRIVATE_TURN_MCP_TOOLS`: Google Workspace reads (`search_gmail_messages`, `get_gmail_message_content`, `get_events`, `list_calendars`, `query_freebusy`, and the Drive, Docs and Sheets reads such as `search_drive_files`, `get_drive_file_content`, `get_doc_content` and `read_sheet_values`) and the two Gmail tools this gate narrows to the principal (`send_gmail_message`, `draft_gmail_message`). It is an exact allow-list, not a server: workspace-mcp runs at the tier `WORKSPACE_MCP_TOOL_TIER` names, `complete` by default, where a Google Chat message to a space, a Docs, Sheets or Drive write into a file already shared with others, `manage_event` on a shared calendar (its gate checks attendees and pins notifications, nothing else) reaches people with no recipient check; and every other server has none at all (a Slack or Notion server, the default `fetch` server, whose URL can carry the turn's content, a server loaded at runtime). Its `search_tools` results show only the allowed tools (`workflows.tool_catalog.filter_search_results`; output it cannot parse reads as no match), and a `call_tool` naming anything else is refused with an error tool_result and an audit row private to the principal (`schedule_tools.private_turn_withholds`), a missing name included. `search_tools` and `call_tool` stay offered, so the tool list and its cached prefix do not change. The typed calendar tool (`_resolve_attendees`) and the chat DM tools (`message_person`, `send_telegram_message`, `send_discord_dm` and their person-id recovery) apply the same rule — a contact's id reads as an unknown one off the principal's turn — and a private turn may DM or invite only the principal (`PRIVATE_TURN_REFUSAL` otherwise); `message_person` never falls back to a \"Needs you\" alert for a contact, who cannot sign in to see it. 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 optional `WORKSPACE_MCP_TOOLS` (comma-separated service names, default `all`) limits which Google services it loads. The gateway forwards the Google secrets to the child via `_FORWARDED_ENV_VARS`. Every `google_workspace__*` call acts as the Executive's own account. workspace-mcp takes the acting account per call (`user_google_email`) and nothing used to check it, so under domain-wide delegation a model-chosen address could open anyone's mailbox in the domain; `mcp_gateway._check_acting_account` now refuses a value naming any other address — before every other gate, with an `integration_outbound_blocked` audit row. An absent value stays allowed (the server's own account).\n\n**What the model is told is connected.** `MCPGateway.start()` records the configured server names (`server_names`), and the Executive renders them with the channel settings into block 0's *Connected Systems* section (`prompts.connected_systems`; see the caching section). While Google is connected that section pins the Google tool names the Executive uses constantly (`GOOGLE_TOOL_MANIFEST`, narrowed by `connected_systems.google_tool_manifest` to the services and tier actually loaded) and tells it to call them with `call_tool` directly, with no `search_tools` round trip. The narrowing is the point: a name pinned for a service workspace-mcp never imported is not in the index, so the model calls it, receives extensible-mcp's “has not been discovered via search_tools” refusal, and has no way to square that with its own instructions. extensible-mcp only runs a tool one of the session's searches has returned, and remembers it for the session's life, so the gateway does that discovery itself: the lifespan starts `MCPGateway.prime_pinned_tools()` in the background once the gateway is up with `google_workspace` configured (an exact-name search per pinned tool, the way `workflows.tool_catalog.resolve` does it, over the same narrowed set the prompt advertises — `connected_systems.pinned_google_tools`, so priming never probes a service that was not loaded). A name neither the prompt nor priming can account for is logged once, naming both causes: excluded by `WORKSPACE_MCP_TOOLS` / `WORKSPACE_MCP_TOOL_TIER`, or renamed by workspace-mcp since the pin. A pinned call that still comes back with extensible-mcp's \"has not been discovered via search_tools\" refusal, for example before priming finished, is discovered and retried once. That happens after every gate has passed the same arguments, and only for pinned names: any other tool still needs the model's own search, and nothing here widens what a call may do, including the private-turn allow-list.\n\n**Microsoft 365** is the Outlook twin: `@softeria/ms-365-mcp-server` (a Node package, pinned) is installed in a throwaway Node build stage and only the `node` binary plus the package are copied into the API image, launched by `docker/ms365-mcp-launch.sh` as the `microsoft_365` entry with an **explicit tool allow-list** (`--enabled-tools`, an anchored regex) rather than the upstream `mail,calendar` preset — that preset also registers inbox forwarding rules, mailbox settings (external auto-reply), calendar sharing and event forwarding, which can address people the gateway never sees. Exactly the Outlook mail + calendar tools and the OneDrive tools are exposed (`microsoft_365__send-mail`, `microsoft_365__create-calendar-event`, `microsoft_365__search-onedrive-files`, …; hyphenated Graph endpoint aliases, proxied verbatim), and every admitted tool is either roster-gated or carries no recipient; the gate also covers the excluded writers in case an operator widens the list. Both servers can be configured at once. Auth is the MSAL device-code flow against the operator's own Entra app registration (`MS365_MCP_CLIENT_ID` is required; the server's built-in public client is refused); the refresh token persists at `/data/ms365_credentials` and is seeded once with `ms365-mcp-launch.sh --login` from inside the container — the server has a native device-code CLI, so there is no mint script and nothing to copy. The launcher scrubs the literal `$VAR` placeholders extensible-mcp leaves for unset variables (otherwise MSAL would be handed `$MS365_MCP_TENANT_ID` as an authority), and `MS365_MCP_EXPECTED_USERNAME` pins the bound mailbox. The egress gate for this family walks Graph's nested shapes (`body.Message.toRecipients[].emailAddress.address`, `body.attendees[]…`) — every email-shaped string outside the free-text fields must be on the roster, control characters and non-ASCII addresses are refused, unforeseen keys are still scanned (fail-closed) — and covers the whole write surface: send, reply, reply-all, forward, every draft tool, `update-mail-message` (it can PATCH recipients onto a draft) and create-/update-calendar-event; reads and `delete-calendar-event` (the only cancel path) pass through. Graph's reply, reply-all and send-draft actions carry no recipient in their arguments (the recipient is whoever the referenced `messageId` names), so for those the gate first reads the referenced message through the server and roster-checks the recipients Graph will derive (`replyTo` else `from` for a reply; `replyTo` and `from` together, plus the original to/cc, for reply-all; the draft's own to/cc/bcc for send-draft), refusing on any lookup failure; RSVP and cancel actions get the same treatment through an event lookup, because their comment is emailed to the organizer or every attendee; `download-bytes` is pinned to mail attachment bytes and OneDrive file content (`/drives/{id}/items/{id}/content`, optionally Graph's `?format=pdf` rendering), and a OneDrive result comes back as the file's extracted text rather than base64 — the attachment pin is what makes the poller's promise that an unrostered sender cannot be auto-replied to hold on Outlook as it does on Gmail; and the rendered inbound text quotes any forged `--- REPLY ---` line inside a body so the persona only ever reads the real block. Every mail write's `from`, `sender` and `replyTo` may name only the Executive's own address (the Outlook twin of the Gmail acting-account pin), so the model cannot send as a rostered colleague's mailbox or steer replies elsewhere; and `move-mail-message` into Deleted Items, Junk Email or Recoverable Items is refused, so a move cannot trash mail ungated. The server registers its account tools whatever its tool allow-list says, so the gateway itself refuses `login`, `logout`, `select-account` and `remove-account` (audited like any other refusal) and drops them from `search_tools` results — a chat turn cannot sign the mailbox out, switch accounts or start a sign-in; setup is only the launcher's `--login`, and the read-only `verify-login` / `list-accounts` stay callable. The example config's hyphenated patterns still deny `delete-mail-*`, `logout`, `remove-account` and `download-bytes-to-file` as defense in depth. A successful `send-mail` records the same outbound-context linkage Gmail does.\n\n**OneDrive in chat** (opt-in with `MS365_MCP_ONEDRIVE=true` and a fresh `--login`, since the server asks for its tools' permissions on every token refresh and a sign-in without file consent would otherwise fail mail and calendar too) matches what the Executive can do on Google Drive: search, list a folder, read a file, upload and edit, create folders, move, rename, copy and share; there is no delete tool. The launcher adds `Files.Read.All` at sign-in (`--extra-scopes`), so folders shared *with* the Executive can be read too; writes (upload, new folder, move, copy) land only in the Executive's own drives, checked against `list-drives` at call time, so a planted instruction cannot save company files into a stranger's shared folder. Sharing is gated like Drive sharing: `share-drive-item` invitees must be People on the roster and named by email (an `objectId` or `alias` grantee is refused, since nothing can check it), no `owner` role, and `create-drive-item-share-link` must be scoped to specific people (`scope: \"users\"`): an anonymous or whole-organization link, or one with no scope (the tenant default), is refused. An invite must require sign-in and grant only view or edit, a link must be a view or edit link, and `search-onedrive-files` takes plain words only, since its query goes into the request path unencoded.\n\nAs 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. The same expansion serves the Microsoft 365 mail writes: the entry becomes a Graph `#microsoft.graph.fileAttachment` (`name`, `contentType`, `contentBytes`) placed where Graph expects it for that tool (`body.Message.attachments` for `send-mail`, reply, forward and the createReply drafts; `body.attachments` for `create-draft-email`), whether the model put it at the top level or inside the message; an entry anywhere else, one on `update-mail-message` or `send-draft-message` (their requests cannot carry attachments), or one behind a body that is not an object is refused rather than forwarded unexpanded.\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`. All three per-Person DMs refuse a recipient id that matches no non-archived Person row (`schedule_tools._dm_recipient_on_roster`), which is what stops untrusted content in a turn — inbound mail, a chat message, a knowledge document — from directing a DM at an arbitrary workspace member. `send_slack_dm` previously consulted the roster only when the turn was already private to the principal, so on an ordinary turn it applied no roster check at all while its Discord and Telegram siblings did; the room-targeted tools are deliberately ungated, since those channels are team-visible. 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### AI disclosure\n\nWhat the Executive sends says it is an AI assistant (`orchestrator.disclosure`), added by plain code so a reply the model writes can't leave it out. **Mail** from its own mailbox gets a line under the body, by default \"<EXEC_DISPLAY_NAME> is an AI assistant working for <company>. To reach a person, reply and ask, or write to <principal's address>.\": the MCP gateway adds it to every Gmail send and draft and every Outlook send, reply, forward and draft (`mcp_gateway._with_disclosure`) **after** every outbound gate has passed and only on what goes to the server, so the gates, the outbound-context record and the audit see the model's own words, and `send_from_executive` gets it the same way. It counts as already there only when it is the last line that shows (in a quoted earlier message or hidden in markup it doesn't), and a send of an existing draft and mail whose every recipient is the principal go as they are. HTML that could hide what follows (an unclosed comment, a style or script block, text styled out of sight: `disclosure.hides_what_follows`) is refused, so the line can't be hidden after it; the model is told to send plain text. The roster acknowledgement to a new sender, the one send to an address nobody checked, gets `BARE_MAIL_LINE` (\"This message was sent by an AI assistant.\"), which names no one, like the acknowledgement itself. **Chat** gets a shorter line (\"<name> · AI assistant\", in italics) on the Executive's replies in Slack, Telegram, Discord and Google Chat and on its own DMs and room posts (`send_slack_dm`, `send_discord_dm`, `send_telegram_message`, `broadcast_tools._dispatch`), but only on the first message in a conversation and again after 24 hours without one (`with_chat_line`, kept in memory, so a restart shows it once more); session history keeps the reply without it. `AI_DISCLOSURE` (default on) turns it off; `AI_DISCLOSURE_MAIL_TEXT` / `AI_DISCLOSURE_CHAT_TEXT` reword the lines, and a wording that doesn't say \"AI\" is ignored for the built-in one. It fails open: a line that can't be built is left off, never a send refused. Replies sent *as a person* under Act as me are the delegation section's (**AI line on replies**).\n\n### Calendar & video links\n\nThe Executive books meetings through two typed tools over the configured calendar backend (`CALENDAR_PROVIDER`: Google Calendar via `manage_event`, or Outlook via `create-calendar-event` — see *Workspace providers*). `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. Because nothing approves it, an instant meeting, and `cancel_calendar_event` too, runs only when someone on the team asked on a surface that verified who they are (the principal, or a rostered teammate in the app or their own chat); a turn an inbound email started gets a refusal to pass on instead, and a team-mode `create_calendar_event` the operations department would auto-execute is proposed instead. Both attach a video-meeting link by default (`add_video_link`; opt out for in-person) — a **Google Meet** link parsed from the created event's `conferenceData`, or a **Microsoft Teams** link from `onlineMeeting.joinUrl` — surfaced to the caller plus persisted on the decision ledger as `meet_link`. The tool descriptions are static, backend-neutral text, so the cached tool block never depends on settings; the pre-rename `add_google_meet` key is still honoured for old ledger rows. 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### Workspace providers\n\nThe Executive can *discover* any mail or calendar tool the gateway exposes, but three code paths call a fixed backend with no model in the loop and used to spell Gmail tool names inline: the inbound mailbox poller (list unread → fetch → mark read), alert email dispatch plus the scheduler's email send-tool hint, and the typed booking tools plus the approval-time conflict check. `integrations.workspace` puts those behind two Protocols (`MailProvider`, `CalendarProvider`) with one module per backend (`google.py`, `microsoft.py`) and a registry keyed on `EMAIL_PROVIDER` / `CALENDAR_PROVIDER` — separate switches (Outlook mail with a Google calendar is legitimate), both defaulting to `google`, so an existing install changes nothing until an operator opts in. The Google backend is the old inline code moved verbatim; tests pin its argument dicts byte-for-byte. The Microsoft backend polls only the Inbox folder (`list-mail-folder-messages` with `isRead eq false`, never the all-folders listing that includes Junk), converts Graph's HTML bodies to text with a real parser, lists a message's attachments so the names appear in the same `N. name (mime, size KB)` shape Gmail's text uses (and reach peer memory), marks read with `update-mail-message`, sends through `send-mail`'s nested shape, books with `isOnlineMeeting` + `onlineMeetingProvider=teamsForBusiness`, cancels with `delete-calendar-event`, and answers the advisory conflict check from the Executive's **own** calendar view (delegated permissions cannot read attendees' free/busy — narrower than Google's `query_freebusy`).\n\nEvery backend renders an inbound message into the same `Subject:` / `From:` / `To:` / `Cc:` + `--- BODY ---` text the persona already expects, and the poller adds a `--- REPLY ---` block naming the exact reply tool and threading ids for *that* message (Gmail: `send_gmail_message` + `thread_id`; Outlook: `reply-mail-message` + `messageId`) after the mail's `<untrusted_content>` block, never inside it. The block rides in the user turn — which is what lets the cached persona say \"use the reply tool in the REPLY block\" instead of naming a vendor tool — and the scheduler's proactive-email trigger names the backend's send tool the same way. Providers never raise on a malformed backend response (they return empty / `None` / `{\"error\": …}`), so one bad cycle never kills a loop, and a chosen backend whose MCP server is missing from `mcp_servers.json` is logged at startup and skipped by the poller: fail-soft, never a boot failure. The poller's newer checks run on that rendered text for both backends (contacts and private turns, roster requests and their emailed answers, the audit row), with three Outlook differences that fail closed: no sender is ever authenticated (the `dmarc=pass` read is Gmail's), so there is no acknowledgement to an unknown sender, no emailed fact confirmation and no principal-authenticated mail; attachments stay a list (the download is Gmail's); and the brief's calendar block is skipped (its listing is Google Calendar's). The code's own emails to the principal (roster prompts, fact confirmations, scheduled deliveries) go through `workspace.registry.send_from_executive`, and `runner.email_ready` follows `EMAIL_PROVIDER`. A private turn's allow-list (`schedule_tools.PRIVATE_TURN_MCP_TOOLS`) and Act as me's mail-touched reads include the Outlook twins of the Gmail and Calendar tools, and roster answer tokens are hidden from Microsoft 365 results as from Google's.\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 and the recipient is not one of the principal's contacts (a contact cannot DM the bot, and quoting the principal's conversation into their email reply's unattended turn would put it in the audit log) — 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` or `microsoft_365__send-mail`, 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.\n\n### OneDrive folder sync\n\nThe Microsoft twin of the Drive folder sync below (`knowledge.onedrive_sync`, `ONEDRIVE_SYNC_ENABLED`; setup in `docs/onedrive_sync_setup.md`). It copies the files in `ONEDRIVE_SYNC_FOLDERS` (`<drive id>/<item id>` pairs; `openexecutive onedrive-folder <link>` resolves a sharing link) into the isolated `onedrive_docs` collection on its own heartbeat, and shows them on the knowledge page as \"OneDrive\" rows with a **Sync now** button. Microsoft has no service account that sees only what is shared with it (app-only Graph access covers the whole tenant), so it reads as the Executive's own Microsoft 365 sign-in, and the folder list is the scope. It never stores a credential: each tick asks the launcher for a token (`ms365-mcp-launch.sh --access-token`, which runs `docker/ms365-access-token.mjs` through the server's own token cache and will only mint file-read tokens), keeps it in memory, and sends it only to Graph. `knowledge.onedrive_client` issues GETs only, follows a paging link only back to Graph, and fetches a file's pre-authenticated download link without the token; errors never carry that link. PowerPoint and older Office formats are read through Graph's PDF rendering.\n\n### Google Drive folder sync\n\nThe synced files show on the knowledge page's Company documents list as \"Google Drive\" rows (sync time, last edit in Drive, an Open in Drive link and a text view), and the page's source card shows the last run, any sign-in error or count of files that failed to sync, and a **Sync now** button that runs one tick on demand.\n\n\nSeparate from the Drive tools the gateway proxies. The optional folder sync (`knowledge.drive_sync`, `DRIVE_SYNC_ENABLED`; setup in `docs/drive_sync_setup.md`) copies the files in `DRIVE_SYNC_FOLDER_IDS` into the isolated `drive_docs` knowledge collection on a scheduler heartbeat, so the Executive knows those folders without searching Drive live (see RAG). It calls the Drive v3 API directly (`knowledge.drive_client`, `httpx`) as a **service account** with the `drive.readonly` scope (`DRIVE_SYNC_SERVICE_ACCOUNT_FILE`), not as the Executive's own account through workspace-mcp. Google enforces the folder scope, because the account sees only what is shared with it, and the sync can change nothing. Structured JSON means no display text to parse, and every file or folder id is checked against `[A-Za-z0-9_-]{1,128}` before it goes into a URL or a query. The two paths meet in two places. A synced chunk carries its Drive file id and sync time, so the Executive can open the live file with its own `get_drive_file_content`. The setup doc says to share each synced folder with the Executive's account too, so that live open works.\n\n### Confluence space sync\n\nThe optional Confluence sync (`knowledge.confluence_sync`, `CONFLUENCE_SYNC_ENABLED`; setup in `docs/confluence_sync_setup.md`) copies the pages of the spaces in `CONFLUENCE_SYNC_SPACE_KEYS` into the isolated `confluence_wiki` knowledge collection on a scheduler heartbeat, so the Executive knows the company wiki without a tool call (see RAG). It works with Confluence Cloud and Server/Data Center: `knowledge.confluence_client` calls the v1 REST API both serve, directly with `httpx`, signing in with a personal access token (Server/DC) or a username and API token (Cloud). It reads only, never follows a redirect (so the token stays on the configured site), streams responses with a 20 MB cap, and checks page ids and space keys before they reach a URL or a CQL query. The URL must be `https://` unless `CONFLUENCE_SYNC_ALLOW_HTTP` is set, and `CONFLUENCE_SSL_VERIFY` takes `true`, `false` or a CA bundle path for a private certificate authority. With `CONFLUENCE_SYNC_PUBLIC_HOSTS_ONLY` (off by default, for an install where whoever sets the URL must not reach the backend's own network) every request resolves the site's host, refuses it when any address is not public (loopback, private, link-local, shared), and connects to the checked address with the site's name kept for the Host header and the TLS certificate check, directly rather than through a proxy. `confluence_client.config_problem` is the same settings check the app runs at start, for a caller that writes these settings on someone's behalf.\n\nIt is separate from a Confluence MCP server such as mcp-atlassian, which a deployment can add to `mcp_servers.json` for live reads and edits in chat. The two share the env names `CONFLUENCE_URL`, `CONFLUENCE_PERSONAL_TOKEN`, `CONFLUENCE_USERNAME`, `CONFLUENCE_API_TOKEN` and `CONFLUENCE_SSL_VERIFY`, so one set of values serves both, and a synced chunk carries its page id so the Executive can open the live page with such a tool. A Confluence token is a user's, and what the sync reads becomes retrievable by everyone who talks to the Executive, so the space list is required and pages with a read restriction (their own or a parent's) are skipped unless `CONFLUENCE_SYNC_SKIP_RESTRICTED=false`. That keeps any existing member's token safe to use, without a dedicated licence. Manual runs: `openexecutive sync-confluence` / `purge-confluence`.\n\n### Your own Gmail or Outlook (Act as me)\n\nA second, separate mail connection, for **Act as me** (see **Act as Me (Delegation)**): a person's *own* mailbox, which `delegation.gmail.DelegateGmail` reads and drafts into over the Gmail REST API. It is never registered with the MCP gateway, so the model can reach it only through the typed `ghostwrite_email` handler — never by tool name through `call_tool`. The credential is one file per person in `DELEGATION_GOOGLE_CREDENTIALS_DIR` (default `company/delegation_google/`, `/data/delegation_google` in Docker), minted on a computer with a browser by `scripts/connect-own-gmail.py --email <you>` with the Executive's own OAuth client and the scopes `gmail.readonly` and `gmail.compose` — the same seed-it-yourself flow as the Executive's token, since the API serves no OAuth callback. It never lives in `WORKSPACE_MCP_CREDENTIALS_DIR`, where workspace-mcp picks a credential by address.\n\nEvery use re-checks with Google that the credential opens the mailbox on the person's People entry, and refuses outright when that address is the Executive's own: a shared mailbox would make everything the Executive writes look like theirs. Drafts are threaded (`In-Reply-To`, `References` of whole ids ending with the parent, `threadId`) and stamped `X-OE-Ghostwritten`; the only send is `drafts.send` of an existing draft by id, when the person taps Send on its reply card (`delegation.reply_send`). A Gmail rate limit, even as a 403, is an error to retry rather than a reconnect. The voice learner and the thread shown to the ghostwriter keep only each sender's own words through `email_poller.sender_new_text`, the poller's quoted-reply stripper made public. Setup status shows it as **Your own mailbox (Act as me)**.\n\nThe same file can instead hold an Outlook sign-in (`\"provider\": \"microsoft\"`), minted by `scripts/connect-own-outlook.py --email <you>` with a device-code sign-in on the Executive's own Entra app (`MS365_MCP_CLIENT_ID`, `MS365_MCP_TENANT_ID`, default `common`) and the delegated scopes `User.Read`, `Mail.ReadWrite`, `Mail.Send` and `offline_access`. `delegation.gmail.gmail_for` then hands back `delegation.outlook.DelegateOutlook`, which talks to Microsoft Graph directly — never the Microsoft 365 MCP server the Executive's own Outlook uses — with the same methods and the same one send: Graph's `send` on an existing draft, with no body. Microsoft rotates the refresh token on use and the new one is written back into the file. A sender counts as verified only from the topmost `Authentication-Results`, the one Exchange wrote, and only mail in their Sent Items counts as theirs.",+ "markdown": "External channels connect callers to the Executive. Each inbound adapter resolves the sender to a Person — the chat adapters via `find_person_by_{slack,discord,telegram}_id`, the email poller via `people.identity.resolve_email_sender` (a primary address or an alias, then the company-domain rule; see Org) — and threads `person_id` into `Executive.chat()`. A sender who resolves to nobody is no longer simply dropped: see **New senders (roster requests)** below.\n\n### Inbound channels\n\n- **Slack** (`integrations.slack_bot`) — async Bolt app (`AsyncApp`) embedded in the lifespan, hearing Slack one of two ways: socket mode (`AsyncSocketModeHandler`, with `SLACK_APP_TOKEN`) or, with only `SLACK_SIGNING_SECRET`, the Events API over HTTP at `POST /webhook/slack` (`integrations.slack_events`), where the route checks each request's signature and age (and a 1 MB cap) before Bolt sees it, so unsigned traffic never reaches Bolt's logging; it then takes each signed request once, answering an identical replay (same signature) or Slack's re-signed retry of an `event_id` it already took with an empty 200 that never reaches Bolt (an in-memory, per-process set kept for twice the signature window and capped in size; keys are forgotten if Bolt fails, so a retry of a failed delivery still runs), and Bolt acknowledges at once while the listener runs. Either way a repeated event id is dropped (Slack resends what it thinks went unacknowledged), as is an event delivered for another workspace. 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. Replies (and every outbound Telegram message) go out as Telegram's HTML subset (`utils.markdown_telegram`: markdown-it-py with raw HTML and images off, text escaped), so the Executive's Markdown shows as formatting; links show as their text and target in plain text and never become tags, so quoted text can't hide where one goes; a chunk Telegram refuses is sent again as plain text.\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`) — MCP poll loop over the Executive's own mailbox — Gmail via `workspace-mcp` or Outlook via `ms-365-mcp-server`, chosen by `EMAIL_PROVIDER` (see *Workspace providers* below); it starts only once the MCP gateway is up, never surfaces Reply-To redirects, filters auto-replies. Its sessions carry `origin_channel=\"email\"`: the untrusted-content policy (`orchestrator.content_trust`) reads that tag to tell mail from the principal's own surfaces — left empty, as it once was, every stranger's body reached the decision extractor as the principal's words. The mail goes into the turn inside an `<untrusted_content source=\"email\" author=\"<sender>\" author_verified=\"no\">` block that says it carries none of the principal's authority, with the framing line and any `[POLICY]` notice outside it; mail from the principal's primary address that Gmail authenticated (`dmarc=pass`) is their own words — but only their new text goes in unwrapped: when the mail quotes or forwards another message (`_new_text_lines` cut something), the message as received follows in an `<untrusted_content source=\"email_quoted\">` block, since a stranger's text they replied to or passed on is not theirs. 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 from the rendered message with any trailing `--- REPLY ---` block dropped first, 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. The poller's `integration_inbound` row keeps the mail's text for the audit log, the way the reply's `chat_turn` row keeps the Executive's answer: `full.message` is the sender's new text (what web chat keeps for a turn), `full.attachments` the attachment filenames, and `details.preview` the first 120 characters of the new text, so /audit shows what was asked next to what was answered (the summary still reads `Inbound email from <sender>: <subject>`). The whole body with its quoted chain (`full.body`) is kept only on a row private to the principal: the chain is other people's mail — a contact's, on the principal's reply to one — and every signed-in user reads a public row. Each field is cut by its escaped JSON length (20,000 characters of text, 8,000 of attachment names), the measure the logger's 64 KB cap uses, so a long mail in a non-Latin script loses its tail rather than the row's structure. Outbound, the principal briefs and the client-rotation digest are emailed through the same gateway with the configured backend's send tool (`google_workspace__send_gmail_message` or `microsoft_365__send-mail`, via `workspace.registry.send_from_executive`, from the Executive's own mailbox to the principal's address, subject `<brief title> — <date>`, the date in the user's zone) as formatted HTML — rendered from the brief's Markdown with raw HTML and images off, so text quoted from outside shows as text and opening the email loads nothing remote. Email is first when the principal prefers it, and otherwise the backup after every chat channel, tried only when Slack, Discord and Telegram are missing or fail; an in-band error from the tool counts as a failed send and the next channel is tried. An emailed brief is not a DM, so the per-Person outbound guard below does not apply — the gateway's roster egress gate does.\n\n Two senders get their own framing. Mail from one of the principal's **contacts** (a `kind=\"contact\"` People row — see Org) replaces the non-roster `[POLICY]` notice with a contact one: it names them (name and role/company), says not to reply unless the principal asks and not to tell anyone else, and asks for a summary for the principal instead. Both this turn and the forwarded-by-principal turn below are marked `Session.private_to_principal`: they can email, DM or invite only the principal, an alert they raise is private to the principal, and they are not offered the tools that reach anyone else or start work outside the turn (`schedule_tools.PRIVATE_TURN_WITHHELD_TOOLS`: broadcasts, meeting bookings, workflows, follow-ups, watches, artifacts, goal updates, skill drafts, connecting a new MCP server), and of the MCP tools only Google Workspace reads and the gated Gmail send (see MCP below). Every audit row about such mail is private to the principal (see Audit Log), the poller's two `integration_inbound` rows included (`_private_to_principal_mail`), so the audit log's other readers see none of it. The poller holds `audit.private_rows` for the whole handling of such a mail, because some rows are written before the turn binds its private session: the knowledge retrieval quotes the mail's From line, subject and opening. The rows themselves read exactly like an outside sender's: the `integration_inbound` row is the non-roster one (`accepted_non_roster`), and the notice opens with the non-roster notice's exact sentence. The poller handles each message with no session bound, so one message's private turn never marks the next message's rows. The turn stays unattributed (`person_id` None — no peer memory, no co-presence), and the gateway refuses mail to a contact on a poller turn anyway. Mail **forwarded by the principal** — the sender resolves to the principal and `_new_text_lines` reports a forwarded message — is wrapped in a `<forwarded_by_principal>` block: summarise it, draft a reply the principal could send (as text in the reply, never sent or saved as a Gmail draft), note any commitment or date, and offer to add the original sender as a contact (confirmed from the web app or the principal's Slack / Discord, since an ordinary email turn cannot change the People list — the one email that can is the principal's tokened reply to a roster-request email, which is parsed before any model turn; see below). The reply still goes to the principal only. The From header is unauthenticated, so this framing grants nothing: a spoofed \"forward\" just gets the real principal a summary.\n\nSlack, Discord, and Telegram are roster-gated on inbound: an unrostered sender's message never reaches the Executive (`details.outcome=\"rejected_unknown_sender\"`). The gates look up **team members only** — a contact's Slack, Discord or Telegram id is treated as unknown, so a contact can never talk to the bot (nor count as a co-present peer). What happens next is the roster request below — except for a contact, a thread continuation, a Telegram group or an unverified Telegram webhook, which stay silent. 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). Slack only continues a thread it has replied in: it reads the thread with `conversations_replies` (5 s bound) and looks for its own user id, which `auth_test` resolves at startup. If that lookup fails, mentions and DMs still work and thread continuations stop until a retry succeeds (`slack_bot._resolve_bot_user_id`, at most once a minute, from the channel `message` listener). When Slack doesn't return the thread in time, the thread's stored history (`slack:thread:{channel}:{thread_ts}`, written on every turn the bot answers there) stands in: with history, a rostered sender gets an ephemeral \"I couldn't read this thread just now… @-mention me\" and the drop is audited (`outcome=dropped_thread_unreadable`). A thread the bot never answered in stays silent. A message the gate skips is audited (`outcome=skipped_gate`, with the gate's reason) and gets an :eyes: reaction (`reactions_add`, which needs the bot's `reactions:write` scope; without it the reaction is skipped), so a sender the gate misjudged can see the message was read and @-mention the bot.\n\n**No link previews on replies.** The Executive's replies go out with previews off — Telegram `sendMessage` carries `link_preview_options.is_disabled`, Slack's reply `say` passes `unfurl_links=False` / `unfurl_media=False`, and every Discord reply send passes `suppress_embeds=True`. The direct messages the Executive starts are the same: `send_slack_dm` posts with `unfurl_links=False` / `unfurl_media=False`, and Discord's `send_dm` sets the `SUPPRESS_EMBEDS` flag on each chunk, so a reminder or a brief sent by DM carries no preview either. Otherwise the chat service fetches a link in the text on its own, so a reply that quotes someone's mail (Act as me reads it) could carry data to a sender's server with no click. The web chat does the same for images: `Message.tsx` loads only an image the app itself serves (`lib/markdownImages.loadsInline`) and shows any other as a link.\n\n### Alert triage of chat messages\n\nEvery chat-app message that passes the roster gate (Telegram, Slack, Discord, Google Chat) is also handed to alert triage through `alerts.pipeline.schedule_chat_message_evaluation`. The sender is named by their People record (`full_name`), not by the name they typed into the chat app, so a person whose account there is called something else is never read as a stranger; the chat app's own name (or raw user id) is used only when nobody on the roster matched. The principal's own messages to their Executive are a conversation, not news for their brief, so they are not triaged at all. Triage sees the sender as `sender:` and the room as `channel:`.\n\n### New senders (roster requests)\n\nSomeone who writes in and is not on the People list — and is not one of the principal's contacts — is **held, acknowledged and asked about** instead of dropped (`integrations.roster_intake.intake` over the `people.roster_requests` ledger; lifecycle in Org). Each adapter calls it after its gate:\n\n- **Slack** — a DM or an `@mention` (not a thread continuation: the bot was not addressed there). The name and profile email come from `users_info` (5 s timeout). The acknowledgement goes in the DM, or as an **ephemeral** message for a mention, so nobody else in the channel learns who is and is not on the roster. The held event keeps only a fixed set of keys (text, user, channel, ts, thread, files).\n- **Discord** — a DM or a mention (not a thread the bot merely follows). The acknowledgement goes in the DM, or by DM for a channel mention; `/ask` answers the interaction with an ephemeral acknowledgement first (Discord allows 3 s), then holds the prompt. Its old \"ask the admin to add you\" reply is gone.\n- **Telegram** — only a **private** chat, and only when `TELEGRAM_WEBHOOK_SECRET` is set and valid: Telegram identifies the chat rather than the sender, and without the secret anyone could forge an update. A group, or an unverified webhook, stays silent as before. Attachment file ids are held and downloaded only on replay.\n- **Email** — non-roster mail that is not private to the principal (so never a contact's) and does not look machine-sent (`looks_automated`: a no-reply / notifications / billing-style local part, a `List-Id` / `List-Unsubscribe` / `Auto-Submitted` / bulk `Precedence` header, or a DMARC failure). The mail is **still triaged** by the Executive on this pass; its `[POLICY]` notice now says the sender was already told their message is waiting and the principal was asked who they are, so the model raises no second alert just to add them, and that the email will come back once they are added.\n\nEvery path skips a contact first (`find_person_by_*_id(..., include_contacts=True)`, or the email poller's private-mail rule): a contact has no chat access and gets no request and no acknowledgement, and the team-visible `rejected_unknown_sender` / `accepted_non_roster` rows read the same for a contact as for a stranger.\n\n**The acknowledgement** is one fixed text (`roster_intake.ACK_TEXT` — \"your message arrived … waiting for confirmation\"), never the model and never an echo of what they wrote, so a forged sender gains nothing by triggering it. It is sent at most once per sender per `ROSTER_ACK_WINDOW_DAYS` (7) and at most `ROSTER_ACK_DAILY_CAP` (20) a day across all senders (`claim_ack`, one transaction; a failed send releases its claim). An email acknowledgement is the one send the MCP gateway lets reach an address off the roster: `send_email_ack` sets `mcp_gateway.roster_ack_grant`, a one-shot ContextVar grant that admits a single `send_gmail_message` with exactly the granted recipient (a plain string, no list), subject and body and no other key, then is spent (audited `integration_outbound`, `kind: roster_ack`, private). An email sender is acknowledged only when Gmail authenticated them: once `claim_ack` succeeds, the poller's `send_ack` re-reads the mail as raw MIME and needs Gmail's own topmost `Authentication-Results` reporting `dmarc=pass` for the From domain (`fact_confirmation.sender_authenticated`, fail-closed). The printed headers the poller reads never carry that header, so without the second read a forged From would draw the acknowledgement to whoever it names — backscatter from the Executive's mailbox. An unauthenticated sender makes `send_ack` raise `roster_intake.AckWithheld`: the claim is released, and they are held silently. `authenticated_by_gmail` strips quoted strings and comments before reading the verdict — Gmail copies the envelope sender and DKIM tags into its own stamp, and a quoted local part could otherwise carry a fake `dmarc=pass` — and needs exactly one `dmarc=` verdict reading exactly `dmarc=pass header.from=<domain>` (Gmail may follow it with its own `dara=` resinfo, so its position is not checked). Residual: when Gmail writes no verdict at all (a From domain without DMARC) and echoes an unsanitised `;dmarc=pass header.from=…` elsewhere in its stamp, that echo would read as the verdict; bounded by the acknowledgement caps. A withheld acknowledgement is audited `roster_ack_withheld`. `intake` acknowledges before surfacing the card and telling the principal, and both follow the request's `ack_sent_at`: a withheld, failed or capped acknowledgement reads \"haven't been told anything yet\" on the Today card, in the principal's prompt and in the email `[POLICY]` notice.\n\n**Telling the principal.** A new request puts a private card on the principal's `/today` (see Today) and pushes a prompt on their delivery plan — preferred chat DM, then the others, then email — for a chat sender or an email sender on the company's own domain; an outside email sender waits on the card, as does everything past `ROSTER_REQUEST_DAILY_CAP` (30) pushes a day (the same cap bounds how many requests open a day; a declined sender is not raised again for 30 days). A chat prompt can be answered in place (\"that's Annamarie, add her to the team\"). An email prompt carries a one-time token (`RR-` + 20 base32 characters, stored hashed); the poller checks every inbound mail for one **before** triage (`try_email_roster_answer`): the reply must come from the principal's primary address exactly (not an alias, not the company-domain rule), carry the token of a pending request, not be an automatic reply, and not fail DMARC where the header is visible; and is parsed by `parse_decision`'s `roster_identity` shape — anything else falls through to the ordinary path. The token is hidden (`RR-[hidden]`) in every other Google Workspace result the gateway returns — the confirmation sits in the Executive's Sent folder, and any turn could otherwise read it — except the poller's own fetch of an inbound message (`mcp_gateway.reveal_roster_tokens`); a token-bearing mail that is not an answer is scrubbed before triage.\n\n**Replay.** Once the principal answers (web card, chat tool, email reply) — or a People-page / `upsert_person` write makes the sender match someone (`after_roster_write`) — the held messages are replayed through the adapter that received them (`register_replayer`: Slack re-runs the held event, Discord and Telegram their held text, email re-fetches the message from Gmail and handles it as mail from a known sender), oldest first, now attributed to the new Person. A teammate gets every held message; a new contact only held email (it takes the private contact path; held chat is dropped); a decline drops everything. Replays run in a **fresh `contextvars.Context`**: the answer may have come from the principal's own verified turn, and a stranger's message must never be read with the principal's session — and their contacts — still bound.\n\n### Standing facts by email (confirm by reply)\n\nThe principal can ask for a standing fact, a retirement or a company-profile edit by email, and the fact tools check it exactly as in chat (the own-words gates run on `_email_memory_text`, the sender's new text, not the quoted chain or attachments). An email's From line proves nothing, though, and a standing fact is read by every later prompt as the principal's own account. So an emailed change is **held, never applied**, until the principal's own mailbox confirms it (`integrations.fact_confirmation`, `memory.facts.fact_confirmations`):\n\n- **Who may ask.** The poller stamps every email turn with `Session.email_from` (the bare lowercased From address) and `email_authenticated`. The text the poller reads never carries `Authentication-Results` (workspace-mcp prints a fixed set of headers), so for mail claiming the principal's primary address it reads the message again as raw MIME (`fact_confirmation.sender_authenticated`) and requires Gmail's own stamp: the **topmost** `Authentication-Results` header (Gmail adds it on receipt, above anything the sender wrote), authserv-id `mx.google.com`, reporting `dmarc=pass` for the From address's domain, with the raw From matching (`authenticated_by_gmail`). It fails closed: no header, `dmarc=none`, a temporary error or a failed read all leave the turn unauthenticated. Mail from a teammate other than the principal is read the same way, before its inbound audit row is written: authenticated, the whole handling of it is theirs alone in the audit log (`rows_for_person`, see Audit) and the turn reads their own mail as them (`Session.email_sender_authenticated`); unauthenticated, it keeps the ordinary rule. Mail from anyone else costs no second read and is never authenticated. `fact_tools._gate` admits an email turn only from the principal's **primary** address, exactly (no alias, no company-domain rule), authenticated, and not private to the principal (mail they forwarded stays refused, as do contacts, teammates and unknown senders).\n- **The hold.** The tool returns `awaiting_confirmation` (no action chip, and the model is told to say nothing has changed). `request_confirmation` stores the change with the SHA-256 of a fresh one-time token (`FC-` + 20 base32 characters, 100 bits; 7-day expiry; at most 10 waiting at once) and emails the token to the principal's roster address, outside any turn's outbound context. A profile edit is dry-run first, so one that cannot apply is reported in the turn, before any email goes out. If the email fails, nothing is held.\n- **Keeping the token from any model.** The tool result never carries it, and `mcp_gateway.hide_roster_tokens` now scrubs `FC-` tokens as well as `RR-` ones (`FC-[hidden]`) from every Google Workspace result except the poller's own fetch of an inbound message. Act as me's reads of the principal's own Gmail, where the confirmation email lands, hide them too (`delegation.gmail.parse_message` and the thread search), so the drafting model never sees a live token either.\n- **The reply.** `_handle_one_email` hands every message to `try_email_fact_confirmation` right after the roster-answer check, before any model turn. It acts only on a reply from the principal's primary address carrying the token of a **pending** confirmation. A made-up, spent, cancelled or expired reference matches nothing and falls through to the ordinary path with the token hidden, so no old or forged token can make the Executive email the principal. A reply with a live token is read again as raw MIME (`read_raw`) and must pass the same Gmail DMARC check as the request; one that doesn't (or whose raw read fails) is refused, the change keeps waiting, and the principal is told. Then an **automatic reply** is consumed quietly — no answer, no model turn, the change keeps waiting: the printed headers catch a Gmail vacation reply (`Precedence: bulk`), and the raw headers catch what they don't show (`automatic_reply`: `Auto-Submitted` other than `no`, `X-Auto-Response-Suppress` and similar, `Precedence: auto_reply`, an out-of-office subject), since an Exchange out-of-office echoes the token from the principal's own address and may well say \"I'll confirm on my return\". The raw message starts at the tool's exact separator line (`\\n\\n--- RAW MIME ---\\n`), so a sender-written Subject imitating it cannot supply the headers. CONFIRM (or yes / approve) applies the change through `fact_tools.apply_confirmed`, the same apply step chat uses. CANCEL (or no) drops it, and an unclear reply leaves it waiting. The principal gets a one-line result either way. A compare-and-set on the row means two replies can apply it only once.\n- **Audit.** Private `fact_confirmation` rows record held / applied / cancelled / refused. The applied change also writes the fact tools' usual private rows, with `source_channel=\"email\"` as its provenance.\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. A listening Slack is amber while the listener hasn't resolved its own user id (`slack_bot.bot_user_id()`), since thread continuations are off until it does. 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. Gmail is also amber when startup priming could not find every pinned Google tool (`MCPGateway.prime_pinned_tools`, whose result the gateway keeps on `pinned_tools`): the row names a few of the missing tools and counts the rest, and points at the `MCPGateway` log lines. It is amber too while that probe has not finished, and when the probe itself failed — the one check that reads green is the one that ran and found everything, so a crashed probe is never silently fine. The row speaks for the whole `google_workspace` server, so a missing Docs or Drive tool shows up under Email (Gmail).\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\n**Conversations within a chat app.** A Telegram chat, a Slack or Discord DM and a person's @mentions in one channel (`slack:channel:…`, `discord:channel:…`) are each one endless stream, so they are cut into conversations (`memory.conversations`, shared helpers in `integrations/conversations.py`). Each adapter computes the stream's base id as before and asks `conversation_for` which conversation a message belongs to: the newest, unless the stream has been quiet for two hours (`CONVERSATION_GAP`), when the next one starts. The first conversation keeps the bare base id; later ones add `~2`, `~3`, … (`memory.conversation_ids`). A whole message of `/new`, \"new chat\" or \"new conversation\" starts a fresh one instead of a turn and is answered with the name of the one it ended; the new row has no messages and stays off the Chats page until its first turn. After a conversation's first exchange `title_after_turn` names it in the background with `utils.session_title.generate_session_title` (the first words of the message if that fails), as a web chat's first turn does. Threads (`slack:thread:…`, `discord:thread:…`), email and every other id are left whole. What has to see the whole stream compares base ids: the inbound resolver, so an approval asked before a cut is answered after it, and the session-scoped decisions and advice `format_for_prompt` renders. At boot `split_existing_streams` cuts history saved before this by the same rule, once (`app_migrations`), titling each part from its first message and carrying a read-mail lock to every part. An adapter installed outside the package adds its streams with `conversation_ids.register_rolling` and cuts its own old history once, with its own migration name and an `only` filter for its base ids, because the built-in sweep may already have run without it.\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, Telegram, Slack and Google Chat. Images become Anthropic vision blocks; documents (PDF/DOCX/TXT/MD/CSV) are inlined into the turn that carried them — inside an `<untrusted_content source=\"attachment\" author=\"<name>\">` block (`content_trust.wrap_untrusted`, whose closing tag the text cannot forge), under an `[Attached: <name>]` label, which the open-loop pass reads as \"not the speaker's words\" and the decision extractor strips before it reads the turn — and indexed into the ChromaDB `inbound_attachments` collection. 20 MB/file cap; web chat uses `POST /chat/upload`.\n\n**Scanned PDFs** are read, not reported empty. A PDF with no text layer goes through `knowledge.pdf_reader`: with `PDF_PROVIDER_READING=true` (opt-in, off by default) the deployment's own model reads it through its provider's PDF support (Anthropic natively, OpenRouter's `file-parser`, a local server only with `LOCAL_PDF_INPUT`); otherwise, and as the fallback, local OCR (pypdfium2 + RapidOCR, offline, no key) — so every deployment converts them. The label then reads `(converted from scanned pages)`, and an unreadable one says why. The index takes the text already extracted for the turn, so a scan is converted once. A file a channel delivered (everything here except `POST /chat/upload`, where the signed-in user sends it) converts at most `PDF_INBOUND_MAX_PAGES` (30) pages and draws on a rolling `PDF_INBOUND_PAGES_PER_HOUR` (300) budget shared by all senders, so sending scans cannot run up unbounded model spend or CPU.\n\nPer channel:\n- **Slack** — a `file_share` message (previously dropped outright for its `subtype`) is handled like any message; files download only after the roster gate and the response gate, with the bot token sent only to `https://files.slack.com/` (needs the `files:read` scope). History and peer memory record the words plus `(Attached files: …)`, never a document's text.\n- **Google Chat** — uploaded attachments download through `media.download` with the reply credentials (`chat.bot`), checked against the 20 MB cap per chunk, 5 per message; an attachment-only message is no longer dropped. The webhook authenticates Google, not the sender, so files are read only when the event's `user.email` is on the People roster (a team member); anyone else's files are named to the Executive, never downloaded. A Drive file shared into a message is left to the Drive tools, with its id.\n- **Email** — the poller (`integrations.email_attachments`) downloads up to 5 readable attachments of the message itself via `get_gmail_attachment_content` — workspace-mcp in stdio mode saves the file and answers `Saved to: <path>`, which must start its line, be the last such line and end in the answer's `Saved filename:` (the answer echoes the sender-chosen attachment name first, and a name carrying `Saved to: /…` must not redirect the read), then resolve inside the tool download folders — and appends their text to the turn (15k chars each). Only for a sender the principal knows (team, contact, principal); a stranger's files stay a list. It runs outside the model loop, so it works on private turns without adding the attachment tool to `PRIVATE_TURN_MCP_TOOLS`.\n- Anything else (a Drive PDF, a skipped attachment) — the Executive's `read_document` tool.\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, Outlook mail and calendar — whatever `mcp_servers.json` configures) as Executive tools, with egress gating on Gmail recipients, Calendar attendees, Drive share grantees, and Microsoft 365 recipients/attendees against the roster (and a refusal of public / whole-domain Drive sharing). The Gmail gate also accepts only a fixed set of argument keys, so workspace-mcp's `reply_all` (recipients taken from the thread, never checked) and `forward_message_id` / `include_forwarded_attachments` (forwarding any inbox message) are refused; a reply is `thread_id` plus an explicit, roster-checked `to`. Three more refusals close paths around those gates: every Apps Script tool (code running as the Executive's account, outside the gates, and since workspace-mcp 1.29.0 schedulable to keep running); any argument that makes the server fetch a URL (`fileUrl` / `file_url` on the Drive and import tools, a Gmail attachment given as a `url`), since the fetch can carry data out in its query string before any recipient gate matters; and text Google would mail to someone the roster never checked (`rsvp_comment` to an event's organizer, an out-of-office `decline_message` to whoever invites the Executive). Every gate reads its arguments by normalized spelling: workspace-mcp 1.29.0 renames a camelCase key such as `Attendees`, `userGoogleEmail` or `rsvpComment` to the real parameter, so a gate matching the exact key would never see it. Arguments that are not a JSON object are refused for the same reason. Google-side fetches are refused too: any key ending in `url` / `uri` at any depth whose value has a URL scheme (a Slides image or page background, a Docs or Forms image; a document hyperlink and a meeting link are stored, not fetched, and pass, as does a Drive file id), (a value is a URL after the characters a URL parser strips are removed, and `//host` counts), and on every tool that can write cells — the Sheets tools and the Drive create / update / import tools, which turn CSV into a Sheet — any string anywhere holding a formula call that fetches (`IMPORTDATA`, `IMPORTXML`, `IMPORTHTML`, `IMPORTFEED`, `IMAGE`), JSON-encoded or mid-CSV included: a string argument that encodes JSON is read as the server decodes it (one too large to read is refused), text is also scanned with character references decoded and comments / CDATA removed, and an upload that would become a native Sheet may only be text `content` — a `base64_content` or server-side `file_path` upload there is refused, since an XLSX hides its formulas behind zip members and XML encodings; a PNG to Drive or a DOCX to Docs is untouched. Not covered, unverified: whether Drive's HTML / Markdown import fetches an `<img src>` when it converts `content` into a Doc. A `manage_event` call that names no attendees is sent with `send_updates=\"none\"`, so the event's existing guests are not emailed text the gate never checked. The allow-list (`_egress_sets`, built by `_roster_allow_set` as a `people.identity.RosterAllow`) is every team member's email and email aliases plus the Executive's own address, always, and — for a teammate — any address on one of the company's own domains whose local part (`+tag` dropped) matches theirs, the same rule inbound mail is matched by; a **contact's** email joins it only when `people_tools.contacts_reachable_now()` is true — a turn the principal started on a verified surface (web chat, their own Slack or Discord, a verified private Telegram chat), or inside `grant_contact_egress()` (the decisions approve route, when the approver is the principal). On any other turn — an inbound email, a teammate, the scheduler, a workflow, the alert review — a contact's address is refused exactly like a stranger's, so the refusal cannot reveal that it belongs to a contact (contacts are private to the principal). The single exception to the roster rule is the fixed roster-request acknowledgement above, under its one-shot `roster_ack_grant`. A turn about the principal's private mail (`Session.private_to_principal`) narrows the list to the principal's own address and the Executive's. Such a turn may call only the MCP tools in `schedule_tools.PRIVATE_TURN_MCP_TOOLS`: Google Workspace reads (`search_gmail_messages`, `get_gmail_message_content`, `get_events`, `list_calendars`, `query_freebusy`, and the Drive, Docs and Sheets reads such as `search_drive_files`, `get_drive_file_content`, `get_doc_content` and `read_sheet_values`) and the two Gmail tools this gate narrows to the principal (`send_gmail_message`, `draft_gmail_message`). It is an exact allow-list, not a server: workspace-mcp runs at the tier `WORKSPACE_MCP_TOOL_TIER` names, `complete` by default, where a Google Chat message to a space, a Docs, Sheets or Drive write into a file already shared with others, `manage_event` on a shared calendar (its gate checks attendees and pins notifications, nothing else) reaches people with no recipient check; and every other server has none at all (a Slack or Notion server, the default `fetch` server, whose URL can carry the turn's content, a server loaded at runtime). Its `search_tools` results show only the allowed tools (`workflows.tool_catalog.filter_search_results`; output it cannot parse reads as no match), and a `call_tool` naming anything else is refused with an error tool_result and an audit row private to the principal (`schedule_tools.private_turn_withholds`), a missing name included. `search_tools` and `call_tool` stay offered, so the tool list and its cached prefix do not change. The typed calendar tool (`_resolve_attendees`) and the chat DM tools (`message_person`, `send_telegram_message`, `send_discord_dm` and their person-id recovery) apply the same rule — a contact's id reads as an unknown one off the principal's turn — and a private turn may DM or invite only the principal (`PRIVATE_TURN_REFUSAL` otherwise); `message_person` never falls back to a \"Needs you\" alert for a contact, who cannot sign in to see it. 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 optional `WORKSPACE_MCP_TOOLS` (comma-separated service names, default `all`) limits which Google services it loads. The gateway forwards the Google secrets to the child via `_FORWARDED_ENV_VARS`. Every `google_workspace__*` call acts as the Executive's own account. workspace-mcp takes the acting account per call (`user_google_email`) and nothing used to check it, so under domain-wide delegation a model-chosen address could open anyone's mailbox in the domain; `mcp_gateway._check_acting_account` now refuses a value naming any other address — before every other gate, with an `integration_outbound_blocked` audit row. An absent value stays allowed (the server's own account).\n\n**What the model is told is connected.** `MCPGateway.start()` records the configured server names (`server_names`), and the Executive renders them with the channel settings into block 0's *Connected Systems* section (`prompts.connected_systems`; see the caching section). While Google is connected that section pins the Google tool names the Executive uses constantly (`GOOGLE_TOOL_MANIFEST`, narrowed by `connected_systems.google_tool_manifest` to the services and tier actually loaded) and tells it to call them with `call_tool` directly, with no `search_tools` round trip. The narrowing is the point: a name pinned for a service workspace-mcp never imported is not in the index, so the model calls it, receives extensible-mcp's “has not been discovered via search_tools” refusal, and has no way to square that with its own instructions. extensible-mcp only runs a tool one of the session's searches has returned, and remembers it for the session's life, so the gateway does that discovery itself: the lifespan starts `MCPGateway.prime_pinned_tools()` in the background once the gateway is up with `google_workspace` configured (an exact-name search per pinned tool, the way `workflows.tool_catalog.resolve` does it, over the same narrowed set the prompt advertises — `connected_systems.pinned_google_tools`, so priming never probes a service that was not loaded). A name neither the prompt nor priming can account for is logged once, naming both causes: excluded by `WORKSPACE_MCP_TOOLS` / `WORKSPACE_MCP_TOOL_TIER`, or renamed by workspace-mcp since the pin. A pinned call that still comes back with extensible-mcp's \"has not been discovered via search_tools\" refusal, for example before priming finished, is discovered and retried once. That happens after every gate has passed the same arguments, and only for pinned names: any other tool still needs the model's own search, and nothing here widens what a call may do, including the private-turn allow-list.\n\n**Microsoft 365** is the Outlook twin: `@softeria/ms-365-mcp-server` (a Node package, pinned) is installed in a throwaway Node build stage and only the `node` binary plus the package are copied into the API image, launched by `docker/ms365-mcp-launch.sh` as the `microsoft_365` entry with an **explicit tool allow-list** (`--enabled-tools`, an anchored regex) rather than the upstream `mail,calendar` preset — that preset also registers inbox forwarding rules, mailbox settings (external auto-reply), calendar sharing and event forwarding, which can address people the gateway never sees. Exactly the Outlook mail + calendar tools and the OneDrive tools are exposed (`microsoft_365__send-mail`, `microsoft_365__create-calendar-event`, `microsoft_365__search-onedrive-files`, …; hyphenated Graph endpoint aliases, proxied verbatim), and every admitted tool is either roster-gated or carries no recipient; the gate also covers the excluded writers in case an operator widens the list. Both servers can be configured at once. Auth is the MSAL device-code flow against the operator's own Entra app registration (`MS365_MCP_CLIENT_ID` is required; the server's built-in public client is refused); the refresh token persists at `/data/ms365_credentials` and is seeded once with `ms365-mcp-launch.sh --login` from inside the container — the server has a native device-code CLI, so there is no mint script and nothing to copy. The launcher scrubs the literal `$VAR` placeholders extensible-mcp leaves for unset variables (otherwise MSAL would be handed `$MS365_MCP_TENANT_ID` as an authority), and `MS365_MCP_EXPECTED_USERNAME` pins the bound mailbox. The egress gate for this family walks Graph's nested shapes (`body.Message.toRecipients[].emailAddress.address`, `body.attendees[]…`) — every email-shaped string outside the free-text fields must be on the roster, control characters and non-ASCII addresses are refused, unforeseen keys are still scanned (fail-closed) — and covers the whole write surface: send, reply, reply-all, forward, every draft tool, `update-mail-message` (it can PATCH recipients onto a draft) and create-/update-calendar-event; reads and `delete-calendar-event` (the only cancel path) pass through. Graph's reply, reply-all and send-draft actions carry no recipient in their arguments (the recipient is whoever the referenced `messageId` names), so for those the gate first reads the referenced message through the server and roster-checks the recipients Graph will derive (`replyTo` else `from` for a reply; `replyTo` and `from` together, plus the original to/cc, for reply-all; the draft's own to/cc/bcc for send-draft), refusing on any lookup failure; RSVP and cancel actions get the same treatment through an event lookup, because their comment is emailed to the organizer or every attendee; `download-bytes` is pinned to mail attachment bytes and OneDrive file content (`/drives/{id}/items/{id}/content`, optionally Graph's `?format=pdf` rendering), and a OneDrive result comes back as the file's extracted text rather than base64 — the attachment pin is what makes the poller's promise that an unrostered sender cannot be auto-replied to hold on Outlook as it does on Gmail; and the rendered inbound text quotes any forged `--- REPLY ---` line inside a body so the persona only ever reads the real block. Every mail write's `from`, `sender` and `replyTo` may name only the Executive's own address (the Outlook twin of the Gmail acting-account pin), so the model cannot send as a rostered colleague's mailbox or steer replies elsewhere; and `move-mail-message` into Deleted Items, Junk Email or Recoverable Items is refused, so a move cannot trash mail ungated. The server registers its account tools whatever its tool allow-list says, so the gateway itself refuses `login`, `logout`, `select-account` and `remove-account` (audited like any other refusal) and drops them from `search_tools` results — a chat turn cannot sign the mailbox out, switch accounts or start a sign-in; setup is only the launcher's `--login`, and the read-only `verify-login` / `list-accounts` stay callable. The example config's hyphenated patterns still deny `delete-mail-*`, `logout`, `remove-account` and `download-bytes-to-file` as defense in depth. A successful `send-mail` records the same outbound-context linkage Gmail does.\n\n**OneDrive in chat** (opt-in with `MS365_MCP_ONEDRIVE=true` and a fresh `--login`, since the server asks for its tools' permissions on every token refresh and a sign-in without file consent would otherwise fail mail and calendar too) matches what the Executive can do on Google Drive: search, list a folder, read a file, upload and edit, create folders, move, rename, copy and share; there is no delete tool. The launcher adds `Files.Read.All` at sign-in (`--extra-scopes`), so folders shared *with* the Executive can be read too; writes (upload, new folder, move, copy) land only in the Executive's own drives, checked against `list-drives` at call time, so a planted instruction cannot save company files into a stranger's shared folder. Sharing is gated like Drive sharing: `share-drive-item` invitees must be People on the roster and named by email (an `objectId` or `alias` grantee is refused, since nothing can check it), no `owner` role, and `create-drive-item-share-link` must be scoped to specific people (`scope: \"users\"`): an anonymous or whole-organization link, or one with no scope (the tenant default), is refused. An invite must require sign-in and grant only view or edit, a link must be a view or edit link, and `search-onedrive-files` takes plain words only, since its query goes into the request path unencoded.\n\nAs 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. The same expansion serves the Microsoft 365 mail writes: the entry becomes a Graph `#microsoft.graph.fileAttachment` (`name`, `contentType`, `contentBytes`) placed where Graph expects it for that tool (`body.Message.attachments` for `send-mail`, reply, forward and the createReply drafts; `body.attachments` for `create-draft-email`), whether the model put it at the top level or inside the message; an entry anywhere else, one on `update-mail-message` or `send-draft-message` (their requests cannot carry attachments), or one behind a body that is not an object is refused rather than forwarded unexpanded.\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`. All three per-Person DMs refuse a recipient id that matches no non-archived Person row (`schedule_tools._dm_recipient_on_roster`), which is what stops untrusted content in a turn — inbound mail, a chat message, a knowledge document — from directing a DM at an arbitrary workspace member. `send_slack_dm` previously consulted the roster only when the turn was already private to the principal, so on an ordinary turn it applied no roster check at all while its Discord and Telegram siblings did; the room-targeted tools are deliberately ungated, since those channels are team-visible. 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. Once the guard allows a send, the handlers apply the recipient's own notification settings to the Executive's own (tagged) outreach: in their quiet hours, or when they chose *In my briefs*, the DM is stored and returned as `{\"status\":\"held\"}` rather than sent, and goes when quiet hours end or with their next brief (`outbound_guard.check_hold`; see Org).\n\n### AI disclosure\n\nWhat the Executive sends says it is an AI assistant (`orchestrator.disclosure`), added by plain code so a reply the model writes can't leave it out. **Mail** from its own mailbox gets a line under the body, by default \"<EXEC_DISPLAY_NAME> is an AI assistant working for <company>. To reach a person, reply and ask, or write to <principal's address>.\": the MCP gateway adds it to every Gmail send and draft and every Outlook send, reply, forward and draft (`mcp_gateway._with_disclosure`) **after** every outbound gate has passed and only on what goes to the server, so the gates, the outbound-context record and the audit see the model's own words, and `send_from_executive` gets it the same way. It counts as already there only when it is the last line that shows (in a quoted earlier message or hidden in markup it doesn't), and a send of an existing draft and mail whose every recipient is the principal go as they are. HTML that could hide what follows (an unclosed comment, a style or script block, text styled out of sight: `disclosure.hides_what_follows`) is refused, so the line can't be hidden after it; the model is told to send plain text. The roster acknowledgement to a new sender, the one send to an address nobody checked, gets `BARE_MAIL_LINE` (\"This message was sent by an AI assistant.\"), which names no one, like the acknowledgement itself. **Chat** gets a shorter line (\"<name> · AI assistant\", in italics) on the Executive's replies in Slack, Telegram, Discord and Google Chat and on its own DMs and room posts (`send_slack_dm`, `send_discord_dm`, `send_telegram_message`, `broadcast_tools._dispatch`), but only on the first message in a conversation and again after 24 hours without one (`with_chat_line`, kept in memory, so a restart shows it once more); session history keeps the reply without it. `AI_DISCLOSURE` (default on) turns it off; `AI_DISCLOSURE_MAIL_TEXT` / `AI_DISCLOSURE_CHAT_TEXT` reword the lines, and a wording that doesn't say \"AI\" is ignored for the built-in one. It fails open: a line that can't be built is left off, never a send refused. Replies sent *as a person* under Act as me are the delegation section's (**AI line on replies**).\n\n### Calendar & video links\n\nThe Executive books meetings through two typed tools over the configured calendar backend (`CALENDAR_PROVIDER`: Google Calendar via `manage_event`, or Outlook via `create-calendar-event` — see *Workspace providers*). `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. Because nothing approves it, an instant meeting, and `cancel_calendar_event` too, runs only when someone on the team asked on a surface that verified who they are (the principal, or a rostered teammate in the app or their own chat); a turn an inbound email started gets a refusal to pass on instead, and a team-mode `create_calendar_event` the operations department would auto-execute is proposed instead. Both attach a video-meeting link by default (`add_video_link`; opt out for in-person) — a **Google Meet** link parsed from the created event's `conferenceData`, or a **Microsoft Teams** link from `onlineMeeting.joinUrl` — surfaced to the caller plus persisted on the decision ledger as `meet_link`. The tool descriptions are static, backend-neutral text, so the cached tool block never depends on settings; the pre-rename `add_google_meet` key is still honoured for old ledger rows. 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### Workspace providers\n\nThe Executive can *discover* any mail or calendar tool the gateway exposes, but three code paths call a fixed backend with no model in the loop and used to spell Gmail tool names inline: the inbound mailbox poller (list unread → fetch → mark read), alert email dispatch plus the scheduler's email send-tool hint, and the typed booking tools plus the approval-time conflict check. `integrations.workspace` puts those behind two Protocols (`MailProvider`, `CalendarProvider`) with one module per backend (`google.py`, `microsoft.py`) and a registry keyed on `EMAIL_PROVIDER` / `CALENDAR_PROVIDER` — separate switches (Outlook mail with a Google calendar is legitimate), both defaulting to `google`, so an existing install changes nothing until an operator opts in. The Google backend is the old inline code moved verbatim; tests pin its argument dicts byte-for-byte. The Microsoft backend polls only the Inbox folder (`list-mail-folder-messages` with `isRead eq false`, never the all-folders listing that includes Junk), converts Graph's HTML bodies to text with a real parser, lists a message's attachments so the names appear in the same `N. name (mime, size KB)` shape Gmail's text uses (and reach peer memory), marks read with `update-mail-message`, sends through `send-mail`'s nested shape, books with `isOnlineMeeting` + `onlineMeetingProvider=teamsForBusiness`, cancels with `delete-calendar-event`, and answers the advisory conflict check from the Executive's **own** calendar view (delegated permissions cannot read attendees' free/busy — narrower than Google's `query_freebusy`).\n\nEvery backend renders an inbound message into the same `Subject:` / `From:` / `To:` / `Cc:` + `--- BODY ---` text the persona already expects, and the poller adds a `--- REPLY ---` block naming the exact reply tool and threading ids for *that* message (Gmail: `send_gmail_message` + `thread_id`; Outlook: `reply-mail-message` + `messageId`) after the mail's `<untrusted_content>` block, never inside it. The block rides in the user turn — which is what lets the cached persona say \"use the reply tool in the REPLY block\" instead of naming a vendor tool — and the scheduler's proactive-email trigger names the backend's send tool the same way. Providers never raise on a malformed backend response (they return empty / `None` / `{\"error\": …}`), so one bad cycle never kills a loop, and a chosen backend whose MCP server is missing from `mcp_servers.json` is logged at startup and skipped by the poller: fail-soft, never a boot failure. The poller's newer checks run on that rendered text for both backends (contacts and private turns, roster requests and their emailed answers, the audit row), with three Outlook differences that fail closed: no sender is ever authenticated (the `dmarc=pass` read is Gmail's), so there is no acknowledgement to an unknown sender, no emailed fact confirmation and no principal-authenticated mail; attachments stay a list (the download is Gmail's); and the brief's calendar block is skipped (its listing is Google Calendar's). The code's own emails to the principal (roster prompts, fact confirmations, scheduled deliveries) go through `workspace.registry.send_from_executive`, and `runner.email_ready` follows `EMAIL_PROVIDER`. A private turn's allow-list (`schedule_tools.PRIVATE_TURN_MCP_TOOLS`) and Act as me's mail-touched reads include the Outlook twins of the Gmail and Calendar tools, and roster answer tokens are hidden from Microsoft 365 results as from Google's.\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 and the recipient is not one of the principal's contacts (a contact cannot DM the bot, and quoting the principal's conversation into their email reply's unattended turn would put it in the audit log) — 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` or `microsoft_365__send-mail`, 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.\n\n### OneDrive folder sync\n\nThe Microsoft twin of the Drive folder sync below (`knowledge.onedrive_sync`, `ONEDRIVE_SYNC_ENABLED`; setup in `docs/onedrive_sync_setup.md`). It copies the files in `ONEDRIVE_SYNC_FOLDERS` (`<drive id>/<item id>` pairs; `openexecutive onedrive-folder <link>` resolves a sharing link) into the isolated `onedrive_docs` collection on its own heartbeat, and shows them on the knowledge page as \"OneDrive\" rows with a **Sync now** button. Microsoft has no service account that sees only what is shared with it (app-only Graph access covers the whole tenant), so it reads as the Executive's own Microsoft 365 sign-in, and the folder list is the scope. It never stores a credential: each tick asks the launcher for a token (`ms365-mcp-launch.sh --access-token`, which runs `docker/ms365-access-token.mjs` through the server's own token cache and will only mint file-read tokens), keeps it in memory, and sends it only to Graph. `knowledge.onedrive_client` issues GETs only, follows a paging link only back to Graph, and fetches a file's pre-authenticated download link without the token; errors never carry that link. PowerPoint and older Office formats are read through Graph's PDF rendering.\n\n### Google Drive folder sync\n\nThe synced files show on the knowledge page's Company documents list as \"Google Drive\" rows (sync time, last edit in Drive, an Open in Drive link and a text view), and the page's source card shows the last run, any sign-in error or count of files that failed to sync, and a **Sync now** button that runs one tick on demand.\n\n\nSeparate from the Drive tools the gateway proxies. The optional folder sync (`knowledge.drive_sync`, `DRIVE_SYNC_ENABLED`; setup in `docs/drive_sync_setup.md`) copies the files in `DRIVE_SYNC_FOLDER_IDS` into the isolated `drive_docs` knowledge collection on a scheduler heartbeat, so the Executive knows those folders without searching Drive live (see RAG). It calls the Drive v3 API directly (`knowledge.drive_client`, `httpx`) as a **service account** with the `drive.readonly` scope (`DRIVE_SYNC_SERVICE_ACCOUNT_FILE`), not as the Executive's own account through workspace-mcp. Google enforces the folder scope, because the account sees only what is shared with it, and the sync can change nothing. Structured JSON means no display text to parse, and every file or folder id is checked against `[A-Za-z0-9_-]{1,128}` before it goes into a URL or a query. The two paths meet in two places. A synced chunk carries its Drive file id and sync time, so the Executive can open the live file with its own `get_drive_file_content`. The setup doc says to share each synced folder with the Executive's account too, so that live open works.\n\n### Confluence space sync\n\nThe optional Confluence sync (`knowledge.confluence_sync`, `CONFLUENCE_SYNC_ENABLED`; setup in `docs/confluence_sync_setup.md`) copies the pages of the spaces in `CONFLUENCE_SYNC_SPACE_KEYS` into the isolated `confluence_wiki` knowledge collection on a scheduler heartbeat, so the Executive knows the company wiki without a tool call (see RAG). It works with Confluence Cloud and Server/Data Center: `knowledge.confluence_client` calls the v1 REST API both serve, directly with `httpx`, signing in with a personal access token (Server/DC) or a username and API token (Cloud). It reads only, never follows a redirect (so the token stays on the configured site), streams responses with a 20 MB cap, and checks page ids and space keys before they reach a URL or a CQL query. The URL must be `https://` unless `CONFLUENCE_SYNC_ALLOW_HTTP` is set, and `CONFLUENCE_SSL_VERIFY` takes `true`, `false` or a CA bundle path for a private certificate authority. With `CONFLUENCE_SYNC_PUBLIC_HOSTS_ONLY` (off by default, for an install where whoever sets the URL must not reach the backend's own network) every request resolves the site's host, refuses it when any address is not public (loopback, private, link-local, shared), and connects to the checked address with the site's name kept for the Host header and the TLS certificate check, directly rather than through a proxy. `confluence_client.config_problem` is the same settings check the app runs at start, for a caller that writes these settings on someone's behalf.\n\nIt is separate from a Confluence MCP server such as mcp-atlassian, which a deployment can add to `mcp_servers.json` for live reads and edits in chat. The two share the env names `CONFLUENCE_URL`, `CONFLUENCE_PERSONAL_TOKEN`, `CONFLUENCE_USERNAME`, `CONFLUENCE_API_TOKEN` and `CONFLUENCE_SSL_VERIFY`, so one set of values serves both, and a synced chunk carries its page id so the Executive can open the live page with such a tool. A Confluence token is a user's, and what the sync reads becomes retrievable by everyone who talks to the Executive, so the space list is required and pages with a read restriction (their own or a parent's) are skipped unless `CONFLUENCE_SYNC_SKIP_RESTRICTED=false`. That keeps any existing member's token safe to use, without a dedicated licence. Manual runs: `openexecutive sync-confluence` / `purge-confluence`.\n\n### Your own Gmail or Outlook (Act as me)\n\nA second, separate mail connection, for **Act as me** (see **Act as Me (Delegation)**): a person's *own* mailbox, which `delegation.gmail.DelegateGmail` reads and drafts into over the Gmail REST API. It is never registered with the MCP gateway, so the model can reach it only through the typed `ghostwrite_email` handler — never by tool name through `call_tool`. The credential is one file per person in `DELEGATION_GOOGLE_CREDENTIALS_DIR` (default `company/delegation_google/`, `/data/delegation_google` in Docker), minted on a computer with a browser by `scripts/connect-own-gmail.py --email <you>` with the Executive's own OAuth client and the scopes `gmail.readonly` and `gmail.compose` — the same seed-it-yourself flow as the Executive's token, since the API serves no OAuth callback. It never lives in `WORKSPACE_MCP_CREDENTIALS_DIR`, where workspace-mcp picks a credential by address.\n\nEvery use re-checks with Google that the credential opens the mailbox on the person's People entry, and refuses outright when that address is the Executive's own: a shared mailbox would make everything the Executive writes look like theirs. Drafts are threaded (`In-Reply-To`, `References` of whole ids ending with the parent, `threadId`) and stamped `X-OE-Ghostwritten`; the only send is `drafts.send` of an existing draft by id, when the person taps Send on its reply card (`delegation.reply_send`). A Gmail rate limit, even as a 403, is an error to retry rather than a reconnect. The voice learner and the thread shown to the ghostwriter keep only each sender's own words through `email_poller.sender_new_text`, the poller's quoted-reply stripper made public. Setup status shows it as **Your own mailbox (Act as me)**.\n\nThe same file can instead hold an Outlook sign-in (`\"provider\": \"microsoft\"`), minted by `scripts/connect-own-outlook.py --email <you>` with a device-code sign-in on the Executive's own Entra app (`MS365_MCP_CLIENT_ID`, `MS365_MCP_TENANT_ID`, default `common`) and the delegated scopes `User.Read`, `Mail.ReadWrite`, `Mail.Send` and `offline_access`. `delegation.gmail.gmail_for` then hands back `delegation.outlook.DelegateOutlook`, which talks to Microsoft Graph directly — never the Microsoft 365 MCP server the Executive's own Outlook uses — with the same methods and the same one send: Graph's `send` on an existing draft, with no body. Microsoft rotates the refresh token on use and the new one is written back into the file. A sender counts as verified only from the topmost `Authentication-Results`, the one Exchange wrote, and only mail in their Sent Items counts as theirs.","mermaid": "flowchart TD\n Channels[\"Slack / Discord<br/>Telegram / GChat / Email\"]\n Resolve[\"find_person_by_*_id\"]\n Gate[\"roster gate\"]\n Drop[\"drop\"]\n Hold[\"roster request<br/>(hold + fixed ack,<br/>ask the principal)\"]\n Exec[\"Executive.chat()\"]\n Attach[\"attachments<br/>(vision / inbound_attachments)\"]\n MCP[\"MCP gateway\"]\n GW[\"Google Workspace<br/>(workspace-mcp child)\"]\n M365[\"Microsoft 365<br/>(ms-365-mcp-server child:<br/>Outlook + OneDrive)\"]\n WP[\"workspace providers<br/>(poller / alerts / booking)\"]\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\" --> Hold\n Hold -- \"approved: replay\" --> Exec\n Hold -- \"contact / declined\" --> Drop\n Gate -- \"Person\" --> Exec\n Gate --> Attach\n Attach --> Exec\n Exec --> MCP\n MCP -- \"roster egress gate\" --> GW\n MCP -- \"roster egress gate\" --> M365\n WP -- \"EMAIL_PROVIDER / CALENDAR_PROVIDER\" --> MCP\n WP --> Exec\n Exec --> Guard\n Guard -- \"suppress\" --> Drop\n Guard -- \"allow\" --> Out\n Out --> Channels\n Own[(\"Principal's own Gmail<br/>(Act as me: REST, drafts only)\")]\n Exec -- \"ghostwrite_email\" --> Own\n class Channels entry\n class Resolve compute\n class Gate compute\n class Drop external\n class Hold compute\n class Exec hot\n class Attach compute\n class MCP external\n class GW external\n class M365 external\n class WP compute\n class Guard compute\n class Out compute\n class Own external",- "generated_at": "2026-10-13T16:04:22Z"+ "generated_at": "2026-10-13T18:00:00Z"}diff --git a/packages/core/openexecutive/architecture/prebuilt/lifecycle.json b/packages/core/openexecutive/architecture/prebuilt/lifecycle.jsonindex 0364fd5c..af53cf5b 100644--- a/packages/core/openexecutive/architecture/prebuilt/lifecycle.json+++ b/packages/core/openexecutive/architecture/prebuilt/lifecycle.json@@ -1,7 +1,7 @@{"section_id": "lifecycle","title": "Request Lifecycle",- "markdown": "A single chat message makes a full round-trip through the API, the orchestrator's tool-use loop, a parallel specialist fan-out, and synthesis — all streamed back as server-sent events.\n\n### Steps\n\n1. **Arrival** — the client mints a `client_turn_id` and posts to `POST /chat` (`openexecutive.api.routes.chat`). The turn carries a `<current_speaker>` hint resolved from the caller's `person_id` (followed by that person's `<working_style>` rules when they have any — see the attunement section), plus a `<briefing>` digest of current open alerts (built in parallel with RAG/episodic/peer-memory fetches) so the Executive can discuss any item shown on the `/today` briefing page. A turn arriving from a chat adapter instead of the web app also carries a `<channel>` block naming the surface and stating which approvals can be completed there; on Slack the `<briefing>` digest is gated to the principal's DMs. All three ride in the **user turn**, never a cached system block, as does a `<drive_memory>` block naming the Drive files this conversation already found or opened and the Drive searches that matched nothing (see the memory section). The server registers a stop switch under that id *before* the context fetch, so a Stop pressed during those first seconds halts the turn before any model call is made.\n2. **Tool-use loop** — the `Executive` calls Claude. For a cross-domain question the assistant turn emits multiple `consult_specialist` tool-use blocks at once. The call carries the conversation so far (`Session.get_recent_history`: 20 to 30 turns, its start moving in steps of 10) with a 1h cache marker on the previous reply, so each message reads the earlier conversation from the prompt cache and writes only what is new (see Caching); on the OpenRouter path the translator keeps that marker on the reply's text.\n The person can keep typing while it works. A message sent then (`POST /chat/add`) joins the running turn: the loop adds it after the next round's tool results, so the answer follows it, and it is saved as its own message before the reply. One that arrives while the final answer is being written becomes the next turn instead. A conversation runs one turn at a time.\n3. **Parallel fan-out** — `openexecutive.orchestrator.router.route_parallel` dispatches those calls concurrently, bounded by `MAX_PARALLEL_SPECIALISTS`; calls past the cap get a skip tool_result. A specialist that raises (a timeout, an overloaded model) or returns no text no longer fails the batch: its tool_result says it is unavailable and tells the Executive not to invent its view, the others' results stand, and the turn goes on. It does not count as consulted, so it takes no committee seat and no department memory records the turn, and its documents are left out of the answer's sources. On the web chat the reply need not mention the gap, because the app shows it under the answer; on every other channel the tool_result asks the Executive to say in one sentence that part of the analysis is missing. A knowledge retrieval that fails likewise leaves that specialist without context rather than failing the turn.\n4. **Per-specialist RAG** — each specialist runs its own domain-filtered ChromaDB query, then reasons over the retrieved chunks and returns analysis as a tool_result. Its user turn also carries a `<company_stage>` tag from the session's company profile, so stage-sensitive advice (venture benchmarks vs. cash-first for a bootstrapped company) does not depend on the Executive remembering to mention it. Once the batch is done, the documents each answering specialist's retrieval returned are named, in call order, into the turn's `TurnSources` (`orchestrator/answer_sources.py`), which the web chat route owns and which also holds its own search's documents. Synced Google Drive files are recorded as `drive` sources with their Drive link, and the web chat lists them under **Google Drive**.\n5. **Synthesis** — the Executive feeds the tool_results back to Claude and streams one coherent reply. Every tool round — not just a specialist one — emits an `activity` event naming what is running, immediately followed by a `thinking` keepalive. The label names the *activity*, never the internal agent: \"Putting time on the calendar…\", \"Looking up people…\", or, for a connected (MCP) tool, plain words for what it does (\"Searching Drive…\"), from the same table (`orchestrator/tool_labels.py`) that names the finished chip (\"Searched Drive\"). The raw `server__tool` name never reaches the user. Under the reply, repeats of the same action collapse into one chip with a count, and tapping it lists what each run looked at. A round that really does fan out collapses to the generic \"Consulting specialists…\" — the one voice holds even in the progress line. The keepalive carries no tool information of its own; it used to drive a hardcoded \"Consulting specialists…\" string, so an MCP or calendar round misreported itself as a fan-out.\n6. **Optional committee review** — when enabled, `Executive.stream_chat_with_committee()` runs a silent draft, parallel reviewer critiques, then a streamed revision pass.\n7. **Side effects** — after the reply, every rostered speaker's turn (not only the principal's) schedules a fire-and-forget **open-loop pass** (Attunement) beside the episodic extraction: a keyword prefilter, then one forced-tool call that may open or close loops, every item quote-gated against the speaker's own words. The user message is persisted with `sender_person_id` — the resolved speaker, never the principal fallback a Discord / Telegram session uses for ownership — and the session records the speaker for the turn (`Session.caller_person_id`), which `close_open_loop` reads. A DM sent while proactive work is tagged (`attunement.outcomes.tag_proactive` — scheduler dispatch, reflection, research, alert review) also opens an outcome-ledger row at `_record_outbound_context`; a user's own turn is never tagged. Any side-effecting tool call surfaces an `action_taken` chip, which unlike the ephemeral `activity` label is persisted with the assistant message; once the reply is over — also when it was stopped or timed out — the web chat route sends one `sources` event: the documents and web pages the turn looked at (its own search, each specialist that answered, web search results, and the pages the reply cites, which are always kept) and the areas (\"finance\", never a specialist) it had to go without. The web chat shows it under the reply, and it is persisted with the assistant message as `chat_messages.sources`; other channels don't collect it. The stream closes with a `done` event — preceded by a `stopped` event when the user halted the turn, in which case the partial reply is still persisted and flagged so it reads as cut short rather than complete, and is mirrored into the live in-memory session so the next turn's prompt matches what was saved. The stream still ends with `done` event. One side-effecting tool is gated server-side rather than by its description: `ack_alert` will only accept an `alert_id` from the live alert board the server itself derived this turn — the whole live set, not only the rows the `<briefing>` digest printed, since `/today` renders more cards than the digest lists and every one of them is Discuss-able — and it fails closed, so an id it cannot even parse is refused rather than waved through to the handler's own parse. That check runs on **every** session. It used to run only on turns that arrived from a chat channel, keyed on `origin_channel`, which the browser never sets — so the web, the surface the principal actually uses, was unchecked and the model could ack any id, including one quoted out of an alert body by the briefing page's Discuss handoff. What that buys is bounded and worth stating plainly: an id that is invented, closed, snoozed or expired is refused, including one quoted out of an attacker-written alert body; the model being argued into acking the wrong *live* card is not prevented. The one way to widen that set is `find_alerts`, for an item the principal names that has left the live board (already opened, snoozed, older than the board): a keyword search over alerts of every status whose own results — never an id the model supplies — join the trusted set. It runs only in a turn where `render_and_trust` showed the principal their own board (`Session.principal_board_shown`: the verified principal, and on a channel only in their DM), never merely because the session has a set — every `Session` starts with an empty one, and that empty set is how a Google Chat turn, someone else's DM or an unattended pass refuses every ack — and not on the principal's turn in a shared Slack or Discord thread either, where others read the reply and write into what the model reads. It trusts only rows still open (`unread`, `read`), never a roster-request card, and at most 25 ids per turn across calls, and refuses a query with no word of three or more letters. It also moves the admitted limit outward: a model argued into the wrong search can now reach up to 25 open alerts that are off the board, not only live ones. The board is recorded on the turn's `Session`, and the route binds that session for the **whole** SSE body (`schedule_tools.set_session`, alongside `set_turn`) rather than letting `stream_chat` bind it from inside its own generator. `_sse_body` drives the executive with `asyncio.wait_for(stream.__anext__())`, which runs each step in a fresh Task holding a *copy* of the context, so a binding made inside the generator is discarded with the step that made it: step one sees the session and every later step sees `None`. The tool-call loop runs on those later steps, so the whole guard read an empty set and refused every ack on the web — on live, open cards — until the binding moved out to the route. Anything reading `current_session` mid-turn has the same requirement, and two of them needed more than the binding to behave. `schedule_followup`'s seen-`channel_ref` anti-spam gate refuses a send to an address the session has not seen; with no session it skipped itself, so a web turn could schedule to **any** address, and with an empty one it refused even the principal's own. The route now seeds the caller's own addresses onto the session, so on web the gate means what it means on every other surface. Reply linkage (`_record_outbound_context`, read back by `inbound_hydration` to quote the originating conversation into the turn handling a recipient's reply) is the other: it was never reachable on web, and rather than switch that on for the principal's broadest surface as a side effect it is held back, keyed on an explicit `Session.from_web_chat` flag. Not on an empty `origin_channel` — alert review, the CLI and the unattended workflows all leave it empty while legitimately recording linkage, as does the email poller under its own `email` tag. `scheduled_actions` rows also take their `session_id` from the session. A session that was shown no board has an empty trusted set and can ack nothing, so the unattended passes (the nightly reflection, the research synthesis) are refused by default — they also still withhold the tool outright, which is belt-and-braces rather than the only thing stopping them. After the stream closes, the turn is also handed to the episodic memory extractor (`memory.episodic.schedule_extraction`, fire-and-forget) — on every turn where the principal said anything at all, and only the principal: a turn naming an `origin_channel` must resolve to a person marked `is_principal`, because the quote validator downstream cannot tell whose words it is checking. Both this path and the committee path call the same `should_extract` predicate, and it applies no length floor: the gate used to sum in the assistant's reply, which let a verbose answer drag a trivial turn in and discarded the short, decisive instructions that are the whole point of extracting. A user-side floor would fare no better — \"Do B.\" and \"Done\" are one character apart. See **Memory** for what that cost on a live tenant.\n8. **Tool failures** — a handler that raises instead of returning its JSON error is isolated: both tool gathers run with `return_exceptions=True`, the model gets an error `tool_result` naming only the exception's TYPE — a message can carry a filesystem path, a validation error echoing the input, or a third-party HTTP body, and anything in model context can be quoted back to the user, so the full repr stays in the log and the audit row — and the failure is audited with `ok=false`. Only `CancelledError` is re-raised, so turn-timeout and client-disconnect handling still work. Before this one crashing tool aborted the whole turn, which reached the user as an unexplained apology with no audit row (#136).\n\nWeb search, when invoked on the Anthropic path, executes inside the Anthropic API itself (`web_search_20250305`) and returns within the same generation; for any model routed via OpenRouter the same tool becomes OpenRouter's `openrouter:web_search` server tool, which also runs inside the generation with the same search cap and domain lists.\n\nThe install's workspace mode (solo or team, see Org) is read fresh at the start of each turn by `memory.workspace_settings.pin_turn_workspace_mode(session)` and pinned on the session for that turn only (`Session.turn_workspace_mode`): the persona, the org block, the tool list and every tool handler in the turn then agree, and a switch made mid-turn applies from the next turn. A session can instead carry an explicit override, `Session.workspace_mode` (`None` by default), which wins over both — so a caller that runs many conversations concurrently on one Executive, such as evals, can pick the mode per session rather than flipping the install-wide setting. Everything reads it through `effective_workspace_mode(session)` (override, then the turn's pin, then the setting). The principal's role is pinned the same way (`pin_turn_principal_role(session, mode)` → `Session.turn_principal_role`: in solo the `Session.principal_role` override, else the workspace settings read fresh; in team an empty role). The org block renders it, each specialist batch gets it as a `<principal_role>` user-turn tag, and a workflow the turn starts reads the same pin through `effective_principal_role` (override, then the pin, then the setting), so a role edited mid-turn applies from the next turn; a team turn sends none.\n\nAct as me is pinned beside them: `delegation.settings.pin_turn_delegation(session, speaker_text)` records on `Session.turn_delegation` whether the speaker has it on, whether `ghostwrite_email` is offered this turn (the principal, or a team member once the owner lets them, on a verified surface, in a conversation private to them, attended), and the speaker's own words. The pin is also held in a context variable for the turn's task, so two turns running at once on one session each read their own. The tool list, the tool handler and the turn's audit privacy all read that one pin, so a switch flipped mid-turn applies from the next turn. Once the tool touches the speaker's mailbox, the conversation is the speaker's alone (`session_store.mark_mail_private`, the principal included when it isn't theirs), the rest of the turn's audit rows are private (a team member's theirs alone) and the turn teaches no memory: no extraction, open-loop, working-style or Honcho pass runs on it. Later turns of that conversation stay private the same way; the pin also records whether the reading turn is still in the history the model is shown (`mail_in_view`, from `sessions.mail_read_at` against `session.history_window_start`), and links, scripts, workflows and posts to everyone stay withheld only while it is.",+ "markdown": "A single chat message makes a full round-trip through the API, the orchestrator's tool-use loop, a parallel specialist fan-out, and synthesis — all streamed back as server-sent events.\n\n### Steps\n\n1. **Arrival** — the client mints a `client_turn_id` and posts to `POST /chat` (`openexecutive.api.routes.chat`). The turn carries a `<current_speaker>` hint resolved from the caller's `person_id` (followed by that person's `<working_style>` rules when they have any — see the attunement section), plus a `<briefing>` digest of current open alerts (built in parallel with RAG/episodic/peer-memory fetches) so the Executive can discuss any item shown on the `/today` briefing page. A turn arriving from a chat adapter instead of the web app also carries a `<channel>` block naming the surface and stating which approvals can be completed there; on Slack the `<briefing>` digest is gated to the principal's DMs. All three ride in the **user turn**, never a cached system block, as does a `<drive_memory>` block naming the Drive files this conversation already found or opened and the Drive searches that matched nothing (see the memory section). The server registers a stop switch under that id *before* the context fetch, so a Stop pressed during those first seconds halts the turn before any model call is made.\n2. **Tool-use loop** — the `Executive` calls Claude. For a cross-domain question the assistant turn emits multiple `consult_specialist` tool-use blocks at once. The call carries the conversation so far (`Session.get_recent_history`: 20 to 30 turns, its start moving in steps of 10) with a 1h cache marker on the previous reply, so each message reads the earlier conversation from the prompt cache and writes only what is new (see Caching); on the OpenRouter path the translator keeps that marker on the reply's text.\n The person can keep typing while it works. A message sent then (`POST /chat/add`) joins the running turn: the loop adds it after the next round's tool results, so the answer follows it, and it is saved as its own message before the reply. One that arrives while the final answer is being written becomes the next turn instead. A conversation runs one turn at a time.\n3. **Parallel fan-out** — `openexecutive.orchestrator.router.route_parallel` dispatches those calls concurrently, bounded by `MAX_PARALLEL_SPECIALISTS`; calls past the cap get a skip tool_result. A specialist that raises (a timeout, an overloaded model) or returns no text no longer fails the batch: its tool_result says it is unavailable and tells the Executive not to invent its view, the others' results stand, and the turn goes on. It does not count as consulted, so it takes no committee seat and no department memory records the turn, and its documents are left out of the answer's sources. On the web chat the reply need not mention the gap, because the app shows it under the answer; on every other channel the tool_result asks the Executive to say in one sentence that part of the analysis is missing. A knowledge retrieval that fails likewise leaves that specialist without context rather than failing the turn.\n4. **Per-specialist RAG** — each specialist runs its own domain-filtered ChromaDB query, then reasons over the retrieved chunks and returns analysis as a tool_result. Its user turn also carries a `<company_stage>` tag from the session's company profile, so stage-sensitive advice (venture benchmarks vs. cash-first for a bootstrapped company) does not depend on the Executive remembering to mention it. Once the batch is done, the documents each answering specialist's retrieval returned are named, in call order, into the turn's `TurnSources` (`orchestrator/answer_sources.py`), which the web chat route owns and which also holds its own search's documents. Synced Google Drive files are recorded as `drive` sources with their Drive link, and the web chat lists them under **Google Drive**.\n5. **Synthesis** — the Executive feeds the tool_results back to Claude and streams one coherent reply. Every tool round — not just a specialist one — emits an `activity` event naming what is running, immediately followed by a `thinking` keepalive. The label names the *activity*, never the internal agent: \"Putting time on the calendar…\", \"Looking up people…\", or, for a connected (MCP) tool, plain words for what it does (\"Searching Drive…\"), from the same table (`orchestrator/tool_labels.py`) that names the finished chip (\"Searched Drive\"). The raw `server__tool` name never reaches the user. Under the reply, repeats of the same action collapse into one chip with a count, and tapping it lists what each run looked at. A round that really does fan out collapses to the generic \"Consulting specialists…\" — the one voice holds even in the progress line. The keepalive carries no tool information of its own; it used to drive a hardcoded \"Consulting specialists…\" string, so an MCP or calendar round misreported itself as a fan-out.\n6. **Optional committee review** — when enabled, `Executive.stream_chat_with_committee()` runs a silent draft, parallel reviewer critiques, then a streamed revision pass.\n7. **Side effects** — after the reply, every rostered speaker's turn (not only the principal's) schedules a fire-and-forget **open-loop pass** (Attunement) beside the episodic extraction: a keyword prefilter, then one forced-tool call that may open or close loops, every item quote-gated against the speaker's own words. The user message is persisted with `sender_person_id` — the resolved speaker, never the principal fallback a Discord / Telegram session uses for ownership — and the session records the speaker for the turn (`Session.caller_person_id`), which `close_open_loop` reads. A DM sent while proactive work is tagged (`attunement.outcomes.tag_proactive` — scheduler dispatch, reflection, research, alert review) also opens an outcome-ledger row at `_record_outbound_context`; a user's own turn is never tagged. A tagged DM is also subject to the recipient's own notification settings: in their quiet hours, or when they chose *In my briefs*, the send handler stores it (`outbound_guard.check_hold`, `people.held_messages`) and returns `{\"status\": \"held\"}` instead of sending (see Org). Any side-effecting tool call surfaces an `action_taken` chip, which unlike the ephemeral `activity` label is persisted with the assistant message; once the reply is over — also when it was stopped or timed out — the web chat route sends one `sources` event: the documents and web pages the turn looked at (its own search, each specialist that answered, web search results, and the pages the reply cites, which are always kept) and the areas (\"finance\", never a specialist) it had to go without. The web chat shows it under the reply, and it is persisted with the assistant message as `chat_messages.sources`; other channels don't collect it. The stream closes with a `done` event — preceded by a `stopped` event when the user halted the turn, in which case the partial reply is still persisted and flagged so it reads as cut short rather than complete, and is mirrored into the live in-memory session so the next turn's prompt matches what was saved. The stream still ends with `done` event. One side-effecting tool is gated server-side rather than by its description: `ack_alert` will only accept an `alert_id` from the live alert board the server itself derived this turn — the whole live set, not only the rows the `<briefing>` digest printed, since `/today` renders more cards than the digest lists and every one of them is Discuss-able — and it fails closed, so an id it cannot even parse is refused rather than waved through to the handler's own parse. That check runs on **every** session. It used to run only on turns that arrived from a chat channel, keyed on `origin_channel`, which the browser never sets — so the web, the surface the principal actually uses, was unchecked and the model could ack any id, including one quoted out of an alert body by the briefing page's Discuss handoff. What that buys is bounded and worth stating plainly: an id that is invented, closed, snoozed or expired is refused, including one quoted out of an attacker-written alert body; the model being argued into acking the wrong *live* card is not prevented. The one way to widen that set is `find_alerts`, for an item the principal names that has left the live board (already opened, snoozed, older than the board): a keyword search over alerts of every status whose own results — never an id the model supplies — join the trusted set. It runs only in a turn where `render_and_trust` showed the principal their own board (`Session.principal_board_shown`: the verified principal, and on a channel only in their DM), never merely because the session has a set — every `Session` starts with an empty one, and that empty set is how a Google Chat turn, someone else's DM or an unattended pass refuses every ack — and not on the principal's turn in a shared Slack or Discord thread either, where others read the reply and write into what the model reads. It trusts only rows still open (`unread`, `read`), never a roster-request card, and at most 25 ids per turn across calls, and refuses a query with no word of three or more letters. It also moves the admitted limit outward: a model argued into the wrong search can now reach up to 25 open alerts that are off the board, not only live ones. The board is recorded on the turn's `Session`, and the route binds that session for the **whole** SSE body (`schedule_tools.set_session`, alongside `set_turn`) rather than letting `stream_chat` bind it from inside its own generator. `_sse_body` drives the executive with `asyncio.wait_for(stream.__anext__())`, which runs each step in a fresh Task holding a *copy* of the context, so a binding made inside the generator is discarded with the step that made it: step one sees the session and every later step sees `None`. The tool-call loop runs on those later steps, so the whole guard read an empty set and refused every ack on the web — on live, open cards — until the binding moved out to the route. Anything reading `current_session` mid-turn has the same requirement, and two of them needed more than the binding to behave. `schedule_followup`'s seen-`channel_ref` anti-spam gate refuses a send to an address the session has not seen; with no session it skipped itself, so a web turn could schedule to **any** address, and with an empty one it refused even the principal's own. The route now seeds the caller's own addresses onto the session, so on web the gate means what it means on every other surface. Reply linkage (`_record_outbound_context`, read back by `inbound_hydration` to quote the originating conversation into the turn handling a recipient's reply) is the other: it was never reachable on web, and rather than switch that on for the principal's broadest surface as a side effect it is held back, keyed on an explicit `Session.from_web_chat` flag. Not on an empty `origin_channel` — alert review, the CLI and the unattended workflows all leave it empty while legitimately recording linkage, as does the email poller under its own `email` tag. `scheduled_actions` rows also take their `session_id` from the session. A session that was shown no board has an empty trusted set and can ack nothing, so the unattended passes (the nightly reflection, the research synthesis) are refused by default — they also still withhold the tool outright, which is belt-and-braces rather than the only thing stopping them. After the stream closes, the turn is also handed to the episodic memory extractor (`memory.episodic.schedule_extraction`, fire-and-forget) — on every turn where the principal said anything at all, and only the principal: a turn naming an `origin_channel` must resolve to a person marked `is_principal`, because the quote validator downstream cannot tell whose words it is checking. Both this path and the committee path call the same `should_extract` predicate, and it applies no length floor: the gate used to sum in the assistant's reply, which let a verbose answer drag a trivial turn in and discarded the short, decisive instructions that are the whole point of extracting. A user-side floor would fare no better — \"Do B.\" and \"Done\" are one character apart. See **Memory** for what that cost on a live tenant.\n8. **Tool failures** — a handler that raises instead of returning its JSON error is isolated: both tool gathers run with `return_exceptions=True`, the model gets an error `tool_result` naming only the exception's TYPE — a message can carry a filesystem path, a validation error echoing the input, or a third-party HTTP body, and anything in model context can be quoted back to the user, so the full repr stays in the log and the audit row — and the failure is audited with `ok=false`. Only `CancelledError` is re-raised, so turn-timeout and client-disconnect handling still work. Before this one crashing tool aborted the whole turn, which reached the user as an unexplained apology with no audit row (#136).\n\nWeb search, when invoked on the Anthropic path, executes inside the Anthropic API itself (`web_search_20250305`) and returns within the same generation; for any model routed via OpenRouter the same tool becomes OpenRouter's `openrouter:web_search` server tool, which also runs inside the generation with the same search cap and domain lists.\n\nThe install's workspace mode (solo or team, see Org) is read fresh at the start of each turn by `memory.workspace_settings.pin_turn_workspace_mode(session)` and pinned on the session for that turn only (`Session.turn_workspace_mode`): the persona, the org block, the tool list and every tool handler in the turn then agree, and a switch made mid-turn applies from the next turn. A session can instead carry an explicit override, `Session.workspace_mode` (`None` by default), which wins over both — so a caller that runs many conversations concurrently on one Executive, such as evals, can pick the mode per session rather than flipping the install-wide setting. Everything reads it through `effective_workspace_mode(session)` (override, then the turn's pin, then the setting). The principal's role is pinned the same way (`pin_turn_principal_role(session, mode)` → `Session.turn_principal_role`: in solo the `Session.principal_role` override, else the workspace settings read fresh; in team an empty role). The org block renders it, each specialist batch gets it as a `<principal_role>` user-turn tag, and a workflow the turn starts reads the same pin through `effective_principal_role` (override, then the pin, then the setting), so a role edited mid-turn applies from the next turn; a team turn sends none.\n\nAct as me is pinned beside them: `delegation.settings.pin_turn_delegation(session, speaker_text)` records on `Session.turn_delegation` whether the speaker has it on, whether `ghostwrite_email` is offered this turn (the principal, or a team member once the owner lets them, on a verified surface, in a conversation private to them, attended), and the speaker's own words. The pin is also held in a context variable for the turn's task, so two turns running at once on one session each read their own. The tool list, the tool handler and the turn's audit privacy all read that one pin, so a switch flipped mid-turn applies from the next turn. Once the tool touches the speaker's mailbox, the conversation is the speaker's alone (`session_store.mark_mail_private`, the principal included when it isn't theirs), the rest of the turn's audit rows are private (a team member's theirs alone) and the turn teaches no memory: no extraction, open-loop, working-style or Honcho pass runs on it. Later turns of that conversation stay private the same way; the pin also records whether the reading turn is still in the history the model is shown (`mail_in_view`, from `sessions.mail_read_at` against `session.history_window_start`), and links, scripts, workflows and posts to everyone stay withheld only while it is.","mermaid": "sequenceDiagram\n participant C as Client\n participant API as FastAPI /chat\n participant E as Executive\n participant CL as Claude\n participant S as Specialists\n participant KB as ChromaDB\n C->>API: POST /chat message\n API->>E: start turn\n E->>CL: messages (tool-use loop)\n CL-->>E: consult_specialist calls\n E->>S: route_parallel fan-out\n S->>KB: domain-filtered RAG\n KB-->>S: chunks\n S-->>E: analysis tool_results\n E->>CL: synthesize\n CL-->>E: streamed reply\n E-->>API: SSE chunks then done\n API-->>C: streamed response",- "generated_at": "2026-10-08T21:50:00Z"+ "generated_at": "2026-10-13T18:00:00Z"}diff --git a/packages/core/openexecutive/architecture/prebuilt/org.json b/packages/core/openexecutive/architecture/prebuilt/org.jsonindex 7e31b80a..181233b5 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**. A new install starts with **no departments**: nothing is created at boot. Setup's commit creates only the departments its draft names (none for a solo workspace or a team that names none), and the Executive's `create_goal` tool creates one when a goal names an area that has none. A department named after one of the eight catalogue areas in `departments/charters` (Strategy, Finance, People & Talent, Legal, Operations, Marketing, Product, Board & Investor Comms) starts from that area's charter, and setup and `create_goal` wire it to the matching specialist (at most one department per specialist). Workspaces created before this keep the departments they have. `seed_default_departments` still inserts the full catalogue once per database (tracked by a `default_departments_seeded` sentinel in `departments_meta`), but only tests and tooling call it.\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 5 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. Until a profile exists the owner (the principal)\nis sent to `/onboard` from Home and every shell page except Settings, unless\nthey chose \"I'll do this later\"; after the save and the voice step a last\nscreen shows what was kept and the two accounts worth connecting (the\nExecutive's own mailbox, and the owner's own for Act as me), and Home's\nbanner slot carries a getting-started checklist (profile, first question,\nthe two mailboxes, the team) until every required row is done or it is hidden\n(`ui/src/lib/firstRun.ts`).\n\nTwo properties matter here. First, **the interview never writes the profile**:\nthe exchange lives in a TTL'd session (2 h, 50 at most) that the API process\nholds and also writes through to the `onboarding_interviews` table of the\nepisodic SQLite database after every turn (`onboarding/interview_store.py`),\nso a restart or another worker finds it again (a newer stored row replaces\na held copy, so two workers never overwrite each other) and the browser,\nwhich keeps only the session id, resumes at the same question or draft via\n`GET /onboard/interview/{id}`. A session answers only to the caller who\nstarted it; anyone else gets the 404 an unknown id gets. The single profile write happens at\n`POST /onboard/interview/commit`, so a rejected save leaves the draft editable\nand retryable, and a successful one deletes the stored transcript at once (it\ncarries the company's financials). 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 departments the workspace already\nhas, with their goals and `specialist_key` wiring, on a re-run of setup. A\ndrafted department that matches nothing is created, wired to the specialist\nwhose area it is named after (`specialist_key_for_area`) unless another\ndepartment already has that specialist. Matching goes through\n`departments.store.match_department` (slug as given or as the store would slug\nit, else case-insensitive title), the same rule the `create_goal` chat tool uses. `profile.org_structure` is derived from the reviewed\npeople and department tables at commit time, so it cannot drift from them.\n\nExactly one person is marked `is_principal` and receives `WILDCARD` authority;\nno contact details are imported, even if the user volunteers them, because\nchannels and handles are a deliberate action on the People page. The one\nexception is the owner's own sign-in email: the review screen has a separate\nfield for it, pre-filled with the current owner's email on a re-run and with the\nsigned-in user's on a first setup. The commit checks it before writing anything\n(malformed, already another person's — as their address or one of their\naliases — 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. One case is adopted rather than rejected: when the address is\nthe one the caller signed in with and sits on the current principal's row\nunder another name (a hosted sign-up seeds that row from the address when no\nname was given), `adopt_owner_row` renames that row to the drafted name\nbefore the roster upsert, so the first save updates the owner's entry instead\nof failing with \"use the owner's name exactly as on the People page\". 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 or SSO sign-in) the field is optional: that\nsession carries no email, which the backend already reads as the principal.\nBecause the save demotes the old principal, only the current owner may draft\nsomeone else as \"This is me\" when setup is re-run (403 otherwise); a re-run\nthat keeps the owner, or a first setup, is open to anyone who can sign in. On such a re-run, someone who isn't the owner may fill in the owner's missing email only with the address they signed in with (403 otherwise): the roster is the sign-in allow-list, so any other address would let them sign in as the owner. That keeps the way in for an owner whose entry has no email, which is also where Setup status and the Executive send them, since the People page refuses anyone it can't recognise as the owner. Re-running setup stays open to everyone deliberately: the Company Profile and Departments pages already let anyone signed in change the same things. The original\n12-step form wizard remains available at `/onboard?mode=form` and backs the\n`openexecutive onboard` CLI. It adds people with their emails, so once there is an owner only they can save it.\n\nA first setup opens on one free-text box: the user describes their work in their own words, optionally attaching a one-pager. `POST /onboard/interview/understand` reads that text once (no session, nothing stored) and reports what it already says: Personal or Team, the principal's role (owner / founder, an executive inside an organisation, independent or fractional, or other), title, who they report to, the company and this year's focus. The next screen shows those for a quick confirm, with Personal / Team as the one required answer; confirming writes `PUT /workspace` (mode, the browser's time zone and, for Personal, the role) and then starts the interview with the same text, so it asks only about what is still missing, at most five questions. If the read fails the text is kept and the user simply picks. A re-run over an existing profile skips these steps; they are changed in Settings. The tone question comes last, after the draft is saved. In solo the interviewer's first user turn carries a short\nhint, one static constant per role kind (`onboarding.interview.solo_hint`):\nalways draft only the principal, as principal, and no departments; an owner is\nasked about the offer, customers, pricing, cash and runway; an in-house\nexecutive about their organisation (the company profile is their employer),\ntheir function and remit, their manager, their team size as context rather\nthan a roster, and what they are measured on; an independent about their\npractice, clients and pricing; with no role given, the role-neutral hint asks\nwhich of these they are. Each also asks their top goals. The hint never\ncarries the principal's own text, and it rides in the user turn, so the cached\nsystem prompt is the same constant in both modes. The solo review screen shows only **You**\n(name and role) and the sign-in email, and commits that one principal with no\ndepartments — the existing departments stay, as the areas goals are grouped\nby. The form wizard (and the CLI) read the mode when a session starts and skip\nthe Team Size, Team Members and Fractional Executives steps in solo; each\nstatus response numbers the steps it actually asks and flags whether the\ncurrent one is `optional`.\n\n### Departments\nEach department carries a charter, `Goal` rows, `ChecklistItem`s, and named cadences. Cadence specs (`daily@HH:MM`, `weekly@DOW@HH:MM`, `quarterly@DD-HH:MM`, UTC) run a `department_check_in` workflow when due (never in solo mode, below), then chain the next occurrence. A new department starts with `check_in: weekly@mon@09:00` (`DEFAULT_CHECK_IN_CADENCE`; it was daily, and departments created before keep theirs). An empty spec turns the check-in off. `PATCH /departments/{slug}` rejects a spec that does not parse with a 422, and a changed `check_in` re-times the department at once (`cadence.reschedule_check_in` cancels the pending check-in and queues the next one on the new schedule, or none when it is off). The department page offers Daily / Weekly (day and time) / Off rather than the raw spec, and shows the next check-in from `next_check_in_at`. The check-in is skipped (and still chained) when the department has no specialist, no Goals, or nothing new since its Goals were last reviewed (a row private to the principal does not count as new: whether it runs is visible to the department). An idle initiative is chased with the department's head, or with the principal when there is none. A department may map to a specialist agent via `specialist_key`, or stay informational. No department is seeded for the `sales` specialist (existing installs keep their departments unchanged), so its consults skip the department-memory prefetch and the Honcho department sync, as `triage`'s do. An assigned head gets a generated department-head voice persona.\n\n**Goals from chat.** Besides the goal routes and the UI, the Executive keeps goals current from a chat turn: `update_department_goal` records reported progress, and `create_goal` starts tracking a new goal the principal states (\"20 paying clients by the end of Q4\"). Only the principal, on a surface that verified it is them (`people_tools.is_principal_on_verified_surface`, the roster tools' rule: the web chat, their own Slack or Discord, a private Telegram chat with a valid webhook secret), may call it: a goal renders in every turn's org block as one of the principal's own, so a goal from an inbound email, Google Chat, a teammate or an unattended run would be text carrying their authority. Anyone else gets a refusal (audited with the caller and surface) and nothing is written. `create_goal` names the area as free text — a slug or a title, resolved by `match_department` — so its schema is static and adding an area never changes the cached tool prefix. When nothing matches it creates the area (`create_department`), giving it a specialist only when the title is obviously one's domain (`specialist_key_for_area`: the default departments' slugs and titles, plus Sales) and no department holds that specialist yet; anything else is informational. It refuses a goal the area already tracks (pointing at `update_department_goal`), caps a turn at 5 new goals (a sweep is not a stated goal) and an area at 8 (common practice keeps 3–5 key results per objective, and every goal renders in the 4000-character org block, so one area cannot crowd the others out), returns only the exception type on a store failure, is audited with its rationale, and is never offered to an unattended run (`schedule_tools.UNATTENDED_WITHHELD_TOOLS`: reflection, research and the scheduler's proactive trigger). The solo persona teaches it; team mode learns it from the tool description, so the team persona stays byte-identical.\n\nA department can also list **watched entities** (`watched_entities`, edited one per line on its page): vendors it is evaluating, competitors in its lane, tickers it tracks. The research watch policy treats them as strong grounding — a proposal about one can be added to the watch list on its own — and routes the resulting watch, its alerts and any suggestion cards to the department and its head rather than the principal (see External monitoring).\n\n### Solo and team mode\nAn install is either a **team** (the default) or **solo** — one person using Open Executive just for themselves. The mode lives with the user's time zone in its own one-row table, `workspace_settings` (`openexecutive.memory.workspace_settings`, `GET`/`PUT /workspace`), not on the company profile, because onboarding's commit and the form wizard rebuild the profile from scratch and would wipe it. Changing it is the principal's call (open while no principal exists, so first-run setup can choose).\n\nThe same row holds the **principal's role** (`PrincipalRole`, every field nullable): `role_kind` (`owner`, `in_house`, `independent` or `other`), `role_title`, `reports_to` (free text, e.g. \"VP of Operations, Dana Ruiz\"), `remit` (what they are responsible for) and `measured_on` (what they are judged on). Solo is about who uses Open Executive, not the principal's level — a business owner, an executive inside a larger organisation, an independent or fractional executive — and this is the context the solo persona reads the role from. Only solo mode reads it; a mode switch keeps it. `GET /workspace` returns it only to the principal (nulls for anyone else). The columns are added to an existing table additively, and a read of an older table (no role columns yet) never migrates it and reads the role as unset.\n\nSolo also changes how the Executive speaks and what it can do. It works for one person — the principal — without assuming their role (an owner, an executive inside a larger organisation, or an independent); the people in their world are contacts it helps them work with, not a team it routes to. The cached org block becomes the principal's own line (\"Your Principal\") — followed by their role lines when a role is set (a fixed lead-in marking the role private to the principal — use it to tailor advice and drafts, share it with no one else — then `- Role: <title> — <kind in plain words>`, `- Reports to:`, `- Responsible for:`, `- Measured on:`, each only when set, sanitized and capped) — plus their goals grouped by **area** (a department row is an area; no authority levels, heads, cadences, channels or roster), and posting to a department room, broadcasting to the company and assigning a department head are not offered. Specialists never see that block, so each consult in a solo turn also carries a `<principal_role>` tag in its user turn (kind, title and remit). The role is pinned on the session for the turn with the mode (`pin_turn_principal_role`), so the org block, the tag and any workflow the turn starts agree even if the role is edited mid-turn, so a VP inside a large company is told to make the case to their CFO rather than to raise a round. A follow-up the Executive schedules to the principal goes straight to them — its department and scope are dropped, so the authority gate never files a card asking the principal to approve a message to themselves. Meeting bookings are gated on the `meeting_scheduling` class mode, not a department (see below).\n\nSolo turns the department rhythm off without touching the org: switching to solo cancels every pending `dept_cadence` row, `bootstrap_cadences` does nothing (the check sits inside it, so boot, the fixture reset and client-slot activation all honour it), and the scheduler cancels any stray check-in without running or chaining it, and a check-in already running across the switch schedules no successor. Department and people rows are kept, so switching back to team re-schedules the check-ins at once. The boot-time org-completeness warnings (departments with no head) are skipped in solo. A chat `Session` can carry an explicit `workspace_mode` override (read through `effective_workspace_mode`), so a caller that runs many conversations on one Executive — evals, for one — can pick the mode per session instead of flipping the install-wide setting; a `principal_role` override (read through `effective_principal_role`: the override, then the turn's pin, then the setting) does the same for the role.\n\nIn the UI, a `WorkspaceProvider` in the root layout reads the mode and role once (and again after Settings changes them) and reads **team** while loading or on error, so a team install never flashes the solo UI. Solo swaps the sidebar's Company group for **You** — Goals, People and the profile — where `/goals` lists every goal grouped by area (a department row) and adds, edits and deletes them through the slug-scoped goal routes. Team mode lists Goals in the Company group too, after Departments, and the page says \"department\" instead of \"area\". Adding a goal asks only for the goal itself: the timeframe is a one-click chip (this quarter by default, filled with the current period's label), target and current are optional, and a new goal starts `on_track` until the check-in grades it. The profile entry follows the principal's role kind: **Business profile** for an owner, **Your work** for anyone else, including an unset role or one `GET /workspace` hides from a non-principal. One rule (`profileWording(mode, roleKind)` in `navConfig.ts`) also words the `/company-profile` breadcrumb, intro and section headings, the form wizard and the draft review; it is copy only, so no profile field is renamed, and team wording is unchanged. `/departments` and `/people` stay reachable by URL.\n\nThe setting is per company: a blank client slot starts on the defaults, a saved slot keeps its own (restoring one runs the additive column migration), a fixture load resets it and applies the fixture's optional `workspace.yaml` (`mode`, `timezone` and the optional role keys; read and validated before anything is swapped; a bad value is skipped, never a failed load; the load and unload responses report the mode and zone only, never the role), and the factory reset returns it to team with no zone and no role. The user's own settings survive a demo: the backup a fixture load takes (or reuses) always gets the live settings written to its `workspace.yaml` while the live state is the user's, and an unload from an older backup without one leaves the settings as they are. A zone that cannot be loaded is never fatal — the API answers 422, and a stored one reads as unset.\n\n### Authority gate\nEach department declares an `AuthorityLevel`, which `departments.authority.gate_action` checks whenever a department-scoped scheduled action comes due. The check-in cadence is the exception: it sends nothing itself, and each action it proposes is run through the gate and shown with its verdict in the report — so a propose-only department's check-ins actually run instead of becoming a one-shot approval card. `auto_execute` (autonomous) fires directly. `propose_only` turns the action into an approval card for an approver (`propose_via_alert`) and sends nothing, deferring the card to the approver's next availability window when they are outside it. `escalate` also sends nothing until someone approves: it raises an urgent `[ESCALATION]` card (severity high) right away, never deferred — filed unrouted when nobody holds the scope and no principal is set, since the Briefing lists every unread card — what the Departments page promises (\"the specialist will not act — it forwards everything to a human\"). It used to raise the card *and* dispatch, so approving the card sent the action a second time. Calendar bookings follow the same rule in team mode. In solo mode there is no operations department to consult: the booking is decided by the `meeting_scheduling` class mode — `propose` puts it on the briefing for whoever holds the **Meetings** approval range on People (`meeting_scheduling`), else the principal — a booking with a contact on it always stays the principal's — and `auto_execute` books right away only when the principal started the turn on a surface that verified it is them (the roster-write rule: the web chat, their own Slack or Discord, or a private Telegram chat with the webhook secret set). A booking asked for in an inbound email, by a contact, or by an unattended run is proposed to the principal instead, so text someone else wrote cannot put a meeting on their calendar. The principal sets it with `GET`/`PUT /decisions/classes/meeting_scheduling` (`{\"decision_class\": \"meeting_scheduling\", \"mode\": \"propose\" | \"auto_execute\"}`; the PUT is principal-only and audited). The approver is chosen by `AuthorityScope` — a scheduled action's `required_scope` (e.g. `vendor_onboarding`, `spend_lt_10k`) feeds `find_approvers(scope)`, which ranks non-principal scope-holders ahead of `WILDCARD` holders. A null/unknown scope falls back to `WILDCARD` (the principal).\n\n### People & channels\nThe people registry resolves each `Person` to a `(channel, channel_ref)` pair via `prefer_channel_for()`, honoring `preferred_channel` (falling back email → slack → discord → telegram) and availability windows. The principal briefs use their own order — the preferred channel, then Slack → Discord → Telegram, then email as the backup for every preference (first for an `email` one); see Scheduler. Departments can also set `slack_channel_id` / `discord_channel_id` / `telegram_chat_id` to broadcast to a team room instead of DMing the head.\n\nEach person's page also lists their **open loops** (see Attunement) — what they committed to or were asked for in conversation — with a *Mark done* action; archiving a person closes their open loops, since an archived person can no longer be chased. The list is the principal's or that person's only; `people.store.is_principal_or_self` is the one check behind it, the close action and reply feedback.\n\nThe Executive can change the roster from a chat turn (`upsert_person`, `archive_person`, `set_department_head`) only when the principal asks, from the web chat, their own Slack or Discord, or a private Telegram chat when `TELEGRAM_WEBHOOK_SECRET` is set to a value Telegram can send. A teammate, an email (even one from the principal's address), Google Chat, the CLI, the MCP server and unattended runs are refused, because a team member's People row is also the web sign-in allow-list, the outbound-email allow-list and approval routing. The People page follows the same rule: adding, editing and archiving people (`POST`/`PATCH /people`, `POST /people/{id}/archive`) are the principal's alone, or anyone's while no one is principal yet, so a first setup can add its owner (`chat._caller_is_principal_or_unclaimed`). Anyone else gets 403. That includes a teammate editing their own entry: its email and chat ids are how they sign in and how the Executive reaches them, and the rest decides their approvals and how they are chased. Their working style and open loops stay theirs. A signed-in owner whose email is on no People entry is refused too; they sign in with the email on their entry, or re-run the setup interview, which fills a missing one with the email they signed in with. The one roster change that can come from an email is the principal's tokened reply to a roster-request email, and the one a chat turn can make beyond these tools is `resolve_roster_request` — both below, both the principal's alone.\n\n### Team and contacts\nA `Person` is either on the **team** (`kind = \"team\"`, the default) or a **contact** (`kind = \"contact\"`): a client, contractor or advisor the Executive may need to email or invite but who must not get what a team row grants. Before contacts existed, emailing a client meant adding them as a Person, which also let them sign in and talk to the bot.\n\nContacts are **denied by default**. `people.store.list_people`, every `find_person_by_*` (and `find_person_by_channel_ref`), and the `people.registry` cache return team members only unless the caller passes `include_contacts=True`; `find_approvers` has no opt-in at all. So a contact is never in the web sign-in list (`GET /auth/allowed-emails`), the Slack / Telegram / Discord inbound gates, approvers, the alert review's roster slice, `/today`'s people list and insights, open-loop owners (an ask of a contact opens no loop, so the nudge engine never chases them), a workflow gate's approver or cadence recipient, the recap DM after a meeting, or a department head (`set_department_head` and `PATCH /departments/{slug}` refuse one). `get_person(id)` returns either kind and its security-relevant callers check `kind`.\n\nThe roster reads that **opt in** are few: the Executive's egress checks (Gmail, Calendar and Drive in the MCP gateway, calendar attendee resolution, and the chat DM tools), the People page's listing (`GET /people?include_contacts=true`), the chat `list_people` tool (both kinds, with `kind`), the org prompt block, and the roster-request intake (which looks a sender up with contacts included only to leave a contact out). Even there, reaching a contact needs **the principal's own turn**: `people_tools.contacts_reachable_now()` is true only on a turn the principal started on a surface that verified them — the same rule as roster writes above — or inside `grant_contact_egress()`, which the decisions approve route uses when the approver resolves to the principal. An inbound email (even from the principal's address), a teammate's turn, and unattended runs (scheduler, workflows, alert review) can still reach the team but not contacts. A workflow resumed by `apply_resolution`'s kick runs with no chat session, like the resumer's poll loop, so it never inherits the approver's turn.\n\n**Contacts are private to the principal.** A solo user may be an executive whose contacts include their boss, reports, board and clients, so nobody else using the install sees one. The rule is `contacts_reachable_now()` again: off the principal's own verified turn a contact does not exist — `list_people` returns the team with the same count, a contact's id or address gets exactly the error an unknown one gets (never a contact-specific refusal), and the org prompt block has no Contacts section. The API applies the same rule by caller (`people.caller_is_principal`: the signed-in email is the principal's, or no `x-caller-email` — CLI, local login; unlike the owner rule above, nobody is while no one is principal yet): `?include_contacts=true` is ignored for anyone else, a contact's id is a 404 on `GET /people/{id}` and its open loops exactly like a missing one (editing and archiving are already a 403 before any lookup), only the principal may create a contact or turn someone into one (403, a first setup with no principal included), and `GET /people/me` tells the UI whether to offer contacts at all.\n\nWhatever the Executive raises about a contact stays with the principal too. A meeting with a contact is proposed to the principal (not the scope's approver), its decision is hidden from everyone else's `/decisions` (404 by id), and its card carries `alerts.models.PRIVATE_ALERT_TAG`. So does an alert raised on a turn about the principal's private mail (`Session.private_to_principal`, set by the email poller for mail from a contact and for mail the principal forwards): the pipeline routes it to the principal, stores it without a live push or broadcast, and dedups it only against other private alerts. Private alerts appear on the principal's own `/today` and chat digest only — never a teammate's, the activity rail, the narrative, the morning brief, the end-of-day digest, the reflection or the alert review — and a teammate's ack, reopen or bulk sweep cannot touch one (404). A private turn itself reaches the principal and nobody else (email, DMs, invites). It is not offered, and cannot run, the tools that post to other people, publish where the team reads (artifacts, goal updates, saved workflows, skill drafts) or start work outside the turn (`schedule_tools.PRIVATE_TURN_WITHHELD_TOOLS`), and of the MCP tools it may use only Google Workspace reads and the Gmail send the gateway narrows to the principal. Its audit rows are the principal's alone, as is any row on the principal's own turn that names one of their contacts (see Audit Log). DMs to a contact stay off the activity rail.\n\n`upsert_person` takes `kind`: explicit wins; an update that omits it keeps the row's kind (the store's full-row UPDATE preserves it, so nothing promotes a contact to the team by accident); a new person defaults to `team`, or to `contact` in solo mode. On the principal's own verified turn the org prompt block lists contacts in a short `## Contacts` section after the team block (or, in solo, after `## Your Principal` and their goals) — name, role/company and whether an email is on file, capped at 25 — in both modes. Every other turn gets the team block, byte-identical to an install with no contacts, so the 5-minute cached block has two stable variants.\n\nOn the **People page** the principal sees **Team** and **Contacts** tabs; anyone else sees the team only (no Contacts tab, no kind selector). Solo mode opens on Contacts, and its Team tab shows only the principal. The add form has a kind selector and hides authority scopes, reply SLA and the principal checkbox for a contact; a contact's page hides scopes, SLA, availability windows, open loops, outreach and working style. Adding a team member in solo offers to switch the workspace to team mode, or keep solo.\n\n### Addresses: aliases and company domains\nA `Person` has one **primary** address (`email`) — the one they sign in with — and up to 10 **aliases** (`email_aliases`, the `person_emails` table: `email_norm` unique across the roster, `source` `manual` / `chat_tool` / `roster_request`, deleted with the person or when they are archived, so an archived person never blocks the address). An alias matches their mail and may be emailed, but **is never a login**: `find_person_by_email` stays primary-only and is what web sign-in and `/auth/allowed-emails` read; mail goes through `find_person_by_address` (primary or alias, case-insensitive, the team row winning over a contact) and `people.identity.resolve_email_sender`. Aliases are edited on the person's page (\"Other addresses\") and by `upsert_person`'s `email_aliases` (the full list, replacing the current one); an address that is already someone else's primary or alias is refused (`AddressInUseError`, a 409 on the API), and so is a new primary that is someone's alias. Onboarding still imports no addresses beyond the owner's own sign-in email, and an alias counts as taken there too.\n\nOn top of exact matches, `resolve_email_sender` applies a **company-domain rule, team only**: on one of the company's own domains an address's local part (lowercased, `+tag` dropped) matches a teammate whose own address on any company domain has that local part — `[email protected]` is the Anna whose address is `[email protected]`. A domain alone proves nothing: an unknown local part on the company domain matches nobody (it becomes a roster request, pre-filled as a teammate), and when two teammates would match, nobody does. The company's domains are the `company_domains` workspace setting (Settings → Workspace, `PUT /workspace`, at most 10), or, when that is unset, the domains of the principal's own addresses — never a free-mail provider's (`identity.FREEMAIL_DOMAINS`: gmail.com, outlook.com and the like, refused as a setting too), where a local part says nothing about who someone is. The outbound gates build `RosterAllow` from the same rule, so the Executive may email exactly the addresses inbound mail would match (see Integrations).\n\n### New senders: roster requests\nWhen someone not on the roster — and not one of the principal's contacts — writes in (an email address, a Slack or Discord user, a private verified Telegram chat), their message is held as a **roster request** (`people.roster_requests`: tables `roster_requests`, `roster_request_messages`, `roster_ack_log`) instead of being dropped; they get a fixed acknowledgement (an email sender only when Gmail authenticated them — see Integrations) and the principal gets a private card on `/today`, which says whether they were actually told (`surface_card(acknowledged=...)`, from `ack_sent_at` after the acknowledgement is attempted) and, for a chat or company-domain sender, a prompt on their delivery channel (the per-channel mechanics are in Integrations). A request holds at most 10 messages (later ones only count), is one per `(channel, sender)` while pending, and suggests a match only from a chat account whose profile email is already someone's (never from a display name, which the sender chooses) — and `suggested_kind = team` for an address (or a chat profile email) on a company domain.\n\nThe principal answers one of three ways, all ending in `roster_requests.resolve` (a claim on the row, so two answers race and one wins; nothing is written unless it succeeds):\n\n- **approve** — add them as a new Person with this address or chat id, `team` or `contact`;\n- **link** — they are someone already on the list writing from somewhere new: an email becomes that person's alias — never their primary, even if they had none, so a link never creates a login, a chat id fills that person's field (replacing a different one only when the principal says so; otherwise `ChannelIdConflict`);\n- **decline** — leave them off; they are not raised again for 30 days.\n\nOnly the principal answers, and only where they are verified: the **web card** (`POST /people/requests/{id}/approve|decline`, which requires an explicit team/contact choice), their **own Slack or Discord DM or verified private Telegram chat** (the `resolve_roster_request` chat tool, which answers only ids the server showed that turn in its `<roster_requests>` block — see Agents), or an **email reply from their own primary address** (not an alias) carrying the request's one-time token, which the gateway hides from every other read of the Executive's mailbox so no model turn can copy it. When the chat or email answer does not say team or contact, the default is team for a sender on a company domain, else contact — the least access. Whoever answers, the held messages are then replayed as if the sender had been on the roster all along (a new contact gets only held email, on the private contact path); a decline drops them. A roster write outside a request — the People page (`POST`/`PATCH /people`) or `upsert_person` — reconciles too: any pending request whose sender now matches someone closes as `superseded` and replays.\n\nUnanswered requests expire after `ROSTER_REQUEST_TTL_DAYS` (14). A held message's text is kept only until the request is resolved or expires (then purged, even on decline), its card, routes and audit rows are private to the principal (404 for anyone else), and the tables are wiped with the rest of the People data on a company swap or fixture load.\n",+ "markdown": "The org model has two persistent registries backed by SQLite (both share `episodic_memory.db`): **departments** and **people**. A new install starts with **no departments**: nothing is created at boot. Setup's commit creates only the departments its draft names (none for a solo workspace or a team that names none), and the Executive's `create_goal` tool creates one when a goal names an area that has none. A department named after one of the eight catalogue areas in `departments/charters` (Strategy, Finance, People & Talent, Legal, Operations, Marketing, Product, Board & Investor Comms) starts from that area's charter, and setup and `create_goal` wire it to the matching specialist (at most one department per specialist). Workspaces created before this keep the departments they have. `seed_default_departments` still inserts the full catalogue once per database (tracked by a `default_departments_seeded` sentinel in `departments_meta`), but only tests and tooling call it.\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 5 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. Until a profile exists the owner (the principal)\nis sent to `/onboard` from Home and every shell page except Settings, unless\nthey chose \"I'll do this later\"; after the save and the voice step a last\nscreen shows what was kept and the two accounts worth connecting (the\nExecutive's own mailbox, and the owner's own for Act as me), and Home's\nbanner slot carries a getting-started checklist (profile, first question,\nthe two mailboxes, the team) until every required row is done or it is hidden\n(`ui/src/lib/firstRun.ts`).\n\nTwo properties matter here. First, **the interview never writes the profile**:\nthe exchange lives in a TTL'd session (2 h, 50 at most) that the API process\nholds and also writes through to the `onboarding_interviews` table of the\nepisodic SQLite database after every turn (`onboarding/interview_store.py`),\nso a restart or another worker finds it again (a newer stored row replaces\na held copy, so two workers never overwrite each other) and the browser,\nwhich keeps only the session id, resumes at the same question or draft via\n`GET /onboard/interview/{id}`. A session answers only to the caller who\nstarted it; anyone else gets the 404 an unknown id gets. The single profile write happens at\n`POST /onboard/interview/commit`, so a rejected save leaves the draft editable\nand retryable, and a successful one deletes the stored transcript at once (it\ncarries the company's financials). 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 departments the workspace already\nhas, with their goals and `specialist_key` wiring, on a re-run of setup. A\ndrafted department that matches nothing is created, wired to the specialist\nwhose area it is named after (`specialist_key_for_area`) unless another\ndepartment already has that specialist. Matching goes through\n`departments.store.match_department` (slug as given or as the store would slug\nit, else case-insensitive title), the same rule the `create_goal` chat tool uses. `profile.org_structure` is derived from the reviewed\npeople and department tables at commit time, so it cannot drift from them.\n\nExactly one person is marked `is_principal` and receives `WILDCARD` authority;\nno contact details are imported, even if the user volunteers them, because\nchannels and handles are a deliberate action on the People page. The one\nexception is the owner's own sign-in email: the review screen has a separate\nfield for it, pre-filled with the current owner's email on a re-run and with the\nsigned-in user's on a first setup. The commit checks it before writing anything\n(malformed, already another person's — as their address or one of their\naliases — 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. One case is adopted rather than rejected: when the address is\nthe one the caller signed in with and sits on the current principal's row\nunder another name (a hosted sign-up seeds that row from the address when no\nname was given), `adopt_owner_row` renames that row to the drafted name\nbefore the roster upsert, so the first save updates the owner's entry instead\nof failing with \"use the owner's name exactly as on the People page\". 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 or SSO sign-in) the field is optional: that\nsession carries no email, which the backend already reads as the principal.\nBecause the save demotes the old principal, only the current owner may draft\nsomeone else as \"This is me\" when setup is re-run (403 otherwise); a re-run\nthat keeps the owner, or a first setup, is open to anyone who can sign in. On such a re-run, someone who isn't the owner may fill in the owner's missing email only with the address they signed in with (403 otherwise): the roster is the sign-in allow-list, so any other address would let them sign in as the owner. That keeps the way in for an owner whose entry has no email, which is also where Setup status and the Executive send them, since the People page refuses anyone it can't recognise as the owner. Re-running setup stays open to everyone deliberately: the Company Profile and Departments pages already let anyone signed in change the same things. The original\n12-step form wizard remains available at `/onboard?mode=form` and backs the\n`openexecutive onboard` CLI. It adds people with their emails, so once there is an owner only they can save it.\n\nA first setup opens on one free-text box: the user describes their work in their own words, optionally attaching a one-pager. `POST /onboard/interview/understand` reads that text once (no session, nothing stored) and reports what it already says: Personal or Team, the principal's role (owner / founder, an executive inside an organisation, independent or fractional, or other), title, who they report to, the company and this year's focus. The next screen shows those for a quick confirm, with Personal / Team as the one required answer; confirming writes `PUT /workspace` (mode, the browser's time zone and, for Personal, the role) and then starts the interview with the same text, so it asks only about what is still missing, at most five questions. If the read fails the text is kept and the user simply picks. A re-run over an existing profile skips these steps; they are changed in Settings. The tone question comes last, after the draft is saved. In solo the interviewer's first user turn carries a short\nhint, one static constant per role kind (`onboarding.interview.solo_hint`):\nalways draft only the principal, as principal, and no departments; an owner is\nasked about the offer, customers, pricing, cash and runway; an in-house\nexecutive about their organisation (the company profile is their employer),\ntheir function and remit, their manager, their team size as context rather\nthan a roster, and what they are measured on; an independent about their\npractice, clients and pricing; with no role given, the role-neutral hint asks\nwhich of these they are. Each also asks their top goals. The hint never\ncarries the principal's own text, and it rides in the user turn, so the cached\nsystem prompt is the same constant in both modes. The solo review screen shows only **You**\n(name and role) and the sign-in email, and commits that one principal with no\ndepartments — the existing departments stay, as the areas goals are grouped\nby. The form wizard (and the CLI) read the mode when a session starts and skip\nthe Team Size, Team Members and Fractional Executives steps in solo; each\nstatus response numbers the steps it actually asks and flags whether the\ncurrent one is `optional`.\n\n### Departments\nEach department carries a charter, `Goal` rows, `ChecklistItem`s, and named cadences. Cadence specs (`daily@HH:MM`, `weekly@DOW@HH:MM`, `quarterly@DD-HH:MM`, UTC) run a `department_check_in` workflow when due (never in solo mode, below), then chain the next occurrence. A new department starts with `check_in: weekly@mon@09:00` (`DEFAULT_CHECK_IN_CADENCE`; it was daily, and departments created before keep theirs). An empty spec turns the check-in off. `PATCH /departments/{slug}` rejects a spec that does not parse with a 422, and a changed `check_in` re-times the department at once (`cadence.reschedule_check_in` cancels the pending check-in and queues the next one on the new schedule, or none when it is off). The department page offers Daily / Weekly (day and time) / Off rather than the raw spec, and shows the next check-in from `next_check_in_at`. The check-in is skipped (and still chained) when the department has no specialist, no Goals, or nothing new since its Goals were last reviewed (a row private to the principal does not count as new: whether it runs is visible to the department). An idle initiative is chased with the department's head, or with the principal when there is none. A department may map to a specialist agent via `specialist_key`, or stay informational. No department is seeded for the `sales` specialist (existing installs keep their departments unchanged), so its consults skip the department-memory prefetch and the Honcho department sync, as `triage`'s do. An assigned head gets a generated department-head voice persona.\n\n**Goals from chat.** Besides the goal routes and the UI, the Executive keeps goals current from a chat turn: `update_department_goal` records reported progress, and `create_goal` starts tracking a new goal the principal states (\"20 paying clients by the end of Q4\"). Only the principal, on a surface that verified it is them (`people_tools.is_principal_on_verified_surface`, the roster tools' rule: the web chat, their own Slack or Discord, a private Telegram chat with a valid webhook secret), may call it: a goal renders in every turn's org block as one of the principal's own, so a goal from an inbound email, Google Chat, a teammate or an unattended run would be text carrying their authority. Anyone else gets a refusal (audited with the caller and surface) and nothing is written. `create_goal` names the area as free text — a slug or a title, resolved by `match_department` — so its schema is static and adding an area never changes the cached tool prefix. When nothing matches it creates the area (`create_department`), giving it a specialist only when the title is obviously one's domain (`specialist_key_for_area`: the default departments' slugs and titles, plus Sales) and no department holds that specialist yet; anything else is informational. It refuses a goal the area already tracks (pointing at `update_department_goal`), caps a turn at 5 new goals (a sweep is not a stated goal) and an area at 8 (common practice keeps 3–5 key results per objective, and every goal renders in the 4000-character org block, so one area cannot crowd the others out), returns only the exception type on a store failure, is audited with its rationale, and is never offered to an unattended run (`schedule_tools.UNATTENDED_WITHHELD_TOOLS`: reflection, research and the scheduler's proactive trigger). The solo persona teaches it; team mode learns it from the tool description, so the team persona stays byte-identical.\n\nA department can also list **watched entities** (`watched_entities`, edited one per line on its page): vendors it is evaluating, competitors in its lane, tickers it tracks. The research watch policy treats them as strong grounding — a proposal about one can be added to the watch list on its own — and routes the resulting watch, its alerts and any suggestion cards to the department and its head rather than the principal (see External monitoring).\n\n### Solo and team mode\nAn install is either a **team** (the default) or **solo** — one person using Open Executive just for themselves. The mode lives with the user's time zone in its own one-row table, `workspace_settings` (`openexecutive.memory.workspace_settings`, `GET`/`PUT /workspace`), not on the company profile, because onboarding's commit and the form wizard rebuild the profile from scratch and would wipe it. Changing it is the principal's call (open while no principal exists, so first-run setup can choose).\n\nThe same row holds the **principal's role** (`PrincipalRole`, every field nullable): `role_kind` (`owner`, `in_house`, `independent` or `other`), `role_title`, `reports_to` (free text, e.g. \"VP of Operations, Dana Ruiz\"), `remit` (what they are responsible for) and `measured_on` (what they are judged on). Solo is about who uses Open Executive, not the principal's level — a business owner, an executive inside a larger organisation, an independent or fractional executive — and this is the context the solo persona reads the role from. Only solo mode reads it; a mode switch keeps it. `GET /workspace` returns it only to the principal (nulls for anyone else). The columns are added to an existing table additively, and a read of an older table (no role columns yet) never migrates it and reads the role as unset.\n\nSolo also changes how the Executive speaks and what it can do. It works for one person — the principal — without assuming their role (an owner, an executive inside a larger organisation, or an independent); the people in their world are contacts it helps them work with, not a team it routes to. The cached org block becomes the principal's own line (\"Your Principal\") — followed by their role lines when a role is set (a fixed lead-in marking the role private to the principal — use it to tailor advice and drafts, share it with no one else — then `- Role: <title> — <kind in plain words>`, `- Reports to:`, `- Responsible for:`, `- Measured on:`, each only when set, sanitized and capped) — plus their goals grouped by **area** (a department row is an area; no authority levels, heads, cadences, channels or roster), and posting to a department room, broadcasting to the company and assigning a department head are not offered. Specialists never see that block, so each consult in a solo turn also carries a `<principal_role>` tag in its user turn (kind, title and remit). The role is pinned on the session for the turn with the mode (`pin_turn_principal_role`), so the org block, the tag and any workflow the turn starts agree even if the role is edited mid-turn, so a VP inside a large company is told to make the case to their CFO rather than to raise a round. A follow-up the Executive schedules to the principal goes straight to them — its department and scope are dropped, so the authority gate never files a card asking the principal to approve a message to themselves. Meeting bookings are gated on the `meeting_scheduling` class mode, not a department (see below).\n\nSolo turns the department rhythm off without touching the org: switching to solo cancels every pending `dept_cadence` row, `bootstrap_cadences` does nothing (the check sits inside it, so boot, the fixture reset and client-slot activation all honour it), and the scheduler cancels any stray check-in without running or chaining it, and a check-in already running across the switch schedules no successor. Department and people rows are kept, so switching back to team re-schedules the check-ins at once. The boot-time org-completeness warnings (departments with no head) are skipped in solo. A chat `Session` can carry an explicit `workspace_mode` override (read through `effective_workspace_mode`), so a caller that runs many conversations on one Executive — evals, for one — can pick the mode per session instead of flipping the install-wide setting; a `principal_role` override (read through `effective_principal_role`: the override, then the turn's pin, then the setting) does the same for the role.\n\nIn the UI, a `WorkspaceProvider` in the root layout reads the mode and role once (and again after Settings changes them) and reads **team** while loading or on error, so a team install never flashes the solo UI. Solo swaps the sidebar's Company group for **You** — Goals, People and the profile — where `/goals` lists every goal grouped by area (a department row) and adds, edits and deletes them through the slug-scoped goal routes. Team mode lists Goals in the Company group too, after Departments, and the page says \"department\" instead of \"area\". Adding a goal asks only for the goal itself: the timeframe is a one-click chip (this quarter by default, filled with the current period's label), target and current are optional, and a new goal starts `on_track` until the check-in grades it. The profile entry follows the principal's role kind: **Business profile** for an owner, **Your work** for anyone else, including an unset role or one `GET /workspace` hides from a non-principal. One rule (`profileWording(mode, roleKind)` in `navConfig.ts`) also words the `/company-profile` breadcrumb, intro and section headings, the form wizard and the draft review; it is copy only, so no profile field is renamed, and team wording is unchanged. `/departments` and `/people` stay reachable by URL.\n\nThe setting is per company: a blank client slot starts on the defaults, a saved slot keeps its own (restoring one runs the additive column migration), a fixture load resets it and applies the fixture's optional `workspace.yaml` (`mode`, `timezone` and the optional role keys; read and validated before anything is swapped; a bad value is skipped, never a failed load; the load and unload responses report the mode and zone only, never the role), and the factory reset returns it to team with no zone and no role. The user's own settings survive a demo: the backup a fixture load takes (or reuses) always gets the live settings written to its `workspace.yaml` while the live state is the user's, and an unload from an older backup without one leaves the settings as they are. A zone that cannot be loaded is never fatal — the API answers 422, and a stored one reads as unset.\n\n### Authority gate\nEach department declares an `AuthorityLevel`, which `departments.authority.gate_action` checks whenever a department-scoped scheduled action comes due. The check-in cadence is the exception: it sends nothing itself, and each action it proposes is run through the gate and shown with its verdict in the report — so a propose-only department's check-ins actually run instead of becoming a one-shot approval card. `auto_execute` (autonomous) fires directly. `propose_only` turns the action into an approval card for an approver (`propose_via_alert`) and sends nothing, deferring the card to the approver's next availability window when they are outside it. `escalate` also sends nothing until someone approves: it raises an urgent `[ESCALATION]` card (severity high) right away, never deferred — filed unrouted when nobody holds the scope and no principal is set, since the Briefing lists every unread card — what the Departments page promises (\"the specialist will not act — it forwards everything to a human\"). It used to raise the card *and* dispatch, so approving the card sent the action a second time. Calendar bookings follow the same rule in team mode. In solo mode there is no operations department to consult: the booking is decided by the `meeting_scheduling` class mode — `propose` puts it on the briefing for whoever holds the **Meetings** approval range on People (`meeting_scheduling`), else the principal — a booking with a contact on it always stays the principal's — and `auto_execute` books right away only when the principal started the turn on a surface that verified it is them (the roster-write rule: the web chat, their own Slack or Discord, or a private Telegram chat with the webhook secret set). A booking asked for in an inbound email, by a contact, or by an unattended run is proposed to the principal instead, so text someone else wrote cannot put a meeting on their calendar. The principal sets it with `GET`/`PUT /decisions/classes/meeting_scheduling` (`{\"decision_class\": \"meeting_scheduling\", \"mode\": \"propose\" | \"auto_execute\"}`; the PUT is principal-only and audited). The approver is chosen by `AuthorityScope` — a scheduled action's `required_scope` (e.g. `vendor_onboarding`, `spend_lt_10k`) feeds `find_approvers(scope)`, which ranks non-principal scope-holders ahead of `WILDCARD` holders. A null/unknown scope falls back to `WILDCARD` (the principal).\n\n### People & channels\nThe people registry resolves each `Person` to a `(channel, channel_ref)` pair via `prefer_channel_for()`, honoring `preferred_channel` (falling back email → slack → discord → telegram) and availability windows. The principal briefs use their own order — the preferred channel, then Slack → Discord → Telegram, then email as the backup for every preference (first for an `email` one); see Scheduler. Departments can also set `slack_channel_id` / `discord_channel_id` / `telegram_chat_id` to broadcast to a team room instead of DMing the head.\n\nEach person's page also lists their **open loops** (see Attunement) — what they committed to or were asked for in conversation — with a *Mark done* action; archiving a person closes their open loops, since an archived person can no longer be chased. The list is the principal's or that person's only; `people.store.is_principal_or_self` is the one check behind it, the close action and reply feedback.\n\nThe Executive can change the roster from a chat turn (`upsert_person`, `archive_person`, `set_department_head`) only when the principal asks, from the web chat, their own Slack or Discord, or a private Telegram chat when `TELEGRAM_WEBHOOK_SECRET` is set to a value Telegram can send. A teammate, an email (even one from the principal's address), Google Chat, the CLI, the MCP server and unattended runs are refused, because a team member's People row is also the web sign-in allow-list, the outbound-email allow-list and approval routing. The People page follows the same rule: adding, editing and archiving people (`POST`/`PATCH /people`, `POST /people/{id}/archive`) are the principal's alone, or anyone's while no one is principal yet, so a first setup can add its owner (`chat._caller_is_principal_or_unclaimed`). Anyone else gets 403. That includes a teammate editing their own entry: its email and chat ids are how they sign in and how the Executive reaches them, and the rest decides their approvals and how they are chased. Their working style and open loops stay theirs. A signed-in owner whose email is on no People entry is refused too; they sign in with the email on their entry, or re-run the setup interview, which fills a missing one with the email they signed in with. The one roster change that can come from an email is the principal's tokened reply to a roster-request email, and the one a chat turn can make beyond these tools is `resolve_roster_request` — both below, both the principal's alone.\n\n### Each person's notifications\n\nEvery team member sets their own on Settings → Notifications (`GET`/`PUT /notifications/settings`, see API), stored one row per person in `person_notification_settings` (`people.notifications`): **quiet hours** (off by default; from–to in their zone, which may cross midnight; every day, or weekdays with the weekend quiet all day), **delivery** — *As they happen* (the default) or *In my briefs* — and **Let urgent things through** (on by default). No row means the defaults, which hold nothing back.\n\nThey apply only to the Executive's **own** outreach: a DM sent while a proactive source is tagged (`attunement.outcomes.tag_proactive` — the scheduler's nudge dispatch, the reflection, research findings, alert review). Replies in a conversation, a message someone asked for in chat, a follow-up someone scheduled (it was asked for at a time), the briefs themselves and reminders a person set are never held. Quiet hours are deliberately not part of the outbound guard's availability check, which runs on every DM — the brief included — and would refuse a brief scheduled inside the person's own quiet hours.\n\nTwo places apply them. **Nudge routing** asks `people.channel` with `quiet_hours=True` (`is_within_availability`, `next_window_for`, `prefer_channel_for`, `next_available_window`), so the nudge engine and the scheduler's `proactive_nudge` re-check defer a nudge to the end of quiet hours exactly as they defer to an availability window — nothing is written at 3am. **Every other proactive DM** meets `outbound_guard.check_hold` in the send handlers once the anti-spam guard has allowed it: if the recipient is in quiet hours, or chose *In my briefs*, the text is stored in `held_messages` (`people.held_messages`) and the tool returns `{\"status\": \"held\"}`; `message_person` stops there instead of trying another channel; alert review counts a route as made but not a nudge toward its cap, and holds no second nudge about an alert while one waits. If it can't be stored it is sent. A scheduler dispatch whose message was held is audited as `held`, not `delivered`. Quiet-hours rows go out when quiet hours end, as one *While you were away* message (see Scheduler); brief rows ride the principal's next morning brief or end-of-day digest as one *While you were away* block, and anyone else's go out on their own when those briefs run, since only the principal has a brief. Switching back to *As they happen* releases what waited. Whoever sends a row claims it first, so a brief and a release pass never both send it. Someone on leave or outside their availability windows is postponed to when that ends; any other failed delivery backs off (2, 4, 8 … minutes, at most an hour). Rows are capped at 50 per person and dropped after 7 days undelivered, each drop audited privately to the person as a count; a brief row with no brief to carry it for 36 hours goes on its own.\n\n**Urgent** messages — approval nudges (`nudge_stalled`) and alert-review DMs about a critical (`urgent`-severity) alert (`notifications.urgent_send`) — get through when the person lets urgent things through. A workflow approval question (`gate_delivery`, `notifications.approval_send`) is never held, whatever the setting, since only a reply to it resolves the gate. If quiet hours cover every availability window, a nudge falls back to the next window rather than being dropped. Not covered: nudges on the email channel (the MCP mail tool bypasses the send handlers, so routing defers them for quiet hours but they are never held for a brief), department channel broadcasts, and the alert dispatcher's own channels (the web stream, a self-addressed email, and a Slack DM that is still a stub). Department check-ins send no DM: what they propose becomes approval cards.\n\n### Team and contacts\nA `Person` is either on the **team** (`kind = \"team\"`, the default) or a **contact** (`kind = \"contact\"`): a client, contractor or advisor the Executive may need to email or invite but who must not get what a team row grants. Before contacts existed, emailing a client meant adding them as a Person, which also let them sign in and talk to the bot.\n\nContacts are **denied by default**. `people.store.list_people`, every `find_person_by_*` (and `find_person_by_channel_ref`), and the `people.registry` cache return team members only unless the caller passes `include_contacts=True`; `find_approvers` has no opt-in at all. So a contact is never in the web sign-in list (`GET /auth/allowed-emails`), the Slack / Telegram / Discord inbound gates, approvers, the alert review's roster slice, `/today`'s people list and insights, open-loop owners (an ask of a contact opens no loop, so the nudge engine never chases them), a workflow gate's approver or cadence recipient, the recap DM after a meeting, or a department head (`set_department_head` and `PATCH /departments/{slug}` refuse one). `get_person(id)` returns either kind and its security-relevant callers check `kind`.\n\nThe roster reads that **opt in** are few: the Executive's egress checks (Gmail, Calendar and Drive in the MCP gateway, calendar attendee resolution, and the chat DM tools), the People page's listing (`GET /people?include_contacts=true`), the chat `list_people` tool (both kinds, with `kind`), the org prompt block, and the roster-request intake (which looks a sender up with contacts included only to leave a contact out). Even there, reaching a contact needs **the principal's own turn**: `people_tools.contacts_reachable_now()` is true only on a turn the principal started on a surface that verified them — the same rule as roster writes above — or inside `grant_contact_egress()`, which the decisions approve route uses when the approver resolves to the principal. An inbound email (even from the principal's address), a teammate's turn, and unattended runs (scheduler, workflows, alert review) can still reach the team but not contacts. A workflow resumed by `apply_resolution`'s kick runs with no chat session, like the resumer's poll loop, so it never inherits the approver's turn.\n\n**Contacts are private to the principal.** A solo user may be an executive whose contacts include their boss, reports, board and clients, so nobody else using the install sees one. The rule is `contacts_reachable_now()` again: off the principal's own verified turn a contact does not exist — `list_people` returns the team with the same count, a contact's id or address gets exactly the error an unknown one gets (never a contact-specific refusal), and the org prompt block has no Contacts section. The API applies the same rule by caller (`people.caller_is_principal`: the signed-in email is the principal's, or no `x-caller-email` — CLI, local login; unlike the owner rule above, nobody is while no one is principal yet): `?include_contacts=true` is ignored for anyone else, a contact's id is a 404 on `GET /people/{id}` and its open loops exactly like a missing one (editing and archiving are already a 403 before any lookup), only the principal may create a contact or turn someone into one (403, a first setup with no principal included), and `GET /people/me` tells the UI whether to offer contacts at all.\n\nWhatever the Executive raises about a contact stays with the principal too. A meeting with a contact is proposed to the principal (not the scope's approver), its decision is hidden from everyone else's `/decisions` (404 by id), and its card carries `alerts.models.PRIVATE_ALERT_TAG`. So does an alert raised on a turn about the principal's private mail (`Session.private_to_principal`, set by the email poller for mail from a contact and for mail the principal forwards): the pipeline routes it to the principal, stores it without a live push or broadcast, and dedups it only against other private alerts. Private alerts appear on the principal's own `/today` and chat digest only — never a teammate's, the activity rail, the narrative, the morning brief, the end-of-day digest, the reflection or the alert review — and a teammate's ack, reopen or bulk sweep cannot touch one (404). A private turn itself reaches the principal and nobody else (email, DMs, invites). It is not offered, and cannot run, the tools that post to other people, publish where the team reads (artifacts, goal updates, saved workflows, skill drafts) or start work outside the turn (`schedule_tools.PRIVATE_TURN_WITHHELD_TOOLS`), and of the MCP tools it may use only Google Workspace reads and the Gmail send the gateway narrows to the principal. Its audit rows are the principal's alone, as is any row on the principal's own turn that names one of their contacts (see Audit Log). DMs to a contact stay off the activity rail.\n\n`upsert_person` takes `kind`: explicit wins; an update that omits it keeps the row's kind (the store's full-row UPDATE preserves it, so nothing promotes a contact to the team by accident); a new person defaults to `team`, or to `contact` in solo mode. On the principal's own verified turn the org prompt block lists contacts in a short `## Contacts` section after the team block (or, in solo, after `## Your Principal` and their goals) — name, role/company and whether an email is on file, capped at 25 — in both modes. Every other turn gets the team block, byte-identical to an install with no contacts, so the 5-minute cached block has two stable variants.\n\nOn the **People page** the principal sees **Team** and **Contacts** tabs; anyone else sees the team only (no Contacts tab, no kind selector). Solo mode opens on Contacts, and its Team tab shows only the principal. The add form has a kind selector and hides authority scopes, reply SLA and the principal checkbox for a contact; a contact's page hides scopes, SLA, availability windows, open loops, outreach and working style. Adding a team member in solo offers to switch the workspace to team mode, or keep solo.\n\n### Addresses: aliases and company domains\nA `Person` has one **primary** address (`email`) — the one they sign in with — and up to 10 **aliases** (`email_aliases`, the `person_emails` table: `email_norm` unique across the roster, `source` `manual` / `chat_tool` / `roster_request`, deleted with the person or when they are archived, so an archived person never blocks the address). An alias matches their mail and may be emailed, but **is never a login**: `find_person_by_email` stays primary-only and is what web sign-in and `/auth/allowed-emails` read; mail goes through `find_person_by_address` (primary or alias, case-insensitive, the team row winning over a contact) and `people.identity.resolve_email_sender`. Aliases are edited on the person's page (\"Other addresses\") and by `upsert_person`'s `email_aliases` (the full list, replacing the current one); an address that is already someone else's primary or alias is refused (`AddressInUseError`, a 409 on the API), and so is a new primary that is someone's alias. Onboarding still imports no addresses beyond the owner's own sign-in email, and an alias counts as taken there too.\n\nOn top of exact matches, `resolve_email_sender` applies a **company-domain rule, team only**: on one of the company's own domains an address's local part (lowercased, `+tag` dropped) matches a teammate whose own address on any company domain has that local part — `[email protected]` is the Anna whose address is `[email protected]`. A domain alone proves nothing: an unknown local part on the company domain matches nobody (it becomes a roster request, pre-filled as a teammate), and when two teammates would match, nobody does. The company's domains are the `company_domains` workspace setting (Settings → Workspace, `PUT /workspace`, at most 10), or, when that is unset, the domains of the principal's own addresses — never a free-mail provider's (`identity.FREEMAIL_DOMAINS`: gmail.com, outlook.com and the like, refused as a setting too), where a local part says nothing about who someone is. The outbound gates build `RosterAllow` from the same rule, so the Executive may email exactly the addresses inbound mail would match (see Integrations).\n\n### New senders: roster requests\nWhen someone not on the roster — and not one of the principal's contacts — writes in (an email address, a Slack or Discord user, a private verified Telegram chat), their message is held as a **roster request** (`people.roster_requests`: tables `roster_requests`, `roster_request_messages`, `roster_ack_log`) instead of being dropped; they get a fixed acknowledgement (an email sender only when Gmail authenticated them — see Integrations) and the principal gets a private card on `/today`, which says whether they were actually told (`surface_card(acknowledged=...)`, from `ack_sent_at` after the acknowledgement is attempted) and, for a chat or company-domain sender, a prompt on their delivery channel (the per-channel mechanics are in Integrations). A request holds at most 10 messages (later ones only count), is one per `(channel, sender)` while pending, and suggests a match only from a chat account whose profile email is already someone's (never from a display name, which the sender chooses) — and `suggested_kind = team` for an address (or a chat profile email) on a company domain.\n\nThe principal answers one of three ways, all ending in `roster_requests.resolve` (a claim on the row, so two answers race and one wins; nothing is written unless it succeeds):\n\n- **approve** — add them as a new Person with this address or chat id, `team` or `contact`;\n- **link** — they are someone already on the list writing from somewhere new: an email becomes that person's alias — never their primary, even if they had none, so a link never creates a login, a chat id fills that person's field (replacing a different one only when the principal says so; otherwise `ChannelIdConflict`);\n- **decline** — leave them off; they are not raised again for 30 days.\n\nOnly the principal answers, and only where they are verified: the **web card** (`POST /people/requests/{id}/approve|decline`, which requires an explicit team/contact choice), their **own Slack or Discord DM or verified private Telegram chat** (the `resolve_roster_request` chat tool, which answers only ids the server showed that turn in its `<roster_requests>` block — see Agents), or an **email reply from their own primary address** (not an alias) carrying the request's one-time token, which the gateway hides from every other read of the Executive's mailbox so no model turn can copy it. When the chat or email answer does not say team or contact, the default is team for a sender on a company domain, else contact — the least access. Whoever answers, the held messages are then replayed as if the sender had been on the roster all along (a new contact gets only held email, on the private contact path); a decline drops them. A roster write outside a request — the People page (`POST`/`PATCH /people`) or `upsert_person` — reconciles too: any pending request whose sender now matches someone closes as `superseded` and replays.\n\nUnanswered requests expire after `ROSTER_REQUEST_TTL_DAYS` (14). A held message's text is kept only until the request is resolved or expires (then purged, even on decline), its card, routes and audit rows are private to the principal (404 for anyone else), and the tables are wiped with the rest of the People data on a company swap or fixture load.\n","mermaid": "flowchart TD\n People[\"People registry (Person, is_principal, kind)\"]\n Contacts[\"Contacts (kind = contact): egress only on the principal's turn\"]\n Req[\"Roster requests (new senders held for the 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 People -. include_contacts .-> Contacts\n Req -->|approve / link| People\n Dept -->|team room| Chan\n class People storage\n class Contacts storage\n class Req 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-10-13T18:00:00Z"+ "generated_at": "2026-10-13T20:00:00Z"}diff --git a/packages/core/openexecutive/architecture/prebuilt/scheduler.json b/packages/core/openexecutive/architecture/prebuilt/scheduler.jsonindex dcd955d7..7650f674 100644--- a/packages/core/openexecutive/architecture/prebuilt/scheduler.json+++ b/packages/core/openexecutive/architecture/prebuilt/scheduler.json@@ -1,7 +1,7 @@{"section_id": "scheduler","title": "Scheduler & Cadences",- "markdown": "The scheduler is an asyncio task started in the FastAPI lifespan (`openexecutive.scheduler.runner.run_scheduler`). It polls every 30s and reads due rows from `scheduled_actions` (in `episodic_memory.db`). The due query uses `claim_due_actions`, an UPDATE…RETURNING claim, so each row fires at most once per process — this assumes a single scheduler instance per database. Each due row runs in its own task, started with no audit scope (`audit.context.unscoped_audit_rows`): a scheduled action is unattended and never part of the turn that scheduled it, so its audit rows follow the ordinary rule. Polls are gated on an active company profile via `_company_profile_active()`; before onboarding, due rows stay `pending`.\n\n### Operator pause\n\nA global pause switch (`openexecutive.scheduler.pause`, one row in the `executive_control` table) stops everything the Executive starts on its own. It is the first check of every scheduler tick: while paused the tick does nothing — no alert/watchlist sweep, no claim — so due rows stay `pending` and fire on the first tick after resume. Actions already claimed when the pause lands run to completion; pausing holds work, it never cancels it. The same check gates the Gmail poller (the inbox is left unread) and the workflow resumer (no `wait_for_human` timeouts or resumes, and `apply_resolution` records a reply without kicking the run). Inbound conversations — web chat, Slack, Discord, Telegram, Google Chat — are deliberately not gated. The switch is set from the sidebar, the paused banner or Settings in the UI, or via `POST /executive/pause` / `POST /executive/resume`; each flip writes an `executive_paused` / `executive_resumed` audit row. Any signed-in caller may pause (it only holds work); resuming releases every held action at once, so it is the principal's alone (open only while no principal is on the roster). The state persists across restarts (boot logs a warning while paused) and across client-slot switches. `is_paused()` is read-only: a DB file or table that does not exist yet reads as \"running\", but a read error on an existing DB reads as \"paused\" — the brake fails closed, so a storage fault holds work rather than silently releasing it while the UI still shows \"paused\" (the UI shows \"status unknown\" when it cannot read the state).\n\n### Liveness heartbeat\n\nEvery tick ends by recording when it finished and what it did — `ran`, `paused`, `waiting_for_company`, `rotating`, or `failed` when the tick raised — and `run_scheduler` notes when it started. `scheduler_heartbeat()` returns both; they live in process memory, not the database. Settings → Setup status (`GET /setup/status`) reads them: no start means the task isn't running; no tick five minutes after starting, or none for three poll intervals (at least 90 s), means the loop has stopped; `failed` and `waiting_for_company` get their own light. Liveness is judged before the pause switch, because a paused scheduler still ticks: one that has stopped shows as stopped, where the Resume button wouldn't help. A restart clears the previous run's last tick. Due actions run as their own tasks, so a slow brief never ages the heartbeat.\n\n### Cadence DSL\n\n`openexecutive.departments.cadence` supports, all in UTC for department and workflow cadences:\n\n- `daily@HH:MM`\n- `weekly@DOW@HH:MM` or `weekly@DOW-HH:MM` (DOW is a 3-letter day, e.g. `weekly@thu@09:00`)\n- `quarterly@DD-HH:MM`\n\n`PATCH /departments/{slug}` rejects a spec that does not parse (bad format, unknown DOW, out-of-range time) with a 422 naming the valid formats, so a typo is caught at save time instead of silently never firing. An empty spec means no cadence (the department page's **Off**). A new department starts weekly, `weekly@mon@09:00`. Changing a department's `check_in` through that route re-times it at once: `cadence.reschedule_check_in()` cancels its pending `dept_cadence` row and queues the next occurrence of the new spec (nothing when it is off or in solo); a check-in already running finishes, and its chain adds nothing because the new row is pending.\n\nWhen a department cadence is due, the runner invokes the `department_check_in` workflow and chains the following occurrence via `cadence.enqueue_next()`. The fire is not passed through the authority gate: the check-in sends nothing (it grades Goals, writes one audit row and a Honcho note), and every action it proposes carries its own `gate_action` verdict in the report. Before creating a run the runner applies a skip rule (`department_check_in.needs_check_in`): the check-in is skipped when the department has no specialist agent, has no Goals, or nothing is new since its Goals were last reviewed — no decision or audit row tagged to the department (the check-in's own review row aside) since the oldest Goal's `last_reviewed_at`, and no Goal edited after it was graded. A Goal never reviewed always runs it. A skip leaves no run in the activity rail, is recorded as `cancelled` with its reason (`skipped: …` in `last_error`) rather than `done` — a done cadence row means \"the check-in ran\" to the nudge engine — and still chains the next occurrence; so does a check-in that fails once its retries are spent, so one broken department does not fall out of its cycle. Chaining is idempotent: while a next occurrence for the department is already pending nothing is added, so a row that chained and then failed to record its outcome never leaves two. Seeded departments start with no Goals, so their weekly check-ins cost nothing until someone adds one. Deleting a department cancels its pending `dept_cadence` rows, and `cancel_orphaned_cadences()` sweeps orphans on boot.\n\nIn **solo mode** (one person using Open Executive just for themselves; see Org) there are no department check-ins: `bootstrap_cadences()` is a no-op, switching to solo cancels every pending `dept_cadence` row, a row that was already pending is marked `cancelled` by the runner without running and without chaining — ahead of the authority gate, so a `propose_only` department cannot turn it into an approval card, and cancelled rather than done because the nudge engine reads a done check-in as a recent department pulse — and a check-in already running across the switch finishes without `enqueue_next` scheduling another. Switching back to team re-bootstraps them. Solo has one kind of its own, the **weekly review** (`principal_weekly_review`, below): switching to solo seeds it (`seed_weekly_review`), switching to team cancels its pending row (`cancel_weekly_reviews`), and one that fires while the stored mode is team is marked `cancelled` without running or chaining. That check reads the mode strictly (`workspace_settings.read_stored_mode`) and fails open: a mode that can't be read (a locked database) is not taken for team, so one bad read neither retires the review nor breaks its chain — the next run checks again.\n\nThe parser also takes a zone: `_parse_cadence_spec(spec, after, tz=UTC)` builds the wall-clock time in `tz` and only then converts to UTC, so a local schedule stays at the same local time across daylight-saving changes (a time the spring-forward gap skips fires once, just after the jump; a time the fall-back repeats fires at its first occurrence).\n\n### The principal's rhythm\n\nThe morning brief (`principal_brief_morning`, 08:00), end-of-day digest (`principal_brief_eod`, 18:00) and reflection (`executive_reflection`, 07:30) are seeded once per database by `seed_principal_briefs()` and each chains its next occurrence when it fires. In a solo workspace it also seeds the **weekly review** (`principal_weekly_review`, Friday 16:00 local by default), which runs the `weekly_review` workflow and is delivered like the briefs; its `PRINCIPAL_WEEKLY_REVIEW_TIME` takes a whole weekly spec (`weekly@fri@16:00`), read as UTC when valid, like the pinned times below, and it chains only while the workspace is still solo — and never when a weekly row is already pending, so a switch to solo while a review finishes cannot leave two. Their default times are local to the user's zone — `memory.workspace_settings.get_user_timezone()`: the zone set through `PUT /workspace`, else `USER_TIMEZONE`, else UTC — computed with the cadence parser above. An operator who pinned a valid `HH:MM` in `PRINCIPAL_BRIEF_MORNING_TIME` / `PRINCIPAL_BRIEF_EOD_TIME` / `PRINCIPAL_REFLECTION_TIME` keeps that time read as UTC, as before zones existed, so a pinned time never moves; a malformed value is logged and treated as unset. An install that set `USER_TIMEZONE` but pinned nothing does move to that zone, from each kind's first fire after the upgrade (a row seeded before it keeps its old UTC time once). When the zone in effect changes, `reschedule_principal_rhythm()` re-times each kind's pending, not-yet-due row **in place** — it only updates `run_at` (guarded on the row being unchanged since it was read), never inserts or cancels, so it cannot race a chain into a duplicate. The new time is the next occurrence in the new zone after `max(now, last fired run + 12h)`, so a kind never runs twice within 12 hours; and if that is more than 12 hours later than the row's current time — moving would skip a day, as when someone switches to Europe/London at 07:59 UTC with the 08:00 UTC brief a minute away — the row keeps its time once. A kind with no such row is left alone: a row that is running, one between being marked done and its chain insert, or a due row held by a pause or a missing company profile. Its chain times the next one in the new zone, and the chain itself starts from `max(now, fired run + 12h)`, so a zone change while a brief runs cannot put a second brief a few hours after it. The weekly review follows the same rules with a 3.5-day gap (`_min_gap`) in place of 12 hours, so a zone change can neither run it twice in a week nor skip one.\n\nUser-created (dynamic) workflows can carry the same cadence DSL. A cadence-enabled definition enqueues a `dynamic_workflow` action (`workflows.dynamic_cadence`); when due, the runner runs the stored `DynamicWorkflow`, DMs the artifact to the definition's `cadence_person_id`, and re-chains the next occurrence. Saving/updating/deleting the definition reconciles its pending `dynamic_workflow` rows. A cadence definition may not contain an approval gate — a cron fire has no human to ask — with one exception, the **held-writes** pause: when an action step holds a write to a new target, the runner checkpoints the run (`checkpoint_gate`, the owner is DMed), still marks the row done and re-chains the cadence, and stamps `deliver_to_person_id` on the resume payload so the resumer DMs the artifact to the cadence recipient once the owner answers (or the 48 h timeout skips the held writes). Any other gate is still refused at execution: it calls `workflows.gate.ensure_workflow_event`, which raises on a gate so the run is recorded as failed. It previously ignored the gate and stored a completed run with `\"(no artifact)\"` as its body, which looked like a success every period.\n\n### Department authority & cancelling\n\nA department-scoped row passes the authority gate (`departments.authority.gate_action`, see Org) before it is dispatched: `auto_execute` dispatches; `propose_only` raises an approval card and marks the row done without dispatching (deferred to the approver's next availability window when they are outside it); `escalate` raises an urgent `[ESCALATION]` card (severity high) straight away — never deferred — and likewise does not dispatch, because approving the card is what sends it. As that card is the action's only trace it always lands: unrouted when there is no approver and no principal, and deduped on the whole action (kind, channel, recipient and intent) rather than the summary's first 60 characters, so another escalation sharing an opening — or the same text for someone else — cannot swallow it. An identical escalation folds into a still-open card and gets a fresh one once that card was handled, and a card that cannot be written retries the row with backoff and, once the retries are spent, marks it `failed` — never `done`. (It used to raise the card *and* dispatch.) A `dept_cadence` row is not gated at all — gating it turned every check-in on a propose-only department (all eight seeded ones) into a one-shot card, and the row never chained its next occurrence. Nudge-engine rows carry no department and bypass the gate.\n\nA `pending` row can be cancelled with `DELETE /scheduled/{id}` — the Pulse page's Cancel; the update only moves a row that is still `pending`, so one the scheduler has just claimed is never overwritten. Cancelling only stops work, so, like pause, any signed-in user may: the route accepts a signed-in caller through the UI proxy (its `x-caller-email`, trusted only alongside the `BACKEND_SHARED_SECRET` `x-api-key`), a matching `X-Admin-Token` (`SCHEDULED_ADMIN_TOKEN`, for scripts), or a loopback caller when no token is set — otherwise 401 (token set) or 503. Each cancel is audited as `scheduled_action_cancelled` with who did it.\n\n### Channel routing & nudges\n\nThe delivery channel lives on the `scheduled_actions` row (`channel` / `channel_ref`); the runner dispatches through whichever was set at enqueue time — `telegram`, `slack_dm`, `discord_dm`, `email`, or `__internal__` (workflow steps and heartbeats bypass outbound dispatch). Rows left pending by the removed staff-onboarding kinds drain through that same `__internal__` short-circuit (marked done, no dispatch); the removed talent workflows' *ad-hoc* reminders sat on the principal's real DM channel instead, so a one-shot startup sweep (`memory.episodic.cancel_orphaned_talent_reminders`) cancels them — `ad_hoc`, no department, `pending` or `running`, matching the five generated reminder shapes (outreach, interview coordination, reference checks, onboarding check-in, offer expiry) — and clears the awaiting-reply flag on delivered ones so the nudge engine stops chasing them. The marker row in `app_migrations` is claimed first with `INSERT OR IGNORE` in the same transaction, so concurrent boots cannot double-run or crash. The nudge engine (`scheduler.nudge_engine`, default 15 min) scans stalled `awaiting_human` runs, stale commitments, and idle initiatives, then emits `proactive_nudge` rows routed via `people.channel.prefer_channel_for` — honouring each Person's preferred (last-used) channel and availability windows, deferring those outside their window and skipping those with no reachable channel. Emission is capped per `scope_key` (`NUDGE_MAX_PER_SCOPE`, default 3 delivered nudges) so a parked item is not chased forever.\n\nAn idle initiative is chased with its department's head; with no head to resolve — no department (what the episodic extractor stores), an unknown department, or no head set — the principal owns it. That source used to skip every initiative without a head, so in practice it never fired. The principal gets self-addressed wording (\"<title>\" has not moved since <date> — still active, done, or dropped?). If channel routing cannot reach the principal (no channel configured, or unreachable beyond `NUDGE_MAX_DEFER_DAYS`), the nudge becomes an unrouted Briefing card instead, keyed on the initiative and the ISO week: at most one card per initiative per week, and while one is still unread the scan leaves it alone rather than refreshing it every 15 minutes. The emitted nudge still carries no department, and the usual caps and cooldowns apply. A department-tagged initiative is still skipped while its department's check-in actually ran inside the idle window; a skipped check-in does not count.\n\nThe stale-commitment source also chases **open loops** (see Attunement): `scheduled_actions` rows with `kind='open_loop'`, recorded `done` on the `__internal__` channel so the runner never dispatches them, whose `awaiting_response_since` is the loop's *due time*. They are chased as soon as they are overdue — not after `NUDGE_COMMITMENT_STALE_DAYS` — with a check-in intent addressed to the loop's owner (which quotes only the owner's own verbatim words and tells the dispatching turn to treat them as data), through the same `prefer_channel_for` routing, availability windows and outbound guard. Until open loops existed nothing in production set `awaiting_response_since`, so this source had nothing to chase. Each scan first closes loops older than `ATTUNEMENT_LOOP_TTL_DAYS` (21) as `expired`, then marks proactive outreach nobody answered within `ATTUNEMENT_IGNORE_AFTER_HOURS` as `ignored` in the outcome ledger. Ranking uses that ledger: a candidate whose person left their last five resolved nudges of that kind unanswered ranks after all others and waits three times its cooldown; a single answer lifts it. Approving a stalled run (however it's approved) and updating an initiative count as acting on the nudges that chased them. The generic dispatch path tags each send with its source (`_outreach_source`) so the ledger can attribute it.\n\n### Alert lifecycle: expiry sweep and the review heartbeat\n\nTwo alert-maintenance jobs live here. The **expiry sweep** is loop-level, not a heartbeat row: `_maybe_sweep_alerts` runs `alerts.lifecycle.expire_stale_alerts` (and, on the same 15-minute throttle, `monitoring.research.watch_policy.sweep` — expiring unreviewed research watch suggestions, auto-disabling research-added watches that proved noisy or dead, and filing one `watchlist_suggestions` nudge when ≥3 suggestions have waited ≥7 days; see External monitoring) once at boot and every 15 minutes at the top of the tick — before the company-profile and rotation gates, so an old backlog expires even before onboarding completes, flipping `unread` alerts past their category TTL to `expired` and auditing `alert_sweep`. Pure DB hygiene, no model call, reversible via `POST /alerts/{id}/reopen`. The same throttled call also deletes Always in the loop notes past their expiry (`memory.history.sweep_expired`; reads already skip them, and it never raises). Each tick also calls `_maybe_remind_notes` → `memory.history_reminders.maybe_remind` (its own 15-minute throttle, 09:00–18:00 local, one task at a time): a person whose notes say something they promised by email is due today gets one message saying how many, through `deliver_to_person` — the brief's own channel order for any Person, never a shared channel (`delivery_order` now skips a Telegram group id, for the briefs too), with the senders' audit rows private to that person. A hook rather than a `scheduled_actions` row, which `/scheduled` would show to everyone (see Memory).\n\nThe **Executive alert review** is a real heartbeat — kind `alert_review_scan`, `__internal__` channel, bootstrapped idempotently at startup when `ALERT_REVIEW_ENABLED` and chained every `ALERT_REVIEW_INTERVAL_HOURS` (6) with the same crash-resilient run → mark-done → chain shape as `nudge_scan`. `_run_principal_brief` also runs a `pre_brief` pass right before the morning brief (a review failure never blocks the brief). Each pass re-examines open alerts with evidence and, within department authority and the privacy rule, routes, nudges, escalates, drafts, merges or resolves them — see the Today section for the policy. The moves go through the real handlers (`message_person`, `draft_artifact`), so the outbound anti-spam guard applies, and `ALERT_REVIEW_MAX_MOVES_PER_SCAN` bounds side effects per pass.\n\nThe /today **\"What's going on\" header** is kept current from the tick too, so it is fresh before anyone opens the page. `_maybe_refresh_narrative` is a throttled call inside the loop, like the alert sweep — no `scheduled_actions` row. It runs after the pause, company-profile and rotation gates, every `BRIEFING_NARRATIVE_REFRESH_MINUTES` (10; 0 turns it off) and only between `BRIEFING_NARRATIVE_REFRESH_START_HOUR` and `_END_HOUR` (06–22) in the user's zone. It starts `today.refresh_principal_narrative` as its own task, so a slow model call never holds the tick, and never starts a second while one runs. That refreshes the cached calendar read (`live_signals.refresh_calendar`, at most once per 15 minutes) and rewrites the principal's header only when its key moved — new mail, a held reply, a proposal, the hour — with the route's own per-scope lock, so a page view and the tick never write the same header twice (see Today).\n\nAct as me's **reminders** are loop-level too: `_maybe_send_reminders` starts `delegation.reminders.maybe_send` at most once a minute, which claims each due `delegation_reminders` row once (due times are stored in UTC, so they compare in order) (compare-and-set on `claimed_at`) and sends its stored text, prefixed \"Reminder you set on <date>:\", to the person who set it alone through `deliver_to_person`. No model and no tool run; a reminder missed by more than two days is dropped rather than sent late, and one due in the person's quiet hours or leave waits, unclaimed, until they end; audit rows are private to the person. They are not `scheduled_actions` rows for the same reason as the scan below: that list is everyone's, and its rows run an Executive turn when they fire.\n\nAct as me's **inbox watcher** is loop-level the same way: `_maybe_scan_inbox`, after the same gates, starts the due scans (`delegation.inbox.maybe_scan`) as one task and never a second while one runs. A person is due every `DELEGATION_INBOX_POLL_MINUTES` (default 5) once their **Draft replies to my inbox** switch is on, unless a Gmail failure set a back-off; nobody is scanned while a client slot is active. It is deliberately not a `scheduled_actions` row: those are listed on `/scheduled` for everyone and anyone may cancel them, and a scan reads the owner's own mail. Every row a scan writes is private to the principal (see Act as Me).\n\n### Principal briefs\n\nThe `principal_brief_morning` / `principal_brief_eod` / `principal_weekly_review` rows (and the client-rotation digest) are delivered by `_deliver_to_principal`, not through a row channel. The principal's `preferred_channel` (`slack` / `discord` / `telegram` / `email` / `any`) is tried first, then the other chat channels they have an id for (Slack → Discord → Telegram). Email goes through the active MCP gateway: first when the preference is `email`, and otherwise last, as the backup after every chat channel. Before planning, the delivery asks the gateway supervisor for a start if the gateway is down (`runner.ensure_email_ready` → `mcp_gateway.ensure_active_gateway`, the lazy re-check), and a row action resolves the gateway at execution time rather than from what boot had, so a gateway that failed at boot and came up on a retry carries the brief. The outcome names what happened: `gateway_down` when email is set up but the gateway is not running (the Executive's fault, with the start failure, never `no_channel`, which blamed the owner's setup), and a `send_failed` detail that quotes each channel's own error (`email: invalid_grant …`, `slack_dm: channel_not_found`), stored with the outcome (`brief_state.record_delivery_outcome(detail=…)`) and shown on the Briefing notice and the Setup page's *Daily brief* light, whose fix says to reconnect when the detail shows a dead grant. Delivery stops at the first channel that sends, so an owner linked by email at setup keeps their Slack delivery without extra email, and gets the brief by email only when Slack is missing or fails. The email is formatted HTML (`utils.markdown_email`: raw HTML and images off, unsafe link schemes dropped) with a subject dated in the user's zone (\"Morning Brief — Fri 25 Sep\"). Email counts as ready only when the MCP gateway runs the Google Workspace server. Every run's outcome — delivered, no owner, nowhere to send it, every send failed, or the brief couldn't be written at all (the workflow failed or produced nothing) — is recorded with the channel's name (never an address) under `brief_state`, for the Briefing's notice and the Setup status \"Daily brief\" light (the weekly review's outcome too — `brief_state.DELIVERY_KINDS` — so a weekly review that wasn't sent is reported the same way). The light also turns amber when a brief got through only on a backup channel, naming the one that failed. `_run_principal_brief` sets `morning_brief.PRINCIPAL_DELIVERY` for the run, because it goes to the principal alone: only then (or on the principal's own verified chat turn) does the morning brief read what is private to them. When the workflow reports `private_to_principal` on its `result` event — it did read such a row — the run history keeps `persistence.PRIVATE_RUN_ARTIFACT` in place of the text (`stored_artifact`), since `/workflows/runs` is readable by everyone signed in; the principal gets the full text where it is delivered. When no channel can deliver at all (a web-only principal, or email with no gateway), the brief is still generated and stored as a run with its artifact — a web-only principal reads it on the Artifacts page — it is just not delivered, and the next occurrence is chained; see Workflows.\n\n## Client rotation claim pause\n\nThe `client_rotation` kind (multi-client practice mode, opt-in via `CLIENT_ROTATION_ENABLED`) adds one loop-level behavior: while a rotation's `.rotation_in_progress` marker exists, the scheduler **skips claiming entirely** for that tick. Rotation switches the live company context between parked clients; claiming during the window would fire the just-activated client's overdue outbound follow-ups from a context nobody is watching. Everything due fires on the first tick after the original client is restored. Stale markers (crash mid-rotation) are reconciled at scheduler startup, and the rotation row is idempotently re-seeded both at boot and after every slot activation (scheduled rows swap with the client). See the Client Companies section for the rotation's full design.\n\nAn optional `notion_sync_scan` heartbeat (`NOTION_SYNC_ENABLED`, off by default) incrementally re-indexes Notion pages the workspace integration can see into the isolated `notion_wiki` collection (not COMPANY), reconciles un-shared pages, then chains the next tick. An optional `drive_sync_scan` heartbeat (`DRIVE_SYNC_ENABLED`, off by default, bootstrapped in the lifespan beside it) does the same for the configured Google Drive folders, into the isolated `drive_docs` collection (see RAG). An optional `onedrive_sync_scan` heartbeat (`ONEDRIVE_SYNC_ENABLED`, off by default) does the same for the configured OneDrive folders, into `onedrive_docs`. An optional `confluence_sync_scan` heartbeat (`CONFLUENCE_SYNC_ENABLED`, off by default, bootstrapped in the lifespan the same way) re-indexes the changed pages of the configured Confluence spaces into the isolated `confluence_wiki` collection, leaving out restricted pages, and purges pages that were deleted, moved out or restricted.\n\n**Take the lead wakes.** With Take the lead as the Executive on, a turn from a channel (mail, Slack, Discord, Telegram, Google Chat) calls `take_the_lead.wake`, which inserts one `take_the_lead_wake` `__internal__` action five minutes out. It does nothing while one is pending or running, and nothing within 30 minutes of the last wake. The runner's `_run_take_the_lead_wake` runs the same reflection as the daily rhythm (`_reflect`, shared with `_run_executive_reflection`), only if the switch is still on, and never chains. The pause holds it like every claim.",+ "markdown": "The scheduler is an asyncio task started in the FastAPI lifespan (`openexecutive.scheduler.runner.run_scheduler`). It polls every 30s and reads due rows from `scheduled_actions` (in `episodic_memory.db`). The due query uses `claim_due_actions`, an UPDATE…RETURNING claim, so each row fires at most once per process — this assumes a single scheduler instance per database. Each due row runs in its own task, started with no audit scope (`audit.context.unscoped_audit_rows`): a scheduled action is unattended and never part of the turn that scheduled it, so its audit rows follow the ordinary rule. Polls are gated on an active company profile via `_company_profile_active()`; before onboarding, due rows stay `pending`.\n\n### Operator pause\n\nA global pause switch (`openexecutive.scheduler.pause`, one row in the `executive_control` table) stops everything the Executive starts on its own. It is the first check of every scheduler tick: while paused the tick does nothing — no alert/watchlist sweep, no claim — so due rows stay `pending` and fire on the first tick after resume. Actions already claimed when the pause lands run to completion; pausing holds work, it never cancels it. The same check gates the Gmail poller (the inbox is left unread) and the workflow resumer (no `wait_for_human` timeouts or resumes, and `apply_resolution` records a reply without kicking the run). Inbound conversations — web chat, Slack, Discord, Telegram, Google Chat — are deliberately not gated. The switch is set from the sidebar, the paused banner or Settings in the UI, or via `POST /executive/pause` / `POST /executive/resume`; each flip writes an `executive_paused` / `executive_resumed` audit row. Any signed-in caller may pause (it only holds work); resuming releases every held action at once, so it is the principal's alone (open only while no principal is on the roster). The state persists across restarts (boot logs a warning while paused) and across client-slot switches. `is_paused()` is read-only: a DB file or table that does not exist yet reads as \"running\", but a read error on an existing DB reads as \"paused\" — the brake fails closed, so a storage fault holds work rather than silently releasing it while the UI still shows \"paused\" (the UI shows \"status unknown\" when it cannot read the state).\n\n### Liveness heartbeat\n\nEvery tick ends by recording when it finished and what it did — `ran`, `paused`, `waiting_for_company`, `rotating`, or `failed` when the tick raised — and `run_scheduler` notes when it started. `scheduler_heartbeat()` returns both; they live in process memory, not the database. Settings → Setup status (`GET /setup/status`) reads them: no start means the task isn't running; no tick five minutes after starting, or none for three poll intervals (at least 90 s), means the loop has stopped; `failed` and `waiting_for_company` get their own light. Liveness is judged before the pause switch, because a paused scheduler still ticks: one that has stopped shows as stopped, where the Resume button wouldn't help. A restart clears the previous run's last tick. Due actions run as their own tasks, so a slow brief never ages the heartbeat.\n\n### Cadence DSL\n\n`openexecutive.departments.cadence` supports, all in UTC for department and workflow cadences:\n\n- `daily@HH:MM`\n- `weekly@DOW@HH:MM` or `weekly@DOW-HH:MM` (DOW is a 3-letter day, e.g. `weekly@thu@09:00`)\n- `quarterly@DD-HH:MM`\n\n`PATCH /departments/{slug}` rejects a spec that does not parse (bad format, unknown DOW, out-of-range time) with a 422 naming the valid formats, so a typo is caught at save time instead of silently never firing. An empty spec means no cadence (the department page's **Off**). A new department starts weekly, `weekly@mon@09:00`. Changing a department's `check_in` through that route re-times it at once: `cadence.reschedule_check_in()` cancels its pending `dept_cadence` row and queues the next occurrence of the new spec (nothing when it is off or in solo); a check-in already running finishes, and its chain adds nothing because the new row is pending.\n\nWhen a department cadence is due, the runner invokes the `department_check_in` workflow and chains the following occurrence via `cadence.enqueue_next()`. The fire is not passed through the authority gate: the check-in sends nothing (it grades Goals, writes one audit row and a Honcho note), and every action it proposes carries its own `gate_action` verdict in the report. Before creating a run the runner applies a skip rule (`department_check_in.needs_check_in`): the check-in is skipped when the department has no specialist agent, has no Goals, or nothing is new since its Goals were last reviewed — no decision or audit row tagged to the department (the check-in's own review row aside) since the oldest Goal's `last_reviewed_at`, and no Goal edited after it was graded. A Goal never reviewed always runs it. A skip leaves no run in the activity rail, is recorded as `cancelled` with its reason (`skipped: …` in `last_error`) rather than `done` — a done cadence row means \"the check-in ran\" to the nudge engine — and still chains the next occurrence; so does a check-in that fails once its retries are spent, so one broken department does not fall out of its cycle. Chaining is idempotent: while a next occurrence for the department is already pending nothing is added, so a row that chained and then failed to record its outcome never leaves two. Seeded departments start with no Goals, so their weekly check-ins cost nothing until someone adds one. Deleting a department cancels its pending `dept_cadence` rows, and `cancel_orphaned_cadences()` sweeps orphans on boot.\n\nIn **solo mode** (one person using Open Executive just for themselves; see Org) there are no department check-ins: `bootstrap_cadences()` is a no-op, switching to solo cancels every pending `dept_cadence` row, a row that was already pending is marked `cancelled` by the runner without running and without chaining — ahead of the authority gate, so a `propose_only` department cannot turn it into an approval card, and cancelled rather than done because the nudge engine reads a done check-in as a recent department pulse — and a check-in already running across the switch finishes without `enqueue_next` scheduling another. Switching back to team re-bootstraps them. Solo has one kind of its own, the **weekly review** (`principal_weekly_review`, below): switching to solo seeds it (`seed_weekly_review`), switching to team cancels its pending row (`cancel_weekly_reviews`), and one that fires while the stored mode is team is marked `cancelled` without running or chaining. That check reads the mode strictly (`workspace_settings.read_stored_mode`) and fails open: a mode that can't be read (a locked database) is not taken for team, so one bad read neither retires the review nor breaks its chain — the next run checks again.\n\nThe parser also takes a zone: `_parse_cadence_spec(spec, after, tz=UTC)` builds the wall-clock time in `tz` and only then converts to UTC, so a local schedule stays at the same local time across daylight-saving changes (a time the spring-forward gap skips fires once, just after the jump; a time the fall-back repeats fires at its first occurrence).\n\n### The principal's rhythm\n\nThe morning brief (`principal_brief_morning`, 08:00), end-of-day digest (`principal_brief_eod`, 18:00) and reflection (`executive_reflection`, 07:30) are seeded once per database by `seed_principal_briefs()` and each chains its next occurrence when it fires. In a solo workspace it also seeds the **weekly review** (`principal_weekly_review`, Friday 16:00 local by default), which runs the `weekly_review` workflow and is delivered like the briefs; its `PRINCIPAL_WEEKLY_REVIEW_TIME` takes a whole weekly spec (`weekly@fri@16:00`), read as UTC when valid, like the pinned times below, and it chains only while the workspace is still solo — and never when a weekly row is already pending, so a switch to solo while a review finishes cannot leave two. Their default times are local to the user's zone — `memory.workspace_settings.get_user_timezone()`: the zone set through `PUT /workspace`, else `USER_TIMEZONE`, else UTC — computed with the cadence parser above. An operator who pinned a valid `HH:MM` in `PRINCIPAL_BRIEF_MORNING_TIME` / `PRINCIPAL_BRIEF_EOD_TIME` / `PRINCIPAL_REFLECTION_TIME` keeps that time read as UTC, as before zones existed, so a pinned time never moves; a malformed value is logged and treated as unset. An install that set `USER_TIMEZONE` but pinned nothing does move to that zone, from each kind's first fire after the upgrade (a row seeded before it keeps its old UTC time once). When the zone in effect changes, `reschedule_principal_rhythm()` re-times each kind's pending, not-yet-due row **in place** — it only updates `run_at` (guarded on the row being unchanged since it was read), never inserts or cancels, so it cannot race a chain into a duplicate. The new time is the next occurrence in the new zone after `max(now, last fired run + 12h)`, so a kind never runs twice within 12 hours; and if that is more than 12 hours later than the row's current time — moving would skip a day, as when someone switches to Europe/London at 07:59 UTC with the 08:00 UTC brief a minute away — the row keeps its time once. A kind with no such row is left alone: a row that is running, one between being marked done and its chain insert, or a due row held by a pause or a missing company profile. Its chain times the next one in the new zone, and the chain itself starts from `max(now, fired run + 12h)`, so a zone change while a brief runs cannot put a second brief a few hours after it. The weekly review follows the same rules with a 3.5-day gap (`_min_gap`) in place of 12 hours, so a zone change can neither run it twice in a week nor skip one.\n\nUser-created (dynamic) workflows can carry the same cadence DSL. A cadence-enabled definition enqueues a `dynamic_workflow` action (`workflows.dynamic_cadence`); when due, the runner runs the stored `DynamicWorkflow`, DMs the artifact to the definition's `cadence_person_id`, and re-chains the next occurrence. Saving/updating/deleting the definition reconciles its pending `dynamic_workflow` rows. A cadence definition may not contain an approval gate — a cron fire has no human to ask — with one exception, the **held-writes** pause: when an action step holds a write to a new target, the runner checkpoints the run (`checkpoint_gate`, the owner is DMed), still marks the row done and re-chains the cadence, and stamps `deliver_to_person_id` on the resume payload so the resumer DMs the artifact to the cadence recipient once the owner answers (or the 48 h timeout skips the held writes). Any other gate is still refused at execution: it calls `workflows.gate.ensure_workflow_event`, which raises on a gate so the run is recorded as failed. It previously ignored the gate and stored a completed run with `\"(no artifact)\"` as its body, which looked like a success every period.\n\n### Department authority & cancelling\n\nA department-scoped row passes the authority gate (`departments.authority.gate_action`, see Org) before it is dispatched: `auto_execute` dispatches; `propose_only` raises an approval card and marks the row done without dispatching (deferred to the approver's next availability window when they are outside it); `escalate` raises an urgent `[ESCALATION]` card (severity high) straight away — never deferred — and likewise does not dispatch, because approving the card is what sends it. As that card is the action's only trace it always lands: unrouted when there is no approver and no principal, and deduped on the whole action (kind, channel, recipient and intent) rather than the summary's first 60 characters, so another escalation sharing an opening — or the same text for someone else — cannot swallow it. An identical escalation folds into a still-open card and gets a fresh one once that card was handled, and a card that cannot be written retries the row with backoff and, once the retries are spent, marks it `failed` — never `done`. (It used to raise the card *and* dispatch.) A `dept_cadence` row is not gated at all — gating it turned every check-in on a propose-only department (all eight seeded ones) into a one-shot card, and the row never chained its next occurrence. Nudge-engine rows carry no department and bypass the gate.\n\nA `pending` row can be cancelled with `DELETE /scheduled/{id}` — the Pulse page's Cancel; the update only moves a row that is still `pending`, so one the scheduler has just claimed is never overwritten. Cancelling only stops work, so, like pause, any signed-in user may: the route accepts a signed-in caller through the UI proxy (its `x-caller-email`, trusted only alongside the `BACKEND_SHARED_SECRET` `x-api-key`), a matching `X-Admin-Token` (`SCHEDULED_ADMIN_TOKEN`, for scripts), or a loopback caller when no token is set — otherwise 401 (token set) or 503. Each cancel is audited as `scheduled_action_cancelled` with who did it.\n\n### Channel routing & nudges\n\nThe delivery channel lives on the `scheduled_actions` row (`channel` / `channel_ref`); the runner dispatches through whichever was set at enqueue time — `telegram`, `slack_dm`, `discord_dm`, `email`, or `__internal__` (workflow steps and heartbeats bypass outbound dispatch). Rows left pending by the removed staff-onboarding kinds drain through that same `__internal__` short-circuit (marked done, no dispatch); the removed talent workflows' *ad-hoc* reminders sat on the principal's real DM channel instead, so a one-shot startup sweep (`memory.episodic.cancel_orphaned_talent_reminders`) cancels them — `ad_hoc`, no department, `pending` or `running`, matching the five generated reminder shapes (outreach, interview coordination, reference checks, onboarding check-in, offer expiry) — and clears the awaiting-reply flag on delivered ones so the nudge engine stops chasing them. The marker row in `app_migrations` is claimed first with `INSERT OR IGNORE` in the same transaction, so concurrent boots cannot double-run or crash. The nudge engine (`scheduler.nudge_engine`, default 15 min) scans stalled `awaiting_human` runs, stale commitments, and idle initiatives, then emits `proactive_nudge` rows routed via `people.channel.prefer_channel_for` — honouring each Person's preferred (last-used) channel and availability windows, deferring those outside their window and skipping those with no reachable channel. Emission is capped per `scope_key` (`NUDGE_MAX_PER_SCOPE`, default 3 delivered nudges) so a parked item is not chased forever.\n\nAn idle initiative is chased with its department's head; with no head to resolve — no department (what the episodic extractor stores), an unknown department, or no head set — the principal owns it. That source used to skip every initiative without a head, so in practice it never fired. The principal gets self-addressed wording (\"<title>\" has not moved since <date> — still active, done, or dropped?). If channel routing cannot reach the principal (no channel configured, or unreachable beyond `NUDGE_MAX_DEFER_DAYS`), the nudge becomes an unrouted Briefing card instead, keyed on the initiative and the ISO week: at most one card per initiative per week, and while one is still unread the scan leaves it alone rather than refreshing it every 15 minutes. The emitted nudge still carries no department, and the usual caps and cooldowns apply. A department-tagged initiative is still skipped while its department's check-in actually ran inside the idle window; a skipped check-in does not count.\n\nThe stale-commitment source also chases **open loops** (see Attunement): `scheduled_actions` rows with `kind='open_loop'`, recorded `done` on the `__internal__` channel so the runner never dispatches them, whose `awaiting_response_since` is the loop's *due time*. They are chased as soon as they are overdue — not after `NUDGE_COMMITMENT_STALE_DAYS` — with a check-in intent addressed to the loop's owner (which quotes only the owner's own verbatim words and tells the dispatching turn to treat them as data), through the same `prefer_channel_for` routing, availability windows and outbound guard. Until open loops existed nothing in production set `awaiting_response_since`, so this source had nothing to chase. Each scan first closes loops older than `ATTUNEMENT_LOOP_TTL_DAYS` (21) as `expired`, then marks proactive outreach nobody answered within `ATTUNEMENT_IGNORE_AFTER_HOURS` as `ignored` in the outcome ledger. Ranking uses that ledger: a candidate whose person left their last five resolved nudges of that kind unanswered ranks after all others and waits three times its cooldown; a single answer lifts it. Approving a stalled run (however it's approved) and updating an initiative count as acting on the nudges that chased them. The generic dispatch path tags each send with its source (`_outreach_source`) so the ledger can attribute it.\n\n### Alert lifecycle: expiry sweep and the review heartbeat\n\nTwo alert-maintenance jobs live here. The **expiry sweep** is loop-level, not a heartbeat row: `_maybe_sweep_alerts` runs `alerts.lifecycle.expire_stale_alerts` (and, on the same 15-minute throttle, `monitoring.research.watch_policy.sweep` — expiring unreviewed research watch suggestions, auto-disabling research-added watches that proved noisy or dead, and filing one `watchlist_suggestions` nudge when ≥3 suggestions have waited ≥7 days; see External monitoring) once at boot and every 15 minutes at the top of the tick — before the company-profile and rotation gates, so an old backlog expires even before onboarding completes, flipping `unread` alerts past their category TTL to `expired` and auditing `alert_sweep`. Pure DB hygiene, no model call, reversible via `POST /alerts/{id}/reopen`. The same throttled call also deletes Always in the loop notes past their expiry (`memory.history.sweep_expired`; reads already skip them, and it never raises). Each tick also calls `_maybe_remind_notes` → `memory.history_reminders.maybe_remind` (its own 15-minute throttle, 09:00–18:00 local, one task at a time): a person whose notes say something they promised by email is due today gets one message saying how many, through `deliver_to_person` — the brief's own channel order for any Person, never a shared channel (`delivery_order` now skips a Telegram group id, for the briefs too), with the senders' audit rows private to that person. A hook rather than a `scheduled_actions` row, which `/scheduled` would show to everyone (see Memory).\n\nThe **Executive alert review** is a real heartbeat — kind `alert_review_scan`, `__internal__` channel, bootstrapped idempotently at startup when `ALERT_REVIEW_ENABLED` and chained every `ALERT_REVIEW_INTERVAL_HOURS` (6) with the same crash-resilient run → mark-done → chain shape as `nudge_scan`. `_run_principal_brief` also runs a `pre_brief` pass right before the morning brief (a review failure never blocks the brief). Each pass re-examines open alerts with evidence and, within department authority and the privacy rule, routes, nudges, escalates, drafts, merges or resolves them — see the Today section for the policy. The moves go through the real handlers (`message_person`, `draft_artifact`), so the outbound anti-spam guard applies, and `ALERT_REVIEW_MAX_MOVES_PER_SCAN` bounds side effects per pass.\n\nThe /today **\"What's going on\" header** is kept current from the tick too, so it is fresh before anyone opens the page. `_maybe_refresh_narrative` is a throttled call inside the loop, like the alert sweep — no `scheduled_actions` row. It runs after the pause, company-profile and rotation gates, every `BRIEFING_NARRATIVE_REFRESH_MINUTES` (10; 0 turns it off) and only between `BRIEFING_NARRATIVE_REFRESH_START_HOUR` and `_END_HOUR` (06–22) in the user's zone. It starts `today.refresh_principal_narrative` as its own task, so a slow model call never holds the tick, and never starts a second while one runs. That refreshes the cached calendar read (`live_signals.refresh_calendar`, at most once per 15 minutes) and rewrites the principal's header only when its key moved — new mail, a held reply, a proposal, the hour — with the route's own per-scope lock, so a page view and the tick never write the same header twice (see Today).\n\nAct as me's **reminders** are loop-level too: `_maybe_send_reminders` starts `delegation.reminders.maybe_send` at most once a minute, which claims each due `delegation_reminders` row once (due times are stored in UTC, so they compare in order) (compare-and-set on `claimed_at`) and sends its stored text, prefixed \"Reminder you set on <date>:\", to the person who set it alone through `deliver_to_person`. No model and no tool run; a reminder missed by more than two days is dropped rather than sent late, and one due in the person's quiet hours or leave waits, unclaimed, until they end; audit rows are private to the person. They are not `scheduled_actions` rows for the same reason as the scan below: that list is everyone's, and its rows run an Executive turn when they fire.\n\n**Held messages** are loop-level as well: `_maybe_release_held` starts `people.held_messages.maybe_release` at most once a minute, which sends each person whatever is due to them — messages held for their quiet hours once those end, and brief-held messages made due when the briefs run — as one *While you were away* message through `deliver_to_person`, claims each row first so a brief can't send it too, marks them sent only once that went, postpones a person back in quiet hours, on leave or outside their windows to when that ends, backs off 2, 4, 8 … minutes (at most an hour) after any other failure, and audits every drop (too old, over the cap) privately as a count, and writes audit rows private to the person. The principal-brief handler appends the principal's brief-held messages to the morning brief or end-of-day digest it delivers (`_with_held_messages`; the stored run artifact is unchanged), claims them, marks them sent only when the brief went (otherwise frees the claim), then makes everyone else's due (`_release_others_digests`). The `proactive_nudge` re-check calls `prefer_channel_for` / `next_available_window` with `quiet_hours=True` (urgent for a `nudge:stalled:` scope key), so a nudge due in the person's quiet hours is deferred to their end like one outside an availability window. A dispatch whose message was held is audited `held`, not `delivered`. See Org for the notification settings.\n\nAct as me's **inbox watcher** is loop-level the same way: `_maybe_scan_inbox`, after the same gates, starts the due scans (`delegation.inbox.maybe_scan`) as one task and never a second while one runs. A person is due every `DELEGATION_INBOX_POLL_MINUTES` (default 5) once their **Draft replies to my inbox** switch is on, unless a Gmail failure set a back-off; nobody is scanned while a client slot is active. It is deliberately not a `scheduled_actions` row: those are listed on `/scheduled` for everyone and anyone may cancel them, and a scan reads the owner's own mail. Every row a scan writes is private to the principal (see Act as Me).\n\n### Principal briefs\n\nThe `principal_brief_morning` / `principal_brief_eod` / `principal_weekly_review` rows (and the client-rotation digest) are delivered by `_deliver_to_principal`, not through a row channel. The principal's `preferred_channel` (`slack` / `discord` / `telegram` / `email` / `any`) is tried first, then the other chat channels they have an id for (Slack → Discord → Telegram). Email goes through the active MCP gateway: first when the preference is `email`, and otherwise last, as the backup after every chat channel. Before planning, the delivery asks the gateway supervisor for a start if the gateway is down (`runner.ensure_email_ready` → `mcp_gateway.ensure_active_gateway`, the lazy re-check), and a row action resolves the gateway at execution time rather than from what boot had, so a gateway that failed at boot and came up on a retry carries the brief. The outcome names what happened: `gateway_down` when email is set up but the gateway is not running (the Executive's fault, with the start failure, never `no_channel`, which blamed the owner's setup), and a `send_failed` detail that quotes each channel's own error (`email: invalid_grant …`, `slack_dm: channel_not_found`), stored with the outcome (`brief_state.record_delivery_outcome(detail=…)`) and shown on the Briefing notice and the Setup page's *Daily brief* light, whose fix says to reconnect when the detail shows a dead grant. Delivery stops at the first channel that sends, so an owner linked by email at setup keeps their Slack delivery without extra email, and gets the brief by email only when Slack is missing or fails. The email is formatted HTML (`utils.markdown_email`: raw HTML and images off, unsafe link schemes dropped) with a subject dated in the user's zone (\"Morning Brief — Fri 25 Sep\"). Email counts as ready only when the MCP gateway runs the Google Workspace server. Every run's outcome — delivered, no owner, nowhere to send it, every send failed, or the brief couldn't be written at all (the workflow failed or produced nothing) — is recorded with the channel's name (never an address) under `brief_state`, for the Briefing's notice and the Setup status \"Daily brief\" light (the weekly review's outcome too — `brief_state.DELIVERY_KINDS` — so a weekly review that wasn't sent is reported the same way). The light also turns amber when a brief got through only on a backup channel, naming the one that failed. `_run_principal_brief` sets `morning_brief.PRINCIPAL_DELIVERY` for the run, because it goes to the principal alone: only then (or on the principal's own verified chat turn) does the morning brief read what is private to them. When the workflow reports `private_to_principal` on its `result` event — it did read such a row — the run history keeps `persistence.PRIVATE_RUN_ARTIFACT` in place of the text (`stored_artifact`), since `/workflows/runs` is readable by everyone signed in; the principal gets the full text where it is delivered. When no channel can deliver at all (a web-only principal, or email with no gateway), the brief is still generated and stored as a run with its artifact — a web-only principal reads it on the Artifacts page — it is just not delivered, and the next occurrence is chained; see Workflows.\n\n## Client rotation claim pause\n\nThe `client_rotation` kind (multi-client practice mode, opt-in via `CLIENT_ROTATION_ENABLED`) adds one loop-level behavior: while a rotation's `.rotation_in_progress` marker exists, the scheduler **skips claiming entirely** for that tick. Rotation switches the live company context between parked clients; claiming during the window would fire the just-activated client's overdue outbound follow-ups from a context nobody is watching. Everything due fires on the first tick after the original client is restored. Stale markers (crash mid-rotation) are reconciled at scheduler startup, and the rotation row is idempotently re-seeded both at boot and after every slot activation (scheduled rows swap with the client). See the Client Companies section for the rotation's full design.\n\nAn optional `notion_sync_scan` heartbeat (`NOTION_SYNC_ENABLED`, off by default) incrementally re-indexes Notion pages the workspace integration can see into the isolated `notion_wiki` collection (not COMPANY), reconciles un-shared pages, then chains the next tick. An optional `drive_sync_scan` heartbeat (`DRIVE_SYNC_ENABLED`, off by default, bootstrapped in the lifespan beside it) does the same for the configured Google Drive folders, into the isolated `drive_docs` collection (see RAG). An optional `onedrive_sync_scan` heartbeat (`ONEDRIVE_SYNC_ENABLED`, off by default) does the same for the configured OneDrive folders, into `onedrive_docs`. An optional `confluence_sync_scan` heartbeat (`CONFLUENCE_SYNC_ENABLED`, off by default, bootstrapped in the lifespan the same way) re-indexes the changed pages of the configured Confluence spaces into the isolated `confluence_wiki` collection, leaving out restricted pages, and purges pages that were deleted, moved out or restricted.\n\n**Take the lead wakes.** With Take the lead as the Executive on, a turn from a channel (mail, Slack, Discord, Telegram, Google Chat) calls `take_the_lead.wake`, which inserts one `take_the_lead_wake` `__internal__` action five minutes out. It does nothing while one is pending or running, and nothing within 30 minutes of the last wake. The runner's `_run_take_the_lead_wake` runs the same reflection as the daily rhythm (`_reflect`, shared with `_run_executive_reflection`), only if the switch is still on, and never chains. The pause holds it like every claim.","mermaid": "flowchart TD\n Loop[\"run_scheduler<br/>poll every 30s\"]\n Pause{\"is_paused()?<br/>(executive_control)\"}\n Claim[\"claim_due_actions<br/>(status=pending, by kind)\"]\n Table[(\"scheduled_actions\")]\n Dispatch[\"dispatch via row channel<br/>(ad_hoc / proactive_nudge)\"]\n Dept[\"dept_cadence →<br/>department_check_in<br/>(skipped when nothing is new)\"]\n Solo[\"solo workspace →<br/>cancelled, no chain\"]\n Nudge[\"nudge_scan →<br/>nudge_engine scan\"]\n Brief[\"principal_brief_morning / _eod →<br/>morning_brief / end_of_day_digest<br/>(user's local time)\"]\n Weekly[\"principal_weekly_review (solo) →<br/>weekly_review, Fri 16:00 local\"]\n Reflect[\"executive_reflection →<br/>reflection (artifact only)\"]\n ExtMon[\"external_monitor_scan →<br/>monitoring pipeline\"]\n Research[\"watchlist_research_scan →<br/>executive_research (skip-if-unchanged)\"]\n Notion[\"notion_sync_scan →<br/>isolated wiki ingest\"]\n Drive[\"drive_sync_scan →<br/>isolated Drive folder ingest\"]\n Confluence[\"confluence_sync_scan →<br/>isolated Confluence space ingest\"]\n Chain[\"enqueue_next<br/>(re-arm recurring tick)\"]\n Prefer[\"prefer_channel_for<br/>(availability + last-used)\"]\n Channels[\"Slack / Discord<br/>Telegram / Email\"]\n Principal[\"DM or email principal\"]\n Alerts[\"alerts pipeline → /today\"]\n Loop --> Pause\n Pause -- \"paused: hold, sleep\" --> Loop\n Pause -- \"running\" --> Claim\n Claim -- \"claim due rows\" --> Table\n Claim -- \"ad_hoc / proactive_nudge\" --> Dispatch\n Claim -- \"dept_cadence\" --> Dept\n Claim -- \"dept_cadence (solo)\" --> Solo\n Claim -- \"nudge_scan\" --> Nudge\n Claim -- \"principal_brief_*\" --> Brief\n Claim -- \"principal_weekly_review\" --> Weekly\n Claim -- \"executive_reflection\" --> Reflect\n Claim -- \"external_monitor_scan\" --> ExtMon\n Claim -- \"watchlist_research_scan\" --> Research\n Claim -- \"notion_sync_scan\" --> Notion\n Claim -- \"drive_sync_scan\" --> Drive\n Claim -- \"confluence_sync_scan\" --> Confluence\n Nudge -- \"prefer_channel_for\" --> Prefer\n Prefer -- \"emits proactive_nudge\" --> Table\n Dispatch --> Channels\n Brief --> Principal\n Weekly --> Principal\n ExtMon --> Alerts\n Dept --> Chain\n Nudge --> Chain\n Brief --> Chain\n Weekly -- \"while solo\" --> Chain\n Reflect --> Chain\n ExtMon --> Chain\n Research --> Chain\n Notion --> Chain\n Drive --> Chain\n Confluence --> Chain\n Chain --> Table\n class Loop entry\n class Claim compute\n class Table storage\n class Dispatch compute\n class Dept compute\n class Solo compute\n class Nudge compute\n class Brief compute\n class Weekly compute\n class Reflect compute\n class ExtMon compute\n class Research compute\n class Notion compute\n class Drive compute\n class Confluence compute\n class Chain compute\n class Prefer compute\n class Channels external\n class Principal external\n class Alerts hot",- "generated_at": "2026-10-13T18:00:00Z"+ "generated_at": "2026-10-13T20:00:00Z"}diff --git a/packages/core/openexecutive/architecture/prebuilt/today.json b/packages/core/openexecutive/architecture/prebuilt/today.jsonindex de8703d9..e33bc3ea 100644--- a/packages/core/openexecutive/architecture/prebuilt/today.json+++ b/packages/core/openexecutive/architecture/prebuilt/today.json@@ -1,7 +1,7 @@{"section_id": "today","title": "Today / Morning Brief",- "markdown": "`openexecutive.api.routes.today` serves the morning brief — a one-screen, read-only view of what is happening across the org. It is the default landing surface (the Next.js root renders `<Briefing>`). Every signed-in page shares one sidebar (`AppSidebar`). Its Recent list is capped at the 7 newest web chats. The full history, including Slack, Telegram and Discord conversations (recognised by their session-id prefix), lives on `/chats`. A chat opens from any page through `/?session=<id>`.\n\n`GET /today` returns `TodayResponse` assembled by `_build_today()`, which is synchronous and caller-agnostic:\n\n- **`departments`** — per-department goal health, rolling up each department's goal counts (`total`, `at_risk`, `off_track`) plus its awaiting-workflow count, and `attention_goals`: the actual off-track/at-risk goals (worst first, capped at 3) with `key_result`, `current`, `target`, and `status`, so the briefing's Department card shows *which* goal is off and how far without a click. Empty for healthy/inactive departments.\n- **Private cards.** An alert tagged `private:principal` (`alerts.models.PRIVATE_ALERT_TAG` — raised on a turn about mail from one of the principal's contacts or mail they forwarded, or a meeting proposal with a contact) is in `proposals` only when the caller is the principal. `_build_today` leaves it out by default, so the end-of-day digest, the reflection and Discord's `/today` never see it, and the morning brief reads it only on a run for the principal (the scheduler's, or the principal's own verified chat turn in a conversation only they can read — see Workflows). The narrative is written from one only in the principal's own `principal` scope, which nobody else is served; the shared `company` scope an unresolved caller gets, and a teammate's scope, never are. The activity rail skips it, and the chat digest includes it only on the principal's own verified turn.\n- **Roster-request cards.** When someone not on the People list writes in (see Org and Integrations), `people.roster_requests.surface_card` raises an alert of source `roster_request` (medium, tagged `roster_request:<id>` and `private:principal`, routed to the principal), so it follows every private-card rule above. `GET /today` attaches `roster_request` to that proposal (`_roster_request_card`: channel, address or account id, the sender's sanitised and unverified name, profile email, company-domain flag, suggested kind and person, message count, whether they were acknowledged, first seen, and the held messages' first lines) while the request is still pending. The Briefing renders it as its own card (`RosterRequestCard`: add as a new person with a name and an explicit team/contact choice — pre-filled as team on a company domain — or \"someone already on the list\", with a replace-account option for a chat id, or Ignore), which calls `/people/requests/{id}` directly and never hands off to chat, so what a stranger wrote never seeds a turn. The card is kept out of everything that could close it without answering it or put the stranger's words in front of a model: the narrative (`_action_proposals` drops it), the chat's open-alert digest (`<briefing>` — the principal's verified turn gets a separate `<roster_requests>` block instead; see Agents), `ack_alert`, a single ack (`POST /alerts/{id}/ack` is a 409), the \"Dismiss N older than 7 days\" count and the server's bulk ack, reopen, the TTL sweep and the alert review (`roster_request` is in `lifecycle.TTL_EXEMPT_SOURCES`). It ends when the request does: answered (`ack`, or `dismissed` on a decline) or expired after `ROSTER_REQUEST_TTL_DAYS`.\n- **`people`** — an attention-ranked roster of the **team** (the principal's contacts are never listed, and get no insight note). Each person carries `awaiting_action` count, soonest SLA, a `status` (`on_leave` / `needs_reply` / `awaiting` / `clear`), reachability, `overdue`, a server `priority` sort key, and a cached one-line `insight`. Sorted by `(-priority, full_name)`. Stale insight notes are regenerated in the background only when the roster has more than one person: the UI shows the People sidebar only for more than one, so a one-person install (solo, or a team before anyone else is added) does not pay a daily model and peer-memory call for a note nobody sees. Cached notes are still served.\n- **`proposals`** — the *live* unread alerts (workflow approvals, triage-classified inbound, Executive signals, flagged artifacts, and gated calendar bookings; an artifact is listed only to its owner (`alerts.models.visible_alert`; every other build of the board — the briefs, the reflection, the review, the chat digest on anyone else's turn, the activity rail — leaves drafted artifacts out) and carries `artifact_format` / `artifact_url` and a `body` already rendered to Markdown for its format, so the card badges it as a web page, Word doc, spreadsheet or link and offers *Open artifact*): unread, inside their category TTL, not snoozed — see *Alert lifecycle* below. Each carries `score`, `category` (`action` vs `monitoring`), `surfaced_reason` from `openexecutive.briefing.ranking`, the lifecycle fields (`occurrence_count`, `last_seen_at`, `last_reviewed_at`, `review_verdict`, `review_note`, `recommended_move`, `why_now`, `due_at`, `superseded_count`, `suggested_workflow`), and `decision_instance_id` (set only when the proposal is backed by a decision-ledger row — a calendar booking awaiting approval). The UI splits them into 'mine' vs 'across the team' using `caller_person_id`. For decision-backed proposals the card's Approve/Reject call the `/decisions` endpoints (which book or cancel the event server-side and clear the alert) instead of the ack-and-hand-off-to-chat flow — so meeting bookings are reviewed in the briefing itself rather than on a separate page.\n- **`narrative`** — a per-viewer Executive-voice header (\"What's going on\") synthesized by `synthesize_briefing_narrative`, cached per scope in `briefing_narrative`: the resolved principal gets the whole-company `principal` scope (which may carry what is private to them), a caller who resolves to no roster row the shared `company` scope (written from what everyone may see), and each teammate a role-scoped `person:<id>` one. `narrative_generated_at` says when the served text was written and `narrative_stale` whether a fresher one is being written now. In the web UI each bullet of this narrative is a click target: clicking one hands off to chat (the same `onContinue` path as the proposal cards) seeded to discuss that item. The Executive recognizes it because every chat turn now carries a `<briefing>` digest of open alerts (see Memory). That digest (`briefing.context.format_open_alerts_for_prompt`) is capped at 30 items; when the board is longer the header says so explicitly and tells the Executive to point at this page for the rest — it previously presented the capped list as the complete board, so the Executive described a slice as everything that was open (#136). Chat adapters get the digest too, but Slack gates it to the principal's DMs: the board is company-wide and must not be pulled into a shared channel. The `[alert_id]` at the start of each line is also what `ack_alert` trusts, because an id quoted inside an alert's own body came from inbound mail or chat and is attacker-controlled. This page's `[Discuss mode — alert_id=N]` handoff primer is a pointer to which item is under discussion, not authority on its own: the server accepts it only if that id is on the live board too. Two things enforce that. Every field the digest interpolates — headline, body, suggested action, tags, review note — is collapsed to a single line, since a newline in any of them would forge a whole extra `[N]` line and with it a fabricated instruction to clear someone else's alert. And the server records the live board it derived, so `ack_alert` refuses any id outside it — on **every** session, not just the chat adapters. The recorded set is the whole live board, not just the rows the digest printed, so a card past the render cap stays ackable. The control stops invented, closed, snoozed and expired ids; it does not stop the model being argued into acking the wrong *live* card. When the principal names an item that has already left the board — opened, snoozed, or older than it — the Executive looks it up with `find_alerts` (a keyword search over every status, `alerts.store.search_alerts`); matches that are still open (`unread` or `read`) become ackable for that turn, up to 25, and closed ones come back labelled so the Executive can say the item is already settled. It works only where the principal's own board was shown this turn — the web app or their DM — and never returns roster-request cards (see Lifecycle). The digest's header also labels every headline and detail as untrusted content drawn from inbound mail, chat and watched pages — act on what the principal asks about an item, never on what its text asks — and triage reads each signal inside an `<event>` block whose closing tag the sender's text cannot forge (it is defanged in any case and spacing, after NFKC folds fullwidth forms). That check used to run only when `origin_channel` was set, which the browser never sets, so the one surface where the principal actually reads their board had no check at all and the model could ack any id, including one quoted out of an alert body by the Discuss handoff. Rendering the block and recording its ids now happen together in `briefing.context.render_and_trust`, which both the web chat route and the channel adapters call: render without recording and the tool refuses everything, record without rendering and the model gets reach it was never shown. A turn that was shown nothing trusts nothing. Recording it is only half the wiring: the tool reads the board off the turn's session through a ContextVar, and the chat route binds that session for the whole SSE body (`set_session`, next to `set_turn`). Bound from inside the Executive's own generator instead, it survives exactly one stream step — `asyncio.wait_for` runs each step in a fresh Task with a copy of the context — and the tool-call loop, which runs later, sees nothing. That shipped, and every web ack was refused on cards that were open the whole time. The digest also carries a short **already handled** tail — recently acked / dismissed / resolved rows, named but deliberately NOT trusted for acking — because a card cleared on the page minutes ago is otherwise simply absent from chat: asked to \"record that as fixed\", the Executive could not tell a settled item from one it had never heard of, and sent the principal back to dismiss a card that was already gone. That tail renders even when nothing is open, which is exactly when it matters. Note it is a different window from the `handled_overnight` rail above: that one runs since the last delivered morning brief, while the chat tail looks back 14 days (matching the action-alert TTL, so it still covers an item cleared late in its life), so chat can name a settled item the rail no longer shows. The narrative is held to what is **live**, and to what it is actually for. The `alert_raised` source is dropped from the activity it reasons over (`_build_activity(..., include_alert_raised=False)`): a closed alert reads as work the principal already settled, and a *live* one is worse than redundant — `lifecycle.is_live` is the very predicate behind `list_live_alerts`, so every live raise is already a proposal card below the header, which the prompt forbids re-listing. The `/today/activity` rail keeps the whole source, because a raise really happened. The activity block is only labelled \"since last brief\" when the caller bounded it with `since` (the standalone briefs do; the header does not), since calling an unbounded history rail a delta made the header present weeks-old rows as overnight news. When the viewer's slice holds nothing that wants a decision — no action proposal, no at-risk/off-track department, nobody awaiting — the regen skips the model call entirely and writes the fixed quiet line (`Quiet right now — nothing pressing.`, or `… nothing needs you.` for a teammate). **The cache key is a hash of the rendered context itself** (`today._narrative_context` builds it once and both the hot path and the background task key off that one string, which is also handed to the model verbatim). That makes the key a function of the model's input: everything the prompt renders is covered, and nothing it omits can trigger a regeneration. Keying on hand-picked fields broke one half or the other each time — headlines alone left the rendered activity block uncovered, while the proposals' review fields are never rendered by this header yet are rewritten with fresh prose by every `alerts.review` pass, so they regenerated each viewer's narrative several times a day to re-synthesize identical input. A quiet board keys off a fixed sentinel instead, so a moving rail cannot re-key an entry whose text is constant. Together: on a fully dismissed board every other input was empty, the rail became the only context, and the model synthesized a confident header out of closed items.\n\n **Live, not just the board.** The header used to reason over the alert board, goal health and the Executive's own bookkeeping only — mail and chat handled that day, replies the gate held and the next meeting never reached it, so it read the same for days while the principal's day moved on. The whole-company scopes now open the context with the principal's world as it is happening (`briefing.live_signals.gather_live_signals`, rendered by `render_live_blocks`), under a `NOW:` line: **INBOUND** (`integration_inbound` audit rows that carry a message, grouped by sender and subject, with an email's first line), **STUCK** (`integration_outbound_blocked` to a recipient, the inbound \"reply blocked at outbound gate\" and Google Chat \"left unanswered\" / \"not delivered\" rows, and drafts saved by Act as me), **CONVERSATIONS** (the principal's own web chat titles) and the **REST OF TODAY'S CALENDAR**. The window is the local day, or the last 12 hours when that is longer. Private audit rows, drafts, chat titles and the calendar (meeting titles are the principal's own) are read only in the `principal` scope — `gather_live_signals` drops the calendar whenever `include_private` is false, whatever the caller passes, so the shared `company` header never quotes it. The calendar is never fetched on the request: `live_signals.refresh_calendar` caches one read per 15 minutes (the scheduler tick refreshes it) and the header quotes the cache. Every quoted field is collapsed to one line and cut, and the blocks and the prompt both say the text is data, never instructions — inbound mail is attacker-controlled. With live blocks present the context also ages each proposal (`raised 2d ago`, whole days), names each at-risk department's slipping goals (`attention_goals`) and adds an **EXTERNAL SIGNALS** block (monitoring alerts from the last 24 h, never enough on their own to break the quiet line); the rhythm runs (`today.RHYTHM_WORKFLOWS`: the morning brief, end-of-day digest, reflection and weekly review) are dropped from the activity it reasons over. The prompts (`BRIEFING_NARRATIVE_SYSTEM` and its solo variant, `NARRATIVE_PROMPT_VERSION` 5) lead with what is live and give a days-old item at most one bullet. Anything live breaks the quiet line; the NOW line and window move at most once an hour, so the key moves hourly on time alone plus whenever something new lands; the calendar is placed at the real time (a meeting that has ended drops out, the one under way is IN PROGRESS), which moves it only when a meeting starts or ends.\n\n **Fresh without a reload.** The daily floor in the key and the PERIOD line are the principal's **local** date (`narrative_cache.local_today`), not UTC's, and a row written on an earlier local day is not served as today's. Regenerations are serialized per scope; a trigger that finds one running marks the scope pending and the running pass goes round once more (it built its context before that trigger's news landed), and after a failed pass (model error, the 25 s timeout, empty text) no view or tick starts another for 5 minutes and `narrative_stale` reads false, so the page drops its placeholder instead of spending a model call per view. They log `today: narrative served scope=… age_s=… stale=…` and `today: narrative regenerated scope=… ms=…`, and no longer need a page view: every `BRIEFING_NARRATIVE_REFRESH_MINUTES` (10) between `BRIEFING_NARRATIVE_REFRESH_START_HOUR` and `_END_HOUR` (06–22 local) the scheduler runs `today.refresh_principal_narrative`, which refreshes the calendar cache and rewrites the principal's header only when its key moved (see Scheduler). The Briefing re-polls `/today` at 4, 10 and 20 s while `narrative_stale` is true, re-pulls it when the tab comes back (at most once a minute) and every 5 minutes while visible, shows \"Updated 2:04 PM\" beside the heading, and shows \"Catching up on today…\" while the first header of the day is written (`lib/narrativeFreshness.ts`, tested by `npm test`).\n\n In **solo mode** (one person using Open Executive for themselves) the header speaks to the principal, whatever their role: a solo prompt over a context that lists goals at risk by *area* and has no \"people waiting on you\" block, and the quiet check ignores who is awaiting. The cache key carries the mode for solo only, so solo and team never share a cached narrative while every team key stays exactly what it was — no team cache is invalidated. The response shape does not change. For the principal's own view the solo context also carries a **DUE THIS WEEK** block — the principal's open loops that are overdue or due within 7 days (`today._with_due_soon` → `open_loops.principal_due_soon`, labelled OVERDUE / due today / due <weekday>) — which counts as needing attention in the quiet check and moves the cache key when an item is added, closed or falls due; a teammate's scoped view and team mode never get it. The header never gets the morning brief's *top three today* block — that is the DM brief's (see Workflows); the page shows the same top three in a card of its own (see *Solo focus cards* below). It does get the rest of today's calendar through the live blocks above, from the cached read.\n- **`in_flight`** / **`awaiting`** — upcoming Executive commitments and people we are waiting on.\n- **`handled_overnight`** — the autonomous moves the Executive *completed* since the last delivered morning brief: the alert review's (routed, nudged, escalated, drafted, merged, closed) plus the research watch policy's (`watching` — a watch added on its own because it was grounded in company data; `stopped_watching` — a research watch auto-disabled as noisy or dead; no alert id, re-enable from `/watchlist`). A `changed` verdict (the review rewrote an open alert's headline / body / severity) is deliberately **not** here: the alert is still open in \"Needs you\" and its card carries the note, so the brief reports it under \"what changed\" (a REWRITTEN block) rather than as done. Each row is structured, not just a sentence: `kind`, the audit `summary` (nudge bookkeeping marker stripped), `at`, `alert_id`, `event_type` (for a pre-filtered `/audit` deep link), `headline` (the alert's headline at move time; a watch's slug), `target` (person name for routed / nudged, survivor headline for merged, new severity for escalated, draft title, workflow name), `detail` (the cited evidence or the watch policy's reason), `outcome` (`resolved` | `dismissed` for a close, `proposed` for a route that went through the authority gate), `evidence_ref` (S1 / R2 / A3), `superseded_by_alert_id`, and `status` — the alert's lifecycle state **now** (`open` = live in the queue per `lifecycle.is_live` | `resolved` | `dismissed` | `expired` | `merged` | `acked` | `inactive` for snoozed / past-TTL rows), looked up per row so a close the principal already undid renders as reopened instead of offering a second Undo, and a \"still open\" jump link only appears when there is a card to land on. Audit rows private to the principal (say, one naming their contact) are in this list only on the principal's own `/today`: `brief_state.handled_since` leaves them out unless asked, and the written briefs never ask, since a brief can be read by others. The Pulse heatmap's per-day counts (`GET /today/activity/daily`) likewise leave out a private decision or private alert, as the activity rail does. The morning brief also carries a one-line count of research watch suggestions waiting on `/watchlist`.\n\n**Standing facts.** `render_briefing_context` appends the standing facts (`memory.facts`: corrections kept from chat, a teammate's marked `(per <name>)`) as its last block, after the quiet-day check, so a fact never makes a quiet day look busy. The morning brief also carries **TEAMMATE CORRECTIONS SINCE LAST BRIEF** (`facts.render_teammate_changes(since)`: each teammate fact recorded in the window that is in use now, plus — only when the brief is the principal's own private one (`_private_ok`), which then keeps the run out of the shared history — those waiting for their approval, since other teammates may run the brief and never see a proposal that is not theirs) before the quiet check — it is news, the principal's only FYI of it — and in the brief's fingerprint (`build_brief_fingerprint(teammate_changes=)`), so a correction alone un-suppresses an otherwise unchanged brief. Every other caller passes none, so its context is unchanged. The /today header hashes that rendered string as its cache key, so a new or retired fact marks the header stale and it is rewritten with the correction. The morning brief (standalone) and the teammate-scoped header get the same block. On the scheduler's delivery to the owner alone, with their Always in the loop switch on, `render_briefing_context(owner_notes=)` also carries FROM YOUR NOTES — DUE SOON (their own notes of what they promised or asked, overdue to a week ahead; `memory.history_brief`), which counts against a quiet day, enters the fingerprint and marks the run private; both standalone prompts turn it into a **From your notes** section. The /today header never gets it. The alert review's `render_batch` puts the same block ahead of the alerts (read once per pass), so a note, rewrite or routed DM never repeats a figure the principal already corrected.\n\n**When a brief isn't sent.** Above the Briefing, the owner sees a one-line notice when their latest morning brief, end-of-day digest or (in solo mode) weekly review wasn't sent — \"Your morning brief wasn't sent: nothing is set up to send it to you\" — with the day, what fixes it, a link to read the brief on the Artifacts page (left out when the brief couldn't be written at all) and one to Setup status. It comes from `GET /today/brief-delivery` (the scheduler records each run's outcome), shows nothing while briefs go out or while the scheduler is off, and clears once the cause is fixed. When the Executive's mail connection wasn't running (the MCP gateway failed to start and is retrying), the notice says that instead of blaming the owner's setup; a send that failed on every channel names what each channel answered, from the recorded `detail`, with addresses left out. Teammates never see it.\n\n**Replies waiting.** With Act as me's **Draft replies to my inbox** on, the top of the Briefing's left column lists the replies the Executive drafted in the owner's own Gmail for mail that needs them (`RepliesWaiting`, from `GET /delegation/replies` — see Act as Me). They belong to the owner alone: the route answers only the person who can have Act as me, the decisions behind the cards (`delegation_reply`) are principal-only and carry `private: true`, so `/today/activity` and the heatmap leave them out, and none is ever an alert, so nothing of them reaches `GET /today`, the header or the briefs. Each card shows who wrote and who they are to the owner, whether their address was verified, the subject, what they wrote (as plain text), the draft, **Decide before sending** (its open questions) and its warnings, with **Send**, **Edit in Gmail** (the thread in their Gmail) and **Dismiss** (which deletes the draft unless they edited it). **Send** asks first, naming who the reply goes to, then sends the draft exactly as it is in Gmail (`POST /decisions/{id}/approve`); when its recipients changed in Gmail or a newer message arrived, the backend's 409 `confirm` becomes a second question naming them. The card hides itself when nothing is waiting.\n\n**Solo focus cards.** `GET /today/top-three` and `GET /today/weekly-review` feed two solo-only cards, so a principal who only uses the web app — no chat app, no Google Workspace — sees today's top three and the weekly review instead of finding them only in the Workflows run history. Both answer only in solo mode (`effective_workspace_mode`) and only to the principal, by the stricter rule for starting a principal-only run (`workflows._caller_is_the_principal`: the caller's own email on a principal entry that is not archived, or no `x-caller-email` at all — never \"nobody is principal yet\"); a teammate, any other signed-in caller and team mode get null. `top-three` hands `open_loops.principal_due_soon()` to `briefing.top_three.build_top_three` — the morning brief's own inputs and code, so the items, their order and their free slots are the brief's — and returns `{items: [{key, kind, text, why, slot}]}`: `slot` is the free block (\"10:00–11:00\", the user's zone), \"\" when none is left, or null when no calendar was read (none connected, a failure or the 4 s timeout, a weekend); `items` is empty when there is nothing to pick. It is a route of its own, never part of `GET /today`, so the Briefing never waits on the calendar. `weekly-review` returns the latest `weekly_review` run with status `done` (`persistence.list_runs(..., status=\"done\", limit=1)`, newest `updated_at` first; failed and running runs never count) as `{run_id, completed_at, period, top_three, excerpt}`: `weekly_review.summarize_review` reads the artifact's title line and its last *Next week's top 3* section back as plain text, and `excerpt` stands in when that list is empty (the section's own note, else the review's first lines). Null when no review has completed or the run store cannot be read.\n\nThe route resolves the caller from `x-caller-email`, serves the viewer's cached narrative and, when its key moved, rewrites it in a `BackgroundTask` so the request never blocks on an LLM call (the page re-polls while `narrative_stale` is true). `GET /today/activity` returns the recent self-initiated action rail — merged from fired scheduled actions (DMs, follow-ups, nudges, cadences), logged decisions, saved advice, completed workflow runs (briefings/check-ins/research), kicked-off initiatives, resolved gated decisions, and raised alerts, so it reflects all of the Executive's activity rather than just dispatched messages. The Pulse page (`/memories`) polls it (limit 100) every ~20s so new events stream into the 'Recent activity' card, which scrolls internally at a fixed height instead of growing the page. The `morning_brief` workflow calls `_build_today()` directly to build the standalone DM (via a different, enumerated prompt; solo mode has its own, with goals at risk by area and no waiting-on section). `GET /morning-brief` is a deprecated alias.\n\n**Solo mode in the UI.** The response is the same in both modes; the briefing reads the workspace mode from the app-wide `WorkspaceProvider` (which reads team while loading or on error, so a team install never flashes solo) and, in solo, drops the team surfaces: the Departments card, the People card, the \"Across the team\" lane (every action proposal is the one user's, so all of them land in \"Needs you\"), the people-awaiting, people-overdue and departments-at-risk status pills, and the quiet-day \"Set up a check-in\" link. A \"N goals at risk\" pill (at-risk plus off-track goals, from `departments`) links to `/goals` instead, so the strip never reads \"All clear\" over a goal that is slipping. In the Departments card's place, **Your projects** lists the initiatives with status `active` (`GET /memories/initiatives`): **Done** marks one `completed` through `PATCH /memories/initiatives/{id}` (only `completed` takes an initiative out of the Executive's active context), and **Drop** deletes it through `DELETE /memories/initiatives/{id}` after a confirm. Under **Needs you**, a **Due soon** card lists the principal's open loops that are overdue or due within 7 days — their dated commitments and what others asked of them — read from `GET /people/{id}/open-loops` for the principal (the oldest principal in `people`, the backend's rule), labelled by `lib/dueSoon.ts` (tested by `npm test`: \"Overdue since Sep 23\" / \"Due today\" / \"Due Mon, Sep 28\", with a count of anything due later); **Done** closes one through `POST /open-loops/{id}/close`, which also stops the nudge engine chasing it. Above it, **Top three today** numbers the morning brief's three (`GET /today/top-three`) with each one's reason and, when a calendar was read, its free slot (or \"No free time left today\"); at the top of the right-hand column, **This week's review** (`GET /today/weekly-review`) shows the period, when it ran, next week's top three (or the excerpt) and a *Read the review* link to its run page (`/jobs/runs/{id}`). Each card fetches on its own once the Briefing has loaded, so a slow calendar never holds the page up, and renders nothing when the API returns null or an empty list. A commitment in the top three reads as the owner's own (\"Send the proposal\") through `lib/dueSoon.ts`'s `loopText`, as in Due soon; the cards' wording lives in `lib/rhythmCards.ts` (tested by `npm test`). The Pulse page hides its \"Department check-ins\" and \"Awaiting people\" blocks in solo, and its header shows active projects in place of the department check-in count. Team rendering is unchanged.\n\n## Alert lifecycle & the Executive review\n\nAlerts used to be write-once: raised, then never looked at again, so the \"Needs you\" queue grew without bound and the briefs re-listed it daily. Four things now keep it live and true:\n\n- **Time-to-live** (`openexecutive.alerts.lifecycle`). Action items expire after `ALERT_TTL_DAYS_ACTION` (14 d), unrouted low/medium monitoring signals after `ALERT_TTL_DAYS_MONITORING` (3 d). Every surface reads `list_live_alerts` (the same predicate the scheduler's 15-minute sweep persists as status `expired`), so `/today` is right even before the sweep runs. Artifacts and decision-backed alerts are exempt. `POST /alerts/{id}/reopen` is the Undo.\n- **Coalescing** (`alerts.pipeline` + `store.coalesce_alert`). A repeat of an open alert with the same `(source, dedup_key)` updates that row — `occurrence_count`, `last_seen_at`, severity max — instead of stacking a second card, and only re-pings when severity rose to high/urgent. Monitoring alerts carry a stable `watch:<slug>` key, so one watch means one card.\n- **Collection tags** (`alerts.pipeline`). A triaged alert never carries a `collection:<name>` tag: the pipeline strips them before inserting. Only an installed extension's own code files a document into its collection (`orchestrator.extensions`), so injected text can't make a card that the extension would treat as its own.\n- **The review** (`openexecutive.alerts.review`, heartbeat `alert_review_scan`, every 6 h and right before the morning brief). For each open alert the Executive sees what changed since it was raised — newer signals from the same watch, related alerts, activity since, the roster with SLAs (team members only — an alert routed to a contact never puts them in the slice, so they are never routed to, nudged or chased; a private card is never reviewed at all, nor used as evidence for another), department authority — and returns a verdict (relevant / changed / resolved / stale) plus a recommended move. Deterministic policy then acts: **route** (assign + DM the owner; `propose_via_alert` for propose-only departments), **nudge**, **escalate** (severity + `due_at` + DM the principal only), **draft** (`draft_artifact`), **suggest a workflow** (a link, never a run), **merge** (`superseded_by_alert_id`), or **resolve** — only on high confidence citing a server-minted evidence ref (a newer signal, a related alert, an activity item shown for that alert); free text never closes a card, and anything weaker is annotated `likely_stale`, demoted 30 ranking points, and left for one click. Everything that came from outside is rendered as inert data inside the review prompt, so an injected email body cannot steer the batch. Board / comp / legal matters only ever go to a scope-holder or the principal and keep their text. Route and escalate are idempotent across passes, every DM carries an \"[Alert review] Re: …\" header, outbound moves are capped per pass, passes are single-flight, `ALERT_REVIEW_ENABLED=false` stops every caller, every move is audited with its evidence and prior state, and a distinct `resolved` status keeps Executive closes separate from `ack` (user approved).\n- **Grounded text** (`openexecutive.briefing.grounding`). Nobody reads an alert's text before it is dispatched, so what the model wrote onto it must be supported by what it read. After triage (`alerts.pipeline._ground_decision`, before coalescing or inserting), a headline naming a person or figure the event does not hold — sources are the event's subject, sender, title and body, the initiatives triage was shown and the company profile — is replaced by the event's own subject, such body sentences are dropped (all of them → the event body cut to 280 chars); both fallbacks are raw event text, so they are made inert first — links masked, Markdown and Slack `<…>` syntax and @-mentions stripped — because a broadcast posts them as written, and such a suggested action is dropped. A review `changed` rewrite is checked against the alert's own text and the evidence it was reviewed with (signals, related alerts, activity, the roster slice), plus the standing facts the batch was shown, so a rewrite that corrects a card to one of the principal's corrections is grounded; an ungrounded rewrite keeps the old text, still applies a severity change, and audits `text_ungrounded`. A name counts as grounded only when one source line holds all of it; a figure only when a source number matches it within the precision it is written with. Each finding writes a `grounding` audit row; `GROUNDING_CHECKS=report` records without changing anything.\n\nOn the page, cards read as decisions: the one-line \"what changed since you last looked\" (`review_note`) leads, the recommended move is the primary control (Nudge <owner> → chat; Run <workflow> → `/jobs/<name>`), with chips for age, seen ×N, why-now / due, folded-in and draft-ready, a \"Reviewed <ago>\" footer, and an amber Likely-stale treatment with one-click Dismiss. \"Needs you\" shows *Start here* + 8 cards + \"Show N more\", a \"Dismiss N older than 7 days\" footer (explicit ids to `POST /alerts/bulk-ack` — never a server-side age sweep, which would hit teammates' routed items), and \"Re-check relevance\" (`POST /alerts/review`). The handled rail (anchor of the \"Executive handled N overnight\" pill) is deliberately one sentence by default: a first-person heading built from counts only — \"Since your last brief: N off your plate (closes still standing, and merges whose survivor is not itself listed; a merge into a listed survivor counts on that survivor's row), N in others' hands (routed / nudged), N waiting on you (escalated)\", plus \"N drafts ready\", \"N workflows suggested\", \"N watch changes\", \"N other moves\" (a kind the UI does not know) and \"N back on your plate\" (a close that is open again) when present — with the rows behind a \"details\" disclosure, and nothing rendered at all when the grouped rows are empty. The pure logic (grouping, headline, links) lives in `packages/ui/src/lib/handled.ts` and is covered by `npm test`. Expanded, it shows one first-person row per alert (\"Resolved *X* — evidence\", \"Dismissed *X* as stale — evidence\", \"Handed *X* to Dana Kim\" / \"Proposed *X* to Dana Kim (awaiting their approval)\", \"Chased Dana Kim on *X*\", \"Raised *X* to high\", \"Drafted *T* from *X*\", \"Folded *X* into *Y*\", \"Started watching *slug*\"), escalations first; rows sharing an alert collapse to the newest move with the others as an \"also …\" trailer — a close always keeps the visible slot (it carries Undo), otherwise an escalation beats routed / nudged / drafted; a merge whose survivor is listed becomes \"N duplicates folded in\" on the survivor. Every row links its `evidence_ref` (or \"evidence\") to `/audit?event_type=…&q=…` (the audit page pre-fills those filters from the query string), a still-open row jumps to its card (`#alert-<id>`), drafted rows link `/artifacts`, watch rows `/watchlist`. Undo is offered only while the close still stands (`status` not `open`); a reverted close shows \"Reopened\". Dismissing a watch-sourced alert lowers that watch's `trust_score` (which discounts ranking and is shown to the review as evidence); the ack body may carry `mute_topic`. Acknowledging or resolving an alert — including the review closing it itself — marks the review's DMs about it `acted` in the Attunement outcome ledger, for the person it is routed to and the principal only; dismissing it, finding it stale or letting it expire voids them (counted neither way). Review DMs are tagged `alert_review` with `alert:<id>`.\n\n## Multi-client practice section\n\nIn multi-client practice mode (2+ client slots — see the Client Companies section), the response gains an additive `practice_clients` list: rollup cards for the **parked** clients (overdue follow-ups, awaiting replies, unread alerts, onboarding due soon, renewal countdowns), each stamped with the save point its data reflects. Single-company installs always receive an empty list and the UI renders nothing.",+ "markdown": "`openexecutive.api.routes.today` serves the morning brief — a one-screen, read-only view of what is happening across the org. It is the default landing surface (the Next.js root renders `<Briefing>`). Every signed-in page shares one sidebar (`AppSidebar`). Its Recent list is capped at the 7 newest web chats. The full history, including Slack, Telegram and Discord conversations (recognised by their session-id prefix), lives on `/chats`. A chat opens from any page through `/?session=<id>`.\n\n`GET /today` returns `TodayResponse` assembled by `_build_today()`, which is synchronous and caller-agnostic:\n\n- **`departments`** — per-department goal health, rolling up each department's goal counts (`total`, `at_risk`, `off_track`) plus its awaiting-workflow count, and `attention_goals`: the actual off-track/at-risk goals (worst first, capped at 3) with `key_result`, `current`, `target`, and `status`, so the briefing's Department card shows *which* goal is off and how far without a click. Empty for healthy/inactive departments.\n- **Private cards.** An alert tagged `private:principal` (`alerts.models.PRIVATE_ALERT_TAG` — raised on a turn about mail from one of the principal's contacts or mail they forwarded, or a meeting proposal with a contact) is in `proposals` only when the caller is the principal. `_build_today` leaves it out by default, so the end-of-day digest, the reflection and Discord's `/today` never see it, and the morning brief reads it only on a run for the principal (the scheduler's, or the principal's own verified chat turn in a conversation only they can read — see Workflows). The narrative is written from one only in the principal's own `principal` scope, which nobody else is served; the shared `company` scope an unresolved caller gets, and a teammate's scope, never are. The activity rail skips it, and the chat digest includes it only on the principal's own verified turn.\n- **Roster-request cards.** When someone not on the People list writes in (see Org and Integrations), `people.roster_requests.surface_card` raises an alert of source `roster_request` (medium, tagged `roster_request:<id>` and `private:principal`, routed to the principal), so it follows every private-card rule above. `GET /today` attaches `roster_request` to that proposal (`_roster_request_card`: channel, address or account id, the sender's sanitised and unverified name, profile email, company-domain flag, suggested kind and person, message count, whether they were acknowledged, first seen, and the held messages' first lines) while the request is still pending. The Briefing renders it as its own card (`RosterRequestCard`: add as a new person with a name and an explicit team/contact choice — pre-filled as team on a company domain — or \"someone already on the list\", with a replace-account option for a chat id, or Ignore), which calls `/people/requests/{id}` directly and never hands off to chat, so what a stranger wrote never seeds a turn. The card is kept out of everything that could close it without answering it or put the stranger's words in front of a model: the narrative (`_action_proposals` drops it), the chat's open-alert digest (`<briefing>` — the principal's verified turn gets a separate `<roster_requests>` block instead; see Agents), `ack_alert`, a single ack (`POST /alerts/{id}/ack` is a 409), the \"Dismiss N older than 7 days\" count and the server's bulk ack, reopen, the TTL sweep and the alert review (`roster_request` is in `lifecycle.TTL_EXEMPT_SOURCES`). It ends when the request does: answered (`ack`, or `dismissed` on a decline) or expired after `ROSTER_REQUEST_TTL_DAYS`.\n- **`people`** — an attention-ranked roster of the **team** (the principal's contacts are never listed, and get no insight note). Each person carries `awaiting_action` count, soonest SLA, a `status` (`on_leave` / `needs_reply` / `awaiting` / `clear`), reachability, `overdue`, a server `priority` sort key, and a cached one-line `insight`. Sorted by `(-priority, full_name)`. Stale insight notes are regenerated in the background only when the roster has more than one person: the UI shows the People sidebar only for more than one, so a one-person install (solo, or a team before anyone else is added) does not pay a daily model and peer-memory call for a note nobody sees. Cached notes are still served.\n- **`proposals`** — the *live* unread alerts (workflow approvals, triage-classified inbound, Executive signals, flagged artifacts, and gated calendar bookings; an artifact is listed only to its owner (`alerts.models.visible_alert`; every other build of the board — the briefs, the reflection, the review, the chat digest on anyone else's turn, the activity rail — leaves drafted artifacts out) and carries `artifact_format` / `artifact_url` and a `body` already rendered to Markdown for its format, so the card badges it as a web page, Word doc, spreadsheet or link and offers *Open artifact*): unread, inside their category TTL, not snoozed — see *Alert lifecycle* below. Each carries `score`, `category` (`action` vs `monitoring`), `surfaced_reason` from `openexecutive.briefing.ranking`, the lifecycle fields (`occurrence_count`, `last_seen_at`, `last_reviewed_at`, `review_verdict`, `review_note`, `recommended_move`, `why_now`, `due_at`, `superseded_count`, `suggested_workflow`), and `decision_instance_id` (set only when the proposal is backed by a decision-ledger row — a calendar booking awaiting approval). The UI splits them into 'mine' vs 'across the team' using `caller_person_id`. For decision-backed proposals the card's Approve/Reject call the `/decisions` endpoints (which book or cancel the event server-side and clear the alert) instead of the ack-and-hand-off-to-chat flow — so meeting bookings are reviewed in the briefing itself rather than on a separate page.\n- **`narrative`** — a per-viewer Executive-voice header (\"What's going on\") synthesized by `synthesize_briefing_narrative`, cached per scope in `briefing_narrative`: the resolved principal gets the whole-company `principal` scope (which may carry what is private to them), a caller who resolves to no roster row the shared `company` scope (written from what everyone may see), and each teammate a role-scoped `person:<id>` one. `narrative_generated_at` says when the served text was written and `narrative_stale` whether a fresher one is being written now. In the web UI each bullet of this narrative is a click target: clicking one hands off to chat (the same `onContinue` path as the proposal cards) seeded to discuss that item. The Executive recognizes it because every chat turn now carries a `<briefing>` digest of open alerts (see Memory). That digest (`briefing.context.format_open_alerts_for_prompt`) is capped at 30 items; when the board is longer the header says so explicitly and tells the Executive to point at this page for the rest — it previously presented the capped list as the complete board, so the Executive described a slice as everything that was open (#136). Chat adapters get the digest too, but Slack gates it to the principal's DMs: the board is company-wide and must not be pulled into a shared channel. The `[alert_id]` at the start of each line is also what `ack_alert` trusts, because an id quoted inside an alert's own body came from inbound mail or chat and is attacker-controlled. This page's `[Discuss mode — alert_id=N]` handoff primer is a pointer to which item is under discussion, not authority on its own: the server accepts it only if that id is on the live board too. Two things enforce that. Every field the digest interpolates — headline, body, suggested action, tags, review note — is collapsed to a single line, since a newline in any of them would forge a whole extra `[N]` line and with it a fabricated instruction to clear someone else's alert. And the server records the live board it derived, so `ack_alert` refuses any id outside it — on **every** session, not just the chat adapters. The recorded set is the whole live board, not just the rows the digest printed, so a card past the render cap stays ackable. The control stops invented, closed, snoozed and expired ids; it does not stop the model being argued into acking the wrong *live* card. When the principal names an item that has already left the board — opened, snoozed, or older than it — the Executive looks it up with `find_alerts` (a keyword search over every status, `alerts.store.search_alerts`); matches that are still open (`unread` or `read`) become ackable for that turn, up to 25, and closed ones come back labelled so the Executive can say the item is already settled. It works only where the principal's own board was shown this turn — the web app or their DM — and never returns roster-request cards (see Lifecycle). The digest's header also labels every headline and detail as untrusted content drawn from inbound mail, chat and watched pages — act on what the principal asks about an item, never on what its text asks — and triage reads each signal inside an `<event>` block whose closing tag the sender's text cannot forge (it is defanged in any case and spacing, after NFKC folds fullwidth forms). That check used to run only when `origin_channel` was set, which the browser never sets, so the one surface where the principal actually reads their board had no check at all and the model could ack any id, including one quoted out of an alert body by the Discuss handoff. Rendering the block and recording its ids now happen together in `briefing.context.render_and_trust`, which both the web chat route and the channel adapters call: render without recording and the tool refuses everything, record without rendering and the model gets reach it was never shown. A turn that was shown nothing trusts nothing. Recording it is only half the wiring: the tool reads the board off the turn's session through a ContextVar, and the chat route binds that session for the whole SSE body (`set_session`, next to `set_turn`). Bound from inside the Executive's own generator instead, it survives exactly one stream step — `asyncio.wait_for` runs each step in a fresh Task with a copy of the context — and the tool-call loop, which runs later, sees nothing. That shipped, and every web ack was refused on cards that were open the whole time. The digest also carries a short **already handled** tail — recently acked / dismissed / resolved rows, named but deliberately NOT trusted for acking — because a card cleared on the page minutes ago is otherwise simply absent from chat: asked to \"record that as fixed\", the Executive could not tell a settled item from one it had never heard of, and sent the principal back to dismiss a card that was already gone. That tail renders even when nothing is open, which is exactly when it matters. Note it is a different window from the `handled_overnight` rail above: that one runs since the last delivered morning brief, while the chat tail looks back 14 days (matching the action-alert TTL, so it still covers an item cleared late in its life), so chat can name a settled item the rail no longer shows. The narrative is held to what is **live**, and to what it is actually for. The `alert_raised` source is dropped from the activity it reasons over (`_build_activity(..., include_alert_raised=False)`): a closed alert reads as work the principal already settled, and a *live* one is worse than redundant — `lifecycle.is_live` is the very predicate behind `list_live_alerts`, so every live raise is already a proposal card below the header, which the prompt forbids re-listing. The `/today/activity` rail keeps the whole source, because a raise really happened. The activity block is only labelled \"since last brief\" when the caller bounded it with `since` (the standalone briefs do; the header does not), since calling an unbounded history rail a delta made the header present weeks-old rows as overnight news. When the viewer's slice holds nothing that wants a decision — no action proposal, no at-risk/off-track department, nobody awaiting — the regen skips the model call entirely and writes the fixed quiet line (`Quiet right now — nothing pressing.`, or `… nothing needs you.` for a teammate). **The cache key is a hash of the rendered context itself** (`today._narrative_context` builds it once and both the hot path and the background task key off that one string, which is also handed to the model verbatim). That makes the key a function of the model's input: everything the prompt renders is covered, and nothing it omits can trigger a regeneration. Keying on hand-picked fields broke one half or the other each time — headlines alone left the rendered activity block uncovered, while the proposals' review fields are never rendered by this header yet are rewritten with fresh prose by every `alerts.review` pass, so they regenerated each viewer's narrative several times a day to re-synthesize identical input. A quiet board keys off a fixed sentinel instead, so a moving rail cannot re-key an entry whose text is constant. Together: on a fully dismissed board every other input was empty, the rail became the only context, and the model synthesized a confident header out of closed items.\n\n **Live, not just the board.** The header used to reason over the alert board, goal health and the Executive's own bookkeeping only — mail and chat handled that day, replies the gate held and the next meeting never reached it, so it read the same for days while the principal's day moved on. The whole-company scopes now open the context with the principal's world as it is happening (`briefing.live_signals.gather_live_signals`, rendered by `render_live_blocks`), under a `NOW:` line: **INBOUND** (`integration_inbound` audit rows that carry a message, grouped by sender and subject, with an email's first line), **STUCK** (`integration_outbound_blocked` to a recipient, the inbound \"reply blocked at outbound gate\" and Google Chat \"left unanswered\" / \"not delivered\" rows, and drafts saved by Act as me), **CONVERSATIONS** (the principal's own web chat titles) and the **REST OF TODAY'S CALENDAR**. The window is the local day, or the last 12 hours when that is longer. Private audit rows, drafts, chat titles and the calendar (meeting titles are the principal's own) are read only in the `principal` scope — `gather_live_signals` drops the calendar whenever `include_private` is false, whatever the caller passes, so the shared `company` header never quotes it. The calendar is never fetched on the request: `live_signals.refresh_calendar` caches one read per 15 minutes (the scheduler tick refreshes it) and the header quotes the cache. Every quoted field is collapsed to one line and cut, and the blocks and the prompt both say the text is data, never instructions — inbound mail is attacker-controlled. With live blocks present the context also ages each proposal (`raised 2d ago`, whole days), names each at-risk department's slipping goals (`attention_goals`) and adds an **EXTERNAL SIGNALS** block (monitoring alerts from the last 24 h, never enough on their own to break the quiet line); the rhythm runs (`today.RHYTHM_WORKFLOWS`: the morning brief, end-of-day digest, reflection and weekly review) are dropped from the activity it reasons over. The prompts (`BRIEFING_NARRATIVE_SYSTEM` and its solo variant, `NARRATIVE_PROMPT_VERSION` 5) lead with what is live and give a days-old item at most one bullet. Anything live breaks the quiet line; the NOW line and window move at most once an hour, so the key moves hourly on time alone plus whenever something new lands; the calendar is placed at the real time (a meeting that has ended drops out, the one under way is IN PROGRESS), which moves it only when a meeting starts or ends.\n\n **Fresh without a reload.** The daily floor in the key and the PERIOD line are the principal's **local** date (`narrative_cache.local_today`), not UTC's, and a row written on an earlier local day is not served as today's. Regenerations are serialized per scope; a trigger that finds one running marks the scope pending and the running pass goes round once more (it built its context before that trigger's news landed), and after a failed pass (model error, the 25 s timeout, empty text) no view or tick starts another for 5 minutes and `narrative_stale` reads false, so the page drops its placeholder instead of spending a model call per view. They log `today: narrative served scope=… age_s=… stale=…` and `today: narrative regenerated scope=… ms=…`, and no longer need a page view: every `BRIEFING_NARRATIVE_REFRESH_MINUTES` (10) between `BRIEFING_NARRATIVE_REFRESH_START_HOUR` and `_END_HOUR` (06–22 local) the scheduler runs `today.refresh_principal_narrative`, which refreshes the calendar cache and rewrites the principal's header only when its key moved (see Scheduler). The Briefing re-polls `/today` at 4, 10 and 20 s while `narrative_stale` is true, re-pulls it when the tab comes back (at most once a minute) and every 5 minutes while visible, shows \"Updated 2:04 PM\" beside the heading, and shows \"Catching up on today…\" while the first header of the day is written (`lib/narrativeFreshness.ts`, tested by `npm test`).\n\n In **solo mode** (one person using Open Executive for themselves) the header speaks to the principal, whatever their role: a solo prompt over a context that lists goals at risk by *area* and has no \"people waiting on you\" block, and the quiet check ignores who is awaiting. The cache key carries the mode for solo only, so solo and team never share a cached narrative while every team key stays exactly what it was — no team cache is invalidated. The response shape does not change. For the principal's own view the solo context also carries a **DUE THIS WEEK** block — the principal's open loops that are overdue or due within 7 days (`today._with_due_soon` → `open_loops.principal_due_soon`, labelled OVERDUE / due today / due <weekday>) — which counts as needing attention in the quiet check and moves the cache key when an item is added, closed or falls due; a teammate's scoped view and team mode never get it. The header never gets the morning brief's *top three today* block — that is the DM brief's (see Workflows); the page shows the same top three in a card of its own (see *Solo focus cards* below). It does get the rest of today's calendar through the live blocks above, from the cached read.\n- **`in_flight`** / **`awaiting`** — upcoming Executive commitments and people we are waiting on.\n- **`handled_overnight`** — the autonomous moves the Executive *completed* since the last delivered morning brief: the alert review's (routed, nudged, escalated, drafted, merged, closed) plus the research watch policy's (`watching` — a watch added on its own because it was grounded in company data; `stopped_watching` — a research watch auto-disabled as noisy or dead; no alert id, re-enable from `/watchlist`). A `changed` verdict (the review rewrote an open alert's headline / body / severity) is deliberately **not** here: the alert is still open in \"Needs you\" and its card carries the note, so the brief reports it under \"what changed\" (a REWRITTEN block) rather than as done. Each row is structured, not just a sentence: `kind`, the audit `summary` (nudge bookkeeping marker stripped), `at`, `alert_id`, `event_type` (for a pre-filtered `/audit` deep link), `headline` (the alert's headline at move time; a watch's slug), `target` (person name for routed / nudged, survivor headline for merged, new severity for escalated, draft title, workflow name), `detail` (the cited evidence or the watch policy's reason), `outcome` (`resolved` | `dismissed` for a close, `proposed` for a route that went through the authority gate), `evidence_ref` (S1 / R2 / A3), `superseded_by_alert_id`, and `status` — the alert's lifecycle state **now** (`open` = live in the queue per `lifecycle.is_live` | `resolved` | `dismissed` | `expired` | `merged` | `acked` | `inactive` for snoozed / past-TTL rows), looked up per row so a close the principal already undid renders as reopened instead of offering a second Undo, and a \"still open\" jump link only appears when there is a card to land on. Audit rows private to the principal (say, one naming their contact) are in this list only on the principal's own `/today`: `brief_state.handled_since` leaves them out unless asked, and the written briefs never ask, since a brief can be read by others. The Pulse heatmap's per-day counts (`GET /today/activity/daily`) likewise leave out a private decision or private alert, as the activity rail does. The morning brief also carries a one-line count of research watch suggestions waiting on `/watchlist`.\n\n**Standing facts.** `render_briefing_context` appends the standing facts (`memory.facts`: corrections kept from chat, a teammate's marked `(per <name>)`) as its last block, after the quiet-day check, so a fact never makes a quiet day look busy. The morning brief also carries **TEAMMATE CORRECTIONS SINCE LAST BRIEF** (`facts.render_teammate_changes(since)`: each teammate fact recorded in the window that is in use now, plus — only when the brief is the principal's own private one (`_private_ok`), which then keeps the run out of the shared history — those waiting for their approval, since other teammates may run the brief and never see a proposal that is not theirs) before the quiet check — it is news, the principal's only FYI of it — and in the brief's fingerprint (`build_brief_fingerprint(teammate_changes=)`), so a correction alone un-suppresses an otherwise unchanged brief. Every other caller passes none, so its context is unchanged. The /today header hashes that rendered string as its cache key, so a new or retired fact marks the header stale and it is rewritten with the correction. The morning brief (standalone) and the teammate-scoped header get the same block. On the scheduler's delivery to the owner alone, with their Always in the loop switch on, `render_briefing_context(owner_notes=)` also carries FROM YOUR NOTES — DUE SOON (their own notes of what they promised or asked, overdue to a week ahead; `memory.history_brief`), which counts against a quiet day, enters the fingerprint and marks the run private; both standalone prompts turn it into a **From your notes** section. The /today header never gets it. The alert review's `render_batch` puts the same block ahead of the alerts (read once per pass), so a note, rewrite or routed DM never repeats a figure the principal already corrected.\n\n**When a brief isn't sent.** Above the Briefing, the owner sees a one-line notice when their latest morning brief, end-of-day digest or (in solo mode) weekly review wasn't sent — \"Your morning brief wasn't sent: nothing is set up to send it to you\" — with the day, what fixes it, a link to read the brief on the Artifacts page (left out when the brief couldn't be written at all) and one to Setup status. It comes from `GET /today/brief-delivery` (the scheduler records each run's outcome), shows nothing while briefs go out or while the scheduler is off, and clears once the cause is fixed. When the Executive's mail connection wasn't running (the MCP gateway failed to start and is retrying), the notice says that instead of blaming the owner's setup; a send that failed on every channel names what each channel answered, from the recorded `detail`, with addresses left out. Teammates never see it.\n\n**Replies waiting.** With Act as me's **Draft replies to my inbox** on, the top of the Briefing's left column lists the replies the Executive drafted in the owner's own Gmail for mail that needs them (`RepliesWaiting`, from `GET /delegation/replies` — see Act as Me). They belong to the owner alone: the route answers only the person who can have Act as me, the decisions behind the cards (`delegation_reply`) are principal-only and carry `private: true`, so `/today/activity` and the heatmap leave them out, and none is ever an alert, so nothing of them reaches `GET /today`, the header or the briefs. Each card shows who wrote and who they are to the owner, whether their address was verified, the subject, what they wrote (as plain text), the draft, **Decide before sending** (its open questions) and its warnings, with **Send**, **Edit in Gmail** (the thread in their Gmail) and **Dismiss** (which deletes the draft unless they edited it). **Send** asks first, naming who the reply goes to, then sends the draft exactly as it is in Gmail (`POST /decisions/{id}/approve`); when its recipients changed in Gmail or a newer message arrived, the backend's 409 `confirm` becomes a second question naming them. The card hides itself when nothing is waiting.\n\n**Solo focus cards.** `GET /today/top-three` and `GET /today/weekly-review` feed two solo-only cards, so a principal who only uses the web app — no chat app, no Google Workspace — sees today's top three and the weekly review instead of finding them only in the Workflows run history. Both answer only in solo mode (`effective_workspace_mode`) and only to the principal, by the stricter rule for starting a principal-only run (`workflows._caller_is_the_principal`: the caller's own email on a principal entry that is not archived, or no `x-caller-email` at all — never \"nobody is principal yet\"); a teammate, any other signed-in caller and team mode get null. `top-three` hands `open_loops.principal_due_soon()` to `briefing.top_three.build_top_three` — the morning brief's own inputs and code, so the items, their order and their free slots are the brief's — and returns `{items: [{key, kind, text, why, slot}]}`: `slot` is the free block (\"10:00–11:00\", the user's zone), \"\" when none is left, or null when no calendar was read (none connected, a failure or the 4 s timeout, a weekend); `items` is empty when there is nothing to pick. It is a route of its own, never part of `GET /today`, so the Briefing never waits on the calendar. `weekly-review` returns the latest `weekly_review` run with status `done` (`persistence.list_runs(..., status=\"done\", limit=1)`, newest `updated_at` first; failed and running runs never count) as `{run_id, completed_at, period, top_three, excerpt}`: `weekly_review.summarize_review` reads the artifact's title line and its last *Next week's top 3* section back as plain text, and `excerpt` stands in when that list is empty (the section's own note, else the review's first lines). Null when no review has completed or the run store cannot be read.\n\nThe route resolves the caller from `x-caller-email`, serves the viewer's cached narrative and, when its key moved, rewrites it in a `BackgroundTask` so the request never blocks on an LLM call (the page re-polls while `narrative_stale` is true). `GET /today/activity` returns the recent self-initiated action rail — merged from fired scheduled actions (DMs, follow-ups, nudges, cadences), logged decisions, saved advice, completed workflow runs (briefings/check-ins/research), kicked-off initiatives, resolved gated decisions, and raised alerts, so it reflects all of the Executive's activity rather than just dispatched messages. The Pulse page (`/memories`) polls it (limit 100) every ~20s so new events stream into the 'Recent activity' card, which scrolls internally at a fixed height instead of growing the page. The `morning_brief` workflow calls `_build_today()` directly to build the standalone DM (via a different, enumerated prompt; solo mode has its own, with goals at risk by area and no waiting-on section). `GET /morning-brief` is a deprecated alias.\n\n**Solo mode in the UI.** The response is the same in both modes; the briefing reads the workspace mode from the app-wide `WorkspaceProvider` (which reads team while loading or on error, so a team install never flashes solo) and, in solo, drops the team surfaces: the Departments card, the People card, the \"Across the team\" lane (every action proposal is the one user's, so all of them land in \"Needs you\"), the people-awaiting, people-overdue and departments-at-risk status pills, and the quiet-day \"Set up a check-in\" link. A \"N goals at risk\" pill (at-risk plus off-track goals, from `departments`) links to `/goals` instead, so the strip never reads \"All clear\" over a goal that is slipping. In the Departments card's place, **Your projects** lists the initiatives with status `active` (`GET /memories/initiatives`): **Done** marks one `completed` through `PATCH /memories/initiatives/{id}` (only `completed` takes an initiative out of the Executive's active context), and **Drop** deletes it through `DELETE /memories/initiatives/{id}` after a confirm. Under **Needs you**, a **Due soon** card lists the principal's open loops that are overdue or due within 7 days — their dated commitments and what others asked of them — read from `GET /people/{id}/open-loops` for the principal (the oldest principal in `people`, the backend's rule), labelled by `lib/dueSoon.ts` (tested by `npm test`: \"Overdue since Sep 23\" / \"Due today\" / \"Due Mon, Sep 28\", with a count of anything due later); **Done** closes one through `POST /open-loops/{id}/close`, which also stops the nudge engine chasing it. Above it, **Top three today** numbers the morning brief's three (`GET /today/top-three`) with each one's reason and, when a calendar was read, its free slot (or \"No free time left today\"); at the top of the right-hand column, **This week's review** (`GET /today/weekly-review`) shows the period, when it ran, next week's top three (or the excerpt) and a *Read the review* link to its run page (`/jobs/runs/{id}`). Each card fetches on its own once the Briefing has loaded, so a slow calendar never holds the page up, and renders nothing when the API returns null or an empty list. A commitment in the top three reads as the owner's own (\"Send the proposal\") through `lib/dueSoon.ts`'s `loopText`, as in Due soon; the cards' wording lives in `lib/rhythmCards.ts` (tested by `npm test`). The Pulse page hides its \"Department check-ins\" and \"Awaiting people\" blocks in solo, and its header shows active projects in place of the department check-in count. Team rendering is unchanged.\n\n## Alert lifecycle & the Executive review\n\nAlerts used to be write-once: raised, then never looked at again, so the \"Needs you\" queue grew without bound and the briefs re-listed it daily. Four things now keep it live and true:\n\n- **Time-to-live** (`openexecutive.alerts.lifecycle`). Action items expire after `ALERT_TTL_DAYS_ACTION` (14 d), unrouted low/medium monitoring signals after `ALERT_TTL_DAYS_MONITORING` (3 d). Every surface reads `list_live_alerts` (the same predicate the scheduler's 15-minute sweep persists as status `expired`), so `/today` is right even before the sweep runs. Artifacts and decision-backed alerts are exempt. `POST /alerts/{id}/reopen` is the Undo.\n- **Coalescing** (`alerts.pipeline` + `store.coalesce_alert`). A repeat of an open alert with the same `(source, dedup_key)` updates that row — `occurrence_count`, `last_seen_at`, severity max — instead of stacking a second card, and only re-pings when severity rose to high/urgent. Monitoring alerts carry a stable `watch:<slug>` key, so one watch means one card.\n- **Collection tags** (`alerts.pipeline`). A triaged alert never carries a `collection:<name>` tag: the pipeline strips them before inserting. Only an installed extension's own code files a document into its collection (`orchestrator.extensions`), so injected text can't make a card that the extension would treat as its own.\n- **The review** (`openexecutive.alerts.review`, heartbeat `alert_review_scan`, every 6 h and right before the morning brief). For each open alert the Executive sees what changed since it was raised — newer signals from the same watch, related alerts, activity since, the roster with SLAs (team members only — an alert routed to a contact never puts them in the slice, so they are never routed to, nudged or chased; a private card is never reviewed at all, nor used as evidence for another), department authority — and returns a verdict (relevant / changed / resolved / stale) plus a recommended move. Deterministic policy then acts: **route** (assign + DM the owner; `propose_via_alert` for propose-only departments), **nudge**, **escalate** (severity + `due_at` + DM the principal only), **draft** (`draft_artifact`), **suggest a workflow** (a link, never a run), **merge** (`superseded_by_alert_id`), or **resolve** — only on high confidence citing a server-minted evidence ref (a newer signal, a related alert, an activity item shown for that alert); free text never closes a card, and anything weaker is annotated `likely_stale`, demoted 30 ranking points, and left for one click. Everything that came from outside is rendered as inert data inside the review prompt, so an injected email body cannot steer the batch. Board / comp / legal matters only ever go to a scope-holder or the principal and keep their text. Route and escalate are idempotent across passes, every DM carries an \"[Alert review] Re: …\" header, outbound moves are capped per pass, passes are single-flight, `ALERT_REVIEW_ENABLED=false` stops every caller, every move is audited with its evidence and prior state, and a distinct `resolved` status keeps Executive closes separate from `ack` (user approved). A review DM is proactive outreach, so the recipient's notification settings apply: one held for their quiet hours or brief counts as a route made but not as a nudge toward the cap (and no second nudge is held while one waits), and one about an alert whose severity is (or becomes) `urgent` is marked urgent (`notifications.urgent_send`) and gets through when they let urgent things through.\n- **Grounded text** (`openexecutive.briefing.grounding`). Nobody reads an alert's text before it is dispatched, so what the model wrote onto it must be supported by what it read. After triage (`alerts.pipeline._ground_decision`, before coalescing or inserting), a headline naming a person or figure the event does not hold — sources are the event's subject, sender, title and body, the initiatives triage was shown and the company profile — is replaced by the event's own subject, such body sentences are dropped (all of them → the event body cut to 280 chars); both fallbacks are raw event text, so they are made inert first — links masked, Markdown and Slack `<…>` syntax and @-mentions stripped — because a broadcast posts them as written, and such a suggested action is dropped. A review `changed` rewrite is checked against the alert's own text and the evidence it was reviewed with (signals, related alerts, activity, the roster slice), plus the standing facts the batch was shown, so a rewrite that corrects a card to one of the principal's corrections is grounded; an ungrounded rewrite keeps the old text, still applies a severity change, and audits `text_ungrounded`. A name counts as grounded only when one source line holds all of it; a figure only when a source number matches it within the precision it is written with. Each finding writes a `grounding` audit row; `GROUNDING_CHECKS=report` records without changing anything.\n\nOn the page, cards read as decisions: the one-line \"what changed since you last looked\" (`review_note`) leads, the recommended move is the primary control (Nudge <owner> → chat; Run <workflow> → `/jobs/<name>`), with chips for age, seen ×N, why-now / due, folded-in and draft-ready, a \"Reviewed <ago>\" footer, and an amber Likely-stale treatment with one-click Dismiss. \"Needs you\" shows *Start here* + 8 cards + \"Show N more\", a \"Dismiss N older than 7 days\" footer (explicit ids to `POST /alerts/bulk-ack` — never a server-side age sweep, which would hit teammates' routed items), and \"Re-check relevance\" (`POST /alerts/review`). The handled rail (anchor of the \"Executive handled N overnight\" pill) is deliberately one sentence by default: a first-person heading built from counts only — \"Since your last brief: N off your plate (closes still standing, and merges whose survivor is not itself listed; a merge into a listed survivor counts on that survivor's row), N in others' hands (routed / nudged), N waiting on you (escalated)\", plus \"N drafts ready\", \"N workflows suggested\", \"N watch changes\", \"N other moves\" (a kind the UI does not know) and \"N back on your plate\" (a close that is open again) when present — with the rows behind a \"details\" disclosure, and nothing rendered at all when the grouped rows are empty. The pure logic (grouping, headline, links) lives in `packages/ui/src/lib/handled.ts` and is covered by `npm test`. Expanded, it shows one first-person row per alert (\"Resolved *X* — evidence\", \"Dismissed *X* as stale — evidence\", \"Handed *X* to Dana Kim\" / \"Proposed *X* to Dana Kim (awaiting their approval)\", \"Chased Dana Kim on *X*\", \"Raised *X* to high\", \"Drafted *T* from *X*\", \"Folded *X* into *Y*\", \"Started watching *slug*\"), escalations first; rows sharing an alert collapse to the newest move with the others as an \"also …\" trailer — a close always keeps the visible slot (it carries Undo), otherwise an escalation beats routed / nudged / drafted; a merge whose survivor is listed becomes \"N duplicates folded in\" on the survivor. Every row links its `evidence_ref` (or \"evidence\") to `/audit?event_type=…&q=…` (the audit page pre-fills those filters from the query string), a still-open row jumps to its card (`#alert-<id>`), drafted rows link `/artifacts`, watch rows `/watchlist`. Undo is offered only while the close still stands (`status` not `open`); a reverted close shows \"Reopened\". Dismissing a watch-sourced alert lowers that watch's `trust_score` (which discounts ranking and is shown to the review as evidence); the ack body may carry `mute_topic`. Acknowledging or resolving an alert — including the review closing it itself — marks the review's DMs about it `acted` in the Attunement outcome ledger, for the person it is routed to and the principal only; dismissing it, finding it stale or letting it expire voids them (counted neither way). Review DMs are tagged `alert_review` with `alert:<id>`.\n\n## Multi-client practice section\n\nIn multi-client practice mode (2+ client slots — see the Client Companies section), the response gains an additive `practice_clients` list: rollup cards for the **parked** clients (overdue follow-ups, awaiting replies, unread alerts, onboarding due soon, renewal countdowns), each stamped with the save point its data reflects. Single-company installs always receive an empty list and the UI renders nothing.","mermaid": "flowchart TD\n REQ[\"GET /today\"]\n BUILD[\"_build_today()\"]\n DEPTS[\"departments<br/>(per-dept goal health)\"]\n ROSTER[\"people<br/>(attention-ranked roster)\"]\n PROPS[\"proposals<br/>(unread alerts, routed)\"]\n INFLIGHT[\"in_flight<br/>(pending follow-ups / nudges)\"]\n AWAIT[\"awaiting<br/>(replies we await)\"]\n NARR[\"viewer-scoped narrative (BackgroundTask)\"]\n MB[\"morning_brief workflow\"]\n TOP3[\"GET /today/top-three<br/>(solo, principal only)\"]\n PICK[\"build_top_three()<br/>(calendar read, 4 s cap)\"]\n WREV[\"GET /today/weekly-review<br/>(solo, principal only)\"]\n RUNS[\"workflow_runs<br/>(latest done weekly_review)\"]\n LIVE[\"live_signals<br/>(inbound / held replies / chats,<br/>cached calendar)\"]\n TICK[\"scheduler tick<br/>(every 10 min, 06–22 local)\"]\n CACHE[\"briefing_narrative<br/>(principal / company / person:id)\"]\n REQ --> BUILD\n BUILD --> DEPTS\n BUILD --> ROSTER\n BUILD --> PROPS\n BUILD --> INFLIGHT\n BUILD --> AWAIT\n REQ -->|\"resolve caller, attach\"| NARR\n LIVE --> NARR\n TICK -->|\"refresh_principal_narrative\"| NARR\n NARR --> CACHE\n MB -->|\"since last brief\"| LIVE\n MB -->|\"calls directly for standalone DM\"| BUILD\n MB -->|\"same pick for the DM\"| PICK\n TOP3 --> PICK\n WREV --> RUNS\n class REQ entry\n class BUILD compute\n class DEPTS storage\n class ROSTER storage\n class PROPS storage\n class INFLIGHT storage\n class AWAIT storage\n class NARR compute\n class MB compute\n class TOP3 entry\n class PICK compute\n class WREV entry\n class RUNS storage\n class LIVE compute\n class TICK entry\n class CACHE storage",- "generated_at": "2026-10-13T13:10:00Z"+ "generated_at": "2026-10-13T20:00:00Z"}diff --git a/packages/core/openexecutive/architecture/prebuilt/workflows.json b/packages/core/openexecutive/architecture/prebuilt/workflows.jsonindex 3f6db032..0f146fc5 100644--- a/packages/core/openexecutive/architecture/prebuilt/workflows.json+++ b/packages/core/openexecutive/architecture/prebuilt/workflows.json@@ -1,7 +1,7 @@{"section_id": "workflows","title": "Workflows",- "markdown": "Workflows are deterministic, multi-step orchestrations. The built-ins are registered in `openexecutive.workflows.WORKFLOW_REGISTRY`; user-created (dynamic) workflows are stored as data (see below). Each follows the same contract: structured input feeds an ordered list of named steps that render a Markdown artifact, persisted via `complete_run` into `workflow_runs.artifact`. Every step emits a `WorkflowEvent` (start/progress/complete) streamed over SSE at `/workflows/{name}/runs`.\n\nThe registry holds 25 built-in workflows, plus any number of user-created ones. Representative built-ins:\n\n- `board_prep`, `quarterly_plan`, `annual_plan` — planning and governance deliverables.\n- `performance_review`, `comp_refresh`, `org_design`, `exec_search_brief` — people and org artifacts (the last is an advisory hiring brief / scorecard from the CHRO, with input from the hired function's specialist — `sales` for a sales role — kept when the recruiting pipeline was removed).\n- `crisis_comms`, `churn_deep_dive`, `competitive_teardown` — situational analyses.\n- `department_check_in` — runs on department cadence; its `goal_status` step returns structured verdicts persisted back to `department_goals.status` (`department_check_in.persist_goal_verdicts`, shared with `weekly_review`).\n- `weekly_review` — the principal's weekly look back and ahead (see *Weekly review* below).\n\n**Standing facts in unattended output.** `end_of_day_digest`, the weekly review's top-three call and the morning reflection append the standing facts (`memory.facts.with_standing_facts`; a teammate's marked `(per <name>)`) to their user turn, and the morning brief gets them through `render_briefing_context`. A workflow step that consults a specialist gets them through `route_to_specialist`. A correction made in chat therefore holds in every recurring brief and run. The morning brief also reads `facts.render_teammate_changes(since)` off the event loop and passes it to both `render_briefing_context` (a TEAMMATE CORRECTIONS SINCE LAST BRIEF block) and `build_brief_fingerprint`, so the principal hears of each correction a teammate made in the window, and that alone un-suppresses an otherwise unchanged brief. Proposals waiting for approval are listed only in a brief the principal reads privately (`include_proposed=_private_ok()`), and then mark the run private to them. The principal's own Always in the loop notes (`memory.history_brief`, only with their switch on) come in by a stricter rule, only on the scheduler's delivery (`PRINCIPAL_DELIVERY`), never a run from chat, whose tool result reaches the turn's shared audit row and peer memory: the morning brief's FROM YOUR NOTES — DUE SOON block and the end-of-day digest's FROM YOUR NOTES — TODAY block (what they committed to since the last digest, then what is due tomorrow). Either marks the run `private_to_principal` and moves its fingerprint; the digest, which had no private reads before, now emits that flag too.\n\n### Change-aware principal briefs\n\n`morning_brief` and `end_of_day_digest` are the two recurring briefs the scheduler sends to the principal. Both are now a *delta*, not a re-list: the window is \"since the last **delivered** brief\" (`briefing.brief_state.since_for`; 24 h on a cold store, clamped to 7 days), activity comes from `_build_activity(limit, since=…)`, proposals (action category only) split into *new since last brief* — enumerated, with each item's why-now and next move — versus a one-line carried-over count, a *rewritten* block lists carried items the review rewrote inside the window (`brief_state.rewritten_since`: verdict `changed`, still open — the brief reports them under \"what changed\", never as done), and a *handled overnight* block lists what the Executive's alert review **completed** on its own (`brief_state.handled_since`; the `changed` verdict is excluded because the alert is still open). The morning brief also reads the principal's **live world** since that window opened (`briefing.live_signals.gather_live_signals`): mail and chat the Executive handled (INBOUND, grouped by sender and subject), what got stuck (STUCK: a reply the outbound gate held, a non-roster sender who got no reply, a Google Chat message left unanswered, drafts waiting in the principal's Gmail), the principal's own chats, and — in both modes now, unless the solo top three already listed it — today's calendar, read fresh (`live_signals.refresh_calendar(max_age=0)`). The 07:30 reflection's **Flagged for the brief** bullets are carried across (`brief_state.reflection_flags_since`, the latest reflection run finished inside the window) instead of surviving only as an activity line with the run's title, and the rhythm runs themselves (`today.RHYTHM_WORKFLOWS`) are dropped from the brief's activity: their dated titles were noise and moved the fingerprint every day. At-risk departments name their slipping goals and each proposal carries its age. The period is the principal's local date. Section order: top call → **today** (the calendar's shape and anything stuck) → what changed (inbound first, naming who wrote) → handled overnight → needs you (new only) → waiting on → at risk (the slipping goal, or the department left out — never \"no detail yet\"). Quoted mail, chat, invite and reflection text is marked as data, never instructions. **Privacy:** the brief reads what is private to the principal — their contacts' alerts and mail, their drafts, their chats and their calendar — only on a run for them: the scheduler's (`morning_brief.PRINCIPAL_DELIVERY`) or the principal's own verified chat turn in a conversation only they can read (`delegation.settings.private_conversation`: the web chat, a Slack or Discord DM, a private Telegram chat — never a shared channel, where the reply is posted for everyone). A run anyone else starts (a teammate from chat in team mode, `POST /workflows/…/runs`) reads what everyone may see, as before. A run that did read a private row says so on its `result` event (`private_to_principal`: its live read differs from the shared one in any key or count), and the scheduler, `run_workflow` and `POST /workflows/{name}/runs` all then keep `persistence.PRIVATE_RUN_ARTIFACT` in the run history instead of the text. Text another pass wrote (the reflection's flags) renders as quoted ` > ` lines and every goal and headline field is one-lined, so none can start a line that reads as a block header. The fingerprint carries the live signals' time-free keys (who wrote about what, what is stuck, the calendar's shape) and the reflection flags when there are any, so \"nothing new\" means the principal's world was quiet too; the context summary is logged at INFO (`morning_brief: context since=… inbound=… stuck=… suppressed=…`). In **solo mode** (one person using Open Executive for themselves) both briefs speak to the principal, whatever their role: the morning brief runs top call → top three today → what changed (inbound and stuck first) → handled overnight → needs you → due this week (the principal's open loops overdue or due within 7 days, from `open_loops.principal_due_soon`) → goals at risk (named by area), the end-of-day digest what I did → open decisions → goals at risk tomorrow → sleep on this, over a context with goals at risk by area and no people-waiting or department block; the fingerprint carries the mode and ignores who is awaiting, and carries the due items as `(loop_id, state)` pairs when there are any. **Top three today** is picked in code, not by the model (`briefing.top_three`: overdue then due-today commitments, off-track then at-risk goals, commitments due later this week, then active projects, stalest first). The solo Briefing's *Top three today* card shows the same pick from the same code (`GET /today/top-three`, see Today). When the MCP gateway runs the Google Workspace server, one `google_workspace__get_events` call (4 s timeout) lists today's events on the principal's calendar — their address as the calendar id, read with the Executive's account (`primary` when the Executive is signed in as them) — and on a business day (`calendar_tools.is_business_day`, the rule the booking tools apply; at the weekend the day's events are still listed but no slot is suggested) each item gets its own free block inside `CALENDAR_BUSINESS_HOURS_START`–`_END`, rendered with a TODAY'S CALENDAR block — only a date-only event is all day, a zero-length one blocks nothing, and one whose times can't be read is left out; no gateway, no principal address, an error, a timeout or a reply it cannot read all mean no calendar and no slots, never a failed brief; the log records only the reply's length or the error's type, never calendar text. The fingerprint carries the three items' keys (no dates, no slot times) and only a coarse hash of the day (busy blocks rounded to 15 minutes, no titles, no dates), so an unchanged day still suppresses. A day whose calendar read fails after one that worked (or the reverse) changes the fingerprint once, so that brief is written in full. A date-free fingerprint of the inputs is compared to the last delivered one; if unchanged the artifact is the one-liner \"Nothing new since yesterday's brief — N items still waiting on you.\" and no model call is made (`PRINCIPAL_BRIEF_SUPPRESS_UNCHANGED`; `force_full=true` on a manual run bypasses it). The workflow yields a `result` event with the fingerprint; only the scheduler records it, after a successful delivery, in `briefing_narrative` under scope `brief:<kind>` — so manual runs never advance the window.\n\n**Brief delivery.** `scheduler.runner._deliver_to_principal` maps the principal's `preferred_channel` (`slack` / `discord` / `telegram` / `email`) to its delivery channel and tries it first, then the other chat channels the principal has an id for, in the order Slack → Discord → Telegram. Email goes through the active MCP gateway (`google_workspace__send_gmail_message` as the Executive's own address, to the principal, subject `<title> — <date>`) and is used only for an explicit `email` preference, or for `any` when no chat channel resolves — an owner linked by email at setup has `any`, so one who also has Slack does not start getting two emails a day. When nothing can deliver (a web-only principal, or email with no gateway), the brief is still generated and stored as a run with its artifact, as before — a web-only principal reads it on the Artifacts page — it is just not delivered (audited), so the window does not advance, and the next occurrence is chained. The same delivery path carries the client-rotation digest and the weekly review.\n\n**Grounding.** Nothing an unattended pass writes is read by anyone before it goes, so `openexecutive.briefing.grounding` checks it deterministically — no model judges the model. A name (a run of two or more capitalised words once section headers, weekdays, imperative openers and org nouns are trimmed, or one capitalised word in a person slot like \"ask Marcus\" or \"Marcus wrote\") is grounded only when a single line of the pass's inputs holds all of it, or it belongs to a roster person some input mentions — being on the roster alone is not enough. A figure (money, a percentage, a k/M/B number, any bare number of 11 or more; never a date, time, year, duration, id, list marker, `Q3` or small count) is grounded when an input number matches it within the precision it is written with (`$1.2M` matches `$1,234,567`; `47 units` does not match 48). The inputs are the rendered context split into lines labelled by section (a header also carries its bullet count), the company profile and the department titles. `morning_brief` renders its context itself and hands it to the synthesizer as `rendered_context`, so the check reads exactly what the model read; after the quiet fallback, `ground_brief` runs on both briefs. When something is ungrounded it makes one repair call to the fast model (same system prompt, the list of items, \"remove or correct using only the context\"), re-checks, then drops each line still ungrounded and any header left empty, and appends \"_Held back N lines that named people or figures I couldn't match to your data — /today has the full list._\" (everything ungrounded → one held-back line). Then each grounded figure gets a server-chosen ` [n]` — the matching input line with the most words in common with the figure's clause — and a `**Sources**` list closes the brief (`- [n] <section> — <snippet>`, at most 9, snippets quote inbound mail, so links are masked (\"(link removed)\"), Markdown, angle brackets and @-mentions stripped, and they are cut to 90 chars; never `[n]:` at a line start, which Markdown reads as a link definition). Text with nothing to change comes back byte-identical, the fingerprint hashes the inputs so suppression is unaffected, and the grounded text is what is delivered, stored and recorded as delivered. Both brief prompts and the digest prompts say the rule up front. `executive_reflection` wraps its handlers in a `GroundingScope`: `create_alert`, `message_person`, `send_department_message`, `send_company_broadcast` and `schedule_followup` refuse text with an ungrounded name or figure, returning a JSON error that names the items so the model can look the person up or leave the figure out (every tool result joins the inputs, so a `lookup_person` answer grounds the DM after it; the recipient's own name always counts). Its **Flagged for the brief** bullets are filtered the same way before the tool log is appended — the next brief quotes them, where they would ground themselves — and `brief_state.reflection_flags_since` now stops at the tool log's `---`. The reflection's `grounding` rows are private when a private-to-principal alert reached its context, and the digest's always are (its HANDLED block can quote one). Everything fails open. `GROUNDING_CHECKS=enforce` (default) acts, `report` only writes the `grounding` audit rows, `off` skips it; `GROUNDING_CITATIONS=false` drops the markers. Not yet grounded: the /today header (its cards sit beside it), `weekly_review`, the research synthesis, dates and meetings, and a real person named in the wrong role.\n\n### Weekly review (solo)\n\n`weekly_review` (background, inputs all defaulted) closes out the principal's week in six steps. **Goals**: every area with goals is graded by its own specialist, concurrently, with the department check-in's verdict contract (`_parse_verdicts`) and write-back (`persist_goal_verdicts` → `record_goal_review`, one `goal_status_review` audit row per area with actor `weekly_review`); an area with no goals is skipped, one without a specialist is listed ungraded, and one whose specialist fails is shown as last recorded. **Commitments**: `open_loops.principal_due_soon` — overdue or due within 7 days. **Projects**: active initiatives with no update for 7+ days. **Decisions**: the week's (`episodic.decisions_since`). **Revisit**: up to three decisions older than 30 days with an empty outcome (`episodic.decisions_awaiting_outcome`, newest first), listed as `[decision N]` under *How did these turn out?* — the principal's answer is recorded with `record_decision_outcome` (see Agents). **Assemble**: every section always renders (a one-line note when empty), ending with *Next week's top 3* from one fast-model call that follows the `weekly-review` playbook (a constant system prompt; the playbook rides in the user turn), trimmed to at most three list items — or, when that call fails or returns nothing, the same ranked pick the morning brief uses. In solo mode the scheduler fires it weekly (`principal_weekly_review`, see Scheduler) and delivers it through `_deliver_to_principal` like the briefs, recording the delivery outcome. The solo Briefing also shows the latest completed run to the principal (`GET /today/weekly-review`, see Today): `weekly_review.summarize_review` reads the artifact's title line (`TITLE_PREFIX`) and its last `TOP_THREE_HEADING` section back as plain text, so a principal no channel reaches still sees next week's top three. Wording is role-neutral; run by hand in team mode it says *department* instead of *area*.\n\n**Principal-only workflows.** A workflow can name the workspace modes in which only the principal may start it (`Workflow.principal_only_modes`): `weekly_review` in both modes (built from the principal's decision log, commitments and goals, and it re-grades the goals) and `morning_brief` in solo (built from the principal's commitments and calendar). Team `morning_brief` and every other workflow can be started by anyone as before. This decides who may start or trigger a run, not who may read one: stored runs, the scheduled briefs and weekly reviews included, are read under the existing `/workflows/runs` rules — which is why a morning brief that drew on the principal's private rows is stored as `PRIVATE_RUN_ARTIFACT`, not as its text.\n\n- **From chat**, `run_workflow` checks at dispatch, before any run row is created, that the turn is the principal on a verified surface — `create_goal`'s rule — and otherwise refuses with a plain error that does not spell out the rule.\n- **Over HTTP**, the Jobs page's `POST /workflows/{name}/runs` and `POST /evals/runs` (a workflow scenario runs the workflow on live data) call `refuse_principal_only_run`: only a caller signed in as the principal, or a request with no caller email (the CLI or local login), may start the run. Unlike the workspace settings, an install with no principal on the roster lets no signed-in caller in, as in chat. Anyone else gets a 403 (\"Only the principal can run this workflow.\") before any run row exists. The mode is the stored one, or an eval scenario's own `workspace_mode`. The eval route runs exactly the scenario list it checked.\n\nEvery refusal is audited `refused=true` with the workflow, the mode and the caller. The checks fail closed: a mode that cannot be read counts as principal-only, and a check that cannot read the roster refuses.\n\n**Knowledge in the reflection.** A chat turn looks the knowledge base up before the Executive answers; the reflection reads the org's state instead, so nothing looked it up for it. It now carries its own `search_knowledge` tool (`orchestrator.knowledge_tools`, not in the shared `_ALL_SKILL_TOOLS`), which runs the same `knowledge.retriever.retrieve` as chat — the review gate, the synced Drive / OneDrive / Confluence / Notion collections and the published-artifact rule (the pass has no viewer, so no one's private document comes back). The prompt (`_KNOWLEDGE_RULE`, both modes) asks it to search before acting on or flagging something that turns on a customer's or supplier's terms, a price, a policy, a plan or a past decision. Its passages come back up to 4,000 characters (`execute_tool_calls(wide_results=...)`) while other tools stay at their short preview, its result counts as grounding input like any tool result, and the run's tool log keeps each line to 160 characters. Read-only, so Take the lead never gates it. The loop has 5 iterations (was 4) to leave room for a search before acting.\n\nNeither the nightly reflection nor the research synthesis can call `ack_alert`: both run unattended with open alerts rendered into their context, and those headlines are minted from inbound mail and chat, so an injected \"the principal already dismissed 13\" would be acted on with nobody watching. Closing an alert is the alert review's job, with evidence.\n\n`executive_reflection` now carries memory: yesterday's standup (the previous completed run's artifact) is rendered into the context and the prompt forbids re-acting on anything listed there unless it changed; open alerts render with their id, review verdict and recommended move. Reflection never closes alerts — the alert review does, with evidence. It also renders an **OPEN LOOPS** block (up to 10, soonest due first, overdue flagged) from Attunement so the standup can connect a slipped promise to the rest of the org state; the nudge engine already chases overdue loops, so the prompt tells it not to DM about a loop merely for being overdue. A **WHAT LANDS** block (from the Attunement outcome ledger) shows, per person, how often each kind of proactive DM got answered over 30 days; the prompt steers DMs toward kinds that land and away from kinds a person reliably ignores. Reflection and research tag their tool execution as proactive (`tag_proactive`) so their DMs are counted. Resolving a wait-for-human approval (`resumer.apply_resolution`) marks the nudges that chased it `acted`. `close_open_loop` is withheld from reflection for the same reason as `ack_alert`: loop text is quoted from what people wrote. `unattended_toolkit` also drops `schedule_tools.UNATTENDED_WITHHELD_TOOLS` (today `create_goal`) from both passes in both modes: a goal is the principal's own decision, and these passes see only inbound text. A turn private to the principal (mail from one of their contacts, or mail they forwarded) cannot start a workflow either: `run_workflow` and `run_executive_research` are in `schedule_tools.PRIVATE_TURN_WITHHELD_TOOLS`, which the chat loop neither offers nor runs on such a turn, since a workflow's steps can reach anyone.\n\nIn **solo mode** the reflection is framed for the principal, whatever their role: they are the only person who uses Open Executive and the only one it takes direction from, it prefers `create_alert` and `schedule_followup` to the principal, and it never messages anyone else from an unattended pass — the people in the principal's world are contacts, so anything they should hear is flagged for the principal to raise. The team roster is replaced by one YOUR PRINCIPAL line (person_id and follow-up channels), its follow-up guard is seeded from the principal only, and department risk renders as areas with goals at risk. The research synthesis follows the same rule — its routing menu and roster name only the principal. In both, `send_department_message`, `send_company_broadcast` and `set_department_head` are withheld, and so are `create_calendar_event`, `create_instant_meeting` and `run_workflow` — a booking reaches its attendees and a workflow can do anything its steps do, so the principal books and starts workflows from chat — and `message_person` refuses anyone but the principal. These passes run unattended with inbound text in their context, so the rules are enforced in code, not only in the prompt.\n\nIn either mode, both passes now dispatch only the tools they offer: the handler map is built from the offered list, so a name the model emits without being offered it is skipped as an unknown tool. They used to look names up in the full handler registry, so tools they deliberately withhold — the raw DM tools (`send_slack_dm` has no roster check), `ack_alert`, `close_open_loop`, and in research the watchlist writes and `run_workflow` — still ran when the model emitted them. Both read the mode before binding their own session (so a caller's override, such as an eval's, counts) and pin it on that session, so their tool handlers use the same mode. They carry the principal's role across the same way (`effective_principal_role` of the caller's session, pinned as `turn_principal_role`), so a specialist or workflow started from either pass sees the role of the turn that started it. Team runs are unchanged.\n\n### Wait-for-human pause\n\n`wait_for_human` (`openexecutive/workflows/wait_for_human.py`) is a first-class step primitive that pauses a run: the runner calls `save_checkpoint`, the `workflow_runs` row moves to `status='awaiting_human'`, and the serialized `WaitForHumanEvent` is stored in `state_json`. (Department authority is a *separate* mechanism — `propose_only` departments file a briefing alert via `departments.authority.propose_via_alert` and mark the scheduled action done; they do not route through this gate.)\n\n**Delivery.** Both checkpoint sites — the SSE route and the `run_workflow` chat tool — call `workflows.gate_delivery.deliver_gate_question` immediately *before* checkpointing, so `state_json` carries the routing fields a reply is matched against. Two modes. When the approver is the person already in the conversation (the chat session's `origin_channel` is set — to anything but `email`, whose answer is no chat reply and would never be sent — and its `caller_person_id` is the gate's `person_id`), nothing is sent — the question rides in the Executive's own reply — and the gate records `origin_session_id` plus the session's channel. The resolver compares base ids (`memory.conversation_ids.base_session_id`), so a question asked in one conversation of a Telegram chat or a DM is still answered by a reply after a quiet gap or /new has started the next. Otherwise the question is delivered through `schedule_tools.handle_message_person`, which picks the person's preferred channel, falls through on a failed send, and falls back to a briefing alert; the gate then records the channel, address and provider message id that send returned, plus the id of the DM session it landed in — that send is always 1:1, so the answer belongs in that conversation and nowhere else. Without it the gate matched on person and channel alone, so an unrelated @mention in a public channel resolved it and had the acknowledgement, run title included, posted where everyone could read it. Delivery is not guaranteed: the outbound guard can suppress it (duplicate, rate cap, quiet hours) and an unreachable person gets the alert fallback. Both cases leave the routing fields empty and report `delivery` as `suppressed` / `alerted` rather than claiming someone was asked, and the chat tool's presentation hint changes accordingly.\n\n**Matching a reply.** Each inbound adapter passes the message to `inbound_resolver.resolve_inbound_message` with its `session_id`. Matching is three-tier: an explicit `in_reply_to` against a stored `outbound_message_id`; otherwise a single open run on that channel; otherwise one utility-fast disambiguation call gated at 0.85 confidence. An unmatched explicit reference rules out only the candidates that carry a stored outbound id — the ones it could have matched — and the rest continue; rejecting outright meant an adapter that passes a thread id on every message (Slack's `thread_ts`) short-circuited the later tiers forever, and a global test let one delivered gate's id block an unrelated self-approval gate. Channel names are normalized (`slack_dm` ≡ `slack`), the delivered address is compared when both sides know it, a row whose `state_json` will not parse is refused (a corrupt row otherwise presents as a legacy one), and an empty stored channel is treated as a wildcard only for rows checkpointed before gate delivery existed. Two guards keep an open gate from swallowing unrelated traffic: a gate carrying an `origin_session_id` matches replies only from the conversations the adapter names (a Slack or Discord thread offers its parent channel session too, mirroring the history double-write, since a gate raised on a mention recorded that session while the answer arrives under the thread's — on Slack only when that person rooted the thread, or the alias would reach into a colleague's), and the parser can return `unrelated`, which declines to resolve and lets the message reach the normal chat path. The parser is handed the gate's own question, so a bare \"yes\" is judged against something. Its fallback is flagged by a key the model cannot emit rather than by a magic note string it could, and a fallback declines to resolve on *every* reply shape — recording the empty string a `free_text` fallback fabricates would close a sign-off on a parser outage. Every shape can answer `unrelated`, not just `approve_reject`: without it an open `free_text` gate turned the person's next message into its answer verbatim, and a `numeric` one swallowed any message containing a number. The parser has one caller outside workflows: its `roster_identity` shape — `{decision: approve|link|decline|unrelated, name, kind: team|contact|null}`, with `name` only as the person wrote it (never inferred) and a fallback of `unrelated` — reads the principal's emailed answer to a roster request (who a new sender is; see Org). It is not a gate reply shape, and a fallback or `unrelated` leaves the request waiting. `resumer.apply_resolution` then records the decision, marks the run `resolved`, and writes an audit row. A timeout applies the step's `on_timeout` policy (escalate / auto_proceed / fail). The outcome surfaces on the Today dashboard.\n\n**Resuming past the gate.** A paused run continues on its own. Re-entering it was long assumed to mean serializing a Python generator frame; it does not. The only state alive across a dynamic workflow's steps is its inputs (already persisted), a company-profile block that is recomputed, the completed steps' output strings, and the loop cursor — so the engine hands the checkpoint a small JSON `WorkflowResumeState` (workflow name, the gate's id and index, the next index, the outputs so far), stored in `workflow_runs.resume_state_json`, and `DynamicWorkflow.resume` replays its step loop from the recorded index. `run()` and `resume()` share that one loop, which is why a second gate needs no special handling — it is simply another pause raised from the same place. The payload rides on a `WaitForHumanEvent` field declared `exclude=True`, so it can never leak into `state_json`, whose exact key set the resolver branches on. A gate with no payload is *pause-only*: the decision is recorded and the run stops, which is what every caller got before resume existed.\n\n`resumer._process_resumable` claims a resolved run with one guarded UPDATE — `resolved` → `running`, stamping `resumed_at` and minting a claim token — and drives it to a terminal row. It runs two ways: immediately, via a task `apply_resolution` kicks off so a Slack approval starts moving in seconds, and every 60s from the poll loop as the durable backstop. Both share the claim, so a run executes exactly once even with two resumers against one database. The kicked task binds no chat session (`set_session(None)`), exactly like the poll loop: it is created inside the inbound handler that recorded the answer and would otherwise inherit that person's live turn — so a run resumed because the principal replied on Slack does not act with the principal's identity (it cannot, for example, reach the principal's contacts). It drops the handler's audit scope too (`audit.context.unscoped_audit_rows`): inherited, the principal's scope would make private every row of the run that names a contact, and whoever started the run would see those rows vanish after the approval. The poll runs the executor *after* the timeout loop, which is what finally makes `on_timeout='auto_proceed'` do what its name says: the timeout resolves the run and the same tick executes it. While the Executive is paused (`scheduler.pause`) the resumer does nothing — no startup sweep, no timeouts, no resumes — and `apply_resolution` still records the decision but skips the immediate kick; the first unpaused iteration catches up on all of it, so a timeout that lapsed during the pause applies its `on_timeout` policy then.\n\n**The claim is fenced, because it is not a lease.** The stale sweep decides a worker is dead from a wall-clock guess, so a slow but *alive* worker will eventually be declared dead and replaced. Every write the executor makes carries its claim token and is refused once superseded — otherwise the replaced worker's late completion lands on top of its replacement's result, or its checkpoint at a later gate resurrects an already-finished run and asks the approver a second time. The retry budget resets at each new gate (a gate is new work, not a retry), and a run that exhausts it is *ended* rather than dropped: an exhausted run sits in `running` with a payload, in neither queue, and would otherwise show as in-progress forever.\n\n**The gate fails closed.** Continuing is an allowlist — `approve` and the synthetic `auto_proceed` — not \"anything that is not a stop word\". `decision` is whatever a fast model extracted from free-form chat and it drifts; under a denylist, \"rejected\", \"Reject\", \"decline\" and \"no\" would all continue, so the approver declines and the deliverable is produced anyway. Reply shapes that ask a question rather than seek permission always continue, since the answer *is* the value. A stop ends the run at `error` with the human's note. Either way the decision becomes the gate step's own output, so it reads as a section *in* the artifact — capped and blockquoted, because that text reaches the synthesis specialist as prompt context.\n\n**A definition edited during the pause is refused.** Resume re-validates the payload's version, the recorded gate, *and* a fingerprint of the whole step list, and derives the index to continue at rather than reading it from the payload. Pinning only the gate would not be enough: definitions are overwritten by name and any rostered user can save one, so someone could keep the gate identical and replace every step after it — and the approver's sign-off would be recorded against work they never saw, which defeats the one thing an approval gate is for. No built-in workflow yields the gate; only user-created dynamic workflows do.\n\n### Launching from chat\n\nWorkflows are not only reachable from the `/jobs` UI — the Executive can list and run any of them mid-conversation. `openexecutive.orchestrator.workflow_run_tools` wires two tools into the main chat loop: `list_workflows` (the launchable catalog, with each workflow's input fields) and `run_workflow` (runs one to completion and returns its Markdown artifact, using the same engine as `POST /workflows/{name}/runs`). `run_workflow` resolves both built-ins and custom workflows via `get_workflow`, validates `inputs` against the workflow's input model, persists the run (`create_run` → `complete_run` / `fail_run`), and on an approval-gate step checkpoints the run as `awaiting_human` exactly as the HTTP route does — literally the same code, since both call `workflows.gate.checkpoint_gate`, which delivers the question and writes the checkpoint in one place. It never hangs waiting on a human, and it reports both whether the question reached them and whether the run will continue by itself once answered. The runners that *cannot* pause — the schedulers, evals, client rotation, onboarding, the research tools — call `gate.ensure_workflow_event`, which raises on a gate rather than letting one be swallowed; the scheduler's dynamic-workflow branch used to ignore it and record a successful run containing nothing. `executive_research` is excluded (it has the dedicated `run_executive_research` tool). Running a workflow from chat delivers nothing on its own — it renders the artifact into the conversation, and the recurring principal briefs (`morning_brief`, `end_of_day_digest`) reach anyone only via the scheduler's own `_deliver_to_principal`. The tool description used to claim those two DM the principal when run and to confirm before firing them, which had the model soliciting a confirmation on a false premise; it now names `executive_reflection` as the one workflow that really does execute tool calls of its own (DMs to heads, broadcasts, alerts). A successful run surfaces an `action_taken` chip linking to `/jobs/runs/{run_id}`.\n\n### Dynamic (user-created) workflows\n\nUsers create reusable workflows on the fly — from the executive chat, the conversational wizard at `/jobs/new`, or the step-by-step advanced editor — without shipping code. The Workflows page (`/jobs`) opens on a *Start here* panel that leads to all three: the user describes the job in a sentence and *Start* opens the wizard with that text sent as its first message (handed over in `sessionStorage`, so a link cannot make the wizard send text the user never typed; where storage is blocked it falls back to `/jobs/new?describe=`, which only fills the composer and sends nothing), or picks *Step by step* (advanced editor) or *Talk it through in chat* (`/?new=1&draft=`). Below it come the user's own workflows, then four ready-made starter picks with the full built-in list folded behind *Browse all* (`?browse=1`). The picks and the example chips follow the workspace mode: a team gets the investor update, board prep, MBR and competitive teardown (and a board pre-read chip); a solo owner-operator gets the MBR, pricing review, churn deep dive and quarterly plan, with chips for a Friday cash and pipeline check, customers who stopped buying and a competitor digest (`lib/workflowStarters.ts`; a unit test pins every pick to a startable `WORKFLOW_REGISTRY` entry). A dynamic workflow is a stored JSON definition (the `dynamic_workflows` table) interpreted at runtime by one generic `DynamicWorkflow` engine (`openexecutive/workflows/dynamic.py`) that implements the same `Workflow` ABC as the built-ins, so the run path, SSE streaming, run persistence, and `/jobs/[name]` form rendering are unchanged. `get_workflow` / `list_workflows` fall through to the dynamic store after the static registry (built-ins win on a name collision).\n\nA definition declares free-text input fields and an ordered step list of four kinds: **specialist** (consult a specialist with a goal prompt, optionally grounded by RAG), **action** (get something done with tools — see below), **approval_gate** (a `wait_for_human` pause), and a terminal **synthesis** step that assembles the artifact. At least one specialist or action step is required. `validate_definition` enforces the structural rules: exactly one terminal synthesis step, valid specialists, `{placeholder}` tokens that reference declared input fields, rostered approval/cadence people (team members — never one of the principal's contacts, whom an unattended run may not message), and a parseable cadence.\n\nAuthoring from chat uses a **draft → confirm** handshake: the Executive calls `draft_workflow` (validate; return a `confirm_token` plus a plan summary), shows the user the plan, then calls `save_workflow` with the same definition and token — a token mismatch is rejected, so the saved workflow is exactly what the user approved. The step-by-step advanced editor drives the `/workflows/custom` CRUD endpoints directly.\n\n**The New workflow wizard** (`/jobs/new`) is the default way to create one from the UI. It works like conversational onboarding: the user describes the job, the `workflow_designer` Council agent (`openexecutive/workflows/designer.py`) asks one clarifying question per turn — deliverable, per-run inputs, sign-off, schedule, recipient — with up to four clickable suggested answers, then emits a complete definition plus a plain-language summary and the assumptions it made. Every turn offers the model exactly three fixed, name-sorted tools (`ask_clarifying_question`, `emit_workflow_draft` — reusing the chat tool's `DEFINITION_SCHEMA` — and `search_available_tools`, which is answered inside the same turn from the tool catalog, up to four searches per turn, with the tool_use/tool_result pairs never stored in the plain-text transcript; every tool a search returns is remembered on the session and replayed into later turns, so a forced draft or a repair turn — which cannot search — still has the exact names); `tool_choice` flips to the emit tool once, when the six-question budget is spent or the user clicks *Draft it now*. The emitted definition goes through `validate_definition`, the tool-availability check, and a check against saved custom names, with one repair turn that feeds the errors back. The system prompt is a cached constant; the live context — specialists, the roster with person ids, the user's timezone (the one set through `PUT /workspace`, else `USER_TIMEZONE`; cadences stay UTC), and taken names — is rendered once per session into the first user turn, and while refining, the exact current draft is prepended to the latest user turn so the model edits it rather than re-deriving it. Roster names and roles are flattened to one line and capped at 80 characters before they enter that context, and the system prompt tells the model to treat the whole block as data, never instructions. Sessions live in memory (`/workflows/designer/*`, 2 h TTL, 50-session cap), run one model turn at a time (a second concurrent `/message` or `/draft` gets 409, and a failed turn is rolled back by identity), and never write: the review card saves through the same `POST /workflows/custom`, which re-validates, and *Edit details* opens the draft in the advanced editor (`/jobs/new?designer=<id>`) before saving.\n\n**Editing is a conversation too.** *Edit* on a saved workflow (`/jobs/new?edit=<name>`) opens the same designer through `POST /workflows/designer/edit`: the stored definition is the starting draft, so the user's first message (\"have Mark sign off and run it Fridays\") is applied to it like any refinement, and a note in the context block (a user turn, never the cached system block) tells the model it is changing a saved workflow. The draft always keeps the workflow's name — `_check_draft` puts it back and skips the taken-name check — and the route keeps its on/off state, so an edit can neither fork a copy nor switch on a tool workflow waiting for approval. The stored draft is handed to the model marked as data, not instructions. The review card lists *What changes* in plain words against the saved version (`lib/workflowChanges.ts`): every field is compared, with named sentences for the sign-off person and what it asks for — a sign-off moved off approve/reject is called out because the run then continues whatever the answer — the schedule, steps added/removed/reordered, inputs, tools and the tool-call budget, and a catch-all line for any other field. It names only the newly added tools that may change things. *Save changes* calls `POST /workflows/custom/{name}/save-edit`, which saves the session's own draft after re-validating it, only when it is the draft the card showed (the card sends what it displayed; a message that landed since is a 409), and only if the stored workflow has not changed since the conversation opened (409 otherwise), so an edit started before someone switched the workflow off cannot switch it back on. The step-by-step form stays as the advanced editor (`/jobs/new?edit=<name>&mode=advanced`).\n\n**Action steps (workflows that act).** An `action` step (`ActionStepSpec`: `goal`, `tools`, `max_tool_calls` 1–50, default 20) is run by the `workflow_actor` Council agent (`openexecutive/workflows/action_step.py`) as a bounded tool-use loop. Its `tools` list is an allowlist of exact tool names — MCP gateway tools (`server__tool`, e.g. `google_workspace__append_table_rows`) and a small set of built-ins (`oe__read_file`, `oe__message_person`, `oe__create_alert`, plus any installed extension's tools registered with `workflow=True`, as `oe__<name>`, run inside `extensions.workflow_step(name)`; a built-in wins a name clash, and an extension tool counts as reading only when it says so) — and **clicking Create is the user's approval** of that list: the review card shows every tool, flags the ones that may change things (anything whose name doesn't say it reads, and any tool with a URL/URI/endpoint/webhook parameter anywhere in its schema, or whose schema couldn't be read, since a URL can carry data out), and names them in a \"this workflow can use these without asking again\" notice. Because that card is the approval, a workflow with action steps saved from chat (`draft_workflow`/`save_workflow`, whose confirmation is a token the model holds itself) is stored **switched off** (`is_active=false`) and `save_workflow` returns `status: saved_pending_review` with a `/jobs/{name}` link. An inactive workflow can't run or schedule (`get_workflow` and the scheduler skip it); `/jobs/{name}` shows it on the same review card, where **Turn on workflow** (`POST /workflows/custom/{name}/activate`, which re-validates the tools) is the approval — the click sends the definition the card showed, and the server refuses (409) if the stored one has changed since, so chat overwriting it while the card is open can't get new tools switched on. Chat may revise a switched-off workflow but refuses to replace a switched-on one that has action steps (an inbound email steering the Executive could otherwise switch off an approved job and stage new tools under its name); those edits happen in the advanced editor. The Workflows catalog (`/jobs`) lists switched-off workflows in a compact *Waiting for your approval* strip, and saving edits in the advanced editor keeps one off. `tool_catalog.py` resolves names to schemas through the gateway's `search_tools` (extensible-mcp's Markdown output is parsed; resolving is also the per-session discovery its `call_tool` requires) and validates availability at save time (`POST`/`PUT /workflows/custom`, chat `draft_workflow`/`save_workflow`, designer drafts) — an unknown, misspelled or deny-listed tool is a 422. The gateway meta-tools (`search_tools`, `call_tool`, `load_mcp_server`) can never be step tools. `run()` resolves every action step's tools before any step runs, so a vanished tool stops the run before an earlier step acts; `resume()` checks only the steps still to run, after the gate and decision are validated. The last turn of an action step always switches tools off so the agent can report. At run time only the allowlisted tools are offered (sorted; constant cached system block, per-run goal/inputs/earlier results in the user turn), every `tool_use` is re-checked against the allowlist, MCP calls go through `MCPGateway.call_tool` so the config deny-list and the Gmail/Calendar/Drive recipient gates still apply, the call budget is enforced (then a final tools-off turn asks for the report; running out of turns fails the step and lists what was already done), tool errors (the gateway's `Error:` / `Error calling tool` / `Tool error:` prefixes, or a truthy `error` field) return to the model as `is_error` results, each call emits a `progress` event and an audit row (`workflow_tool_call`: tool and outcome; for tools that may change things also a short digest of target arguments — ids, recipients, URLs, paths — so a redirected write is visible; content arguments are never logged), and the step's output is the agent's report plus an \"Actions taken\" list. Tool output is framed as data, never instructions.\n\n**Scripts in action steps.** Besides the step's own tools, the agent is offered one more, `run_script` (`openexecutive/workflows/step_script.py`), for work that repeats over many items — every file in a folder, every row, every email — or chains calls with simple logic. It writes a short Python script once instead of spending a model turn per call; each of the step's tools is a function in the script (`drive__move_file(file_id=…)`, or `call_tool(name, arguments)` by exact name), and only the script's final value and printed output come back. The script runs in **Monty** (`pydantic-monty`), a sandboxed Python interpreter for model-written code, in a worker process spawned per script: no files, network, environment, subprocesses or third-party imports — the step's tools are the only things it can reach. **A script is a faster way to make the same calls, never a way around them:** every call it makes goes through the same per-call path as a direct `tool_use` (`action_step._StepCalls`) — the allowlist, a call budget (a script's calls have their own: 10× the step's `max_tool_calls`, capped at `WORKFLOW_SCRIPT_MAX_CALLS`, default 500, because they cost no model turn each — so a step can work through a folder of hundreds of files while its direct calls stay capped at 1–50), the first-write target check (a held write comes back to the script as `{\"status\": \"held\", …}`) and one `workflow_tool_call` audit row per call — and the script itself is audited as `run_script`, with how many calls it made and how long it took. The step's \"Actions taken\" list collapses repeats into one line with a count. A step whose direct calls are spent keeps its tools on while the script budget has room, so it can still script the rest (a direct call is refused as over budget). When a tool returns a list of five or more items and the round didn't use `run_script`, the step adds the same `FANOUT_HINT` as chat (once a step), pointing the per-item work at one script. The worker is stepped from the step's own task (each call pauses it and is answered there), so cancelling the run stops the script and its in-flight call together, and each call's progress shows as it happens. At most `SCRIPT_MAX_WORKERS` (default 2) scripts run at once across the server, chat and workflows together; another waits for a slot within its own wall clock, else returns \"the server was busy\". A worker exists only while its script runs (about 8 MB idle). Execution time (excluding time waiting on tools), memory and recursion depth are capped inside the worker, the script has a wall-clock limit, and its text is size-capped; printed output past its cap is dropped. A failing script returns its error to the agent as an `is_error` result, with the calls it already made listed first (ahead of any long result, so a cut never drops them) so a fixed re-run doesn't repeat writes; a call cut off by the time limit is listed as `may_have_run`, and gets a `cancelled (may have run)` audit row. A workflow definition still holds no code; a script lives on only if the agent saves it as a tool (below). Because a step can loop at run time, the workflow designer keeps work that repeats over items (each email, file, row or listed follow-up) in ONE action step whose goal spells out the items, rather than a step per item; `run_script` is never a step tool, and a definition that lists it is rejected (`validate_definition`) so the designer's repair turn removes it. `WORKFLOW_STEP_SCRIPTS=false` turns the tool off, and a step then only calls its tools one by one.\n\n**Python jobs (`run_python_job`, `openexecutive/workflows/python_job.py`).** Monty can't run libraries, so library work on files (split or merge PDFs with pypdf, spreadsheets with openpyxl and pandas, charts with matplotlib, images with Pillow, and documents made from scratch or from files: Word with python-docx, PowerPoint with python-pptx, laid-out PDFs with fpdf2) runs as a Python job: Pyodide (Python in WebAssembly) executed by **Deno** in a process of its own per job. Pyodide alone is not a sandbox — its Python can call into the JavaScript runtime, which under plain Node reaches the server's environment, files and network — so Deno is what isolates it: it is started with read access to the sandbox folder and the worker script only, with no network, environment, writes or processes, and an empty process environment. Files go in on stdin and results come back on stdout. A job gets only what the call names: Knowledge-library files, the files attached to the chat message being answered (`attachment_files`, the uploads as sent, bound for that turn only by `POST /chat/upload` in `workflows/turn_files.py`, so the model never retypes an attachment's text), text the caller passes, and `inputs` (a dict the code reads); result files are kept 7 days under the company folder and served to the principal at `GET /python-jobs/{job}/{file}`, which the Executive links in its reply. A deployment can instead send jobs to a separate runner (`PYTHON_JOB_RUNNER_URL`, with `PYTHON_JOB_RUNNER_KEY` as a bearer token): `run_job` POSTs the same job (code, inputs, files, caps, time and memory limits) and reads back the same result object, at most as large as a local job's output, keeping only its known fields, so kept results, links and metering are unchanged; the local sandbox is then not needed, and the runner is trusted to isolate jobs. A runner can turn a job away with `{\"run_locally\": true}` (and an optional `reason`) in a non-200 reply, for example when the deployment's allowance for it is used up: the job then runs in the local sandbox if this machine has one, and otherwise fails with the runner's reason. Any other non-200 reply stays a job error, so a busy or broken runner never moves every job onto the machine. A runner with more libraries lists them in `PYTHON_JOB_EXTRA_LIBRARIES`, which the job tool's description then names, so the Executive doesn't refuse a job that needs one. The tool sits in the `workflows` tool group, labelled for jobs with or without attached files. The library set is fixed at build time: the API image installs Pyodide and Deno from npm and the compiled libraries from Pyodide's CDN, each checked against the sha256 in Pyodide's lock file, and a build smoke runs a job. Pyodide can't infer the compiled packages the pure-Python libraries import (lxml, Pillow, fonttools), so the worker loads them when a job imports docx, pptx or fpdf. Pyodide, Deno and the pure-Python libraries are pinned by hash too (an npm lock installed with `npm ci`, pip `--require-hashes`). One job runs at a time per process (200–450 MB each), with a `PYTHON_JOB_TIMEOUT_S` limit and a memory cap (`PYTHON_JOB_MEMORY_MB`, default 1536, as the process's data limit, plus V8 heap and WebAssembly memory caps); the worker returns at most 20 result files and 25 MB, and the API stops the job as soon as its reply passes that. The job runs at a lower CPU priority and is first in line if the machine runs out of memory, so a heavy job slows or loses itself rather than the API; Deno's own caches go in a temporary folder removed with the job; and kept results are capped at 200 MB in all, oldest first. The tool is chat-only, offered only on the principal's own turns (`PRINCIPAL_ONLY_TOOLS`), withheld on private turns, unattended passes and under the Act as me lockdown, and not offered at all without the sandbox (`PYTHON_JOBS_ENABLED`, `PYTHON_SANDBOX_DIR`).\n\nA job that worked can be kept the same way as a script (below): `save_as` and `description` keep its code as a Custom tool of kind `python`, and `run_python_job(tool=<name>, inputs={...})` with its files runs it again, recording the run, so a job done before costs no code-writing tokens. Python tools run only on the principal's own chat turns: they are never listed for workflow steps and never turn on for workflows (`PUT /saved-tools/{name}` answers 409), and `run_script` refuses one (and `run_python_job` a script tool). Every job writes one `python_job` audit row (`ok`, `duration_ms`, `cpu_ms` and `peak_mb` read from the process's /proc entry just before it is stopped, files and bytes in and out, attachments, the Custom tool it ran or kept), which `GET /audit/usage` sums into `python_jobs` with the model usage of the turns that ran one.\n\n**Saved tools.** A script that works can be kept to run again by name (`openexecutive/workflows/saved_tools.py`); each tool has a `kind`, `script` (`run_script`) or `python` (`run_python_job`, above). `run_script` takes `save_as` and `description` with a new script: if the script succeeds it is saved, with the set of tools it actually called, and a failed script is never saved. Later, `run_script(tool=<name>, inputs={...})` runs the saved script instead of new code, with `inputs` available to it as a dict. Only the principal's own turns save: a chat turn where the principal is speaking on a verified, interactive surface (the same test as `load_mcp_server`), never an inbound email, a teammate, an unattended run or a workflow step — a step is offered `tool=` but not `save_as`. A saved tool runs with the authority of whoever runs it, so its author must be trusted at least as much as anyone who may run it. For the same reason only a workflow step (its tools owner-approved) or the principal's own turn may run one: anyone else's chat turn is refused `tool=` and not offered `list_saved_tools`, so a stranger can neither list the principal's automations nor run one with inputs they choose. Descriptions are kept to one line of printable text (they are shown to models), and every save writes a `saved_tool_changed` audit row (`actor: executive`) beside the owner's own changes. Saving needs no approval beyond that, because a saved tool can do no more than the context running it: its calls go through the same per-call path as any script (in a step: the allowlist, budget, target check and audit), and a step runs one only when the step already allows every tool it used (otherwise the result names the `missing_tools`) and only at the version the owner turned on for workflows (`workflow_version`, Settings → Advanced → Custom tools → Use in workflows). A tool kept on a turn that read outside content could otherwise carry injected code into an unattended run, so keeping stays automatic and works in chat at once, but workflows wait for the owner; a newer save doesn't change the version workflows run, and pruning never drops it. Each step's `run_script` description lists the saved tools that step may run; chat asks `list_saved_tools`. Every save of changed content is a new version (the newest 20 are kept, plus the one that ran until then, so a rolled-back version the owner trusts survives later saves), every run is recorded (`saved_tool_runs`, the newest 200 per tool), and the owner can turn a tool off or switch it back to an earlier version on Settings → Advanced → Saved tools (`/saved-tools` routes, the owner's alone). A turned-off tool never runs, and a new version saved by the model does not turn it back on. `SAVED_TOOLS_ENABLED=false` stops saving and running saved tools everywhere.\n\n**Targets are chosen at run time — and a new one is confirmed once.** Approving a workflow approves its *tools*; which sheet, doc, recipient or URL each call hits is chosen by the model at run time, by design (a tab per month, a reply to whoever sent the invoice, a doc per client). What bounds that is the allowlist, the gateway's recipient gates, the audit digest, and **first-write confirmation**: a `TargetPolicy` (one per run) checks every call to a tool that may change things. `resource_targets` walks its arguments recursively for resource keys (snake- or camel-case ids, `to`/`cc`/`bcc`, recipients, addresses, attendees, members, users, owners, parents, URLs/links/hrefs, paths, channels, spaces, rooms, phones, hosts, buckets, tables, spreadsheet/document/folder/calendar/file); a matching key marks everything beneath it, even a `name`. Outside a resource, only a new item's own `name`/`title`/`subject`, message/thread/draft/label ids, `range`/`sheet` and workspace-mcp's acting `user_google_email` are skipped — and whatever the key, a bare value shaped like an email address, a URL or an international phone number is a target, except inside what the call writes (`rows`, `values`, `body`, `text` …). Key names are a heuristic, so this is a best-effort guard layered on the allowlist, the gateway gates and the audit. Float ids are compared as integers. Arguments too deep, naming too many targets, or holding an over-long value **fail closed** (the call is refused). A target is trusted only when it was approved for this workflow before (`workflow_approved_targets`, by value) or is an id a write in this run created — a top-level id/link field (`id`, `spreadsheetId`, `webViewLink` …) of the **structured JSON object** result of a tool whose name says it creates (create / insert / upload …) and that takes no URL — a tool whose schema couldn't be read is assumed to (free text, nested records and readers' or updaters' results are never read, so a fetched page, an echoed title, a shared page's links or a stranger in `ccRecipients` can't plant one); those survive a pause in the resume payload (`run_created`). Values written in the workflow's own text are *not* trusted, since anyone who can edit the workflow could change them without review: they are asked once, then remembered. Approvals are by value, for any of the workflow's tools, and are **cleared when the workflow's tool set changes** (a newly added tool must earn them again). Any other target makes the call **held**: it is not run and costs no budget, the model is told it is waiting for approval and carries on, and it is audited `held for approval` (at most 10 held per step, 16 KB each; an identical repeat is held once). Whether a call is checked at all follows the read-only label, which now never marks a tool whose name carries a write verb anywhere (`find_and_replace_doc`). After the step finishes, the run pauses with a `WaitForHumanEvent` to the workflow's **owner** (`owner_person_id`, the person who created it on the Workflows page or in chat; falling back to the principal if unknown or archived), `on_timeout=auto_proceed`, 48 h, and a `WorkflowResumeState` of `kind=\"held_writes\"` carrying the exact held calls. On resume (`_resume_held_writes`, fingerprint-checked like a gate, with the remaining steps' tools checked first), only `approve` runs them — each still has to be in the live step's allowlist and resolve; its targets are remembered first — and anything else (decline, timeout, unreadable) skips them; either way a *Held for approval* section is added to the step's output and the run continues at the next step. With no one to ask, held writes are skipped and noted; a step that fails or crashes after holding, or a resume that stops early (definition changed, a later tool missing), audits its held writes as dropped and says they did not run. The question quotes each target JSON-escaped (a value can't add its own lines) and always shows a URL's full scheme and host, saying how much of the rest is hidden. The owner answers by chat reply or with **Approve / Decline** on the run page (`POST /workflows/runs/{id}/decision`, which the principal may also use); remembered targets are listed and removable on the workflow page.\n\n`oe__read_file` extracts text (PDF, Word, Excel, CSV, Markdown, text) only from files under `WORKFLOW_FILE_DIRS` (default: workspace-mcp's attachment folder), resolving symlinks and `..` before the check (`tool_catalog.resolve_readable_file`, shared with the Executive's `read_document` tool). A scanned PDF is converted by `knowledge.pdf_reader` instead of failing as \"may be a scanned image\"; one that still cannot be read returns the reason. Action steps are allowed in scheduled workflows. Because they have external side effects, a resumed run heartbeats its claim (`touch_resume_claim`, at most once a minute as events flow — each tool call emits one; a busy database is retried on the next heartbeat, never treated as a lost claim; the sweep's requeue re-checks the claim's age in the same UPDATE, so a heartbeat landing between the sweep's read and its write wins), so the stale-claim sweep never requeues and replays a slow but live run, and a worker that finds its claim superseded stops at its next event. A worker that actually crashes mid-resume is still requeued; its action steps then run again, so goals should say how to avoid duplicates (the actor reads current state before writing). `GET /workflows/tools/search?q=` and `GET /workflows/tools/describe?names=` back the advanced editor's tool picker and the review card's labels.\n\nAn optional cadence (`daily@` / `weekly@` / `quarterly@`) re-uses the scheduler via the `dynamic_workflow` action kind, which runs the workflow on schedule and DMs the artifact to a rostered recipient. A gate followed by further steps pauses at `awaiting_human` and then resumes once answered, so gates no longer have to sit immediately before synthesis. They remain forbidden in cadence-enabled definitions: a scheduled fire has no interactive human to ask.\n\nBuilt-ins the system runs on its own (`morning_brief`, `end_of_day_digest`, `executive_reflection`, `executive_research`) set `background = True`, surfaced as `WorkflowMeta.background`; the `/jobs` ready-made list files them under a **System** chip instead of the default view. They stay runnable by hand.\n\n**Quick workflows** (`workflows/quick.py`) are one per playbook in effect that no built-in or custom workflow follows (switched-off custom ones count). They are derived whenever the catalog is read, never stored: `list_workflows()` returns built-ins, then Quick ones, then active custom ones, and `get_workflow` resolves a `quick_<playbook>` name after the registry (custom workflows may not take the `quick_` prefix). Each has one required field, `request`, and two steps: **Load context** (company profile plus RAG for the playbook category's specialist) and **Draft** (that specialist writes one Markdown document following the playbook). `WorkflowMeta.quick` is true for them. The 8 built-in playbooks no built-in follows are Quick workflows: board update memo, 1:1 agenda, layoff comms plan, positioning statement, post-mortem, customer interview plan, feature prioritization and market sizing. A company's own playbook shows up as one, hiding a built-in drops it, and a custom workflow that starts following one replaces it. If custom workflows can't be read, none are offered, since their followers are unknown.\n\n**Workflows vs. playbooks.** `/jobs` has two tabs: **Build** (`?tab=catalog`, the default) and **Runs** (`/skills` redirects to `/jobs`). A playbook is a skill (`knowledge/skills_repo.py`): *how* the Executive does a piece of work, with no inputs, schedule or side effects. A workflow is the runnable job. Workflows **follow** playbooks: a step that follows one gets its body appended to the step prompt via `workflows/playbooks.py` (`load_playbook` + `playbook_clause`). Six built-ins do — `board_prep` (`board-prep-deck`), `quarterly_plan` (`quarterly-okr-set`, `quarterly-forecast`), `mbr` (`monthly-business-review`, in the financial, KPI and function steps), `competitive_teardown` (`competitive-teardown`, in the four analysis steps), `fundraising_prep` (`fundraise-narrative`, narrative step) and `exec_search_brief` (`role-scorecard`, profile step). Each declares them in `Workflow.playbooks`; a unit test holds that declaration equal to the `load_playbook(\"…\")` calls in the module, and `WorkflowMeta.playbooks` exposes it. A custom workflow's `specialist` step may name a `playbook` (validated to exist at save; appended after `{field}` rendering, so braces in a playbook are never treated as placeholders). The lookup resolves the playbook in effect, so a company's customized copy changes the workflow's output, and a hidden, missing or malformed one falls back to the step's own prompt plus RAG — a workflow never fails over a playbook (`load_playbook` catches everything; a custom step whose playbook is unavailable emits a `progress` event saying so). Because an approved scheduled workflow reads its playbook at each run, chat never creates or changes a playbook: it saves repeatable work as a workflow (`draft_workflow`, confirmed by the user), and only a person can change what a workflow follows: a workflow's page shows each playbook it follows as **How it's done** (`components/jobs/HowItsDone.tsx`), with **Edit** (`PUT /skills/{name}`; on a built-in that saves the company's customized copy) and, for a customized copy, **Reset to original** (`DELETE`, which reverts). The chat summary of a drafted workflow names each step's playbook. `playbook_users()` maps each playbook to the workflows that follow it — built-ins, every custom workflow (switched-off ones included: turning one on approves its definition) and the Quick ones; the skills API reports it as `used_by`, and the Executive's `search_skills` hits carry it as `workflows`.\n\nCompleted artifacts are discoverable in the unified artifacts section (`/artifacts`, labelled **Documents** in the UI) alongside their run-detail page at `/jobs/runs/{run_id}`. A run someone starts by hand (`POST /workflows/{name}/runs`, `run_workflow`, research in chat) stores them as `workflow_runs.owner_person_id` and its history and output are theirs alone (plus the person a gate waits on); scheduled and system runs keep no owner and stay the team's. Workflow output stays Markdown — the scheduler DMs it and reflection rereads it as text — and gains other formats only on the way out: any run can be downloaded as Word (`/artifacts/run:<id>/download?as=docx`), and the Executive can repackage one with `get_artifact` → `draft_artifact(format=…, supersedes=\"run:<id>\")`.\n\n## Data-driven retrospectives\n\n`engagement_value_report` introduces a new workflow pattern: instead of the user typing the substance into a form (the `investor_update` / `mbr` shape), the workflow **reads its substance from the database**. A deterministic gatherer (`clients/engagement_activity.py`) pulls the period's decisions, initiatives, advisory consultations, delivered workflow artifacts (excluding prior value reports), follow-through counts, and alerts handled — from the live DB for the active client, or a parked client slot's `state.db` opened read-only. A single board-comms call narrates those facts (the prompt forbids inventing anything not in them; an empty period skips the LLM entirely), and the artifact's lists are assembled deterministically. Built for renewal conversations — the engagement record is the evidence.\n\nWith Take the lead as the Executive on (`orchestrator.take_the_lead`), reflection and research build their toolkit through `unattended_toolkit(..., source=...)`. That keeps solo's booking and `run_workflow` tools and an unrestricted `message_person` (teammates as well as the principal). Every acting tool goes through the gate, and a held action waits on Today as a `take_the_lead_action` decision. Reflection also gets the MCP gateway's `search_tools` and `call_tool` (`_with_lead_tools`; `call_tool` behind the gate, `load_mcp_server` left out), so it can find and use whatever the deployment has connected, such as building a sheet to track something. A note in the user turn (never the cached system prompt) tells it to act rather than only report, and it gets more room: 10 iterations, 4000 tokens, and tool results up to 4000 characters. The grounding check still refuses outward text naming people or figures the pass didn't see. New mail and chat also wake the reflection early (scheduler section). In training (`take_the_lead.training`) every acting call that isn't allowed waits too, as a training card for the principal, and both passes append `take_the_lead.learned_note()` to their user turn: that it's in training, and the principal's own edits on earlier cards as examples of how they want those done (never in the cached system blocks).",+ "markdown": "Workflows are deterministic, multi-step orchestrations. The built-ins are registered in `openexecutive.workflows.WORKFLOW_REGISTRY`; user-created (dynamic) workflows are stored as data (see below). Each follows the same contract: structured input feeds an ordered list of named steps that render a Markdown artifact, persisted via `complete_run` into `workflow_runs.artifact`. Every step emits a `WorkflowEvent` (start/progress/complete) streamed over SSE at `/workflows/{name}/runs`.\n\nThe registry holds 25 built-in workflows, plus any number of user-created ones. Representative built-ins:\n\n- `board_prep`, `quarterly_plan`, `annual_plan` — planning and governance deliverables.\n- `performance_review`, `comp_refresh`, `org_design`, `exec_search_brief` — people and org artifacts (the last is an advisory hiring brief / scorecard from the CHRO, with input from the hired function's specialist — `sales` for a sales role — kept when the recruiting pipeline was removed).\n- `crisis_comms`, `churn_deep_dive`, `competitive_teardown` — situational analyses.\n- `department_check_in` — runs on department cadence; its `goal_status` step returns structured verdicts persisted back to `department_goals.status` (`department_check_in.persist_goal_verdicts`, shared with `weekly_review`).\n- `weekly_review` — the principal's weekly look back and ahead (see *Weekly review* below).\n\n**Standing facts in unattended output.** `end_of_day_digest`, the weekly review's top-three call and the morning reflection append the standing facts (`memory.facts.with_standing_facts`; a teammate's marked `(per <name>)`) to their user turn, and the morning brief gets them through `render_briefing_context`. A workflow step that consults a specialist gets them through `route_to_specialist`. A correction made in chat therefore holds in every recurring brief and run. The morning brief also reads `facts.render_teammate_changes(since)` off the event loop and passes it to both `render_briefing_context` (a TEAMMATE CORRECTIONS SINCE LAST BRIEF block) and `build_brief_fingerprint`, so the principal hears of each correction a teammate made in the window, and that alone un-suppresses an otherwise unchanged brief. Proposals waiting for approval are listed only in a brief the principal reads privately (`include_proposed=_private_ok()`), and then mark the run private to them. The principal's own Always in the loop notes (`memory.history_brief`, only with their switch on) come in by a stricter rule, only on the scheduler's delivery (`PRINCIPAL_DELIVERY`), never a run from chat, whose tool result reaches the turn's shared audit row and peer memory: the morning brief's FROM YOUR NOTES — DUE SOON block and the end-of-day digest's FROM YOUR NOTES — TODAY block (what they committed to since the last digest, then what is due tomorrow). Either marks the run `private_to_principal` and moves its fingerprint; the digest, which had no private reads before, now emits that flag too.\n\n### Change-aware principal briefs\n\n`morning_brief` and `end_of_day_digest` are the two recurring briefs the scheduler sends to the principal. Both are now a *delta*, not a re-list: the window is \"since the last **delivered** brief\" (`briefing.brief_state.since_for`; 24 h on a cold store, clamped to 7 days), activity comes from `_build_activity(limit, since=…)`, proposals (action category only) split into *new since last brief* — enumerated, with each item's why-now and next move — versus a one-line carried-over count, a *rewritten* block lists carried items the review rewrote inside the window (`brief_state.rewritten_since`: verdict `changed`, still open — the brief reports them under \"what changed\", never as done), and a *handled overnight* block lists what the Executive's alert review **completed** on its own (`brief_state.handled_since`; the `changed` verdict is excluded because the alert is still open). The morning brief also reads the principal's **live world** since that window opened (`briefing.live_signals.gather_live_signals`): mail and chat the Executive handled (INBOUND, grouped by sender and subject), what got stuck (STUCK: a reply the outbound gate held, a non-roster sender who got no reply, a Google Chat message left unanswered, drafts waiting in the principal's Gmail), the principal's own chats, and — in both modes now, unless the solo top three already listed it — today's calendar, read fresh (`live_signals.refresh_calendar(max_age=0)`). The 07:30 reflection's **Flagged for the brief** bullets are carried across (`brief_state.reflection_flags_since`, the latest reflection run finished inside the window) instead of surviving only as an activity line with the run's title, and the rhythm runs themselves (`today.RHYTHM_WORKFLOWS`) are dropped from the brief's activity: their dated titles were noise and moved the fingerprint every day. At-risk departments name their slipping goals and each proposal carries its age. The period is the principal's local date. Section order: top call → **today** (the calendar's shape and anything stuck) → what changed (inbound first, naming who wrote) → handled overnight → needs you (new only) → waiting on → at risk (the slipping goal, or the department left out — never \"no detail yet\"). Quoted mail, chat, invite and reflection text is marked as data, never instructions. **Privacy:** the brief reads what is private to the principal — their contacts' alerts and mail, their drafts, their chats and their calendar — only on a run for them: the scheduler's (`morning_brief.PRINCIPAL_DELIVERY`) or the principal's own verified chat turn in a conversation only they can read (`delegation.settings.private_conversation`: the web chat, a Slack or Discord DM, a private Telegram chat — never a shared channel, where the reply is posted for everyone). A run anyone else starts (a teammate from chat in team mode, `POST /workflows/…/runs`) reads what everyone may see, as before. A run that did read a private row says so on its `result` event (`private_to_principal`: its live read differs from the shared one in any key or count), and the scheduler, `run_workflow` and `POST /workflows/{name}/runs` all then keep `persistence.PRIVATE_RUN_ARTIFACT` in the run history instead of the text. Text another pass wrote (the reflection's flags) renders as quoted ` > ` lines and every goal and headline field is one-lined, so none can start a line that reads as a block header. The fingerprint carries the live signals' time-free keys (who wrote about what, what is stuck, the calendar's shape) and the reflection flags when there are any, so \"nothing new\" means the principal's world was quiet too; the context summary is logged at INFO (`morning_brief: context since=… inbound=… stuck=… suppressed=…`). In **solo mode** (one person using Open Executive for themselves) both briefs speak to the principal, whatever their role: the morning brief runs top call → top three today → what changed (inbound and stuck first) → handled overnight → needs you → due this week (the principal's open loops overdue or due within 7 days, from `open_loops.principal_due_soon`) → goals at risk (named by area), the end-of-day digest what I did → open decisions → goals at risk tomorrow → sleep on this, over a context with goals at risk by area and no people-waiting or department block; the fingerprint carries the mode and ignores who is awaiting, and carries the due items as `(loop_id, state)` pairs when there are any. **Top three today** is picked in code, not by the model (`briefing.top_three`: overdue then due-today commitments, off-track then at-risk goals, commitments due later this week, then active projects, stalest first). The solo Briefing's *Top three today* card shows the same pick from the same code (`GET /today/top-three`, see Today). When the MCP gateway runs the Google Workspace server, one `google_workspace__get_events` call (4 s timeout) lists today's events on the principal's calendar — their address as the calendar id, read with the Executive's account (`primary` when the Executive is signed in as them) — and on a business day (`calendar_tools.is_business_day`, the rule the booking tools apply; at the weekend the day's events are still listed but no slot is suggested) each item gets its own free block inside `CALENDAR_BUSINESS_HOURS_START`–`_END`, rendered with a TODAY'S CALENDAR block — only a date-only event is all day, a zero-length one blocks nothing, and one whose times can't be read is left out; no gateway, no principal address, an error, a timeout or a reply it cannot read all mean no calendar and no slots, never a failed brief; the log records only the reply's length or the error's type, never calendar text. The fingerprint carries the three items' keys (no dates, no slot times) and only a coarse hash of the day (busy blocks rounded to 15 minutes, no titles, no dates), so an unchanged day still suppresses. A day whose calendar read fails after one that worked (or the reverse) changes the fingerprint once, so that brief is written in full. A date-free fingerprint of the inputs is compared to the last delivered one; if unchanged the artifact is the one-liner \"Nothing new since yesterday's brief — N items still waiting on you.\" and no model call is made (`PRINCIPAL_BRIEF_SUPPRESS_UNCHANGED`; `force_full=true` on a manual run bypasses it). The workflow yields a `result` event with the fingerprint; only the scheduler records it, after a successful delivery, in `briefing_narrative` under scope `brief:<kind>` — so manual runs never advance the window.\n\n**Brief delivery.** `scheduler.runner._deliver_to_principal` maps the principal's `preferred_channel` (`slack` / `discord` / `telegram` / `email`) to its delivery channel and tries it first, then the other chat channels the principal has an id for, in the order Slack → Discord → Telegram. Email goes through the active MCP gateway (`google_workspace__send_gmail_message` as the Executive's own address, to the principal, subject `<title> — <date>`) and is used only for an explicit `email` preference, or for `any` when no chat channel resolves — an owner linked by email at setup has `any`, so one who also has Slack does not start getting two emails a day. When nothing can deliver (a web-only principal, or email with no gateway), the brief is still generated and stored as a run with its artifact, as before — a web-only principal reads it on the Artifacts page — it is just not delivered (audited), so the window does not advance, and the next occurrence is chained. The same delivery path carries the client-rotation digest and the weekly review.\n\n**Grounding.** Nothing an unattended pass writes is read by anyone before it goes, so `openexecutive.briefing.grounding` checks it deterministically — no model judges the model. A name (a run of two or more capitalised words once section headers, weekdays, imperative openers and org nouns are trimmed, or one capitalised word in a person slot like \"ask Marcus\" or \"Marcus wrote\") is grounded only when a single line of the pass's inputs holds all of it, or it belongs to a roster person some input mentions — being on the roster alone is not enough. A figure (money, a percentage, a k/M/B number, any bare number of 11 or more; never a date, time, year, duration, id, list marker, `Q3` or small count) is grounded when an input number matches it within the precision it is written with (`$1.2M` matches `$1,234,567`; `47 units` does not match 48). The inputs are the rendered context split into lines labelled by section (a header also carries its bullet count), the company profile and the department titles. `morning_brief` renders its context itself and hands it to the synthesizer as `rendered_context`, so the check reads exactly what the model read; after the quiet fallback, `ground_brief` runs on both briefs. When something is ungrounded it makes one repair call to the fast model (same system prompt, the list of items, \"remove or correct using only the context\"), re-checks, then drops each line still ungrounded and any header left empty, and appends \"_Held back N lines that named people or figures I couldn't match to your data — /today has the full list._\" (everything ungrounded → one held-back line). Then each grounded figure gets a server-chosen ` [n]` — the matching input line with the most words in common with the figure's clause — and a `**Sources**` list closes the brief (`- [n] <section> — <snippet>`, at most 9, snippets quote inbound mail, so links are masked (\"(link removed)\"), Markdown, angle brackets and @-mentions stripped, and they are cut to 90 chars; never `[n]:` at a line start, which Markdown reads as a link definition). Text with nothing to change comes back byte-identical, the fingerprint hashes the inputs so suppression is unaffected, and the grounded text is what is delivered, stored and recorded as delivered. Both brief prompts and the digest prompts say the rule up front. `executive_reflection` wraps its handlers in a `GroundingScope`: `create_alert`, `message_person`, `send_department_message`, `send_company_broadcast` and `schedule_followup` refuse text with an ungrounded name or figure, returning a JSON error that names the items so the model can look the person up or leave the figure out (every tool result joins the inputs, so a `lookup_person` answer grounds the DM after it; the recipient's own name always counts). Its **Flagged for the brief** bullets are filtered the same way before the tool log is appended — the next brief quotes them, where they would ground themselves — and `brief_state.reflection_flags_since` now stops at the tool log's `---`. The reflection's `grounding` rows are private when a private-to-principal alert reached its context, and the digest's always are (its HANDLED block can quote one). Everything fails open. `GROUNDING_CHECKS=enforce` (default) acts, `report` only writes the `grounding` audit rows, `off` skips it; `GROUNDING_CITATIONS=false` drops the markers. Not yet grounded: the /today header (its cards sit beside it), `weekly_review`, the research synthesis, dates and meetings, and a real person named in the wrong role.\n\n### Weekly review (solo)\n\n`weekly_review` (background, inputs all defaulted) closes out the principal's week in six steps. **Goals**: every area with goals is graded by its own specialist, concurrently, with the department check-in's verdict contract (`_parse_verdicts`) and write-back (`persist_goal_verdicts` → `record_goal_review`, one `goal_status_review` audit row per area with actor `weekly_review`); an area with no goals is skipped, one without a specialist is listed ungraded, and one whose specialist fails is shown as last recorded. **Commitments**: `open_loops.principal_due_soon` — overdue or due within 7 days. **Projects**: active initiatives with no update for 7+ days. **Decisions**: the week's (`episodic.decisions_since`). **Revisit**: up to three decisions older than 30 days with an empty outcome (`episodic.decisions_awaiting_outcome`, newest first), listed as `[decision N]` under *How did these turn out?* — the principal's answer is recorded with `record_decision_outcome` (see Agents). **Assemble**: every section always renders (a one-line note when empty), ending with *Next week's top 3* from one fast-model call that follows the `weekly-review` playbook (a constant system prompt; the playbook rides in the user turn), trimmed to at most three list items — or, when that call fails or returns nothing, the same ranked pick the morning brief uses. In solo mode the scheduler fires it weekly (`principal_weekly_review`, see Scheduler) and delivers it through `_deliver_to_principal` like the briefs, recording the delivery outcome. The solo Briefing also shows the latest completed run to the principal (`GET /today/weekly-review`, see Today): `weekly_review.summarize_review` reads the artifact's title line (`TITLE_PREFIX`) and its last `TOP_THREE_HEADING` section back as plain text, so a principal no channel reaches still sees next week's top three. Wording is role-neutral; run by hand in team mode it says *department* instead of *area*.\n\n**Principal-only workflows.** A workflow can name the workspace modes in which only the principal may start it (`Workflow.principal_only_modes`): `weekly_review` in both modes (built from the principal's decision log, commitments and goals, and it re-grades the goals) and `morning_brief` in solo (built from the principal's commitments and calendar). Team `morning_brief` and every other workflow can be started by anyone as before. This decides who may start or trigger a run, not who may read one: stored runs, the scheduled briefs and weekly reviews included, are read under the existing `/workflows/runs` rules — which is why a morning brief that drew on the principal's private rows is stored as `PRIVATE_RUN_ARTIFACT`, not as its text.\n\n- **From chat**, `run_workflow` checks at dispatch, before any run row is created, that the turn is the principal on a verified surface — `create_goal`'s rule — and otherwise refuses with a plain error that does not spell out the rule.\n- **Over HTTP**, the Jobs page's `POST /workflows/{name}/runs` and `POST /evals/runs` (a workflow scenario runs the workflow on live data) call `refuse_principal_only_run`: only a caller signed in as the principal, or a request with no caller email (the CLI or local login), may start the run. Unlike the workspace settings, an install with no principal on the roster lets no signed-in caller in, as in chat. Anyone else gets a 403 (\"Only the principal can run this workflow.\") before any run row exists. The mode is the stored one, or an eval scenario's own `workspace_mode`. The eval route runs exactly the scenario list it checked.\n\nEvery refusal is audited `refused=true` with the workflow, the mode and the caller. The checks fail closed: a mode that cannot be read counts as principal-only, and a check that cannot read the roster refuses.\n\n**Knowledge in the reflection.** A chat turn looks the knowledge base up before the Executive answers; the reflection reads the org's state instead, so nothing looked it up for it. It now carries its own `search_knowledge` tool (`orchestrator.knowledge_tools`, not in the shared `_ALL_SKILL_TOOLS`), which runs the same `knowledge.retriever.retrieve` as chat — the review gate, the synced Drive / OneDrive / Confluence / Notion collections and the published-artifact rule (the pass has no viewer, so no one's private document comes back). The prompt (`_KNOWLEDGE_RULE`, both modes) asks it to search before acting on or flagging something that turns on a customer's or supplier's terms, a price, a policy, a plan or a past decision. Its passages come back up to 4,000 characters (`execute_tool_calls(wide_results=...)`) while other tools stay at their short preview, its result counts as grounding input like any tool result, and the run's tool log keeps each line to 160 characters. Read-only, so Take the lead never gates it. The loop has 5 iterations (was 4) to leave room for a search before acting.\n\nNeither the nightly reflection nor the research synthesis can call `ack_alert`: both run unattended with open alerts rendered into their context, and those headlines are minted from inbound mail and chat, so an injected \"the principal already dismissed 13\" would be acted on with nobody watching. Closing an alert is the alert review's job, with evidence.\n\n`executive_reflection` now carries memory: yesterday's standup (the previous completed run's artifact) is rendered into the context and the prompt forbids re-acting on anything listed there unless it changed; open alerts render with their id, review verdict and recommended move. Reflection never closes alerts — the alert review does, with evidence. It also renders an **OPEN LOOPS** block (up to 10, soonest due first, overdue flagged) from Attunement so the standup can connect a slipped promise to the rest of the org state; the nudge engine already chases overdue loops, so the prompt tells it not to DM about a loop merely for being overdue. A **WHAT LANDS** block (from the Attunement outcome ledger) shows, per person, how often each kind of proactive DM got answered over 30 days; the prompt steers DMs toward kinds that land and away from kinds a person reliably ignores. Reflection and research tag their tool execution as proactive (`tag_proactive`) so their DMs are counted. Resolving a wait-for-human approval (`resumer.apply_resolution`) marks the nudges that chased it `acted`. `close_open_loop` is withheld from reflection for the same reason as `ack_alert`: loop text is quoted from what people wrote. `unattended_toolkit` also drops `schedule_tools.UNATTENDED_WITHHELD_TOOLS` (today `create_goal`) from both passes in both modes: a goal is the principal's own decision, and these passes see only inbound text. A turn private to the principal (mail from one of their contacts, or mail they forwarded) cannot start a workflow either: `run_workflow` and `run_executive_research` are in `schedule_tools.PRIVATE_TURN_WITHHELD_TOOLS`, which the chat loop neither offers nor runs on such a turn, since a workflow's steps can reach anyone.\n\nIn **solo mode** the reflection is framed for the principal, whatever their role: they are the only person who uses Open Executive and the only one it takes direction from, it prefers `create_alert` and `schedule_followup` to the principal, and it never messages anyone else from an unattended pass — the people in the principal's world are contacts, so anything they should hear is flagged for the principal to raise. The team roster is replaced by one YOUR PRINCIPAL line (person_id and follow-up channels), its follow-up guard is seeded from the principal only, and department risk renders as areas with goals at risk. The research synthesis follows the same rule — its routing menu and roster name only the principal. In both, `send_department_message`, `send_company_broadcast` and `set_department_head` are withheld, and so are `create_calendar_event`, `create_instant_meeting` and `run_workflow` — a booking reaches its attendees and a workflow can do anything its steps do, so the principal books and starts workflows from chat — and `message_person` refuses anyone but the principal. These passes run unattended with inbound text in their context, so the rules are enforced in code, not only in the prompt.\n\nIn either mode, both passes now dispatch only the tools they offer: the handler map is built from the offered list, so a name the model emits without being offered it is skipped as an unknown tool. They used to look names up in the full handler registry, so tools they deliberately withhold — the raw DM tools (`send_slack_dm` has no roster check), `ack_alert`, `close_open_loop`, and in research the watchlist writes and `run_workflow` — still ran when the model emitted them. Both read the mode before binding their own session (so a caller's override, such as an eval's, counts) and pin it on that session, so their tool handlers use the same mode. They carry the principal's role across the same way (`effective_principal_role` of the caller's session, pinned as `turn_principal_role`), so a specialist or workflow started from either pass sees the role of the turn that started it. Team runs are unchanged.\n\n### Wait-for-human pause\n\n`wait_for_human` (`openexecutive/workflows/wait_for_human.py`) is a first-class step primitive that pauses a run: the runner calls `save_checkpoint`, the `workflow_runs` row moves to `status='awaiting_human'`, and the serialized `WaitForHumanEvent` is stored in `state_json`. (Department authority is a *separate* mechanism — `propose_only` departments file a briefing alert via `departments.authority.propose_via_alert` and mark the scheduled action done; they do not route through this gate.)\n\n**Delivery.** Both checkpoint sites — the SSE route and the `run_workflow` chat tool — call `workflows.gate_delivery.deliver_gate_question` immediately *before* checkpointing, so `state_json` carries the routing fields a reply is matched against. Two modes. When the approver is the person already in the conversation (the chat session's `origin_channel` is set — to anything but `email`, whose answer is no chat reply and would never be sent — and its `caller_person_id` is the gate's `person_id`), nothing is sent — the question rides in the Executive's own reply — and the gate records `origin_session_id` plus the session's channel. The resolver compares base ids (`memory.conversation_ids.base_session_id`), so a question asked in one conversation of a Telegram chat or a DM is still answered by a reply after a quiet gap or /new has started the next. Otherwise the question is delivered through `schedule_tools.handle_message_person`, which picks the person's preferred channel, falls through on a failed send, and falls back to a briefing alert; the gate then records the channel, address and provider message id that send returned, plus the id of the DM session it landed in — that send is always 1:1, so the answer belongs in that conversation and nowhere else. Without it the gate matched on person and channel alone, so an unrelated @mention in a public channel resolved it and had the acknowledgement, run title included, posted where everyone could read it. The question is sent with `notifications.approval_send`, so the person's quiet hours and *In my briefs* never hold it, whatever their urgent setting: only a reply to it resolves the gate. Delivery is not guaranteed: the outbound guard can suppress it (duplicate, rate cap, quiet hours) and an unreachable person gets the alert fallback. Both cases leave the routing fields empty and report `delivery` as `suppressed` / `alerted` rather than claiming someone was asked, and the chat tool's presentation hint changes accordingly.\n\n**Matching a reply.** Each inbound adapter passes the message to `inbound_resolver.resolve_inbound_message` with its `session_id`. Matching is three-tier: an explicit `in_reply_to` against a stored `outbound_message_id`; otherwise a single open run on that channel; otherwise one utility-fast disambiguation call gated at 0.85 confidence. An unmatched explicit reference rules out only the candidates that carry a stored outbound id — the ones it could have matched — and the rest continue; rejecting outright meant an adapter that passes a thread id on every message (Slack's `thread_ts`) short-circuited the later tiers forever, and a global test let one delivered gate's id block an unrelated self-approval gate. Channel names are normalized (`slack_dm` ≡ `slack`), the delivered address is compared when both sides know it, a row whose `state_json` will not parse is refused (a corrupt row otherwise presents as a legacy one), and an empty stored channel is treated as a wildcard only for rows checkpointed before gate delivery existed. Two guards keep an open gate from swallowing unrelated traffic: a gate carrying an `origin_session_id` matches replies only from the conversations the adapter names (a Slack or Discord thread offers its parent channel session too, mirroring the history double-write, since a gate raised on a mention recorded that session while the answer arrives under the thread's — on Slack only when that person rooted the thread, or the alias would reach into a colleague's), and the parser can return `unrelated`, which declines to resolve and lets the message reach the normal chat path. The parser is handed the gate's own question, so a bare \"yes\" is judged against something. Its fallback is flagged by a key the model cannot emit rather than by a magic note string it could, and a fallback declines to resolve on *every* reply shape — recording the empty string a `free_text` fallback fabricates would close a sign-off on a parser outage. Every shape can answer `unrelated`, not just `approve_reject`: without it an open `free_text` gate turned the person's next message into its answer verbatim, and a `numeric` one swallowed any message containing a number. The parser has one caller outside workflows: its `roster_identity` shape — `{decision: approve|link|decline|unrelated, name, kind: team|contact|null}`, with `name` only as the person wrote it (never inferred) and a fallback of `unrelated` — reads the principal's emailed answer to a roster request (who a new sender is; see Org). It is not a gate reply shape, and a fallback or `unrelated` leaves the request waiting. `resumer.apply_resolution` then records the decision, marks the run `resolved`, and writes an audit row. A timeout applies the step's `on_timeout` policy (escalate / auto_proceed / fail). The outcome surfaces on the Today dashboard.\n\n**Resuming past the gate.** A paused run continues on its own. Re-entering it was long assumed to mean serializing a Python generator frame; it does not. The only state alive across a dynamic workflow's steps is its inputs (already persisted), a company-profile block that is recomputed, the completed steps' output strings, and the loop cursor — so the engine hands the checkpoint a small JSON `WorkflowResumeState` (workflow name, the gate's id and index, the next index, the outputs so far), stored in `workflow_runs.resume_state_json`, and `DynamicWorkflow.resume` replays its step loop from the recorded index. `run()` and `resume()` share that one loop, which is why a second gate needs no special handling — it is simply another pause raised from the same place. The payload rides on a `WaitForHumanEvent` field declared `exclude=True`, so it can never leak into `state_json`, whose exact key set the resolver branches on. A gate with no payload is *pause-only*: the decision is recorded and the run stops, which is what every caller got before resume existed.\n\n`resumer._process_resumable` claims a resolved run with one guarded UPDATE — `resolved` → `running`, stamping `resumed_at` and minting a claim token — and drives it to a terminal row. It runs two ways: immediately, via a task `apply_resolution` kicks off so a Slack approval starts moving in seconds, and every 60s from the poll loop as the durable backstop. Both share the claim, so a run executes exactly once even with two resumers against one database. The kicked task binds no chat session (`set_session(None)`), exactly like the poll loop: it is created inside the inbound handler that recorded the answer and would otherwise inherit that person's live turn — so a run resumed because the principal replied on Slack does not act with the principal's identity (it cannot, for example, reach the principal's contacts). It drops the handler's audit scope too (`audit.context.unscoped_audit_rows`): inherited, the principal's scope would make private every row of the run that names a contact, and whoever started the run would see those rows vanish after the approval. The poll runs the executor *after* the timeout loop, which is what finally makes `on_timeout='auto_proceed'` do what its name says: the timeout resolves the run and the same tick executes it. While the Executive is paused (`scheduler.pause`) the resumer does nothing — no startup sweep, no timeouts, no resumes — and `apply_resolution` still records the decision but skips the immediate kick; the first unpaused iteration catches up on all of it, so a timeout that lapsed during the pause applies its `on_timeout` policy then.\n\n**The claim is fenced, because it is not a lease.** The stale sweep decides a worker is dead from a wall-clock guess, so a slow but *alive* worker will eventually be declared dead and replaced. Every write the executor makes carries its claim token and is refused once superseded — otherwise the replaced worker's late completion lands on top of its replacement's result, or its checkpoint at a later gate resurrects an already-finished run and asks the approver a second time. The retry budget resets at each new gate (a gate is new work, not a retry), and a run that exhausts it is *ended* rather than dropped: an exhausted run sits in `running` with a payload, in neither queue, and would otherwise show as in-progress forever.\n\n**The gate fails closed.** Continuing is an allowlist — `approve` and the synthetic `auto_proceed` — not \"anything that is not a stop word\". `decision` is whatever a fast model extracted from free-form chat and it drifts; under a denylist, \"rejected\", \"Reject\", \"decline\" and \"no\" would all continue, so the approver declines and the deliverable is produced anyway. Reply shapes that ask a question rather than seek permission always continue, since the answer *is* the value. A stop ends the run at `error` with the human's note. Either way the decision becomes the gate step's own output, so it reads as a section *in* the artifact — capped and blockquoted, because that text reaches the synthesis specialist as prompt context.\n\n**A definition edited during the pause is refused.** Resume re-validates the payload's version, the recorded gate, *and* a fingerprint of the whole step list, and derives the index to continue at rather than reading it from the payload. Pinning only the gate would not be enough: definitions are overwritten by name and any rostered user can save one, so someone could keep the gate identical and replace every step after it — and the approver's sign-off would be recorded against work they never saw, which defeats the one thing an approval gate is for. No built-in workflow yields the gate; only user-created dynamic workflows do.\n\n### Launching from chat\n\nWorkflows are not only reachable from the `/jobs` UI — the Executive can list and run any of them mid-conversation. `openexecutive.orchestrator.workflow_run_tools` wires two tools into the main chat loop: `list_workflows` (the launchable catalog, with each workflow's input fields) and `run_workflow` (runs one to completion and returns its Markdown artifact, using the same engine as `POST /workflows/{name}/runs`). `run_workflow` resolves both built-ins and custom workflows via `get_workflow`, validates `inputs` against the workflow's input model, persists the run (`create_run` → `complete_run` / `fail_run`), and on an approval-gate step checkpoints the run as `awaiting_human` exactly as the HTTP route does — literally the same code, since both call `workflows.gate.checkpoint_gate`, which delivers the question and writes the checkpoint in one place. It never hangs waiting on a human, and it reports both whether the question reached them and whether the run will continue by itself once answered. The runners that *cannot* pause — the schedulers, evals, client rotation, onboarding, the research tools — call `gate.ensure_workflow_event`, which raises on a gate rather than letting one be swallowed; the scheduler's dynamic-workflow branch used to ignore it and record a successful run containing nothing. `executive_research` is excluded (it has the dedicated `run_executive_research` tool). Running a workflow from chat delivers nothing on its own — it renders the artifact into the conversation, and the recurring principal briefs (`morning_brief`, `end_of_day_digest`) reach anyone only via the scheduler's own `_deliver_to_principal`. The tool description used to claim those two DM the principal when run and to confirm before firing them, which had the model soliciting a confirmation on a false premise; it now names `executive_reflection` as the one workflow that really does execute tool calls of its own (DMs to heads, broadcasts, alerts). A successful run surfaces an `action_taken` chip linking to `/jobs/runs/{run_id}`.\n\n### Dynamic (user-created) workflows\n\nUsers create reusable workflows on the fly — from the executive chat, the conversational wizard at `/jobs/new`, or the step-by-step advanced editor — without shipping code. The Workflows page (`/jobs`) opens on a *Start here* panel that leads to all three: the user describes the job in a sentence and *Start* opens the wizard with that text sent as its first message (handed over in `sessionStorage`, so a link cannot make the wizard send text the user never typed; where storage is blocked it falls back to `/jobs/new?describe=`, which only fills the composer and sends nothing), or picks *Step by step* (advanced editor) or *Talk it through in chat* (`/?new=1&draft=`). Below it come the user's own workflows, then four ready-made starter picks with the full built-in list folded behind *Browse all* (`?browse=1`). The picks and the example chips follow the workspace mode: a team gets the investor update, board prep, MBR and competitive teardown (and a board pre-read chip); a solo owner-operator gets the MBR, pricing review, churn deep dive and quarterly plan, with chips for a Friday cash and pipeline check, customers who stopped buying and a competitor digest (`lib/workflowStarters.ts`; a unit test pins every pick to a startable `WORKFLOW_REGISTRY` entry). A dynamic workflow is a stored JSON definition (the `dynamic_workflows` table) interpreted at runtime by one generic `DynamicWorkflow` engine (`openexecutive/workflows/dynamic.py`) that implements the same `Workflow` ABC as the built-ins, so the run path, SSE streaming, run persistence, and `/jobs/[name]` form rendering are unchanged. `get_workflow` / `list_workflows` fall through to the dynamic store after the static registry (built-ins win on a name collision).\n\nA definition declares free-text input fields and an ordered step list of four kinds: **specialist** (consult a specialist with a goal prompt, optionally grounded by RAG), **action** (get something done with tools — see below), **approval_gate** (a `wait_for_human` pause), and a terminal **synthesis** step that assembles the artifact. At least one specialist or action step is required. `validate_definition` enforces the structural rules: exactly one terminal synthesis step, valid specialists, `{placeholder}` tokens that reference declared input fields, rostered approval/cadence people (team members — never one of the principal's contacts, whom an unattended run may not message), and a parseable cadence.\n\nAuthoring from chat uses a **draft → confirm** handshake: the Executive calls `draft_workflow` (validate; return a `confirm_token` plus a plan summary), shows the user the plan, then calls `save_workflow` with the same definition and token — a token mismatch is rejected, so the saved workflow is exactly what the user approved. The step-by-step advanced editor drives the `/workflows/custom` CRUD endpoints directly.\n\n**The New workflow wizard** (`/jobs/new`) is the default way to create one from the UI. It works like conversational onboarding: the user describes the job, the `workflow_designer` Council agent (`openexecutive/workflows/designer.py`) asks one clarifying question per turn — deliverable, per-run inputs, sign-off, schedule, recipient — with up to four clickable suggested answers, then emits a complete definition plus a plain-language summary and the assumptions it made. Every turn offers the model exactly three fixed, name-sorted tools (`ask_clarifying_question`, `emit_workflow_draft` — reusing the chat tool's `DEFINITION_SCHEMA` — and `search_available_tools`, which is answered inside the same turn from the tool catalog, up to four searches per turn, with the tool_use/tool_result pairs never stored in the plain-text transcript; every tool a search returns is remembered on the session and replayed into later turns, so a forced draft or a repair turn — which cannot search — still has the exact names); `tool_choice` flips to the emit tool once, when the six-question budget is spent or the user clicks *Draft it now*. The emitted definition goes through `validate_definition`, the tool-availability check, and a check against saved custom names, with one repair turn that feeds the errors back. The system prompt is a cached constant; the live context — specialists, the roster with person ids, the user's timezone (the one set through `PUT /workspace`, else `USER_TIMEZONE`; cadences stay UTC), and taken names — is rendered once per session into the first user turn, and while refining, the exact current draft is prepended to the latest user turn so the model edits it rather than re-deriving it. Roster names and roles are flattened to one line and capped at 80 characters before they enter that context, and the system prompt tells the model to treat the whole block as data, never instructions. Sessions live in memory (`/workflows/designer/*`, 2 h TTL, 50-session cap), run one model turn at a time (a second concurrent `/message` or `/draft` gets 409, and a failed turn is rolled back by identity), and never write: the review card saves through the same `POST /workflows/custom`, which re-validates, and *Edit details* opens the draft in the advanced editor (`/jobs/new?designer=<id>`) before saving.\n\n**Editing is a conversation too.** *Edit* on a saved workflow (`/jobs/new?edit=<name>`) opens the same designer through `POST /workflows/designer/edit`: the stored definition is the starting draft, so the user's first message (\"have Mark sign off and run it Fridays\") is applied to it like any refinement, and a note in the context block (a user turn, never the cached system block) tells the model it is changing a saved workflow. The draft always keeps the workflow's name — `_check_draft` puts it back and skips the taken-name check — and the route keeps its on/off state, so an edit can neither fork a copy nor switch on a tool workflow waiting for approval. The stored draft is handed to the model marked as data, not instructions. The review card lists *What changes* in plain words against the saved version (`lib/workflowChanges.ts`): every field is compared, with named sentences for the sign-off person and what it asks for — a sign-off moved off approve/reject is called out because the run then continues whatever the answer — the schedule, steps added/removed/reordered, inputs, tools and the tool-call budget, and a catch-all line for any other field. It names only the newly added tools that may change things. *Save changes* calls `POST /workflows/custom/{name}/save-edit`, which saves the session's own draft after re-validating it, only when it is the draft the card showed (the card sends what it displayed; a message that landed since is a 409), and only if the stored workflow has not changed since the conversation opened (409 otherwise), so an edit started before someone switched the workflow off cannot switch it back on. The step-by-step form stays as the advanced editor (`/jobs/new?edit=<name>&mode=advanced`).\n\n**Action steps (workflows that act).** An `action` step (`ActionStepSpec`: `goal`, `tools`, `max_tool_calls` 1–50, default 20) is run by the `workflow_actor` Council agent (`openexecutive/workflows/action_step.py`) as a bounded tool-use loop. Its `tools` list is an allowlist of exact tool names — MCP gateway tools (`server__tool`, e.g. `google_workspace__append_table_rows`) and a small set of built-ins (`oe__read_file`, `oe__message_person`, `oe__create_alert`, plus any installed extension's tools registered with `workflow=True`, as `oe__<name>`, run inside `extensions.workflow_step(name)`; a built-in wins a name clash, and an extension tool counts as reading only when it says so) — and **clicking Create is the user's approval** of that list: the review card shows every tool, flags the ones that may change things (anything whose name doesn't say it reads, and any tool with a URL/URI/endpoint/webhook parameter anywhere in its schema, or whose schema couldn't be read, since a URL can carry data out), and names them in a \"this workflow can use these without asking again\" notice. Because that card is the approval, a workflow with action steps saved from chat (`draft_workflow`/`save_workflow`, whose confirmation is a token the model holds itself) is stored **switched off** (`is_active=false`) and `save_workflow` returns `status: saved_pending_review` with a `/jobs/{name}` link. An inactive workflow can't run or schedule (`get_workflow` and the scheduler skip it); `/jobs/{name}` shows it on the same review card, where **Turn on workflow** (`POST /workflows/custom/{name}/activate`, which re-validates the tools) is the approval — the click sends the definition the card showed, and the server refuses (409) if the stored one has changed since, so chat overwriting it while the card is open can't get new tools switched on. Chat may revise a switched-off workflow but refuses to replace a switched-on one that has action steps (an inbound email steering the Executive could otherwise switch off an approved job and stage new tools under its name); those edits happen in the advanced editor. The Workflows catalog (`/jobs`) lists switched-off workflows in a compact *Waiting for your approval* strip, and saving edits in the advanced editor keeps one off. `tool_catalog.py` resolves names to schemas through the gateway's `search_tools` (extensible-mcp's Markdown output is parsed; resolving is also the per-session discovery its `call_tool` requires) and validates availability at save time (`POST`/`PUT /workflows/custom`, chat `draft_workflow`/`save_workflow`, designer drafts) — an unknown, misspelled or deny-listed tool is a 422. The gateway meta-tools (`search_tools`, `call_tool`, `load_mcp_server`) can never be step tools. `run()` resolves every action step's tools before any step runs, so a vanished tool stops the run before an earlier step acts; `resume()` checks only the steps still to run, after the gate and decision are validated. The last turn of an action step always switches tools off so the agent can report. At run time only the allowlisted tools are offered (sorted; constant cached system block, per-run goal/inputs/earlier results in the user turn), every `tool_use` is re-checked against the allowlist, MCP calls go through `MCPGateway.call_tool` so the config deny-list and the Gmail/Calendar/Drive recipient gates still apply, the call budget is enforced (then a final tools-off turn asks for the report; running out of turns fails the step and lists what was already done), tool errors (the gateway's `Error:` / `Error calling tool` / `Tool error:` prefixes, or a truthy `error` field) return to the model as `is_error` results, each call emits a `progress` event and an audit row (`workflow_tool_call`: tool and outcome; for tools that may change things also a short digest of target arguments — ids, recipients, URLs, paths — so a redirected write is visible; content arguments are never logged), and the step's output is the agent's report plus an \"Actions taken\" list. Tool output is framed as data, never instructions.\n\n**Scripts in action steps.** Besides the step's own tools, the agent is offered one more, `run_script` (`openexecutive/workflows/step_script.py`), for work that repeats over many items — every file in a folder, every row, every email — or chains calls with simple logic. It writes a short Python script once instead of spending a model turn per call; each of the step's tools is a function in the script (`drive__move_file(file_id=…)`, or `call_tool(name, arguments)` by exact name), and only the script's final value and printed output come back. The script runs in **Monty** (`pydantic-monty`), a sandboxed Python interpreter for model-written code, in a worker process spawned per script: no files, network, environment, subprocesses or third-party imports — the step's tools are the only things it can reach. **A script is a faster way to make the same calls, never a way around them:** every call it makes goes through the same per-call path as a direct `tool_use` (`action_step._StepCalls`) — the allowlist, a call budget (a script's calls have their own: 10× the step's `max_tool_calls`, capped at `WORKFLOW_SCRIPT_MAX_CALLS`, default 500, because they cost no model turn each — so a step can work through a folder of hundreds of files while its direct calls stay capped at 1–50), the first-write target check (a held write comes back to the script as `{\"status\": \"held\", …}`) and one `workflow_tool_call` audit row per call — and the script itself is audited as `run_script`, with how many calls it made and how long it took. The step's \"Actions taken\" list collapses repeats into one line with a count. A step whose direct calls are spent keeps its tools on while the script budget has room, so it can still script the rest (a direct call is refused as over budget). When a tool returns a list of five or more items and the round didn't use `run_script`, the step adds the same `FANOUT_HINT` as chat (once a step), pointing the per-item work at one script. The worker is stepped from the step's own task (each call pauses it and is answered there), so cancelling the run stops the script and its in-flight call together, and each call's progress shows as it happens. At most `SCRIPT_MAX_WORKERS` (default 2) scripts run at once across the server, chat and workflows together; another waits for a slot within its own wall clock, else returns \"the server was busy\". A worker exists only while its script runs (about 8 MB idle). Execution time (excluding time waiting on tools), memory and recursion depth are capped inside the worker, the script has a wall-clock limit, and its text is size-capped; printed output past its cap is dropped. A failing script returns its error to the agent as an `is_error` result, with the calls it already made listed first (ahead of any long result, so a cut never drops them) so a fixed re-run doesn't repeat writes; a call cut off by the time limit is listed as `may_have_run`, and gets a `cancelled (may have run)` audit row. A workflow definition still holds no code; a script lives on only if the agent saves it as a tool (below). Because a step can loop at run time, the workflow designer keeps work that repeats over items (each email, file, row or listed follow-up) in ONE action step whose goal spells out the items, rather than a step per item; `run_script` is never a step tool, and a definition that lists it is rejected (`validate_definition`) so the designer's repair turn removes it. `WORKFLOW_STEP_SCRIPTS=false` turns the tool off, and a step then only calls its tools one by one.\n\n**Python jobs (`run_python_job`, `openexecutive/workflows/python_job.py`).** Monty can't run libraries, so library work on files (split or merge PDFs with pypdf, spreadsheets with openpyxl and pandas, charts with matplotlib, images with Pillow, and documents made from scratch or from files: Word with python-docx, PowerPoint with python-pptx, laid-out PDFs with fpdf2) runs as a Python job: Pyodide (Python in WebAssembly) executed by **Deno** in a process of its own per job. Pyodide alone is not a sandbox — its Python can call into the JavaScript runtime, which under plain Node reaches the server's environment, files and network — so Deno is what isolates it: it is started with read access to the sandbox folder and the worker script only, with no network, environment, writes or processes, and an empty process environment. Files go in on stdin and results come back on stdout. A job gets only what the call names: Knowledge-library files, the files attached to the chat message being answered (`attachment_files`, the uploads as sent, bound for that turn only by `POST /chat/upload` in `workflows/turn_files.py`, so the model never retypes an attachment's text), text the caller passes, and `inputs` (a dict the code reads); result files are kept 7 days under the company folder and served to the principal at `GET /python-jobs/{job}/{file}`, which the Executive links in its reply. A deployment can instead send jobs to a separate runner (`PYTHON_JOB_RUNNER_URL`, with `PYTHON_JOB_RUNNER_KEY` as a bearer token): `run_job` POSTs the same job (code, inputs, files, caps, time and memory limits) and reads back the same result object, at most as large as a local job's output, keeping only its known fields, so kept results, links and metering are unchanged; the local sandbox is then not needed, and the runner is trusted to isolate jobs. A runner can turn a job away with `{\"run_locally\": true}` (and an optional `reason`) in a non-200 reply, for example when the deployment's allowance for it is used up: the job then runs in the local sandbox if this machine has one, and otherwise fails with the runner's reason. Any other non-200 reply stays a job error, so a busy or broken runner never moves every job onto the machine. A runner with more libraries lists them in `PYTHON_JOB_EXTRA_LIBRARIES`, which the job tool's description then names, so the Executive doesn't refuse a job that needs one. The tool sits in the `workflows` tool group, labelled for jobs with or without attached files. The library set is fixed at build time: the API image installs Pyodide and Deno from npm and the compiled libraries from Pyodide's CDN, each checked against the sha256 in Pyodide's lock file, and a build smoke runs a job. Pyodide can't infer the compiled packages the pure-Python libraries import (lxml, Pillow, fonttools), so the worker loads them when a job imports docx, pptx or fpdf. Pyodide, Deno and the pure-Python libraries are pinned by hash too (an npm lock installed with `npm ci`, pip `--require-hashes`). One job runs at a time per process (200–450 MB each), with a `PYTHON_JOB_TIMEOUT_S` limit and a memory cap (`PYTHON_JOB_MEMORY_MB`, default 1536, as the process's data limit, plus V8 heap and WebAssembly memory caps); the worker returns at most 20 result files and 25 MB, and the API stops the job as soon as its reply passes that. The job runs at a lower CPU priority and is first in line if the machine runs out of memory, so a heavy job slows or loses itself rather than the API; Deno's own caches go in a temporary folder removed with the job; and kept results are capped at 200 MB in all, oldest first. The tool is chat-only, offered only on the principal's own turns (`PRINCIPAL_ONLY_TOOLS`), withheld on private turns, unattended passes and under the Act as me lockdown, and not offered at all without the sandbox (`PYTHON_JOBS_ENABLED`, `PYTHON_SANDBOX_DIR`).\n\nA job that worked can be kept the same way as a script (below): `save_as` and `description` keep its code as a Custom tool of kind `python`, and `run_python_job(tool=<name>, inputs={...})` with its files runs it again, recording the run, so a job done before costs no code-writing tokens. Python tools run only on the principal's own chat turns: they are never listed for workflow steps and never turn on for workflows (`PUT /saved-tools/{name}` answers 409), and `run_script` refuses one (and `run_python_job` a script tool). Every job writes one `python_job` audit row (`ok`, `duration_ms`, `cpu_ms` and `peak_mb` read from the process's /proc entry just before it is stopped, files and bytes in and out, attachments, the Custom tool it ran or kept), which `GET /audit/usage` sums into `python_jobs` with the model usage of the turns that ran one.\n\n**Saved tools.** A script that works can be kept to run again by name (`openexecutive/workflows/saved_tools.py`); each tool has a `kind`, `script` (`run_script`) or `python` (`run_python_job`, above). `run_script` takes `save_as` and `description` with a new script: if the script succeeds it is saved, with the set of tools it actually called, and a failed script is never saved. Later, `run_script(tool=<name>, inputs={...})` runs the saved script instead of new code, with `inputs` available to it as a dict. Only the principal's own turns save: a chat turn where the principal is speaking on a verified, interactive surface (the same test as `load_mcp_server`), never an inbound email, a teammate, an unattended run or a workflow step — a step is offered `tool=` but not `save_as`. A saved tool runs with the authority of whoever runs it, so its author must be trusted at least as much as anyone who may run it. For the same reason only a workflow step (its tools owner-approved) or the principal's own turn may run one: anyone else's chat turn is refused `tool=` and not offered `list_saved_tools`, so a stranger can neither list the principal's automations nor run one with inputs they choose. Descriptions are kept to one line of printable text (they are shown to models), and every save writes a `saved_tool_changed` audit row (`actor: executive`) beside the owner's own changes. Saving needs no approval beyond that, because a saved tool can do no more than the context running it: its calls go through the same per-call path as any script (in a step: the allowlist, budget, target check and audit), and a step runs one only when the step already allows every tool it used (otherwise the result names the `missing_tools`) and only at the version the owner turned on for workflows (`workflow_version`, Settings → Advanced → Custom tools → Use in workflows). A tool kept on a turn that read outside content could otherwise carry injected code into an unattended run, so keeping stays automatic and works in chat at once, but workflows wait for the owner; a newer save doesn't change the version workflows run, and pruning never drops it. Each step's `run_script` description lists the saved tools that step may run; chat asks `list_saved_tools`. Every save of changed content is a new version (the newest 20 are kept, plus the one that ran until then, so a rolled-back version the owner trusts survives later saves), every run is recorded (`saved_tool_runs`, the newest 200 per tool), and the owner can turn a tool off or switch it back to an earlier version on Settings → Advanced → Saved tools (`/saved-tools` routes, the owner's alone). A turned-off tool never runs, and a new version saved by the model does not turn it back on. `SAVED_TOOLS_ENABLED=false` stops saving and running saved tools everywhere.\n\n**Targets are chosen at run time — and a new one is confirmed once.** Approving a workflow approves its *tools*; which sheet, doc, recipient or URL each call hits is chosen by the model at run time, by design (a tab per month, a reply to whoever sent the invoice, a doc per client). What bounds that is the allowlist, the gateway's recipient gates, the audit digest, and **first-write confirmation**: a `TargetPolicy` (one per run) checks every call to a tool that may change things. `resource_targets` walks its arguments recursively for resource keys (snake- or camel-case ids, `to`/`cc`/`bcc`, recipients, addresses, attendees, members, users, owners, parents, URLs/links/hrefs, paths, channels, spaces, rooms, phones, hosts, buckets, tables, spreadsheet/document/folder/calendar/file); a matching key marks everything beneath it, even a `name`. Outside a resource, only a new item's own `name`/`title`/`subject`, message/thread/draft/label ids, `range`/`sheet` and workspace-mcp's acting `user_google_email` are skipped — and whatever the key, a bare value shaped like an email address, a URL or an international phone number is a target, except inside what the call writes (`rows`, `values`, `body`, `text` …). Key names are a heuristic, so this is a best-effort guard layered on the allowlist, the gateway gates and the audit. Float ids are compared as integers. Arguments too deep, naming too many targets, or holding an over-long value **fail closed** (the call is refused). A target is trusted only when it was approved for this workflow before (`workflow_approved_targets`, by value) or is an id a write in this run created — a top-level id/link field (`id`, `spreadsheetId`, `webViewLink` …) of the **structured JSON object** result of a tool whose name says it creates (create / insert / upload …) and that takes no URL — a tool whose schema couldn't be read is assumed to (free text, nested records and readers' or updaters' results are never read, so a fetched page, an echoed title, a shared page's links or a stranger in `ccRecipients` can't plant one); those survive a pause in the resume payload (`run_created`). Values written in the workflow's own text are *not* trusted, since anyone who can edit the workflow could change them without review: they are asked once, then remembered. Approvals are by value, for any of the workflow's tools, and are **cleared when the workflow's tool set changes** (a newly added tool must earn them again). Any other target makes the call **held**: it is not run and costs no budget, the model is told it is waiting for approval and carries on, and it is audited `held for approval` (at most 10 held per step, 16 KB each; an identical repeat is held once). Whether a call is checked at all follows the read-only label, which now never marks a tool whose name carries a write verb anywhere (`find_and_replace_doc`). After the step finishes, the run pauses with a `WaitForHumanEvent` to the workflow's **owner** (`owner_person_id`, the person who created it on the Workflows page or in chat; falling back to the principal if unknown or archived), `on_timeout=auto_proceed`, 48 h, and a `WorkflowResumeState` of `kind=\"held_writes\"` carrying the exact held calls. On resume (`_resume_held_writes`, fingerprint-checked like a gate, with the remaining steps' tools checked first), only `approve` runs them — each still has to be in the live step's allowlist and resolve; its targets are remembered first — and anything else (decline, timeout, unreadable) skips them; either way a *Held for approval* section is added to the step's output and the run continues at the next step. With no one to ask, held writes are skipped and noted; a step that fails or crashes after holding, or a resume that stops early (definition changed, a later tool missing), audits its held writes as dropped and says they did not run. The question quotes each target JSON-escaped (a value can't add its own lines) and always shows a URL's full scheme and host, saying how much of the rest is hidden. The owner answers by chat reply or with **Approve / Decline** on the run page (`POST /workflows/runs/{id}/decision`, which the principal may also use); remembered targets are listed and removable on the workflow page.\n\n`oe__read_file` extracts text (PDF, Word, Excel, CSV, Markdown, text) only from files under `WORKFLOW_FILE_DIRS` (default: workspace-mcp's attachment folder), resolving symlinks and `..` before the check (`tool_catalog.resolve_readable_file`, shared with the Executive's `read_document` tool). A scanned PDF is converted by `knowledge.pdf_reader` instead of failing as \"may be a scanned image\"; one that still cannot be read returns the reason. Action steps are allowed in scheduled workflows. Because they have external side effects, a resumed run heartbeats its claim (`touch_resume_claim`, at most once a minute as events flow — each tool call emits one; a busy database is retried on the next heartbeat, never treated as a lost claim; the sweep's requeue re-checks the claim's age in the same UPDATE, so a heartbeat landing between the sweep's read and its write wins), so the stale-claim sweep never requeues and replays a slow but live run, and a worker that finds its claim superseded stops at its next event. A worker that actually crashes mid-resume is still requeued; its action steps then run again, so goals should say how to avoid duplicates (the actor reads current state before writing). `GET /workflows/tools/search?q=` and `GET /workflows/tools/describe?names=` back the advanced editor's tool picker and the review card's labels.\n\nAn optional cadence (`daily@` / `weekly@` / `quarterly@`) re-uses the scheduler via the `dynamic_workflow` action kind, which runs the workflow on schedule and DMs the artifact to a rostered recipient. A gate followed by further steps pauses at `awaiting_human` and then resumes once answered, so gates no longer have to sit immediately before synthesis. They remain forbidden in cadence-enabled definitions: a scheduled fire has no interactive human to ask.\n\nBuilt-ins the system runs on its own (`morning_brief`, `end_of_day_digest`, `executive_reflection`, `executive_research`) set `background = True`, surfaced as `WorkflowMeta.background`; the `/jobs` ready-made list files them under a **System** chip instead of the default view. They stay runnable by hand.\n\n**Quick workflows** (`workflows/quick.py`) are one per playbook in effect that no built-in or custom workflow follows (switched-off custom ones count). They are derived whenever the catalog is read, never stored: `list_workflows()` returns built-ins, then Quick ones, then active custom ones, and `get_workflow` resolves a `quick_<playbook>` name after the registry (custom workflows may not take the `quick_` prefix). Each has one required field, `request`, and two steps: **Load context** (company profile plus RAG for the playbook category's specialist) and **Draft** (that specialist writes one Markdown document following the playbook). `WorkflowMeta.quick` is true for them. The 8 built-in playbooks no built-in follows are Quick workflows: board update memo, 1:1 agenda, layoff comms plan, positioning statement, post-mortem, customer interview plan, feature prioritization and market sizing. A company's own playbook shows up as one, hiding a built-in drops it, and a custom workflow that starts following one replaces it. If custom workflows can't be read, none are offered, since their followers are unknown.\n\n**Workflows vs. playbooks.** `/jobs` has two tabs: **Build** (`?tab=catalog`, the default) and **Runs** (`/skills` redirects to `/jobs`). A playbook is a skill (`knowledge/skills_repo.py`): *how* the Executive does a piece of work, with no inputs, schedule or side effects. A workflow is the runnable job. Workflows **follow** playbooks: a step that follows one gets its body appended to the step prompt via `workflows/playbooks.py` (`load_playbook` + `playbook_clause`). Six built-ins do — `board_prep` (`board-prep-deck`), `quarterly_plan` (`quarterly-okr-set`, `quarterly-forecast`), `mbr` (`monthly-business-review`, in the financial, KPI and function steps), `competitive_teardown` (`competitive-teardown`, in the four analysis steps), `fundraising_prep` (`fundraise-narrative`, narrative step) and `exec_search_brief` (`role-scorecard`, profile step). Each declares them in `Workflow.playbooks`; a unit test holds that declaration equal to the `load_playbook(\"…\")` calls in the module, and `WorkflowMeta.playbooks` exposes it. A custom workflow's `specialist` step may name a `playbook` (validated to exist at save; appended after `{field}` rendering, so braces in a playbook are never treated as placeholders). The lookup resolves the playbook in effect, so a company's customized copy changes the workflow's output, and a hidden, missing or malformed one falls back to the step's own prompt plus RAG — a workflow never fails over a playbook (`load_playbook` catches everything; a custom step whose playbook is unavailable emits a `progress` event saying so). Because an approved scheduled workflow reads its playbook at each run, chat never creates or changes a playbook: it saves repeatable work as a workflow (`draft_workflow`, confirmed by the user), and only a person can change what a workflow follows: a workflow's page shows each playbook it follows as **How it's done** (`components/jobs/HowItsDone.tsx`), with **Edit** (`PUT /skills/{name}`; on a built-in that saves the company's customized copy) and, for a customized copy, **Reset to original** (`DELETE`, which reverts). The chat summary of a drafted workflow names each step's playbook. `playbook_users()` maps each playbook to the workflows that follow it — built-ins, every custom workflow (switched-off ones included: turning one on approves its definition) and the Quick ones; the skills API reports it as `used_by`, and the Executive's `search_skills` hits carry it as `workflows`.\n\nCompleted artifacts are discoverable in the unified artifacts section (`/artifacts`, labelled **Documents** in the UI) alongside their run-detail page at `/jobs/runs/{run_id}`. A run someone starts by hand (`POST /workflows/{name}/runs`, `run_workflow`, research in chat) stores them as `workflow_runs.owner_person_id` and its history and output are theirs alone (plus the person a gate waits on); scheduled and system runs keep no owner and stay the team's. Workflow output stays Markdown — the scheduler DMs it and reflection rereads it as text — and gains other formats only on the way out: any run can be downloaded as Word (`/artifacts/run:<id>/download?as=docx`), and the Executive can repackage one with `get_artifact` → `draft_artifact(format=…, supersedes=\"run:<id>\")`.\n\n## Data-driven retrospectives\n\n`engagement_value_report` introduces a new workflow pattern: instead of the user typing the substance into a form (the `investor_update` / `mbr` shape), the workflow **reads its substance from the database**. A deterministic gatherer (`clients/engagement_activity.py`) pulls the period's decisions, initiatives, advisory consultations, delivered workflow artifacts (excluding prior value reports), follow-through counts, and alerts handled — from the live DB for the active client, or a parked client slot's `state.db` opened read-only. A single board-comms call narrates those facts (the prompt forbids inventing anything not in them; an empty period skips the LLM entirely), and the artifact's lists are assembled deterministically. Built for renewal conversations — the engagement record is the evidence.\n\nWith Take the lead as the Executive on (`orchestrator.take_the_lead`), reflection and research build their toolkit through `unattended_toolkit(..., source=...)`. That keeps solo's booking and `run_workflow` tools and an unrestricted `message_person` (teammates as well as the principal). Every acting tool goes through the gate, and a held action waits on Today as a `take_the_lead_action` decision. Reflection also gets the MCP gateway's `search_tools` and `call_tool` (`_with_lead_tools`; `call_tool` behind the gate, `load_mcp_server` left out), so it can find and use whatever the deployment has connected, such as building a sheet to track something. A note in the user turn (never the cached system prompt) tells it to act rather than only report, and it gets more room: 10 iterations, 4000 tokens, and tool results up to 4000 characters. The grounding check still refuses outward text naming people or figures the pass didn't see. New mail and chat also wake the reflection early (scheduler section). In training (`take_the_lead.training`) every acting call that isn't allowed waits too, as a training card for the principal, and both passes append `take_the_lead.learned_note()` to their user turn: that it's in training, and the principal's own edits on earlier cards as examples of how they want those done (never in the cached system blocks).","mermaid": "flowchart TD\n Input[\"Structured input\"]\n Steps[\"Ordered named steps\"]\n Wait[\"wait_for_human pause\"]\n Sched[\"workflow_runs<br/>(awaiting_human)\"]\n Resolver[\"inbound_resolver<br/>+ resumer\"]\n Artifact[\"Markdown artifact<br/>(workflow_runs.artifact)\"]\n Today[\"Today / Documents\"]\n Input --> Steps\n Steps --> Wait\n Wait --> Sched\n Sched -- \"human reply\" --> Resolver\n Resolver -- \"resolved → claim\" --> Steps\n Steps -- \"complete_run\" --> Artifact\n Artifact --> Today\n class Input entry\n class Steps compute\n class Wait compute\n class Sched storage\n class Resolver compute\n class Artifact storage\n class Today external",- "generated_at": "2026-10-13T18:00:00Z"+ "generated_at": "2026-10-13T20:00:00Z"}diff --git a/packages/core/openexecutive/orchestrator/outbound_guard.py b/packages/core/openexecutive/orchestrator/outbound_guard.pyindex e6d06e9f..6086366b 100644--- a/packages/core/openexecutive/orchestrator/outbound_guard.py+++ b/packages/core/openexecutive/orchestrator/outbound_guard.py@@ -21,6 +21,13 @@ suppress-and-log the send and the Executive can read the reason and adapt3. Quiet hours / availability — when ``outbound_respect_quiet_hours`` is set,refuse while the recipient is on leave or outside their availability windows.+Separately, ``check_hold`` applies the recipient's own notification settings+(``people.notifications``: quiet hours, "In my briefs") to the Executive's+own outreach only — a DM sent while a proactive source is tagged+(``attunement.outcomes.tag_proactive``). It does not refuse: the send handler+stores the message (``people.held_messages``) and it goes when their quiet+hours end or with their next brief.+The delivery history is read from the ``status='done'`` ``scheduled_actions``rows that ``_record_send_to_activity`` already writes for every send, so thereis no new table. The guard is *fail-open*: any internal lookup failure returns@@ -44,6 +51,7 @@ from typing import TYPE_CHECKINGif TYPE_CHECKING:from openexecutive.people.models import Person+ from openexecutive.people.notifications import Holdlogger = logging.getLogger(__name__)@@ -192,3 +200,47 @@ def _evaluate(channel: str, channel_ref: str, text: str, now: datetime) -> str |return reasonreturn None+++def check_hold(+ channel: str,+ channel_ref: str,+ *,+ now: datetime | None = None,+) -> tuple[int, str, Hold] | None:+ """``(person_id, source, hold)`` when this DM is the Executive's own+ outreach and the recipient's notification settings hold it back, else+ None (send it now).++ Only a tagged proactive send is ever held (``attunement.outcomes``): a+ message someone asked for in chat, a brief, a reminder they set and a+ release of held messages carry no tag. Fail-open like the guard: any+ lookup error sends.+ """+ try:+ from openexecutive.attunement.outcomes import current_tag++ tag = current_tag()+ if tag is None:+ return None+ from openexecutive.people.notifications import (+ hold_for,+ is_approval_send,+ is_urgent_send,+ )++ if is_approval_send():+ return None # a question something waits on: never held+ from openexecutive.people.store import find_person_by_channel_ref++ person = find_person_by_channel_ref(channel, channel_ref)+ if person is None or person.id is None or person.archived:+ return None+ source = tag[0]+ hold = hold_for(+ person.id, source=source, now=now or datetime.now(UTC), urgent=is_urgent_send()+ )+ return None if hold is None else (person.id, source, hold)+ except Exception:+ logger.exception("outbound_guard: hold check failed; sending")+ return Nonediff --git a/packages/core/openexecutive/orchestrator/schedule_tools.py b/packages/core/openexecutive/orchestrator/schedule_tools.pyindex f5e6786c..a12dd6d5 100644--- a/packages/core/openexecutive/orchestrator/schedule_tools.py+++ b/packages/core/openexecutive/orchestrator/schedule_tools.py@@ -187,7 +187,7 @@ def _guard_outbound(*, tool: str, channel: str, channel_ref: str, text: str) ->reason = check_outbound_allowed(channel, channel_ref, text)if reason is None:- return None+ return _hold_outbound(tool=tool, channel=channel, channel_ref=channel_ref, text=text)from openexecutive.audit import log_event as audit_logaudit_log(@@ -207,6 +207,58 @@ def _guard_outbound(*, tool: str, channel: str, channel_ref: str, text: str) ->return json.dumps({"status": "suppressed", "reason": reason})+def _hold_outbound(*, tool: str, channel: str, channel_ref: str, text: str) -> str | None:+ """Hold the Executive's own outreach back when the recipient asked for+ that (quiet hours, "In my briefs": ``outbound_guard.check_hold``).++ Returns the ``{"status": "held"}`` result once the message is stored+ (``people.held_messages``), or ``None`` to send it now — including when+ it couldn't be stored, so a message is never lost to the hold."""+ from openexecutive.orchestrator.outbound_guard import check_hold++ held = check_hold(channel, channel_ref)+ if held is None:+ return None+ person_id, source, hold = held+ try:+ from openexecutive.attunement.outcomes import current_tag+ from openexecutive.people.held_messages import hold as store_held++ tag = current_tag()+ held_id = store_held(+ person_id, text, source=source, release_at=hold.release_at,+ ref=tag[1] if tag else "",+ )+ except Exception:+ logger.exception("hold_outbound: couldn't store the message; sending it")+ return None+ from openexecutive.audit import log_event as audit_log++ audit_log(+ "tool_invocation",+ f"{tool} HELD for person {person_id}: {hold.reason}",+ actor="executive",+ details={+ "tool": tool,+ "kind": "outbound",+ "ok": True,+ "held": True,+ "held_id": held_id,+ "person_id": person_id,+ "source": source,+ "channel": channel,+ "release_at": hold.release_at.isoformat() if hold.release_at else None,+ },+ )+ return json.dumps({+ "status": "held",+ "reason": (+ f"Not sent now: {hold.reason}. It is saved and will be delivered "+ "then — do not send it again or schedule it."+ ),+ })++def _resolve_recipient_person_id(channel: str, channel_ref: str) -> int | None:"""Best-effort map a DM recipient's channel id to a Person.id for linkagerows. Returns None on any miss or lookup failure (e.g. the people table not@@ -1482,7 +1534,9 @@ async def message_person(tool_input: dict[str, Any], *, alert_fallback: bool = Tparsed = json.loads(result)except (ValueError, TypeError):parsed = {}- if parsed.get("status") == "sent":+ if parsed.get("status") in ("sent", "held"):+ # Held: saved for when they asked to hear (quiet hours, their+ # brief) — trying the next channel would hold it twice.return resultlast_error = parsed.get("error") or last_errordiff --git a/packages/core/openexecutive/people/channel.py b/packages/core/openexecutive/people/channel.pyindex c6dde333..95648ab5 100644--- a/packages/core/openexecutive/people/channel.py+++ b/packages/core/openexecutive/people/channel.py@@ -13,6 +13,13 @@ from datetime import UTC, datetime, timedeltafrom zoneinfo import ZoneInfo, ZoneInfoNotFoundErrorfrom openexecutive.people.models import AvailabilityWindow, Person+from openexecutive.people.notifications import (+ NotificationSettings,+ in_quiet_hours,+ quiet_applies,+ quiet_hours_end,+ zone_for,+)logger = logging.getLogger(__name__)@@ -105,9 +112,26 @@ def _resolve_channel(person: Person) -> tuple[str, str | None]:return "email", None-def is_within_availability(person: Person, *, now: datetime) -> bool:+def _quiet_settings(person: Person, *, quiet_hours: bool, urgent: bool) -> NotificationSettings | None:+ """The person's notification settings when their quiet hours apply to this+ lookup (``quiet_hours`` asked for, quiet hours on, and not an urgent+ message they let through), else None. Fails open."""+ if not quiet_hours or person.id is None:+ return None+ return quiet_applies(person.id, urgent=urgent)+++def is_within_availability(+ person: Person, *, now: datetime, quiet_hours: bool = False, urgent: bool = False+) -> bool:"""Return True if `person` is on the clock right now (leave + windows only).+ With ``quiet_hours`` it is also False during the person's own quiet hours+ (Settings → Notifications, ``people.notifications``), unless ``urgent``+ and they let urgent things through. Only the Executive's own outreach asks+ for that (nudge routing); the outbound guard's availability check does not,+ so a message someone asked for is never held by them here.+False when the person is on leave, or has availability windows configured and`now` falls outside all of them (no windows means "always on"). Unlike`is_reachable_now` this does NOT require a usable channel_ref and ignores the@@ -120,10 +144,15 @@ def is_within_availability(person: Person, *, now: datetime) -> bool:if person.on_leave_until is not None and now.astimezone(UTC).date() <= person.on_leave_until:return False# Window check: no windows means "always on"; otherwise must be inside one.- return not person.availability or any(_in_window(win, now) for win in person.availability)+ if person.availability and not any(_in_window(win, now) for win in person.availability):+ return False+ quiet = _quiet_settings(person, quiet_hours=quiet_hours, urgent=urgent)+ return quiet is None or not in_quiet_hours(quiet, now)-def is_reachable_now(person: Person, *, now: datetime) -> bool:+def is_reachable_now(+ person: Person, *, now: datetime, quiet_hours: bool = False, urgent: bool = False+) -> bool:"""Return True if `person` can be reached right now.False when the person is archived, on leave, has no usable channel_ref for@@ -134,30 +163,46 @@ def is_reachable_now(person: Person, *, now: datetime) -> bool:"""if person.archived:return False- if not is_within_availability(person, now=now):+ if not is_within_availability(person, now=now, quiet_hours=quiet_hours, urgent=urgent):return False_, ref = _resolve_channel(person)return ref is not None-def next_window_for(person: Person, *, after: datetime) -> datetime | None:+def next_window_for(+ person: Person, *, after: datetime, quiet_hours: bool = False, urgent: bool = False+) -> datetime | None:"""Next window-open moment for `person`, or None (Person-object variant).None when no windows are configured (always-reachable, no deferral needed)- or no window falls within the 14-day scan horizon.+ or no window falls within the 14-day scan horizon. With ``quiet_hours``+ (see ``is_within_availability``) the moment must also be outside the+ person's quiet hours; with quiet hours but no windows that is when the+ quiet hours end."""+ quiet = _quiet_settings(person, quiet_hours=quiet_hours, urgent=urgent)if not person.availability:- return None+ # Always on but for quiet hours: the end of them, if they are on now.+ if quiet is None or not in_quiet_hours(quiet, after):+ return None+ return quiet_hours_end(quiet, after)step = timedelta(minutes=_SCAN_STEP_MINUTES)horizon = after + timedelta(days=_SCAN_DAYS)probe = after + step # start one step ahead so we don't return "now"+ zone = zone_for(quiet) if quiet is not None else Nonewhile probe <= horizon:- if any(_in_window(win, probe) for win in person.availability):+ if any(_in_window(win, probe) for win in person.availability) and (+ quiet is None or not in_quiet_hours(quiet, probe, zone=zone)+ ):return probe.astimezone(UTC).replace(second=0, microsecond=0)probe += step+ if quiet is not None:+ # Quiet hours cover every window in the horizon: the window wins,+ # rather than the message never going.+ return next_window_for(person, after=after)return None@@ -165,6 +210,8 @@ def prefer_channel_for(person_id: int,*,now: datetime,+ quiet_hours: bool = False,+ urgent: bool = False,) -> tuple[str, str] | None:"""Return (channel, channel_ref) if the Person is reachable right now.@@ -176,11 +223,15 @@ def prefer_channel_for(- Current time is outside all configured availability windows.(If no windows are configured at all, the Person is always consideredreachable — no windows means "always on".)+ - ``quiet_hours`` is set and it is the person's quiet hours (see+ ``is_within_availability``)."""from openexecutive.people.registry import get_personperson = get_person(person_id)- if person is None or not is_reachable_now(person, now=now):+ if person is None or not is_reachable_now(+ person, now=now, quiet_hours=quiet_hours, urgent=urgent+ ):return None# Reachability guarantees a usable ref; resolve it for the caller.channel, ref = _resolve_channel(person)@@ -193,6 +244,8 @@ def next_available_window(person_id: int,*,after: datetime,+ quiet_hours: bool = False,+ urgent: bool = False,) -> datetime | None:"""Scan forward up to 14 days to find the next window-open moment.@@ -207,4 +260,4 @@ def next_available_window(person = get_person(person_id)if person is None:return None- return next_window_for(person, after=after)+ return next_window_for(person, after=after, quiet_hours=quiet_hours, urgent=urgent)diff --git a/packages/core/openexecutive/people/held_messages.py b/packages/core/openexecutive/people/held_messages.pynew file mode 100644index 00000000..56f85e51--- /dev/null+++ b/packages/core/openexecutive/people/held_messages.py@@ -0,0 +1,585 @@+"""Proactive DMs held back by a person's notification settings, and their+release (``people.notifications``).++The outbound guard stores a held DM here instead of sending it+(``orchestrator.schedule_tools._guard_outbound``). Each row is either:++- **waiting for quiet hours to end** (``release_at`` set): the scheduler's+ tick (``maybe_release``) sends everything due to that person in one message+ once ``release_at`` passes;+- **waiting for their brief** (``release_at`` null, "In my briefs"): the+ principal's morning or end-of-day brief carries them as one "While you were+ away" block (``scheduler.runner._run_principal_brief``). Anyone else who+ chose briefs gets that block on its own when the briefs go out+ (``schedule_digest_release``), since only the principal has a brief.++A row is sent once: whoever sends it (a release pass, a brief) first claims+it (``claimed_at``, compare-and-set; a claim older than ``CLAIM_TTL`` is+free again, so a crash mid-send can't strand a row), marks it sent only+after the delivery went, and frees the claim when it didn't. A person+outside their availability or on leave is postponed to when that ends; any+other failed delivery backs off (``_backoff``). Rows nobody could deliver for+``GIVE_UP_AFTER`` are dropped, as are the oldest past ``MAX_HELD_PER_PERSON``+— each drop audited, private to the person, a count only. A digest row that+has waited ``DIGEST_FALLBACK_AFTER`` with no brief to carry it (the briefs+not going out) is sent on its own.++The text is private to the person it was for: it is never listed anywhere,+only counted (``held_count``) on their own Notifications page, and release+audit rows are private to them.+"""+from __future__ import annotations++import asyncio+import contextlib+import contextvars+import logging+import sqlite3+from collections.abc import Iterator+from dataclasses import dataclass+from datetime import UTC, datetime, timedelta, tzinfo+from pathlib import Path+from typing import TYPE_CHECKING++if TYPE_CHECKING:+ from openexecutive.people.models import Person++logger = logging.getLogger(__name__)++TABLE = "held_messages"++# The most text one held row keeps.+MAX_TEXT = 4000+# The most rows one person can have waiting; past it the oldest go first.+MAX_HELD_PER_PERSON = 50+GIVE_UP_AFTER = timedelta(days=7)+DIGEST_FALLBACK_AFTER = timedelta(hours=36)+RELEASE_EVERY = timedelta(minutes=1)+CLAIM_TTL = timedelta(minutes=10)+# A delivered batch is marked sent with a few tries (see release_due).+_MARK_SENT_TRIES = 3+MAX_BACKOFF = timedelta(hours=1)+HEADING = "While you were away"++_last_release_at: datetime | None = None+_task: asyncio.Task[int] | None = None+++@dataclass(frozen=True)+class HeldMessage:+ id: int+ person_id: int+ source: str+ text: str+ created_at: str+ release_at: str | None+ ref: str = ""+ attempts: int = 0+++def _db(db_path: Path | None) -> Path:+ if db_path is not None:+ return db_path+ from openexecutive.memory import episodic++ return Path(episodic.DB_PATH)+++def _connect(db_path: Path | None) -> sqlite3.Connection:+ conn = sqlite3.connect(str(_db(db_path)))+ conn.executescript(+ f"""+ CREATE TABLE IF NOT EXISTS {TABLE} (+ id INTEGER PRIMARY KEY AUTOINCREMENT,+ person_id INTEGER NOT NULL,+ source TEXT NOT NULL DEFAULT '',+ ref TEXT NOT NULL DEFAULT '',+ text TEXT NOT NULL,+ created_at TEXT NOT NULL,+ release_at TEXT,+ attempts INTEGER NOT NULL DEFAULT 0,+ claimed_at TEXT,+ sent_at TEXT,+ dropped_at TEXT+ );+ CREATE INDEX IF NOT EXISTS idx_held_messages_person+ ON {TABLE}(person_id) WHERE sent_at IS NULL AND dropped_at IS NULL;+ """+ )+ return conn+++def _iso(dt: datetime) -> str:+ # UTC, so string comparison orders them by time.+ return dt.astimezone(UTC).isoformat()+++def _rows(cur: sqlite3.Cursor) -> list[HeldMessage]:+ return [+ HeldMessage(int(r[0]), int(r[1]), str(r[2]), str(r[3]), str(r[4]), r[5], str(r[6]), int(r[7]))+ for r in cur.fetchall()+ ]+++_COLUMNS = "id, person_id, source, text, created_at, release_at, ref, attempts"+++def _audit_dropped(person_id: int, count: int, reason: str) -> None:+ """Say that held messages were dropped: private to the person, a count+ and why, never their text. Never raises."""+ if count <= 0:+ return+ try:+ from openexecutive.audit import log_event++ log_event(+ "held_messages_dropped",+ f"Dropped {count} held message(s) for person {person_id}: {reason}",+ actor="scheduler",+ details={"person_id": person_id, "count": count, "reason": reason},+ private=True,+ private_to_person=person_id,+ )+ except Exception:+ logger.warning("held_messages: couldn't audit a drop", exc_info=True)+++# The ids held during the current block (``track_holds``), so the caller of a+# proactive turn can tell "held" from "delivered".+_tracked: contextvars.ContextVar[list[int] | None] = contextvars.ContextVar(+ "held_messages_tracked", default=None+)+++def track_holds() -> Iterator[list[int]]:+ """Collect the ids of the messages held inside the block. Wrap only+ non-yielding code."""+ ids: list[int] = []+ token = _tracked.set(ids)+ try:+ yield ids+ finally:+ _tracked.reset(token)+_OPEN = "sent_at IS NULL AND dropped_at IS NULL"+++def hold(+ person_id: int,+ text: str,+ *,+ source: str,+ release_at: datetime | None,+ ref: str = "",+ now: datetime | None = None,+ db_path: Path | None = None,+) -> int:+ """Store a DM for ``person_id`` until ``release_at`` (None: their next+ brief). Returns its id. Raises on a write error, so the caller can send+ instead of losing the message."""+ now = now or datetime.now(UTC)+ conn = _connect(db_path)+ try:+ cur = conn.execute(+ f"INSERT INTO {TABLE} (person_id, source, ref, text, created_at, release_at) " # noqa: S608+ "VALUES (?, ?, ?, ?, ?, ?)",+ (+ person_id,+ source[:64],+ ref[:128],+ text[:MAX_TEXT],+ _iso(now),+ _iso(release_at) if release_at is not None else None,+ ),+ )+ held_id = int(cur.lastrowid or 0)+ # Cap what one person can have waiting: drop the oldest past it.+ capped = conn.execute(+ f"UPDATE {TABLE} SET dropped_at = ? WHERE person_id = ? AND {_OPEN} " # noqa: S608+ f"AND id NOT IN (SELECT id FROM {TABLE} WHERE person_id = ? AND {_OPEN} "+ "ORDER BY id DESC LIMIT ?)",+ (_iso(now), person_id, person_id, MAX_HELD_PER_PERSON),+ ).rowcount+ conn.commit()+ finally:+ conn.close()+ _audit_dropped(person_id, int(capped or 0), f"more than {MAX_HELD_PER_PERSON} waiting")+ tracked = _tracked.get()+ if tracked is not None:+ tracked.append(held_id)+ return held_id+++def waiting_for(person_id: int, ref: str, *, db_path: Path | None = None) -> bool:+ """Whether a message about ``ref`` (e.g. ``alert:12``) is already waiting+ for ``person_id``. False on a read error."""+ if not ref:+ return False+ try:+ conn = _connect(db_path)+ try:+ row = conn.execute(+ f"SELECT 1 FROM {TABLE} WHERE person_id = ? AND ref = ? AND {_OPEN} LIMIT 1", # noqa: S608+ (person_id, ref),+ ).fetchone()+ finally:+ conn.close()+ except Exception:+ logger.warning("held_messages: couldn't check what waits for person %s", person_id, exc_info=True)+ return False+ return row is not None+++def claim(ids: list[int], *, now: datetime | None = None, db_path: Path | None = None) -> list[int]:+ """Take ``ids`` for sending; returns the ones this caller got (not sent,+ dropped or claimed by someone else within ``CLAIM_TTL``)."""+ if not ids:+ return []+ now = now or datetime.now(UTC)+ stale = _iso(now - CLAIM_TTL)+ got: list[int] = []+ conn = _connect(db_path)+ try:+ for i in ids:+ cur = conn.execute(+ f"UPDATE {TABLE} SET claimed_at = ? WHERE id = ? AND {_OPEN} " # noqa: S608+ "AND (claimed_at IS NULL OR claimed_at < ?)",+ (_iso(now), i, stale),+ )+ if cur.rowcount == 1:+ got.append(i)+ conn.commit()+ finally:+ conn.close()+ return got+++def unclaim(ids: list[int], *, db_path: Path | None = None) -> None:+ """Give back a claim whose send didn't go."""+ if not ids:+ return+ conn = _connect(db_path)+ try:+ conn.executemany(+ f"UPDATE {TABLE} SET claimed_at = NULL WHERE id = ? AND {_OPEN}", # noqa: S608+ [(i,) for i in ids],+ )+ conn.commit()+ finally:+ conn.close()+++def held_count(person_id: int, *, db_path: Path | None = None) -> int:+ """How many messages are waiting for ``person_id``. 0 on a read error."""+ try:+ conn = _connect(db_path)+ try:+ row = conn.execute(+ f"SELECT COUNT(*) FROM {TABLE} WHERE person_id = ? AND {_OPEN}", # noqa: S608+ (person_id,),+ ).fetchone()+ finally:+ conn.close()+ except Exception:+ logger.warning("held_messages: couldn't count person %s's", person_id, exc_info=True)+ return 0+ return int(row[0] if row else 0)+++def for_brief(person_id: int, *, db_path: Path | None = None) -> list[HeldMessage]:+ """Everything waiting for ``person_id``'s brief, oldest first."""+ conn = _connect(db_path)+ try:+ return _rows(conn.execute(+ f"SELECT {_COLUMNS} FROM {TABLE} WHERE person_id = ? AND {_OPEN} " # noqa: S608+ "AND release_at IS NULL ORDER BY id",+ (person_id,),+ ))+ finally:+ conn.close()+++def mark_sent(ids: list[int], *, now: datetime | None = None, db_path: Path | None = None) -> None:+ if not ids:+ return+ now = now or datetime.now(UTC)+ conn = _connect(db_path)+ try:+ conn.executemany(+ f"UPDATE {TABLE} SET sent_at = ? WHERE id = ? AND {_OPEN}", # noqa: S608+ [(_iso(now), i) for i in ids],+ )+ conn.commit()+ finally:+ conn.close()+++async def mark_sent_after_delivery(+ ids: list[int], *, now: datetime | None = None, db_path: Path | None = None+) -> bool:+ """Mark rows sent once their message went, retrying a few times: a row+ left claimed is claimable again after CLAIM_TTL and would be sent twice.+ Returns whether it stuck. Never raises."""+ if not ids:+ return True+ for attempt in range(_MARK_SENT_TRIES):+ try:+ mark_sent(ids, now=now, db_path=db_path)+ return True+ except Exception:+ if attempt == _MARK_SENT_TRIES - 1:+ logger.error("held_messages: couldn't mark %d sent", len(ids), exc_info=True)+ else:+ await asyncio.sleep(0.5 * (attempt + 1))+ return False+++def release_digest_now(person_id: int, *, now: datetime, db_path: Path | None = None) -> int:+ """Turn ``person_id``'s brief-held messages into ones due at ``now``+ (they leave with the next release pass). Returns how many."""+ conn = _connect(db_path)+ try:+ cur = conn.execute(+ f"UPDATE {TABLE} SET release_at = ? WHERE person_id = ? AND {_OPEN} " # noqa: S608+ "AND release_at IS NULL",+ (_iso(now), person_id),+ )+ conn.commit()+ return int(cur.rowcount or 0)+ finally:+ conn.close()+++def release_quiet_now(person_id: int, *, now: datetime, db_path: Path | None = None) -> int:+ """Bring ``person_id``'s messages waiting on a later time forward to ``now``,+ after they changed their quiet hours. The release pass still checks the+ new quiet hours, so anything that is still quiet waits again. Returns how+ many."""+ conn = _connect(db_path)+ try:+ cur = conn.execute(+ f"UPDATE {TABLE} SET release_at = ? WHERE person_id = ? AND {_OPEN} " # noqa: S608+ "AND release_at > ?",+ (_iso(now), person_id, _iso(now)),+ )+ conn.commit()+ return int(cur.rowcount or 0)+ finally:+ conn.close()+++def schedule_digest_release(+ now: datetime, *, except_person_id: int | None, db_path: Path | None = None+) -> int:+ """When the briefs go out: everyone but ``except_person_id`` (the+ principal, whose brief carries theirs) gets their brief-held messages on+ their own. Returns how many rows were scheduled. Never raises."""+ try:+ conn = _connect(db_path)+ try:+ people = [+ int(r[0]) for r in conn.execute(+ f"SELECT DISTINCT person_id FROM {TABLE} WHERE {_OPEN} " # noqa: S608+ "AND release_at IS NULL"+ ).fetchall()+ ]+ finally:+ conn.close()+ return sum(+ release_digest_now(pid, now=now, db_path=db_path)+ for pid in people+ if pid != except_person_id+ )+ except Exception:+ logger.warning("held_messages: couldn't schedule digest releases", exc_info=True)+ return 0+++def _due(now: datetime, db_path: Path | None) -> dict[int, list[HeldMessage]]:+ conn = _connect(db_path)+ try:+ rows = _rows(conn.execute(+ f"SELECT {_COLUMNS} FROM {TABLE} WHERE {_OPEN} AND (" # noqa: S608+ "(release_at IS NOT NULL AND release_at <= ?) "+ "OR (release_at IS NULL AND created_at <= ?)) ORDER BY id",+ (_iso(now), _iso(now - DIGEST_FALLBACK_AFTER)),+ ))+ finally:+ conn.close()+ by_person: dict[int, list[HeldMessage]] = {}+ for row in rows:+ by_person.setdefault(row.person_id, []).append(row)+ return by_person+++def _drop(ids: list[int], now: datetime, db_path: Path | None) -> None:+ conn = _connect(db_path)+ try:+ conn.executemany(+ f"UPDATE {TABLE} SET dropped_at = ? WHERE id = ? AND {_OPEN}", # noqa: S608+ [(_iso(now), i) for i in ids],+ )+ conn.commit()+ finally:+ conn.close()+++def _postpone(ids: list[int], until: datetime, db_path: Path | None) -> None:+ conn = _connect(db_path)+ try:+ conn.executemany(+ f"UPDATE {TABLE} SET release_at = ?, claimed_at = NULL WHERE id = ? AND {_OPEN}", # noqa: S608+ [(_iso(until), i) for i in ids],+ )+ conn.commit()+ finally:+ conn.close()+++def _backoff(messages: list[HeldMessage], now: datetime, db_path: Path | None) -> None:+ """A delivery that failed for another reason: try again later, waiting+ 2, 4, 8 … minutes, at most ``MAX_BACKOFF``."""+ attempts = max(m.attempts for m in messages) + 1+ wait = min(timedelta(minutes=2 ** min(attempts, 10)), MAX_BACKOFF)+ conn = _connect(db_path)+ try:+ conn.executemany(+ f"UPDATE {TABLE} SET release_at = ?, attempts = ?, claimed_at = NULL " # noqa: S608+ f"WHERE id = ? AND {_OPEN}",+ [(_iso(now + wait), attempts, m.id) for m in messages],+ )+ conn.commit()+ finally:+ conn.close()+++def _unavailable_until(person: Person, now: datetime) -> datetime | None:+ """When ``person`` can next be reached, while the outbound guard would+ refuse them now for leave or availability windows; None when it+ wouldn't."""+ from datetime import time++ from openexecutive.config import get_settings+ from openexecutive.people.channel import is_within_availability, next_window_for++ if not get_settings().outbound_respect_quiet_hours or is_within_availability(person, now=now):+ return None+ if person.on_leave_until is not None and now.astimezone(UTC).date() <= person.on_leave_until:+ return datetime.combine(person.on_leave_until + timedelta(days=1), time.min, tzinfo=UTC)+ return next_window_for(person, after=now)+++def render_block(messages: list[HeldMessage], *, zone: tzinfo) -> str:+ """The held messages as one "While you were away" block, oldest first,+ each with the time it would have gone."""+ lines = [f"**{HEADING}**", ""]+ for msg in messages:+ try:+ at = datetime.fromisoformat(msg.created_at).astimezone(zone)+ when = f"{at:%a} {at.hour % 12 or 12}:{at:%M} {'am' if at.hour < 12 else 'pm'}"+ except ValueError:+ when = ""+ text = msg.text.strip()+ lines.append(f"- {when}: {text}" if when else f"- {text}")+ return "\n".join(lines)+++async def release_due(now: datetime, *, db_path: Path | None = None) -> int:+ """Send each person what is due to them, as one message. Returns how many+ people got one. Never raises."""+ from openexecutive.audit import log_event+ from openexecutive.audit.context import private_rows, rows_for_person+ from openexecutive.people.notifications import (+ get_notification_settings,+ in_quiet_hours,+ quiet_hours_end,+ zone_for,+ )+ from openexecutive.people.store import get_person+ from openexecutive.scheduler.runner import deliver_to_person++ try:+ due = _due(now, db_path)+ except Exception:+ logger.warning("held_messages: couldn't read what is due", exc_info=True)+ return 0+ delivered = 0+ for person_id, due_messages in due.items():+ got = set(claim([m.id for m in due_messages], now=now, db_path=db_path))+ messages = [m for m in due_messages if m.id in got]+ if not messages:+ continue+ ids = [m.id for m in messages]+ try:+ person = get_person(person_id)+ if person is None or person.archived:+ _drop(ids, now, db_path)+ _audit_dropped(person_id, len(ids), "no longer on the People list")+ continue+ # Drop only the rows past the give-up age; newer ones still go.+ stale = [+ m.id for m in messages+ if now - datetime.fromisoformat(m.created_at) > GIVE_UP_AFTER+ ]+ if stale:+ logger.info("held_messages: dropped %d for person %s, too old", len(stale), person_id)+ _drop(stale, now, db_path)+ _audit_dropped(person_id, len(stale), f"undelivered for {GIVE_UP_AFTER.days} days")+ messages = [m for m in messages if m.id not in set(stale)]+ ids = [m.id for m in messages]+ if not messages:+ continue+ settings = get_notification_settings(person_id)+ if in_quiet_hours(settings, now):+ # A digest fallback, or quiet hours someone moved since: wait.+ end = quiet_hours_end(settings, now)+ if end is not None:+ _postpone(ids, end, db_path)+ continue+ until = _unavailable_until(person, now)+ if until is not None:+ # On leave or outside their windows: the guard would refuse.+ _postpone(ids, until, db_path)+ continue+ text = render_block(messages, zone=zone_for(settings))+ rows = private_rows() if person.is_principal else rows_for_person(person_id)+ with rows:+ delivery = await deliver_to_person(person, text, label=HEADING)+ except Exception:+ logger.warning("held_messages: releasing person %s's failed", person_id, exc_info=True)+ with contextlib.suppress(Exception):+ _backoff(messages, now, db_path)+ continue+ if not delivery.ok:+ logger.info("held_messages: person %s's not sent (%s)", person_id, delivery.reason)+ with contextlib.suppress(Exception):+ _backoff(messages, now, db_path)+ continue+ await mark_sent_after_delivery(ids, now=now, db_path=db_path)+ delivered += 1+ log_event(+ "held_messages_released",+ f"Sent person {person_id} {len(ids)} held message(s)",+ actor="scheduler",+ details={"person_id": person_id, "count": len(ids), "channel": delivery.channel},+ private=True,+ private_to_person=person_id,+ )+ return delivered+++def maybe_release(now: datetime) -> bool:+ """Start a release pass when the interval has passed and none is running.+ True when one started. Never raises."""+ global _last_release_at, _task+ try:+ if _task is not None and not _task.done():+ return False+ if _last_release_at is not None and now - _last_release_at < RELEASE_EVERY:+ return False+ _last_release_at = now+ _task = asyncio.get_running_loop().create_task(release_due(now))+ return True+ except Exception:+ logger.warning("held_messages: couldn't start a release pass", exc_info=True)+ return Falsediff --git a/packages/core/openexecutive/people/notifications.py b/packages/core/openexecutive/people/notifications.pynew file mode 100644index 00000000..91037736--- /dev/null+++ b/packages/core/openexecutive/people/notifications.py@@ -0,0 +1,337 @@+"""Each person's own notification settings: quiet hours, digest or instant,+and whether urgent things get through.++Set by the person themselves on Settings → Notifications+(``api/routes/notifications.py``); one row per person in+``person_notification_settings``. A person with no row gets the defaults,+which are today's behaviour: no quiet hours, messages as they happen, urgent+things through.++What the settings hold back is the Executive's *own* outreach on the chat+channels — a Slack, Discord or Telegram DM it sends while a proactive source+is tagged (``attunement.outcomes.tag_proactive``: nudges the scheduler+dispatches, the daily reflection, research findings, alert review). A message+someone asked for in chat, a follow-up someone scheduled, the briefs+themselves and reminders a person set are never held. Mail is not held+either: the mail send tool does not go through the DM send handlers, so an+email nudge is only deferred past quiet hours by nudge routing, never held+for a brief. Two places apply them:++- **Nudge routing** (``people.channel`` with ``quiet_hours=True``): the nudge+ engine and the scheduler's ``proactive_nudge`` dispatch defer the nudge to+ the end of the person's quiet hours, the same way they defer to an+ availability window, so nothing is written at 3am.+- **The outbound guard** (``orchestrator.outbound_guard.check_hold``): a+ proactive DM to someone in quiet hours, or to someone who chose "In my+ briefs", is stored in ``held_messages`` instead of sent, and goes out when+ quiet hours end or with their next brief (``people.held_messages``).++"Let urgent things through" (on by default) exempts approval nudges and+critical alerts: callers mark those with :func:`urgent_send`. A question a+workflow is waiting on (:func:`approval_send`) is never held at all, whatever+the setting: the gate can only be answered by a reply to it.+"""+from __future__ import annotations++import contextlib+import contextvars+import json+import logging+import sqlite3+from collections.abc import Iterator+from dataclasses import dataclass+from datetime import UTC, datetime, timedelta, tzinfo+from pathlib import Path+from typing import Literal++from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator++logger = logging.getLogger(__name__)++TABLE = "person_notification_settings"++QuietDays = Literal["every_day", "weekdays"]+Delivery = Literal["instant", "digest"]++_HHMM = r"^([01]\d|2[0-3]):[0-5]\d$"+++class QuietHours(BaseModel):+ """A nightly quiet window in the person's zone. ``start`` may be later+ than ``end`` (22:00 → 07:00 crosses midnight). ``weekdays`` keeps the+ window on weekday nights and makes Saturday and Sunday quiet all day."""++ model_config = ConfigDict(extra="forbid")++ enabled: bool = False+ start: str = Field(default="22:00", pattern=_HHMM)+ end: str = Field(default="07:00", pattern=_HHMM)+ days: QuietDays = "every_day"++ @model_validator(mode="after")+ def _not_empty(self) -> QuietHours:+ if self.start == self.end:+ raise ValueError("quiet hours must start and end at different times")+ return self+++class NotificationSettings(BaseModel):+ model_config = ConfigDict(extra="forbid")++ quiet_hours: QuietHours = Field(default_factory=QuietHours)+ delivery: Delivery = "instant"+ urgent_through: bool = True+ # IANA zone the quiet hours are read in; "" means the workspace's zone.+ timezone: str = Field(default="", max_length=64)+ updated_at: str = ""++ @field_validator("timezone")+ @classmethod+ def _known_zone(cls, value: str) -> str:+ from openexecutive.memory.workspace_settings import load_zone++ value = (value or "").strip()+ if value and load_zone(value) is None:+ raise ValueError(f"unknown time zone {value!r}")+ return value+++# --------------------------------------------------------------------------- #+# Storage+# --------------------------------------------------------------------------- #++def _db(db_path: Path | None) -> Path:+ if db_path is not None:+ return db_path+ from openexecutive.memory import episodic++ return Path(episodic.DB_PATH)+++def _connect(db_path: Path | None) -> sqlite3.Connection:+ conn = sqlite3.connect(str(_db(db_path)))+ conn.execute(+ f"CREATE TABLE IF NOT EXISTS {TABLE} (" # noqa: S608 — constant table name+ "person_id INTEGER PRIMARY KEY, settings_json TEXT NOT NULL, updated_at TEXT NOT NULL)"+ )+ return conn+++def get_notification_settings(+ person_id: int | None, *, db_path: Path | None = None+) -> NotificationSettings:+ """The person's settings, or the defaults when they have none or the row+ can't be read (fail open: the defaults hold nothing back)."""+ if person_id is None:+ return NotificationSettings()+ try:+ conn = _connect(db_path)+ try:+ row = conn.execute(+ f"SELECT settings_json, updated_at FROM {TABLE} WHERE person_id = ?", # noqa: S608+ (person_id,),+ ).fetchone()+ finally:+ conn.close()+ except Exception:+ logger.warning("notifications: couldn't read settings for person %s", person_id, exc_info=True)+ return NotificationSettings()+ if row is None:+ return NotificationSettings()+ try:+ data = json.loads(row[0])+ data["updated_at"] = str(row[1])+ return NotificationSettings.model_validate(data)+ except Exception:+ logger.warning("notifications: malformed settings for person %s", person_id)+ return NotificationSettings()+++def save_notification_settings(+ person_id: int, settings: NotificationSettings, *, db_path: Path | None = None+) -> NotificationSettings:+ """Replace the person's settings. Raises on a write error."""+ now = datetime.now(UTC).isoformat()+ payload = settings.model_dump(exclude={"updated_at"})+ conn = _connect(db_path)+ try:+ conn.execute(+ f"INSERT INTO {TABLE} (person_id, settings_json, updated_at) VALUES (?, ?, ?) " # noqa: S608+ "ON CONFLICT(person_id) DO UPDATE SET settings_json = excluded.settings_json, "+ "updated_at = excluded.updated_at",+ (person_id, json.dumps(payload), now),+ )+ conn.commit()+ finally:+ conn.close()+ return settings.model_copy(update={"updated_at": now})+++# --------------------------------------------------------------------------- #+# Quiet hours+# --------------------------------------------------------------------------- #++def zone_for(settings: NotificationSettings) -> tzinfo:+ """The zone the settings are read in: theirs, else the workspace's."""+ from openexecutive.memory.workspace_settings import get_user_timezone, load_zone++ if settings.timezone:+ zone = load_zone(settings.timezone)+ if zone is not None:+ return zone+ return get_user_timezone()+++def _minutes(hhmm: str) -> int:+ hh, mm = hhmm.split(":")+ return int(hh) * 60 + int(mm)+++def in_quiet_hours(settings: NotificationSettings, now: datetime, *, zone: tzinfo | None = None) -> bool:+ """True while ``now`` falls in the settings' quiet hours."""+ quiet = settings.quiet_hours+ if not quiet.enabled:+ return False+ local = now.astimezone(zone or zone_for(settings))+ if quiet.days == "weekdays" and local.weekday() >= 5:+ return True+ start, end = _minutes(quiet.start), _minutes(quiet.end)+ minute = local.hour * 60 + local.minute+ if start < end:+ return start <= minute < end+ return minute >= start or minute < end+++def quiet_hours_end(settings: NotificationSettings, after: datetime) -> datetime | None:+ """The first moment after ``after`` that is outside quiet hours (UTC), or+ None when quiet hours are off. Quiet hours only ever end at their ``end``+ time or at midnight (a weekend ending), so those are the only candidates."""+ if not settings.quiet_hours.enabled:+ return None+ zone = zone_for(settings)+ if not in_quiet_hours(settings, after, zone=zone):+ return after.astimezone(UTC)+ local = after.astimezone(zone)+ end_h, end_m = (int(p) for p in settings.quiet_hours.end.split(":"))+ candidates: list[datetime] = []+ for offset in range(0, 4):+ day = (local + timedelta(days=offset)).date()+ for hh, mm in ((end_h, end_m), (0, 0)):+ candidate = datetime(day.year, day.month, day.day, hh, mm, tzinfo=zone)+ if candidate > local:+ candidates.append(candidate)+ for candidate in sorted(candidates):+ if not in_quiet_hours(settings, candidate, zone=zone):+ return candidate.astimezone(UTC)+ return None+++# --------------------------------------------------------------------------- #+# Urgency+# --------------------------------------------------------------------------- #++# None, "urgent" (let through when they let urgent things through) or+# "approval" (never held).+_urgent: contextvars.ContextVar[str | None] = contextvars.ContextVar("notifications_urgent", default=None)+++def urgent_send() -> Iterator[None]:+ """Mark the DMs sent inside the block as urgent (an approval nudge, or a+ critical alert): "Let urgent things through" lets them past quiet hours+ and the digest. Wrap only non-yielding code."""+ token = _urgent.set("urgent")+ try:+ yield+ finally:+ _urgent.reset(token)+++def approval_send() -> Iterator[None]:+ """Mark the DMs sent inside the block as a question something is waiting+ on (a workflow gate): never held, whatever the person's settings, since+ only a reply to it resolves the wait. Wrap only non-yielding code."""+ token = _urgent.set("approval")+ try:+ yield+ finally:+ _urgent.reset(token)+++def is_urgent_send() -> bool:+ return _urgent.get() is not None+++def is_approval_send() -> bool:+ return _urgent.get() == "approval"+++# Proactive sources that are always urgent: a nudge about something waiting+# on the person's approval (attunement.outcomes.SOURCE_NUDGE_STALLED).+URGENT_SOURCES = frozenset({"nudge_stalled"})+# Sources never held: a follow-up runs at the time someone asked for, so+# neither quiet hours nor a brief may move it.+NEVER_HELD_SOURCES = frozenset({"followup"})+++def quiet_applies(person_id: int | None, *, urgent: bool = False) -> NotificationSettings | None:+ """The person's settings when their quiet hours apply to a message of this+ urgency, else None. Never raises."""+ if person_id is None:+ return None+ try:+ settings = get_notification_settings(person_id)+ except Exception:+ return None+ if not settings.quiet_hours.enabled:+ return None+ if urgent and settings.urgent_through:+ return None+ return settings+++@dataclass(frozen=True)+class Hold:+ """Why a proactive DM waits, and until when (None: their next brief)."""++ release_at: datetime | None+ reason: str+++def hold_for(person_id: int, *, source: str, now: datetime, urgent: bool = False) -> Hold | None:+ """Whether a proactive DM from ``source`` to ``person_id`` should wait,+ by the person's own settings. None means send it now."""+ if source in NEVER_HELD_SOURCES:+ return None+ settings = get_notification_settings(person_id)+ urgent = urgent or source in URGENT_SOURCES+ if urgent and settings.urgent_through:+ return None+ if settings.delivery == "digest":+ return Hold(None, "they asked to get these in their brief; it will be in their next one")+ if in_quiet_hours(settings, now):+ end = quiet_hours_end(settings, now)+ when = end.isoformat() if end is not None else "the end of their quiet hours"+ return Hold(end, f"they have quiet hours on; it will reach them at {when}")+ return None+++__all__ = [+ "NEVER_HELD_SOURCES",+ "URGENT_SOURCES",+ "Hold",+ "NotificationSettings",+ "QuietHours",+ "get_notification_settings",+ "hold_for",+ "in_quiet_hours",+ "approval_send",+ "is_approval_send",+ "is_urgent_send",+ "quiet_applies",+ "quiet_hours_end",+ "save_notification_settings",+ "urgent_send",+ "zone_for",+]diff --git a/packages/core/openexecutive/scheduler/nudge_engine.py b/packages/core/openexecutive/scheduler/nudge_engine.pyindex 6cbbeace..d3dc12ef 100644--- a/packages/core/openexecutive/scheduler/nudge_engine.py+++ b/packages/core/openexecutive/scheduler/nudge_engine.py@@ -30,7 +30,7 @@ runner. Each tick:3. Picks a delivery channel per candidate via``people.channel.prefer_channel_for`` — respecting availability- windows and quiet hours. Defers via ``next_available_window`` when+ windows and the person's own quiet hours (Settings → Notifications). Defers via ``next_available_window`` whenthe assignee is temporarily unreachable.4. Emits ``kind="proactive_nudge"`` rows with the resolved@@ -442,7 +442,12 @@ def _route_candidate()if candidate.person_id is not None:- pref = prefer_channel_for(candidate.person_id, now=now)+ # The person's own quiet hours defer a nudge like an availability+ # window does; an approval nudge is urgent (people.notifications).+ urgent = candidate.source == "stalled"+ pref = prefer_channel_for(+ candidate.person_id, now=now, quiet_hours=True, urgent=urgent+ )if pref is not None:people_channel, channel_ref = prefsched = _to_scheduled_channel(people_channel)@@ -460,7 +465,9 @@ def _route_candidate(# the deferral to fall AFTER the leave end date — otherwise an# on-leave person with weekday 9-5 windows ends up in an infinite# defer→defer→defer loop until leave ends.- nxt = next_available_window(candidate.person_id, after=now)+ nxt = next_available_window(+ candidate.person_id, after=now, quiet_hours=True, urgent=urgent+ )leave_end = _leave_end_for(candidate.person_id)deliver_at = nxtif leave_end is not None and (deliver_at is None or deliver_at <= leave_end):diff --git a/packages/core/openexecutive/scheduler/runner.py b/packages/core/openexecutive/scheduler/runner.pyindex 0f2729c6..5797913b 100644--- a/packages/core/openexecutive/scheduler/runner.py+++ b/packages/core/openexecutive/scheduler/runner.py@@ -167,6 +167,19 @@ def _maybe_send_reminders(now: datetime) -> bool:return False+def _maybe_release_held(now: datetime) -> bool:+ """Send the messages held for quiet hours once they end, and the ones held+ for a brief that went to someone without one (people/held_messages.py).+ A hook like the reminders. Never raises."""+ try:+ from openexecutive.people.held_messages import maybe_release++ return maybe_release(now)+ except Exception:+ logger.exception("scheduler: held-message release failed to start")+ return False++def _maybe_sweep_alerts(now: datetime) -> int:"""Run the expiry sweep if the interval has elapsed. Returns rows expired.@@ -329,6 +342,7 @@ async def run_scheduler(_maybe_scan_inbox(now)_maybe_remind_notes(now)_maybe_send_reminders(now)+ _maybe_release_held(now)due = claim_due_actions(now)if due:logger.info("scheduler: %d due action(s)", len(due))@@ -975,11 +989,21 @@ async def _execute_action(next_available_window,prefer_channel_for,)- from openexecutive.scheduler.nudge_engine import _leave_end_for+ from openexecutive.scheduler.nudge_engine import (+ SCOPE_PREFIX_STALLED,+ _leave_end_for,+ )- pref = prefer_channel_for(action.assigned_to_person_id, now=now)+ # The person's own quiet hours defer it too; an approval nudge is+ # urgent (people.notifications).+ urgent = (action.scope_key or "").startswith(SCOPE_PREFIX_STALLED)+ pref = prefer_channel_for(+ action.assigned_to_person_id, now=now, quiet_hours=True, urgent=urgent+ )if pref is None:- nxt = next_available_window(action.assigned_to_person_id, after=now)+ nxt = next_available_window(+ action.assigned_to_person_id, after=now, quiet_hours=True, urgent=urgent+ )leave_end = _leave_end_for(action.assigned_to_person_id)defer_to = nxtif leave_end is not None and (defer_to is None or defer_to <= leave_end):@@ -1096,6 +1120,7 @@ async def _execute_action()return+ held_ids: list[int] = []try:from openexecutive.knowledge.retriever import retrievefrom openexecutive.memory.episodic import format_for_prompt@@ -1154,9 +1179,10 @@ async def _execute_action(executive = Executive(mcp_gateway=gateway)from openexecutive.attunement.outcomes import tag_proactive+ from openexecutive.people.held_messages import track_holdssource, ref = _outreach_source(action)- with tag_proactive(source, ref):+ with tag_proactive(source, ref), track_holds() as held_ids:await executive.chat(user_message=synthetic_message,session=session,@@ -1188,16 +1214,21 @@ async def _execute_action(mark_action_done(action.id)logger.info("scheduler: action %d done", action.id)from openexecutive.audit import log_event as audit_log+ # What it sent was held for the recipient's quiet hours or brief+ # (people.held_messages): say so, not "delivered".+ phase = "held" if held_ids else "delivered"audit_log("scheduled_action",- f"Scheduled action {action.id} delivered via {action.channel} → {action.channel_ref}",+ f"Scheduled action {action.id} {phase} via {action.channel} → {action.channel_ref}"+ + (f" ({len(held_ids)} message(s) held for the recipient)" if held_ids else ""),session_id=action.originating_session_id,actor="scheduler",details={- "phase": "delivered",+ "phase": phase,"action_id": action.id,"channel": action.channel,"channel_ref": action.channel_ref,+ **({"held_count": len(held_ids)} if held_ids else {}),},)@@ -1738,7 +1769,13 @@ def _delivered_ok(result_json: str) -> bool:parsed = _json.loads(result_json)except (ValueError, TypeError):return False- return isinstance(parsed, dict) and "error" not in parsed and parsed.get("status") == "sent"+ # "held": stored for the recipient's quiet hours or brief+ # (people.held_messages), so trying the next channel would hold it twice.+ return (+ isinstance(parsed, dict)+ and "error" not in parsed+ and parsed.get("status") in ("sent", "held")+ )# `Person.preferred_channel` values (people/models.py PreferredChannel) mapped@@ -2229,8 +2266,19 @@ async def _run_principal_brief(action: ScheduledAction, now: datetime) -> None:recorded = Trueelse:sending = True- delivery = await _deliver_to_principal(artifact, label=workflow.title)+ # Messages the principal asked to get in their brief ride along+ # as one "While you were away" block (people.held_messages).+ delivered_text, held_ids = _with_held_messages(kind, artifact)+ try:+ delivery = await _deliver_to_principal(delivered_text, label=workflow.title)+ except BaseException:+ _unclaim_held(held_ids)+ raiseok, detail = delivery.ok, delivery.detail+ if ok:+ await _mark_held_sent(held_ids)+ else:+ _unclaim_held(held_ids)brief_state.record_delivery_outcome(kind, reason=delivery.reason, channel=delivery.channel,detail=None if ok else detail,@@ -2270,6 +2318,11 @@ async def _run_principal_brief(action: ScheduledAction, now: datetime) -> None:detail=f"{type(exc).__name__}: {exc}" if str(exc) else type(exc).__name__,)+ if kind in _DIGEST_BRIEF_KINDS:+ # Everyone else who chose "In my briefs" gets theirs now, on its own:+ # only the principal has a brief to carry them.+ _release_others_digests(now)+# Always chain the next occurrence + mark this row done, so a single# bad brief doesn't kill the recurring rhythm. Worst case the next# tick re-attempts on the same shape of input. A solo-only kind whose@@ -2281,6 +2334,65 @@ async def _run_principal_brief(action: ScheduledAction, now: datetime) -> None:_enqueue_next_principal_brief(kind, after=_chain_after(action))+# The briefs that carry held messages ("In my briefs", people.notifications).+_DIGEST_BRIEF_KINDS: frozenset[str] = frozenset({"principal_brief_morning", "principal_brief_eod"})+++def _with_held_messages(kind: str, artifact: str) -> tuple[str, list[int]]:+ """``artifact`` with the principal's brief-held messages appended as one+ "While you were away" block, and their ids — claimed, so a release pass+ can't send them too; mark them sent once it went, else unclaim them.+ The artifact unchanged when there are none or they can't be read."""+ if kind not in _DIGEST_BRIEF_KINDS:+ return artifact, []+ try:+ from openexecutive.people.held_messages import claim, for_brief, render_block+ from openexecutive.people.notifications import get_notification_settings, zone_for+ from openexecutive.people.store import find_principal_person++ principal = find_principal_person()+ if principal is None or principal.id is None:+ return artifact, []+ waiting = for_brief(principal.id)+ got = set(claim([m.id for m in waiting]))+ held = [m for m in waiting if m.id in got]+ if not held:+ return artifact, []+ zone = zone_for(get_notification_settings(principal.id))+ return f"{artifact.rstrip()}\n\n{render_block(held, zone=zone)}", [m.id for m in held]+ except Exception:+ logger.exception("scheduler: couldn't add held messages to the brief")+ return artifact, []+++def _unclaim_held(ids: list[int]) -> None:+ if not ids:+ return+ try:+ from openexecutive.people.held_messages import unclaim++ unclaim(ids)+ except Exception:+ logger.exception("scheduler: couldn't unclaim %d held message(s)", len(ids))+++async def _mark_held_sent(ids: list[int]) -> None:+ from openexecutive.people.held_messages import mark_sent_after_delivery++ await mark_sent_after_delivery(ids)+++def _release_others_digests(now: datetime) -> None:+ try:+ from openexecutive.people.held_messages import schedule_digest_release+ from openexecutive.people.store import find_principal_person++ principal = find_principal_person()+ schedule_digest_release(now, except_person_id=principal.id if principal else None)+ except Exception:+ logger.exception("scheduler: couldn't release held messages with the briefs")++def _outreach_source(action: ScheduledAction) -> tuple[str, str]:"""``(source, ref)`` for the outcome ledger of one dispatched action.diff --git a/packages/core/openexecutive/workflows/gate_delivery.py b/packages/core/openexecutive/workflows/gate_delivery.pyindex 9d97efa6..b1d4d87a 100644--- a/packages/core/openexecutive/workflows/gate_delivery.py+++ b/packages/core/openexecutive/workflows/gate_delivery.py@@ -108,10 +108,15 @@ async def deliver_gate_question()try:from openexecutive.orchestrator.schedule_tools import handle_message_person-- raw = await handle_message_person(- {"person_id": event.person_id, "text": question}- )+ from openexecutive.people.notifications import approval_send++ # The run waits on their answer, and only a reply to this question+ # resolves it: never held by their quiet hours or digest+ # (people.notifications).+ with approval_send():+ raw = await handle_message_person(+ {"person_id": event.person_id, "text": question}+ )parsed = json.loads(raw)except Exception:logger.exception(diff --git a/packages/core/tests/integration/test_notifications_api.py b/packages/core/tests/integration/test_notifications_api.pynew file mode 100644index 00000000..aef25a5b--- /dev/null+++ b/packages/core/tests/integration/test_notifications_api.py@@ -0,0 +1,202 @@+"""Integration: a person sets their own notifications over HTTP, and the+scheduler then holds a proactive nudge to them until their quiet hours end."""+from __future__ import annotations++import asyncio+from collections.abc import Iterator+from datetime import UTC, datetime, timedelta+from pathlib import Path++import pytest+from fastapi import FastAPI+from fastapi.testclient import TestClient++from openexecutive.api.routes.notifications import router+from openexecutive.audit import logger as audit_logger+from openexecutive.memory import episodic+from openexecutive.people import held_messages as held+from openexecutive.people import registry as people_registry+from openexecutive.people import store as people_store+from openexecutive.people.notifications import get_notification_settings+from openexecutive.scheduler.runner import _execute_action++OWNER = {"x-caller-email": "[email protected]"}+SARA = {"x-caller-email": "[email protected]"}+++def client(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Iterator[TestClient]:+ db = tmp_path / "test.db"+ monkeypatch.setattr(people_store, "DB_PATH", db)+ monkeypatch.setattr(episodic, "DB_PATH", db)+ monkeypatch.setattr(audit_logger, "_default_logger", audit_logger.AuditLogger(db_path=db))+ episodic.initialize_db(db)+ people_store.initialize_db(db)+ people_registry.invalidate()+ for var in ("BACKEND_SHARED_SECRET", "OE_LOCAL_LOGIN", "OE_PUBLIC_DEPLOYMENT"):+ monkeypatch.delenv(var, raising=False)+ people_store.upsert_person(full_name="Pat Principal", is_principal=True, email="[email protected]")+ people_store.upsert_person(+ full_name="Sara Kim", email="[email protected]", slack_user_id="U_SARA",+ preferred_channel="slack",+ )+ app = FastAPI()+ app.include_router(router)+ yield TestClient(app)+ people_registry.invalidate()+++def _id(name: str) -> int:+ person = next(p for p in people_store.list_people() if p.full_name == name)+ assert person.id is not None+ return person.id+++def _body(**overrides: object) -> dict[str, object]:+ body: dict[str, object] = {+ "quiet_hours": {"enabled": True, "start": "22:00", "end": "07:00", "days": "weekdays"},+ "delivery": "digest",+ "urgent_through": True,+ "timezone": "Europe/London",+ }+ body.update(overrides)+ return body+++def test_each_person_reads_and_sets_only_their_own(client: TestClient) -> None:+ mine = client.get("/notifications/settings", headers=SARA)+ assert mine.status_code == 200, mine.text+ got = mine.json()+ assert got["quiet_hours"]["enabled"] is False and got["delivery"] == "instant"+ assert got["urgent_through"] is True and got["gets_briefs"] is False+ assert got["held_count"] == 0++ res = client.put("/notifications/settings", headers=SARA, json=_body())+ assert res.status_code == 200, res.text+ assert res.json()["delivery"] == "digest"+ assert res.json()["effective_timezone"] == "Europe/London"+ assert get_notification_settings(_id("Sara Kim")).quiet_hours.days == "weekdays"+ # The principal's are untouched, and theirs say they get the briefs.+ owner = client.get("/notifications/settings", headers=OWNER).json()+ assert owner["delivery"] == "instant" and owner["gets_briefs"] is True+++def test_who_may_call(client: TestClient, monkeypatch: pytest.MonkeyPatch) -> None:+ res = client.get("/notifications/settings")+ assert res.status_code == 403 and res.json()["detail"]["code"] == "sign_in_required"+ res = client.get("/notifications/settings", headers={"x-caller-email": "[email protected]"})+ assert res.status_code == 403 and res.json()["detail"]["code"] == "not_on_roster"+ monkeypatch.setenv("OE_LOCAL_LOGIN", "1")+ assert client.get("/notifications/settings").json()["gets_briefs"] is True+++def test_bad_settings_are_refused(client: TestClient) -> None:+ bad_times = _body(quiet_hours={"enabled": True, "start": "22:00", "end": "22:00", "days": "every_day"})+ assert client.put("/notifications/settings", headers=SARA, json=bad_times).status_code == 422+ assert client.put(+ "/notifications/settings", headers=SARA, json=_body(timezone="Mars/Olympus")+ ).status_code == 422+ assert client.put(+ "/notifications/settings", headers=SARA, json=_body(delivery="hourly")+ ).status_code == 422+ assert client.put(+ "/notifications/settings", headers=SARA, json={**_body(), "person_id": 1}+ ).status_code == 422+++def test_back_to_as_they_happen_releases_what_waited(client: TestClient) -> None:+ sara = _id("Sara Kim")+ client.put("/notifications/settings", headers=SARA, json=_body())+ held.hold(sara, "Waiting for the brief", source="reflection", release_at=None)+ assert client.get("/notifications/settings", headers=SARA).json()["held_count"] == 1+ client.put("/notifications/settings", headers=SARA, json=_body(delivery="instant"))+ assert held.for_brief(sara) == []+ assert held.held_count(sara) == 1 # now due, for the next release pass+++def test_a_nudge_in_quiet_hours_waits_for_them_to_end(+ client: TestClient, monkeypatch: pytest.MonkeyPatch+) -> None:+ sara = _id("Sara Kim")+ now = datetime.now(UTC)+ start = (now - timedelta(hours=1)).strftime("%H:%M")+ end_at = (now + timedelta(hours=2)).replace(second=0, microsecond=0)+ res = client.put("/notifications/settings", headers=SARA, json=_body(+ quiet_hours={"enabled": True, "start": start, "end": end_at.strftime("%H:%M"), "days": "every_day"},+ delivery="instant", timezone="UTC",+ ))+ assert res.status_code == 200, res.text++ def no_chat(*_a: object, **_k: object) -> None:+ raise AssertionError("the nudge must not be written during quiet hours")++ monkeypatch.setattr("openexecutive.orchestrator.executive.Executive", no_chat)+ action_id = episodic.insert_scheduled_action(+ run_at=(now - timedelta(seconds=1)).isoformat(), channel="slack_dm", channel_ref="U_SARA",+ intent_text="Chase Sara about the Q3 plan", kind="proactive_nudge",+ assigned_to_person_id=sara, scope_key="nudge:initiative:7",+ )+ [claimed] = episodic.claim_due_actions(datetime.now(UTC))+ asyncio.run(_execute_action(claimed, gateway=None))+ stored = episodic.get_scheduled_action(action_id)+ assert stored is not None and stored.status == "pending"+ run_at = datetime.fromisoformat(stored.run_at)+ assert abs((run_at - end_at).total_seconds()) < 60+++def test_a_dispatch_whose_message_was_held_is_audited_as_held(+ client: TestClient, monkeypatch: pytest.MonkeyPatch+) -> None:+ sara = _id("Sara Kim")+ events: list[tuple[str, dict[str, object]]] = []+ monkeypatch.setattr("openexecutive.audit.log_event", lambda et, summary, **kw: events.append((summary, kw)))++ class _HoldingExec:+ def __init__(self, *_a: object, **_k: object) -> None:+ pass++ async def chat(self, **_k: object) -> str:+ held.hold(sara, "Nudge text", source="nudge_initiative", release_at=None)+ return "ok"++ class _Profile:+ def is_empty(self) -> bool:+ return True++ monkeypatch.setattr("openexecutive.orchestrator.executive.Executive", _HoldingExec)+ monkeypatch.setattr("openexecutive.onboarding.profile_builder.load_or_create_profile", lambda: _Profile())+ monkeypatch.setattr("openexecutive.knowledge.retriever.retrieve", lambda query: "")+ episodic.insert_scheduled_action(+ run_at=(datetime.now(UTC) - timedelta(seconds=1)).isoformat(), channel="slack_dm",+ channel_ref="U_SARA", intent_text="Chase Sara", kind="ad_hoc",+ )+ [claimed] = episodic.claim_due_actions(datetime.now(UTC))+ asyncio.run(_execute_action(claimed, gateway=None))+ [(summary, kw)] = [e for e in events if (e[1].get("details") or {}).get("action_id") == claimed.id] # type: ignore[union-attr]+ assert kw["details"]["phase"] == "held" and "held" in summary # type: ignore[index]+++def test_turning_quiet_hours_off_releases_what_waited(client: TestClient) -> None:+ from datetime import UTC, datetime, timedelta++ sara = _id("Sara Kim")+ client.put("/notifications/settings", headers=SARA, json=_body(delivery="instant"))+ later = datetime.now(UTC) + timedelta(hours=8)+ held.hold(sara, "Held overnight", source="reflection", release_at=later)+ assert held._due(datetime.now(UTC) + timedelta(minutes=1), None) == {}+ off = {"enabled": False, "start": "22:00", "end": "07:00", "days": "every_day"}+ client.put("/notifications/settings", headers=SARA, json=_body(delivery="instant", quiet_hours=off))+ assert sara in held._due(datetime.now(UTC) + timedelta(minutes=1), None)+++def test_moving_time_zone_releases_what_waited(client: TestClient) -> None:+ from datetime import UTC, datetime, timedelta++ sara = _id("Sara Kim")+ client.put("/notifications/settings", headers=SARA, json=_body(delivery="instant"))+ held.hold(sara, "Held overnight", source="reflection", release_at=datetime.now(UTC) + timedelta(hours=8))+ client.put(+ "/notifications/settings", headers=SARA,+ json=_body(delivery="instant", timezone="America/New_York"),+ )+ assert sara in held._due(datetime.now(UTC) + timedelta(minutes=1), None)diff --git a/packages/core/tests/unit/test_alert_review.py b/packages/core/tests/unit/test_alert_review.pyindex e835a364..465034be 100644--- a/packages/core/tests/unit/test_alert_review.py+++ b/packages/core/tests/unit/test_alert_review.py@@ -1045,3 +1045,27 @@ def test_ungrounded_rewrite_without_a_severity_change_changes_nothing(assert not any(e[0] == review.EVENT_CHANGED for e in audit_events)refused = [e for e in audit_events if e[2].get("text_ungrounded")]assert refused and refused[0][2]["text_ungrounded"] == ["Marcus Lee"]+++def test_a_held_nudge_does_not_count_toward_the_cap(db: Path, audit_events, monkeypatch) -> None:+ from openexecutive.people import held_messages++ _person(full_name="Pat", role="CEO", is_principal=True)+ dana = _person(full_name="Dana", role="CFO", department_slugs=["finance"])+ aid = _insert(db, "Waiting on Dana", topic_tags=["department:finance"], routed_to_person_id=dana)+ sent: list[int] = []++ async def held_dm(person_id: int, text: str, *, headline: str = "", alert_id: int | None = None):+ sent.append(person_id)+ held_messages.hold(person_id, text, source="alert_review", release_at=None, ref=f"alert:{alert_id}")+ return True, review._HELD_DETAIL++ monkeypatch.setattr(review, "_dm", held_dm)+ monkeypatch.setattr(review, "_nudges_so_far", lambda alert_id: 0)+ summary = review.ReviewSummary()+ _apply(db, aid, _verdict(aid, recommended_move="nudge", message="Gentle ping"), summary=summary)+ assert sent == [dana] and summary.nudged == 0+ assert not any(e[0] == review.EVENT_NUDGED for e in audit_events)+ # While it waits, the next pass doesn't hold another.+ _apply(db, aid, _verdict(aid, recommended_move="nudge", message="again"), summary=summary)+ assert sent == [dana]diff --git a/packages/core/tests/unit/test_held_messages.py b/packages/core/tests/unit/test_held_messages.pynew file mode 100644index 00000000..07afd29e--- /dev/null+++ b/packages/core/tests/unit/test_held_messages.py@@ -0,0 +1,304 @@+"""Held proactive DMs (people/held_messages.py): released when quiet hours+end, carried by the principal's brief, sent on their own to anyone else when+the briefs go out — each exactly once."""+from __future__ import annotations++import asyncio+import sqlite3+from collections.abc import Iterator+from datetime import UTC, datetime, timedelta+from pathlib import Path+from typing import Any+from zoneinfo import ZoneInfo++import pytest++from openexecutive.memory import episodic+from openexecutive.people import held_messages as held+from openexecutive.people import registry as people_registry+from openexecutive.people import store as people_store+from openexecutive.people.notifications import (+ NotificationSettings,+ QuietHours,+ save_notification_settings,+)+from openexecutive.scheduler import runner+from openexecutive.scheduler.runner import PrincipalDelivery++NOW = datetime(2026, 10, 14, 12, 0, tzinfo=UTC)++[email protected](autouse=True)+def db(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Iterator[Path]:+ path = tmp_path / "episodic.db"+ monkeypatch.setattr(episodic, "DB_PATH", path)+ monkeypatch.setattr(people_store, "DB_PATH", path)+ episodic.initialize_db(path)+ people_store.initialize_db(path)+ people_registry.invalidate()+ monkeypatch.setattr("openexecutive.audit.log_event", lambda *a, **k: None)+ yield path+ people_registry.invalidate()+++def ids() -> dict[str, int]:+ return {+ "principal": people_store.upsert_person(+ full_name="Olivia Owner", is_principal=True, email="[email protected]"+ ),+ "teammate": people_store.upsert_person(full_name="Ben", email="[email protected]"),+ }+++def sent(monkeypatch: pytest.MonkeyPatch) -> list[tuple[int, str]]:+ out: list[tuple[int, str]] = []++ async def fake_deliver(person: Any, text: str, *, label: str = "") -> PrincipalDelivery:+ out.append((person.id, text))+ return PrincipalDelivery(True, "slack_dm → U1", "delivered", "slack_dm")++ monkeypatch.setattr(runner, "deliver_to_person", fake_deliver)+ return out+++def test_quiet_hours_messages_go_once_when_due(ids: dict[str, int], sent: list[tuple[int, str]]) -> None:+ pid = ids["teammate"]+ held.hold(pid, "First thing", source="reflection", release_at=NOW + timedelta(hours=1), now=NOW)+ held.hold(pid, "Second thing", source="alert_review", release_at=NOW + timedelta(hours=1), now=NOW)+ assert held.held_count(pid) == 2+ assert asyncio.run(held.release_due(NOW)) == 0 and sent == []+ later = NOW + timedelta(hours=2)+ assert asyncio.run(held.release_due(later)) == 1+ [(to, text)] = sent+ assert to == pid and text.startswith(f"**{held.HEADING}**")+ assert "First thing" in text and "Second thing" in text+ assert held.held_count(pid) == 0+ assert asyncio.run(held.release_due(later)) == 0 and len(sent) == 1+++def test_a_failed_delivery_is_retried(ids: dict[str, int], monkeypatch: pytest.MonkeyPatch) -> None:+ pid = ids["teammate"]+ held.hold(pid, "Try me", source="reflection", release_at=NOW, now=NOW)++ async def failing(person: Any, text: str, *, label: str = "") -> PrincipalDelivery:+ return PrincipalDelivery(False, "no channel", "no_channel")++ monkeypatch.setattr(runner, "deliver_to_person", failing)+ assert asyncio.run(held.release_due(NOW)) == 0+ assert held.held_count(pid) == 1+++def test_still_quiet_postpones(ids: dict[str, int], sent: list[tuple[int, str]]) -> None:+ pid = ids["teammate"]+ # They moved their quiet hours so it is quiet now (12:00–14:00 UTC).+ save_notification_settings(pid, NotificationSettings(+ quiet_hours=QuietHours(enabled=True, start="11:00", end="14:00"), timezone="UTC",+ ))+ held.hold(pid, "Wait", source="reflection", release_at=NOW, now=NOW)+ assert asyncio.run(held.release_due(NOW)) == 0 and sent == []+ assert asyncio.run(held.release_due(NOW.replace(hour=14))) == 1+++def test_old_messages_are_dropped(ids: dict[str, int], sent: list[tuple[int, str]]) -> None:+ pid = ids["teammate"]+ held.hold(pid, "Stale", source="reflection", release_at=NOW, now=NOW - timedelta(days=8))+ assert asyncio.run(held.release_due(NOW)) == 0 and sent == []+ assert held.held_count(pid) == 0+++def test_digest_waits_for_the_briefs_then_goes_to_everyone_but_the_principal(+ ids: dict[str, int], sent: list[tuple[int, str]]+) -> None:+ held.hold(ids["principal"], "For Olivia", source="reflection", release_at=None, now=NOW)+ held.hold(ids["teammate"], "For Ben", source="reflection", release_at=None, now=NOW)+ assert asyncio.run(held.release_due(NOW)) == 0+ assert held.schedule_digest_release(NOW, except_person_id=ids["principal"]) == 1+ assert asyncio.run(held.release_due(NOW)) == 1+ assert sent[0][0] == ids["teammate"] and "For Ben" in sent[0][1]+ # The principal's waits for their brief.+ assert [m.text for m in held.for_brief(ids["principal"])] == ["For Olivia"]+++def test_a_digest_with_no_brief_to_carry_it_goes_on_its_own(+ ids: dict[str, int], sent: list[tuple[int, str]]+) -> None:+ held.hold(ids["principal"], "Waiting", source="reflection", release_at=None, now=NOW)+ later = NOW + held.DIGEST_FALLBACK_AFTER + timedelta(minutes=1)+ assert asyncio.run(held.release_due(later)) == 1+ assert sent[0][0] == ids["principal"]+++def test_one_person_cannot_pile_up_without_end(ids: dict[str, int]) -> None:+ pid = ids["teammate"]+ for i in range(held.MAX_HELD_PER_PERSON + 5):+ held.hold(pid, f"m{i}", source="reflection", release_at=None, now=NOW)+ waiting = held.for_brief(pid)+ assert len(waiting) == held.MAX_HELD_PER_PERSON+ assert waiting[0].text == "m5"+++def test_the_principals_brief_carries_their_held_messages(ids: dict[str, int]) -> None:+ held.hold(ids["principal"], "Ben replied about Q3", source="reflection", release_at=None, now=NOW)+ text, held_ids = runner._with_held_messages("principal_brief_morning", "# Morning brief\n\nAll good.")+ assert text.startswith("# Morning brief") and "Ben replied about Q3" in text+ assert held.HEADING in text and len(held_ids) == 1+ # The weekly review does not carry them.+ assert runner._with_held_messages("principal_weekly_review", "x") == ("x", [])+ asyncio.run(runner._mark_held_sent(held_ids))+ assert held.for_brief(ids["principal"]) == []+ assert runner._with_held_messages("principal_brief_eod", "x") == ("x", [])+++def test_render_block_names_when_each_would_have_gone() -> None:+ msg = held.HeldMessage(1, 1, "reflection", "Hello", "2026-10-14T21:05:00+00:00", None)+ block = held.render_block([msg], zone=ZoneInfo("UTC"))+ assert block == f"**{held.HEADING}**\n\n- Wed 9:05 pm: Hello"+++def test_a_claimed_row_is_not_sent_twice(ids: dict[str, int], sent: list[tuple[int, str]]) -> None:+ pid = ids["principal"]+ later = datetime.now(UTC)+ old = later - held.DIGEST_FALLBACK_AFTER - timedelta(minutes=1)+ held.hold(pid, "Once", source="reflection", release_at=None, now=old)+ # The brief claims it; a fallback release in the meantime skips it.+ text, held_ids = runner._with_held_messages("principal_brief_morning", "brief")+ assert "Once" in text and len(held_ids) == 1+ assert asyncio.run(held.release_due(later)) == 0 and sent == []+ # The brief failed: the claim is given back and the fallback sends it.+ runner._unclaim_held(held_ids)+ assert asyncio.run(held.release_due(later)) == 1 and len(sent) == 1+++def test_someone_on_leave_waits_without_retrying(+ ids: dict[str, int], sent: list[tuple[int, str]], monkeypatch: pytest.MonkeyPatch+) -> None:+ from types import SimpleNamespace++ pid = ids["teammate"]+ people_store.update_person(pid, on_leave_until=NOW.date() + timedelta(days=2))+ people_registry.invalidate()+ monkeypatch.setattr(+ "openexecutive.config.get_settings", lambda: SimpleNamespace(outbound_respect_quiet_hours=True)+ )+ held.hold(pid, "Back soon", source="reflection", release_at=NOW, now=NOW)+ assert asyncio.run(held.release_due(NOW)) == 0 and sent == []+ [row] = held._due(NOW + timedelta(days=3), None)[pid]+ assert row.release_at == datetime(2026, 10, 17, 0, 0, tzinfo=UTC).isoformat()+++def test_a_failed_delivery_backs_off(ids: dict[str, int], monkeypatch: pytest.MonkeyPatch) -> None:+ pid = ids["teammate"]+ held.hold(pid, "Try me", source="reflection", release_at=NOW, now=NOW)++ async def failing(person: Any, text: str, *, label: str = "") -> PrincipalDelivery:+ return PrincipalDelivery(False, "send failed", "send_failed")++ monkeypatch.setattr(runner, "deliver_to_person", failing)+ asyncio.run(held.release_due(NOW))+ assert held._due(NOW + timedelta(minutes=1), None) == {}+ assert pid in held._due(NOW + timedelta(minutes=2), None)+ asyncio.run(held.release_due(NOW + timedelta(minutes=2)))+ assert held._due(NOW + timedelta(minutes=5), None) == {}+ [row] = held._due(NOW + timedelta(minutes=6), None)[pid]+ assert row.attempts == 2+++def test_drops_are_audited_without_their_text(ids: dict[str, int], monkeypatch: pytest.MonkeyPatch) -> None:+ events: list[tuple[str, dict[str, Any]]] = []+ monkeypatch.setattr("openexecutive.audit.log_event", lambda et, summary, **kw: events.append((et, kw)))+ pid = ids["teammate"]+ for i in range(held.MAX_HELD_PER_PERSON + 1):+ held.hold(pid, f"secret {i}", source="reflection", release_at=None, now=NOW)+ held.hold(pid, "old secret", source="reflection", release_at=NOW, now=NOW - timedelta(days=8))+ asyncio.run(held.release_due(NOW))+ drops = [kw for et, kw in events if et == "held_messages_dropped"]+ assert [d["details"]["reason"] for d in drops][:2] == [+ f"more than {held.MAX_HELD_PER_PERSON} waiting",+ f"more than {held.MAX_HELD_PER_PERSON} waiting",+ ]+ assert any("undelivered" in d["details"]["reason"] for d in drops)+ assert all(d["private_to_person"] == pid and "secret" not in str(d) for d in drops)+++def test_only_the_stale_rows_are_dropped(ids: dict[str, int], sent: list[tuple[int, str]]) -> None:+ pid = ids["teammate"]+ held.hold(pid, "Stale", source="reflection", release_at=NOW, now=NOW - timedelta(days=8))+ held.hold(pid, "Fresh", source="alert_review", release_at=NOW, now=NOW - timedelta(minutes=2))+ assert asyncio.run(held.release_due(NOW)) == 1+ [(_, text)] = sent+ assert "Fresh" in text and "Stale" not in text+ assert held.held_count(pid) == 0+++def test_a_failing_backoff_does_not_stop_the_pass(+ ids: dict[str, int], monkeypatch: pytest.MonkeyPatch+) -> None:+ held.hold(ids["principal"], "For Olivia", source="reflection", release_at=NOW, now=NOW)+ held.hold(ids["teammate"], "For Ben", source="reflection", release_at=NOW, now=NOW)+ got: list[int] = []++ async def half(person: Any, text: str, *, label: str = "") -> PrincipalDelivery:+ if person.id == ids["principal"]:+ return PrincipalDelivery(False, "send failed", "send_failed")+ got.append(person.id)+ return PrincipalDelivery(True, "slack_dm → U1", "delivered", "slack_dm")++ def locked(*a: Any, **k: Any) -> None:+ raise sqlite3.OperationalError("database is locked")++ monkeypatch.setattr(runner, "deliver_to_person", half)+ monkeypatch.setattr(held, "_backoff", locked)+ assert asyncio.run(held.release_due(NOW)) == 1+ assert got == [ids["teammate"]]+++def test_mark_sent_is_retried_after_a_delivery(+ ids: dict[str, int], sent: list[tuple[int, str]], monkeypatch: pytest.MonkeyPatch+) -> None:+ pid = ids["teammate"]+ held.hold(pid, "Once", source="reflection", release_at=NOW, now=NOW)+ real = held.mark_sent+ calls: list[int] = []++ def flaky(*a: Any, **k: Any) -> None:+ calls.append(1)+ if len(calls) == 1:+ raise sqlite3.OperationalError("database is locked")+ real(*a, **k)++ async def no_sleep(_: float) -> None:+ return None++ monkeypatch.setattr(held, "mark_sent", flaky)+ monkeypatch.setattr(held.asyncio, "sleep", no_sleep)+ assert asyncio.run(held.release_due(NOW)) == 1+ assert len(calls) == 2 and held.held_count(pid) == 0+ # Past the claim TTL nothing is sent again.+ assert asyncio.run(held.release_due(NOW + held.CLAIM_TTL + timedelta(minutes=1))) == 0+ assert len(sent) == 1+++def test_a_brief_retries_marking_its_held_messages_sent(+ ids: dict[str, int], monkeypatch: pytest.MonkeyPatch+) -> None:+ pid = ids["principal"]+ held.hold(pid, "In the brief", source="reflection", release_at=None, now=NOW)+ [msg] = held.for_brief(pid)+ real = held.mark_sent+ calls: list[int] = []++ def flaky(*a: Any, **k: Any) -> None:+ calls.append(1)+ if len(calls) == 1:+ raise sqlite3.OperationalError("database is locked")+ real(*a, **k)++ async def no_sleep(_: float) -> None:+ return None++ monkeypatch.setattr(held, "mark_sent", flaky)+ monkeypatch.setattr(held.asyncio, "sleep", no_sleep)+ asyncio.run(runner._mark_held_sent([msg.id]))+ assert len(calls) == 2 and held.held_count(pid) == 0diff --git a/packages/core/tests/unit/test_notifications.py b/packages/core/tests/unit/test_notifications.pynew file mode 100644index 00000000..8ec900dd--- /dev/null+++ b/packages/core/tests/unit/test_notifications.py@@ -0,0 +1,337 @@+"""Each person's notification settings (people/notifications.py): quiet hours,+digest or instant, urgent things through — and how nudge routing+(people/channel.py) and the outbound guard (outbound_guard.check_hold,+schedule_tools._hold_outbound) apply them."""+from __future__ import annotations++import asyncio+import json+from collections.abc import Iterator+from datetime import UTC, datetime+from pathlib import Path+from types import SimpleNamespace+from unittest.mock import AsyncMock, patch++import pytest+from pydantic import ValidationError++from openexecutive.attunement.outcomes import (+ SOURCE_ALERT_REVIEW,+ SOURCE_FOLLOWUP,+ SOURCE_NUDGE_STALLED,+ SOURCE_REFLECTION,+ tag_proactive,+)+from openexecutive.memory import episodic+from openexecutive.orchestrator import outbound_guard, schedule_tools+from openexecutive.people import channel+from openexecutive.people import held_messages as held+from openexecutive.people import registry as people_registry+from openexecutive.people import store as people_store+from openexecutive.people.notifications import (+ NotificationSettings,+ QuietHours,+ get_notification_settings,+ hold_for,+ in_quiet_hours,+ quiet_hours_end,+ save_notification_settings,+ urgent_send,+)++# 2026-10-14 is a Wednesday; 2026-10-17 a Saturday.+WED_2300 = datetime(2026, 10, 14, 23, 0, tzinfo=UTC)+WED_1200 = datetime(2026, 10, 14, 12, 0, tzinfo=UTC)+SAT_1200 = datetime(2026, 10, 17, 12, 0, tzinfo=UTC)+++def _quiet(**kw: object) -> NotificationSettings:+ return NotificationSettings(+ quiet_hours=QuietHours(enabled=True, **kw), # type: ignore[arg-type]+ timezone="UTC",+ )++[email protected](autouse=True)+def db(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Iterator[Path]:+ path = tmp_path / "episodic.db"+ monkeypatch.setattr(episodic, "DB_PATH", path)+ monkeypatch.setattr(people_store, "DB_PATH", path)+ episodic.initialize_db(path)+ people_store.initialize_db(path)+ people_registry.invalidate()+ monkeypatch.setattr("openexecutive.audit.log_event", lambda *a, **k: None)+ yield path+ people_registry.invalidate()+++# --------------------------------------------------------------------------- #+# Settings+# --------------------------------------------------------------------------- #++def test_defaults_hold_nothing_back() -> None:+ s = get_notification_settings(42)+ assert s.quiet_hours.enabled is False+ assert s.delivery == "instant" and s.urgent_through is True+ assert hold_for(42, source=SOURCE_REFLECTION, now=WED_2300) is None+++def test_settings_round_trip() -> None:+ saved = save_notification_settings(7, NotificationSettings(+ quiet_hours=QuietHours(enabled=True, start="21:30", end="06:45", days="weekdays"),+ delivery="digest", urgent_through=False, timezone="Europe/London",+ ))+ got = get_notification_settings(7)+ assert got.quiet_hours.start == "21:30" and got.quiet_hours.days == "weekdays"+ assert got.delivery == "digest" and got.urgent_through is False+ assert got.timezone == "Europe/London" and got.updated_at == saved.updated_at != ""+ # Another person keeps the defaults.+ assert get_notification_settings(8).delivery == "instant"+++ "kw",+ [+ {"start": "22:00", "end": "22:00"},+ {"start": "24:00", "end": "07:00"},+ {"start": "7:00", "end": "08:00"},+ ],+)+def test_bad_quiet_hours_are_refused(kw: dict[str, str]) -> None:+ with pytest.raises(ValidationError):+ QuietHours(enabled=True, **kw)+++def test_unknown_zone_is_refused() -> None:+ with pytest.raises(ValidationError):+ NotificationSettings(timezone="Mars/Olympus")+++# --------------------------------------------------------------------------- #+# Quiet hours+# --------------------------------------------------------------------------- #++def test_quiet_hours_cross_midnight() -> None:+ s = _quiet(start="22:00", end="07:00")+ assert in_quiet_hours(s, WED_2300)+ assert in_quiet_hours(s, datetime(2026, 10, 15, 6, 59, tzinfo=UTC))+ assert not in_quiet_hours(s, datetime(2026, 10, 15, 7, 0, tzinfo=UTC))+ assert not in_quiet_hours(s, WED_1200)+ assert quiet_hours_end(s, WED_2300) == datetime(2026, 10, 15, 7, 0, tzinfo=UTC)+++def test_same_day_quiet_hours() -> None:+ s = _quiet(start="12:00", end="14:00")+ assert in_quiet_hours(s, WED_1200)+ assert not in_quiet_hours(s, WED_2300)+ assert quiet_hours_end(s, WED_1200) == datetime(2026, 10, 14, 14, 0, tzinfo=UTC)+++def test_weekdays_only_keeps_the_weekend_quiet() -> None:+ s = _quiet(start="22:00", end="07:00", days="weekdays")+ assert in_quiet_hours(s, SAT_1200)+ assert not in_quiet_hours(s, WED_1200)+ # Friday night runs through the weekend to Monday morning's end.+ fri = datetime(2026, 10, 16, 23, 0, tzinfo=UTC)+ assert quiet_hours_end(s, fri) == datetime(2026, 10, 19, 7, 0, tzinfo=UTC)+ # Every day keeps Saturday noon open.+ assert not in_quiet_hours(_quiet(start="22:00", end="07:00"), SAT_1200)+++def test_quiet_hours_are_read_in_the_persons_zone() -> None:+ s = NotificationSettings(+ quiet_hours=QuietHours(enabled=True, start="22:00", end="07:00"),+ timezone="America/New_York",+ )+ # 23:00 UTC is 19:00 in New York (EDT): not quiet there.+ assert not in_quiet_hours(s, WED_2300)+ # 03:00 UTC is 23:00 in New York: quiet, until 07:00 there (11:00 UTC).+ late = datetime(2026, 10, 15, 3, 0, tzinfo=UTC)+ assert in_quiet_hours(s, late)+ assert quiet_hours_end(s, late) == datetime(2026, 10, 15, 11, 0, tzinfo=UTC)+++def test_off_quiet_hours_have_no_end() -> None:+ assert quiet_hours_end(NotificationSettings(), WED_2300) is None+++# --------------------------------------------------------------------------- #+# What is held+# --------------------------------------------------------------------------- #++def test_quiet_hours_hold_until_they_end() -> None:+ save_notification_settings(1, _quiet(start="22:00", end="07:00"))+ hold = hold_for(1, source=SOURCE_REFLECTION, now=WED_2300)+ assert hold is not None and hold.release_at == datetime(2026, 10, 15, 7, 0, tzinfo=UTC)+ assert hold_for(1, source=SOURCE_REFLECTION, now=WED_1200) is None+++def test_digest_holds_for_the_brief_except_follow_ups() -> None:+ save_notification_settings(1, NotificationSettings(delivery="digest", timezone="UTC"))+ hold = hold_for(1, source=SOURCE_ALERT_REVIEW, now=WED_1200)+ assert hold is not None and hold.release_at is None+ # A follow-up was asked for at a time: never folded into a brief.+ assert hold_for(1, source=SOURCE_FOLLOWUP, now=WED_1200) is None+++def test_urgent_things_get_through_unless_turned_off() -> None:+ save_notification_settings(1, NotificationSettings(+ quiet_hours=QuietHours(enabled=True), delivery="digest", timezone="UTC",+ ))+ # An approval nudge is urgent by its source; a critical alert by the caller.+ assert hold_for(1, source=SOURCE_NUDGE_STALLED, now=WED_2300) is None+ assert hold_for(1, source=SOURCE_ALERT_REVIEW, now=WED_2300, urgent=True) is None+ save_notification_settings(1, NotificationSettings(+ quiet_hours=QuietHours(enabled=True), delivery="instant", urgent_through=False,+ timezone="UTC",+ ))+ hold = hold_for(1, source=SOURCE_NUDGE_STALLED, now=WED_2300)+ assert hold is not None and hold.release_at is not None+++# --------------------------------------------------------------------------- #+# Nudge routing (people.channel)+# --------------------------------------------------------------------------- #++def test_channel_defers_nudges_past_quiet_hours_only_when_asked() -> None:+ pid = people_store.upsert_person(full_name="Ben", email="[email protected]", slack_user_id="U1")+ save_notification_settings(pid, _quiet(start="22:00", end="07:00"))+ person = people_store.get_person(pid)+ assert person is not None+ # The outbound guard's own check (no quiet_hours) is unchanged.+ assert channel.is_within_availability(person, now=WED_2300)+ assert channel.next_window_for(person, after=WED_2300) is None+ # Nudge routing asks for them.+ assert not channel.is_within_availability(person, now=WED_2300, quiet_hours=True)+ assert channel.prefer_channel_for(pid, now=WED_2300, quiet_hours=True) is None+ assert channel.next_available_window(pid, after=WED_2300, quiet_hours=True) == datetime(+ 2026, 10, 15, 7, 0, tzinfo=UTC+ )+ # Outside quiet hours nothing defers.+ assert channel.next_window_for(person, after=WED_1200, quiet_hours=True) is None+ # An approval nudge gets through.+ assert channel.prefer_channel_for(pid, now=WED_2300, quiet_hours=True, urgent=True) is not None+++def test_channel_combines_windows_and_quiet_hours() -> None:+ from openexecutive.people.models import AvailabilityWindow++ pid = people_store.upsert_person(full_name="Cleo", email="[email protected]", slack_user_id="U2")+ people_store.set_availability(pid, [AvailabilityWindow(+ weekdays=[0, 1, 2, 3, 4], start_local="06:00", end_local="20:00", timezone="UTC",+ )])+ save_notification_settings(pid, _quiet(start="19:00", end="08:00"))+ person = people_store.get_person(pid)+ assert person is not None+ # 06:00 opens the window, but quiet hours run to 08:00.+ nxt = channel.next_window_for(person, after=WED_2300, quiet_hours=True)+ assert nxt == datetime(2026, 10, 15, 8, 0, tzinfo=UTC)+++# --------------------------------------------------------------------------- #+# The outbound guard+# --------------------------------------------------------------------------- #++def _settings() -> SimpleNamespace:+ return SimpleNamespace(+ slack_bot_token="tok", discord_bot_token=None, telegram_bot_token=None,+ calendar_booking_enabled=False, mcp_enabled=False,+ outbound_max_per_recipient_per_window=5, outbound_rate_window_minutes=60,+ outbound_dedup_window_minutes=360, outbound_respect_quiet_hours=True,+ )+++def test_check_hold_only_holds_the_executives_own_outreach() -> None:+ pid = people_store.upsert_person(full_name="Ben", email="[email protected]", slack_user_id="U1")+ save_notification_settings(pid, NotificationSettings(delivery="digest", timezone="UTC"))+ # Nobody tagged it: someone asked for it in chat.+ assert outbound_guard.check_hold("slack_dm", "U1", now=WED_1200) is None+ with tag_proactive(SOURCE_REFLECTION):+ got = outbound_guard.check_hold("slack_dm", "U1", now=WED_1200)+ assert got is not None and got[0] == pid and got[1] == SOURCE_REFLECTION+ # Someone not on the People list is never held.+ assert outbound_guard.check_hold("slack_dm", "U-unknown", now=WED_1200) is None+ # A critical alert gets through.+ with urgent_send():+ assert outbound_guard.check_hold("slack_dm", "U1", now=WED_1200) is None+++def test_message_person_holds_once_and_does_not_send() -> None:+ pid = people_store.upsert_person(+ full_name="Ben", email="[email protected]", slack_user_id="U1", telegram_chat_id="555",+ )+ save_notification_settings(pid, NotificationSettings(delivery="digest", timezone="UTC"))+ tg_send = AsyncMock()+ settings = _settings()+ settings.telegram_bot_token = "tok"+ with (+ patch("openexecutive.config.get_settings", return_value=settings),+ patch("openexecutive.integrations.telegram_bot.send_message", tg_send),+ tag_proactive(SOURCE_REFLECTION),+ ):+ raw = asyncio.run(schedule_tools.handle_message_person({"person_id": pid, "text": "Q3 is slipping"}))+ result = json.loads(raw)+ assert result["status"] == "held"+ tg_send.assert_not_awaited()+ waiting = held.for_brief(pid)+ assert [m.text for m in waiting] == ["Q3 is slipping"] and waiting[0].source == SOURCE_REFLECTION+++def test_a_message_that_cannot_be_stored_is_sent() -> None:+ pid = people_store.upsert_person(full_name="Ben", email="[email protected]", slack_user_id="U1")+ save_notification_settings(pid, NotificationSettings(delivery="digest", timezone="UTC"))+ with (+ patch("openexecutive.config.get_settings", return_value=_settings()),+ patch("openexecutive.people.held_messages.hold", side_effect=OSError("disk full")),+ tag_proactive(SOURCE_REFLECTION),+ ):+ assert schedule_tools._hold_outbound(+ tool="send_slack_dm", channel="slack_dm", channel_ref="U1", text="hi",+ ) is None+++def test_follow_ups_are_never_held() -> None:+ save_notification_settings(1, NotificationSettings(+ quiet_hours=QuietHours(enabled=True), delivery="digest", urgent_through=False, timezone="UTC",+ ))+ assert hold_for(1, source=SOURCE_FOLLOWUP, now=WED_2300) is None+ assert hold_for(1, source=SOURCE_FOLLOWUP, now=WED_1200) is None+++def test_a_question_something_waits_on_is_never_held() -> None:+ from openexecutive.people.notifications import approval_send++ pid = people_store.upsert_person(full_name="Ben", email="[email protected]", slack_user_id="U1")+ save_notification_settings(pid, NotificationSettings(+ quiet_hours=QuietHours(enabled=True), delivery="digest", urgent_through=False, timezone="UTC",+ ))+ with tag_proactive(SOURCE_REFLECTION):+ assert outbound_guard.check_hold("slack_dm", "U1", now=WED_2300) is not None+ with urgent_send(): # urgent things turned off: held+ assert outbound_guard.check_hold("slack_dm", "U1", now=WED_2300) is not None+ with approval_send():+ assert outbound_guard.check_hold("slack_dm", "U1", now=WED_2300) is None+++def test_quiet_hours_covering_every_window_fall_back_to_the_window() -> None:+ from openexecutive.people.models import AvailabilityWindow++ pid = people_store.upsert_person(full_name="Dee", email="[email protected]", slack_user_id="U3")+ people_store.set_availability(pid, [AvailabilityWindow(+ weekdays=[0, 1, 2, 3, 4], start_local="23:00", end_local="23:30", timezone="UTC",+ )])+ save_notification_settings(pid, _quiet(start="22:00", end="07:00"))+ person = people_store.get_person(pid)+ assert person is not None+ after = datetime(2026, 10, 14, 12, 0, tzinfo=UTC)+ assert channel.next_window_for(person, after=after, quiet_hours=True) == channel.next_window_for(+ person, after=after+ ) is not None+++def test_runner_counts_a_held_send_as_delivered() -> None:+ from openexecutive.scheduler.runner import _delivered_ok++ assert _delivered_ok('{"status": "held", "reason": "x"}')+ assert _delivered_ok('{"status": "sent"}')+ assert not _delivered_ok('{"status": "suppressed", "reason": "x"}')diff --git a/packages/core/tests/unit/test_nudge_engine.py b/packages/core/tests/unit/test_nudge_engine.pyindex c49fe290..21569d97 100644--- a/packages/core/tests/unit/test_nudge_engine.py+++ b/packages/core/tests/unit/test_nudge_engine.py@@ -517,6 +517,33 @@ class TestRouteCandidate:assert routed.channel_ref == "U_OK"assert routed.deliver_at == now+ def test_quiet_hours_defer_a_nudge_but_not_an_approval_nudge(self) -> None:+ from openexecutive.people.notifications import (+ NotificationSettings,+ QuietHours,+ save_notification_settings,+ )++ pid = _make_person(slack_user_id="U_Q", preferred="slack")+ now = datetime(2026, 10, 14, 23, 0, tzinfo=UTC)+ save_notification_settings(pid, NotificationSettings(+ quiet_hours=QuietHours(enabled=True, start="22:00", end="07:00"), timezone="UTC",+ ))+ cand = nudge_engine.NudgeCandidate(+ scope_key="x", intent_text="hi", source="initiative",+ urgency_seconds=0, cooldown=timedelta(hours=1), person_id=pid,+ )+ routed = nudge_engine._route_candidate(cand, now, max_defer_days=3)+ assert routed is not None+ assert routed.deliver_at == datetime(2026, 10, 15, 7, 0, tzinfo=UTC)+ assert routed.channel_ref == "U_Q"+ urgent = nudge_engine.NudgeCandidate(+ scope_key="y", intent_text="approve?", source="stalled",+ urgency_seconds=0, cooldown=timedelta(hours=1), person_id=pid,+ )+ routed = nudge_engine._route_candidate(urgent, now, max_defer_days=3)+ assert routed is not None and routed.deliver_at == now+def test_archived_person_returns_none(self) -> None:pid = _make_person(preferred="slack")with sqlite3.connect(str(people_store.DB_PATH)) as conn:diff --git a/packages/ui/scripts/navConfig.test.mjs b/packages/ui/scripts/navConfig.test.mjsindex 51db2282..76cb8031 100644--- a/packages/ui/scripts/navConfig.test.mjs+++ b/packages/ui/scripts/navConfig.test.mjs@@ -201,6 +201,7 @@ test("the Settings hub: one tile per page, each with its own route", () => {SETTINGS_PAGES.map((p) => `${p.label} → ${p.href}`),["Your Executive → /settings/executive",+ "Notifications → /settings/notifications","About you → /settings/memory","Workspace → /settings/workspace","Advanced → /settings/advanced",diff --git a/packages/ui/scripts/notifications.test.mjs b/packages/ui/scripts/notifications.test.mjsnew file mode 100644index 00000000..7566881f--- /dev/null+++ b/packages/ui/scripts/notifications.test.mjs@@ -0,0 +1,75 @@+import assert from "node:assert/strict";+import test from "node:test";+import {+ clockLabel,+ crossesMidnight,+ digestDescription,+ heldLine,+ quietError,+ quietSummary,+ tileStatus,+ toUpdate,+} from "../src/lib/notifications.ts";++const NIGHT = { enabled: true, start: "22:00", end: "07:00", days: "every_day" };++test("times read the way people say them", () => {+ assert.equal(clockLabel("22:00"), "10:00 pm");+ assert.equal(clockLabel("07:05"), "7:05 am");+ assert.equal(clockLabel("00:30"), "12:30 am");+ assert.equal(clockLabel("12:00"), "12:00 pm");+});++test("quiet hours say what they do", () => {+ assert.equal(quietSummary({ ...NIGHT, enabled: false }), "Off. Messages can reach you at any hour.");+ assert.equal(quietSummary(NIGHT), "Quiet from 10:00 pm to 7:00 am the next morning, every day.");+ assert.equal(+ quietSummary({ ...NIGHT, days: "weekdays" }),+ "Quiet from 10:00 pm to 7:00 am the next morning on weekdays, and all weekend.",+ );+ assert.equal(+ quietSummary({ ...NIGHT, start: "12:00", end: "13:00" }),+ "Quiet from 12:00 pm to 1:00 pm, every day.",+ );+ assert.ok(crossesMidnight(NIGHT));+ assert.ok(!crossesMidnight({ start: "12:00", end: "13:00" }));+});++test("a quiet window that starts when it ends can't be saved", () => {+ assert.equal(quietError(NIGHT), null);+ assert.equal(quietError({ ...NIGHT, end: "22:00" }), "Quiet hours need to start and end at different times.");+ assert.equal(quietError({ ...NIGHT, start: "" }), "Pick a start and end time.");+ assert.equal(quietError({ ...NIGHT, enabled: false, start: "" }), null);+});++test("In my briefs is worded for whether they get the briefs", () => {+ assert.match(digestDescription(true), /morning brief or end-of-day digest/);+ assert.match(digestDescription(false), /when the morning and end-of-day briefs go out/);+});++test("waiting messages are counted only when there are some", () => {+ assert.equal(heldLine(0, "digest"), null);+ assert.equal(heldLine(1, "digest"), "1 message is waiting for your next brief.");+ assert.equal(heldLine(3, "instant"), "3 messages are waiting for your quiet hours to end.");+});++test("saving fills an unset zone from the browser, never overwrites a chosen one", () => {+ const base = { quiet_hours: NIGHT, delivery: "instant", urgent_through: true };+ assert.equal(toUpdate({ ...base, timezone: "" }, "Europe/London").timezone, "Europe/London");+ assert.equal(toUpdate({ ...base, timezone: "Asia/Tokyo" }, "Europe/London").timezone, "Asia/Tokyo");+ assert.equal(toUpdate({ ...base, timezone: "" }, null).timezone, "");+ assert.deepEqual(Object.keys(toUpdate({ ...base, timezone: "" }, null)).sort(), [+ "delivery",+ "quiet_hours",+ "timezone",+ "urgent_through",+ ]);+});++test("the hub tile sums it up", () => {+ assert.equal(tileStatus({ quiet_hours: NIGHT, delivery: "digest" }), "Quiet 10:00 pm–7:00 am · In my briefs");+ assert.equal(+ tileStatus({ quiet_hours: { ...NIGHT, enabled: false }, delivery: "instant" }),+ "Quiet hours off · As they happen",+ );+});diff --git a/packages/ui/src/app/settings/notifications/page.tsx b/packages/ui/src/app/settings/notifications/page.tsxnew file mode 100644index 00000000..6018309b--- /dev/null+++ b/packages/ui/src/app/settings/notifications/page.tsx@@ -0,0 +1,17 @@+"use client";++import NotificationsCard from "@/components/settings/NotificationsCard";+import SettingsSubpage from "@/components/settings/SettingsSubpage";++// Settings → Notifications: each person's own quiet hours, whether things+// reach them as they happen or in their briefs, and urgent things through.+export default function NotificationsSettingsPage() {+ return (+ <SettingsSubpage+ title="Notifications"+ description="Quiet hours, and whether things reach you as they happen or in your briefs. These are yours: everyone sets their own."+ >+ <NotificationsCard />+ </SettingsSubpage>+ );+}diff --git a/packages/ui/src/app/settings/page.tsx b/packages/ui/src/app/settings/page.tsxindex 0a30c37f..bd8ac6f7 100644--- a/packages/ui/src/app/settings/page.tsx+++ b/packages/ui/src/app/settings/page.tsx@@ -18,15 +18,18 @@ import { useWorkspace } from "@/components/workspace/WorkspaceContext";import {getAgentDetail,getHistory,+ getNotificationSettings,getVersion,listPersonas,type HistoryState,+ type NotificationSettings,} from "@/lib/api";import { retentionLabel } from "@/lib/history";+import { tileStatus as notificationsTileStatus } from "@/lib/notifications";import { versionNotice } from "@/lib/versionNotice";// Settings — a hub of tiles, one per page (SETTINGS_PAGES): Your Executive,-// About you, Workspace, Advanced and About. Each tile says what's on its page+// Notifications, About you, Workspace, Advanced and About. Each tile says what's on its page// and, where it's cheap to know, how things stand right now. The one-page// Settings this replaces used anchors (`/settings#workspace`); a link that// still carries one is sent on to the matching page (Act as me's, to its tab@@ -62,7 +65,13 @@ export default function SettingsPage() {const statuses = useTileStatuses();// About you has a tile only for someone with notes to keep (GET /memories/history// answers null for anyone not signed in or not on the People list).- const pages = SETTINGS_PAGES.filter((p) => p.id !== "memory" || statuses.memoryOffered);+ // Notifications likewise only for someone on the People list (GET+ // /notifications/settings answers null for anyone else).+ const pages = SETTINGS_PAGES.filter(+ (p) =>+ (p.id !== "memory" || statuses.memoryOffered) &&+ (p.id !== "notifications" || statuses.notificationsOffered),+ );if (hash === null || target) return <main className="flex-1" />;@@ -132,12 +141,14 @@ function SettingsTile({ page, status }: { page: SettingsPageDef; status?: TileStfunction useTileStatuses(): {byPage: Partial<Record<SettingsPageId, TileStatus>>;memoryOffered: boolean;+ notificationsOffered: boolean;} {const { status: run, unknown } = useExecutiveStatus();const { mode, effectiveTimezone, loading: workspaceLoading } = useWorkspace();const [voice, setVoice] = useState<string | null>(null);const [version, setVersion] = useState<TileStatus | null>(null);const [history, setHistory] = useState<HistoryState | null | "error">(null);+ const [notifications, setNotifications] = useState<NotificationSettings | null | "error">(null);useEffect(() => {const ctrl = new AbortController();@@ -153,6 +164,11 @@ function useTileStatuses(): {.catch((err) => {if ((err as Error)?.name !== "AbortError") setHistory("error");});+ getNotificationSettings(ctrl.signal)+ .then((n) => setNotifications(n))+ .catch((err) => {+ if ((err as Error)?.name !== "AbortError") setNotifications("error");+ });getVersion(ctrl.signal).then((v) => {const notice = versionNotice(v);@@ -189,6 +205,10 @@ function useTileStatuses(): {};}+ if (notifications && notifications !== "error") {+ byPage.notifications = { text: notificationsTileStatus(notifications), tone: "none" };+ }+if (!workspaceLoading) {byPage.workspace = {text: [MODE_LABEL[mode], effectiveTimezone].filter(Boolean).join(" · "),@@ -199,5 +219,5 @@ function useTileStatuses(): {byPage.advanced = { text: `${ADVANCED_ITEMS.length} tools for power users`, tone: "none" };if (version) byPage.about = version;- return { byPage, memoryOffered: history !== null };+ return { byPage, memoryOffered: history !== null, notificationsOffered: notifications !== null };}diff --git a/packages/ui/src/components/settings/NotificationsCard.tsx b/packages/ui/src/components/settings/NotificationsCard.tsxnew file mode 100644index 00000000..dcbce944--- /dev/null+++ b/packages/ui/src/components/settings/NotificationsCard.tsx@@ -0,0 +1,267 @@+"use client";++import Link from "next/link";+import { useEffect, useMemo, useState } from "react";++import SettingsCard from "@/components/settings/SettingsCard";+import Switch from "@/components/Switch";+import Button from "@/components/ui/Button";+import { getNotificationSettings, updateNotificationSettings, type NotificationSettings } from "@/lib/api";+import {+ DAYS_LABEL,+ DELIVERY_LABEL,+ digestDescription,+ heldLine,+ quietError,+ quietSummary,+ toUpdate,+ type Delivery,+ type QuietDays,+ type QuietHours,+} from "@/lib/notifications";++// Settings → Notifications (GET/PUT /notifications/settings): the signed-in+// person's own quiet hours, whether things reach them as they happen or in+// their briefs, and whether urgent things get through. Every change saves at+// once except the quiet-hours times, which have a Save button so a half-typed+// time is never stored.++const INPUT =+ "w-full h-11 px-3 rounded-xl text-[15px] bg-surface border border-line text-fg focus:outline-none focus:border-line-strong disabled:opacity-60";++function browserTimeZone(): string | null {+ try {+ return Intl.DateTimeFormat().resolvedOptions().timeZone || null;+ } catch {+ return null;+ }+}++type Loaded = NotificationSettings | null | "loading" | "error";++export default function NotificationsCard() {+ const [state, setState] = useState<Loaded>("loading");+ const [draft, setDraft] = useState<QuietHours | null>(null);+ const [busy, setBusy] = useState(false);+ const [error, setError] = useState<string | null>(null);+ const browserZone = useMemo(() => browserTimeZone(), []);++ useEffect(() => {+ const ctrl = new AbortController();+ getNotificationSettings(ctrl.signal)+ .then((s) => {+ setState(s);+ if (s) setDraft(s.quiet_hours);+ })+ .catch((err) => {+ if ((err as Error)?.name !== "AbortError") setState("error");+ });+ return () => ctrl.abort();+ }, []);++ if (state === "loading") return null;+ if (state === "error") {+ return (+ <SettingsCard title="Notifications">+ <p className="text-[15px] text-fg-muted">Couldn't load your notification settings.</p>+ </SettingsCard>+ );+ }+ if (state === null) {+ return (+ <SettingsCard title="Notifications">+ <p className="text-[15px] text-fg-muted">+ Notification settings are for people on the People list. Sign in as one of them to set yours.+ </p>+ </SettingsCard>+ );+ }++ const current = state;+ const quiet = draft ?? current.quiet_hours;+ const dirty = JSON.stringify(quiet) !== JSON.stringify(current.quiet_hours);+ const draftError = quietError(quiet);++ async function save(change: Partial<Pick<NotificationSettings, "quiet_hours" | "delivery" | "urgent_through" | "timezone">>) {+ setBusy(true);+ setError(null);+ try {+ const next = await updateNotificationSettings(toUpdate({ ...current, ...change }, browserZone));+ setState(next);+ setDraft(next.quiet_hours);+ } catch (err) {+ setError(err instanceof Error ? err.message : "Couldn't save the change.");+ } finally {+ setBusy(false);+ }+ }++ const held = heldLine(current.held_count, current.delivery);+ const zone = current.effective_timezone;++ return (+ <>+ {error && (+ <p role="alert" className="rounded-xl border border-red-500/30 bg-red-500/10 px-4 py-3 text-sm text-red-500">+ {error}+ </p>+ )}+ {held && (+ <p role="status" className="rounded-xl border border-line bg-surface px-4 py-3 text-[15px] text-fg">+ {held}+ </p>+ )}++ <SettingsCard+ title="Quiet hours"+ titleId="quiet-hours-label"+ description={quietSummary(current.quiet_hours)}+ action={+ <Switch+ checked={current.quiet_hours.enabled}+ labelledBy="quiet-hours-label"+ disabled={busy}+ onChange={(enabled) => void save({ quiet_hours: { ...quiet, enabled } })}+ />+ }+ >+ {current.quiet_hours.enabled && (+ <div className="space-y-4">+ <p className="text-[15px] text-fg-muted leading-relaxed">+ What the Executive would send you on its own (nudges, check-ins on your work, alerts) waits+ until your quiet hours end. Replies when you message it still come straight away.+ </p>+ <div className="grid grid-cols-1 sm:grid-cols-3 gap-3">+ <label className="flex flex-col gap-1.5 text-sm font-medium text-fg">+ From+ <input+ type="time"+ value={quiet.start}+ disabled={busy}+ onChange={(e) => setDraft({ ...quiet, start: e.target.value })}+ className={INPUT}+ />+ </label>+ <label className="flex flex-col gap-1.5 text-sm font-medium text-fg">+ To+ <input+ type="time"+ value={quiet.end}+ disabled={busy}+ onChange={(e) => setDraft({ ...quiet, end: e.target.value })}+ className={INPUT}+ />+ </label>+ <label className="flex flex-col gap-1.5 text-sm font-medium text-fg">+ Days+ <select+ value={quiet.days}+ disabled={busy}+ onChange={(e) => setDraft({ ...quiet, days: e.target.value as QuietDays })}+ className={INPUT}+ >+ {(Object.keys(DAYS_LABEL) as QuietDays[]).map((d) => (+ <option key={d} value={d}>+ {DAYS_LABEL[d]}+ </option>+ ))}+ </select>+ </label>+ </div>+ {draftError && dirty && <p className="text-sm text-red-500">{draftError}</p>}+ <div className="flex flex-wrap items-center gap-3">+ <Button+ variant="primary"+ disabled={busy || !dirty || draftError !== null}+ onClick={() => void save({ quiet_hours: quiet })}+ >+ {busy ? "Saving…" : "Save quiet hours"}+ </Button>+ {dirty && (+ <Button variant="ghost" disabled={busy} onClick={() => setDraft(current.quiet_hours)}>+ Cancel+ </Button>+ )}+ </div>+ <p className="text-[13px] text-fg-subtle">+ Times are in {zone}.+ {browserZone && browserZone !== zone && (+ <>+ {" "}+ <button+ type="button"+ disabled={busy}+ onClick={() => void save({ timezone: browserZone })}+ className="font-medium text-accent hover:underline cursor-pointer disabled:opacity-50"+ >+ Use {browserZone} instead+ </button>+ </>+ )}+ </p>+ </div>+ )}+ </SettingsCard>++ <SettingsCard+ title="How things reach you"+ titleId="delivery-label"+ description="For what the Executive sends you on its own: nudges, check-ins on your work and alerts."+ >+ <div role="radiogroup" aria-labelledby="delivery-label" className="flex flex-col gap-2">+ {(["instant", "digest"] as Delivery[]).map((d) => {+ const selected = current.delivery === d;+ return (+ <button+ key={d}+ type="button"+ role="radio"+ aria-checked={selected}+ disabled={busy}+ onClick={() => {+ if (!selected) void save({ delivery: d });+ }}+ className={`w-full rounded-xl border px-4 py-3 text-left transition-colors cursor-pointer disabled:cursor-not-allowed disabled:opacity-60 ${+ selected ? "border-accent bg-accent/5" : "border-line bg-surface hover:border-line-strong"+ }`}+ >+ <span className="block text-[15px] font-semibold text-fg">{DELIVERY_LABEL[d]}</span>+ <span className="mt-0.5 block text-sm text-fg-muted leading-relaxed">+ {d === "instant" ? "Sent to you as soon as there's something." : digestDescription(current.gets_briefs)}+ </span>+ </button>+ );+ })}+ </div>+ </SettingsCard>++ <SettingsCard+ title="Let urgent things through"+ titleId="urgent-through-label"+ description={+ current.urgent_through+ ? "On: reminders about things waiting on your approval, and critical alerts, reach you right away, even in quiet hours or when you get things in your briefs."+ : "Off: those wait with everything else. A question a workflow is waiting on you to answer always comes straight away."+ }+ action={+ <Switch+ checked={current.urgent_through}+ labelledBy="urgent-through-label"+ disabled={busy}+ onChange={(urgent_through) => void save({ urgent_through })}+ />+ }+ />++ {current.gets_briefs && (+ <p className="text-[15px] text-fg-muted">+ Your morning brief and end-of-day digest still come at their usual times. They're under{" "}+ <Link href="/settings/executive" className="font-medium text-accent underline-offset-2 hover:underline">+ Your Executive+ </Link>+ .+ </p>+ )}+ </>+ );+}diff --git a/packages/ui/src/components/shell/navConfig.ts b/packages/ui/src/components/shell/navConfig.tsindex a08e5595..f3488d72 100644--- a/packages/ui/src/components/shell/navConfig.ts+++ b/packages/ui/src/components/shell/navConfig.ts@@ -442,7 +442,13 @@ export function advancedItemsByGroup(): {// notes to keep (signed in and on the People list). `hashes` are the anchors the// old one-page Settings used (`/settings#workspace`): links that still// carry one land on the matching page (see settingsPageForHash).-export type SettingsPageId = "executive" | "memory" | "workspace" | "advanced" | "about";+export type SettingsPageId =+ | "executive"+ | "notifications"+ | "memory"+ | "workspace"+ | "advanced"+ | "about";export interface SettingsPageDef {id: SettingsPageId;@@ -463,6 +469,14 @@ export const SETTINGS_PAGES: SettingsPageDef[] = [description: "Pause it, what it does without asking you, and the voice it answers in.",hashes: ["executive", "on-its-own"],},+ {+ id: "notifications",+ label: "Notifications",+ href: "/settings/notifications",+ icon: "bell",+ description: "Quiet hours, and whether things reach you as they happen or in your briefs.",+ hashes: [],+ },{id: "memory",label: "About you",diff --git a/packages/ui/src/lib/api.ts b/packages/ui/src/lib/api.tsindex 6e605d9a..47272bbc 100644--- a/packages/ui/src/lib/api.ts+++ b/packages/ui/src/lib/api.ts@@ -1,5 +1,6 @@import type { AnswerSources } from "@/lib/answerSources";import type { HistoryNote, HistoryState } from "@/lib/history";+import type { NotificationSettings, NotificationSettingsUpdate } from "@/lib/notifications";import type { SetupStatus } from "@/lib/setupStatus";const API_BASE = "/api/backend";@@ -1747,6 +1748,40 @@ export async function getDelegation(signal?: AbortSignal): Promise<DelegationSetreturn res.json();}+// ---------------------------------------------------------------------------+// Settings → Notifications: the caller's own quiet hours, digest or instant,+// and urgent things through (/notifications/settings).+// ---------------------------------------------------------------------------++export type {+ Delivery,+ NotificationSettings,+ NotificationSettingsUpdate,+ QuietDays,+ QuietHours,+} from "@/lib/notifications";++// null when this viewer has none to set (403: not signed in or not on the+// People list) or the backend predates it (404).+export async function getNotificationSettings(signal?: AbortSignal): Promise<NotificationSettings | null> {+ const res = await fetch(`${API_BASE}/notifications/settings`, { signal });+ if (res.status === 403 || res.status === 404) return null;+ if (!res.ok) throw await delegationError(res, "Couldn't load your notification settings.");+ return res.json();+}++export async function updateNotificationSettings(+ update: NotificationSettingsUpdate,+): Promise<NotificationSettings> {+ const res = await fetch(`${API_BASE}/notifications/settings`, {+ method: "PUT",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify(update),+ });+ if (!res.ok) throw await delegationError(res, "Couldn't save your notification settings.");+ return res.json();+}+// ---------------------------------------------------------------------------// Always in the loop: the caller's own notes (/memories/history). Each person// sees and changes only their own; the company retention is the owner's.diff --git a/packages/ui/src/lib/notifications.ts b/packages/ui/src/lib/notifications.tsnew file mode 100644index 00000000..2c103925--- /dev/null+++ b/packages/ui/src/lib/notifications.ts@@ -0,0 +1,114 @@+// Settings → Notifications: the signed-in person's own quiet hours, digest or+// instant, and whether urgent things get through (GET/PUT+// /notifications/settings). Types and wording only, kept free of React so+// scripts/ can test it.++export type QuietDays = "every_day" | "weekdays";+export type Delivery = "instant" | "digest";++export interface QuietHours {+ enabled: boolean;+ /** HH:MM, 24-hour, in `effective_timezone`. May be later than `end`. */+ start: string;+ end: string;+ days: QuietDays;+}++export interface NotificationSettings {+ quiet_hours: QuietHours;+ delivery: Delivery;+ urgent_through: boolean;+ /** The zone they chose; "" for the workspace's. */+ timezone: string;+ effective_timezone: string;+ /** Messages waiting for quiet hours to end or for their next brief. */+ held_count: number;+ /** They get the morning and end-of-day briefs (the account owner). */+ gets_briefs: boolean;+ updated_at: string;+}++export interface NotificationSettingsUpdate {+ quiet_hours: QuietHours;+ delivery: Delivery;+ urgent_through: boolean;+ timezone: string;+}++export const DAYS_LABEL: Record<QuietDays, string> = {+ every_day: "Every day",+ weekdays: "Weekdays (weekends quiet all day)",+};++/** "10:00 pm" for "22:00". */+export function clockLabel(hhmm: string): string {+ const [h, m] = hhmm.split(":").map(Number);+ if (!Number.isFinite(h) || !Number.isFinite(m)) return hhmm;+ const suffix = h < 12 ? "am" : "pm";+ return `${h % 12 || 12}:${String(m).padStart(2, "0")} ${suffix}`;+}++/** Whether the quiet hours run past midnight (22:00 → 07:00). */+export function crossesMidnight(q: Pick<QuietHours, "start" | "end">): boolean {+ return q.end <= q.start;+}++/** One line saying what the quiet hours do, from the person's side. */+export function quietSummary(q: QuietHours): string {+ if (!q.enabled) return "Off. Messages can reach you at any hour.";+ const span = `${clockLabel(q.start)} to ${clockLabel(q.end)}${crossesMidnight(q) ? " the next morning" : ""}`;+ return q.days === "weekdays"+ ? `Quiet from ${span} on weekdays, and all weekend.`+ : `Quiet from ${span}, every day.`;+}++/** Why the form can't be saved yet, or null. */+export function quietError(q: QuietHours): string | null {+ if (!q.enabled) return null;+ if (!/^\d{2}:\d{2}$/.test(q.start) || !/^\d{2}:\d{2}$/.test(q.end)) return "Pick a start and end time.";+ if (q.start === q.end) return "Quiet hours need to start and end at different times.";+ return null;+}++/** What "In my briefs" means for this person: the owner gets briefs; anyone+ * else gets the held messages on their own when the briefs go out. */+export function digestDescription(getsBriefs: boolean): string {+ return getsBriefs+ ? "Held and added to your next morning brief or end-of-day digest, under “While you were away”."+ : "Held and sent to you together, in one message, when the morning and end-of-day briefs go out.";+}++/** "2 messages are waiting for you", or null when none are. */+export function heldLine(count: number, delivery: Delivery): string | null {+ if (count <= 0) return null;+ const what = count === 1 ? "1 message is" : `${count} messages are`;+ return delivery === "digest"+ ? `${what} waiting for your next brief.`+ : `${what} waiting for your quiet hours to end.`;+}++/** The PUT body for a form state; the browser's zone fills an unset one, so+ * the times mean what the person sees. */+export function toUpdate(+ s: Pick<NotificationSettings, "quiet_hours" | "delivery" | "urgent_through" | "timezone">,+ browserZone: string | null,+): NotificationSettingsUpdate {+ return {+ quiet_hours: { ...s.quiet_hours },+ delivery: s.delivery,+ urgent_through: s.urgent_through,+ timezone: s.timezone || browserZone || "",+ };+}++export const DELIVERY_LABEL: Record<Delivery, string> = {+ instant: "As they happen",+ digest: "In my briefs",+};++/** The Settings hub tile's one-line status. */+export function tileStatus(s: Pick<NotificationSettings, "quiet_hours" | "delivery">): string {+ const q = s.quiet_hours;+ const quiet = q.enabled ? `Quiet ${clockLabel(q.start)}–${clockLabel(q.end)}` : "Quiet hours off";+ return `${quiet} · ${DELIVERY_LABEL[s.delivery]}`;+}