Skip to content

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

Bind the session for the whole SSE body, not one stream step

Claude1a7a908f4d5d
diff --git a/packages/core/openexecutive/api/routes/chat.py b/packages/core/openexecutive/api/routes/chat.py
index 6129376f..4a1921ed 100644
--- a/packages/core/openexecutive/api/routes/chat.py
+++ b/packages/core/openexecutive/api/routes/chat.py
@@ -78,7 +78,11 @@ def _get_or_create_session(session_id: str | None, request: Request) -> Any:
new_id = session_id or str(uuid.uuid4())
profile = load_or_create_profile()
- session = Session(session_id=new_id, company_profile=profile if not profile.is_empty() else None)
+ session = Session(
+ session_id=new_id,
+ company_profile=profile if not profile.is_empty() else None,
+ from_web_chat=True,
+ )
if session_id:
# Server may have restarted — reload history from DB so conversation continues.
@@ -152,6 +156,46 @@ def _build_page_context_block(page_context: PageContext | None) -> str:
return "\n".join(lines)
+def _seed_seen_channel_refs(session: Any, person_id: int | None) -> None:
+ """Record the caller's OWN channel addresses as seen on this session.
+
+ `schedule_followup` refuses to queue a send to a `(channel, channel_ref)`
+ the session has not seen — an anti-spam gate, and the reason an injected
+ "email this to attacker@evil" in an alert body cannot become a scheduled
+ send. The chat adapters populate it from the inbound message; nothing
+ populated it for a browser turn.
+
+ The gate was unreachable on web until `set_session` bound the session for
+ the whole stream, so it silently allowed ANY address; reachable, it reads
+ an empty set as "seen nothing" and refuses even the principal's own,
+ breaking "remind me tomorrow at 9am". Seeding the caller's own refs is
+ what makes the gate mean on web what it means everywhere else: you may
+ schedule to yourself, and to whatever this conversation actually used.
+
+ Adds only. An address removed from the roster stays in the set for the
+ life of the in-memory session.
+ """
+ if person_id is None:
+ return
+ try:
+ from openexecutive.people.store import get_person
+
+ person = get_person(person_id)
+ except Exception:
+ logger.warning("chat.seen_refs_seed_failed person_id=%s", person_id, exc_info=True)
+ return
+ if person is None:
+ return
+ for channel, ref in (
+ ("email", getattr(person, "email", None)),
+ ("slack_dm", getattr(person, "slack_user_id", None)),
+ ("discord_dm", getattr(person, "discord_user_id", None)),
+ ("telegram", getattr(person, "telegram_chat_id", None)),
+ ):
+ if ref:
+ session.seen_channel_refs.add((channel, str(ref)))
+
+
def _resolve_caller_person_id(request: Request) -> int | None:
"""Resolve the calling Person from the `x-caller-email` header.
@@ -234,6 +278,11 @@ async def _run_chat_turn(
# sidebar by signed-in user). See `_resolve_caller_person_id` for
# the precedence rule that protects against cross-identity leakage.
caller_person_id = _resolve_caller_person_id(request)
+ # Let the caller schedule to their own addresses. Runs per turn rather than
+ # only on session creation so a newly-added address works without a fresh
+ # session; note it only ever ADDS, so an address removed from the roster
+ # stays scheduleable for the life of this in-memory session.
+ _seed_seen_channel_refs(session, caller_person_id)
# Persist the session row immediately (idempotent INSERT OR IGNORE) so a
# mid-turn failure never leaves a ghost in-memory session with no DB row.
@@ -261,6 +310,7 @@ async def _run_chat_turn(
# on timeout, so failure modes are unchanged.
from openexecutive.audit import set_turn
from openexecutive.memory.honcho_client import prefetch as _honcho_prefetch
+ from openexecutive.orchestrator.schedule_tools import set_session
async def _do_episodic() -> str:
try:
@@ -362,16 +412,22 @@ async def _run_chat_turn(
timeout_s += settings.committee_extra_timeout_s
async def event_generator():
- # Bind the turn for the whole SSE body, not just its first step.
- # `_sse_body` drives the executive with `asyncio.wait_for`, which
- # wraps every `__anext__()` in a fresh Task that copies the context
- # at that moment — so a binding made *inside* the executive's own
- # generator lands in a throwaway per-step context and is gone by the
- # next resume. Everything after step one (the whole tool-call loop
+ # Bind the turn AND the session for the whole SSE body, not just its
+ # first step. `_sse_body` drives the executive with `asyncio.wait_for`,
+ # which wraps every `__anext__()` in a fresh Task that copies the
+ # context at that moment — so a binding made *inside* the executive's
+ # own generator lands in a throwaway per-step context and is gone by
+ # the next resume. Everything after step one (the whole tool-call loop
# and the specialist fan-out) then records with no session or turn.
# Bound out here, in the generator Starlette itself drives, every
- # step inherits it. `set_turn` saves and restores rather than using
- # Token.reset precisely so it survives that task-hopping.
+ # step inherits it. Both managers save and restore rather than using
+ # Token.reset precisely so they survive that task-hopping.
+ #
+ # `set_session` is here for exactly the same reason `set_turn` is, and
+ # was missing until it cost a production incident — see its docstring
+ # in `orchestrator.schedule_tools` for the mechanism and the blast
+ # radius. Every tool handler that reads `current_session` mid-turn
+ # depends on this binding.
# aclosing is load-bearing, not decoration: `async for` does NOT
# close its sub-iterator when the enclosing generator is closed. This
# body used to BE event_generator, so a client disconnect ran its
@@ -379,7 +435,10 @@ async def _run_chat_turn(
# Executive's upstream stream aclose). Wrapping it in a plain
# `async for` would leave `_sse_body` suspended at its yield until a
# later GC hop — or never, if the loop closes first.
- with set_turn(session_id=session.session_id, turn_id=turn_id):
+ with (
+ set_turn(session_id=session.session_id, turn_id=turn_id),
+ set_session(session),
+ ):
async with contextlib.aclosing(_sse_body()) as body:
async for evt in body:
yield evt
diff --git a/packages/core/openexecutive/architecture/architecture-facts.yaml b/packages/core/openexecutive/architecture/architecture-facts.yaml
index 71c161ce..bc4fa53b 100644
--- a/packages/core/openexecutive/architecture/architecture-facts.yaml
+++ b/packages/core/openexecutive/architecture/architecture-facts.yaml
@@ -406,7 +406,7 @@ routing:
side-effecting tool so a chip surfaces in the live stream
("Approved proposal #N" / "Dismissed proposal #N"). The button-driven
Approve / Dismiss path on the briefing page still acks via the HTTP
- TRUST: the server-side check runs on EVERY session, not only those with an origin_channel. It previously skipped web sessions, so the browser — the surface the principal actually uses — had no check and the model could ack any id, including one an inbound email wrote into an alert body that the Discuss handoff quoted into the turn. `briefing.context.render_and_trust` is the single place that renders the digest AND records the live board onto session.trusted_alert_ids (the whole live set, not only the printed rows, so a card past the 30-row render cap stays ackable). The control bounds the model to server-derived live ids — it refuses invented, closed, snoozed and expired ones — but does NOT prevent the model being argued into acking the wrong live card; do not document it as immunity to cross-alert injection; the web chat route and the channel adapters both go through it, so the block shown and the set accepted cannot drift. An empty trusted set refuses everything, which is the safe default for a turn that was shown no board (non-DM / non-principal channel turns, or a digest that failed to build). The digest additionally names recently closed alerts in an 'Already handled' tail so the Executive can say an item is already cleared instead of sending the principal to dismiss it again; those ids are NOT added to the trusted set.
+ TRUST: the server-side check runs on EVERY session, not only those with an origin_channel. It previously skipped web sessions, so the browser — the surface the principal actually uses — had no check and the model could ack any id, including one an inbound email wrote into an alert body that the Discuss handoff quoted into the turn. `briefing.context.render_and_trust` is the single place that renders the digest AND records the live board onto session.trusted_alert_ids (the whole live set, not only the printed rows, so a card past the 30-row render cap stays ackable). The control bounds the model to server-derived live ids — it refuses invented, closed, snoozed and expired ones — but does NOT prevent the model being argued into acking the wrong live card; do not document it as immunity to cross-alert injection; the web chat route and the channel adapters both go through it, so the block shown and the set accepted cannot drift. An empty trusted set refuses everything, which is the safe default for a turn that was shown no board (non-DM / non-principal channel turns, or a digest that failed to build). The tool reads that set off `current_session`, so the BINDING is load-bearing: the chat route binds the session for the whole SSE body via `schedule_tools.set_session`, beside `set_turn`. `Executive.stream_chat` also binds it with a bare `set()` at its top, and that suffices only for callers driving the generator with a plain `async for` (the adapters' .chat() wrapper, CLI, tests). The SSE route drives it under `asyncio.wait_for(stream.__anext__())`, which copies the context per step, so a binding made inside the generator dies with step one and every later step — including the entire tool-call loop — reads None. That shipped in the same change that extended the check to web, and the two combined refused every ack the principal made on live cards. Both managers save/restore rather than Token.reset, because __exit__ runs in a different Context than __enter__ on this path. Anything else reading current_session mid-turn inherits the same requirement, and two needed more than the binding. schedule_followup's seen-channel_ref anti-spam gate is a no-op without a session (so web could schedule to ANY address) and refuses everything with an empty one (so it refused the principal's own), until the route seeds the caller's own addresses onto the session — additive only, so an address dropped from the roster stays scheduleable for the life of the in-memory session. Reply linkage (_record_outbound_context, read back by inbound_hydration) is deliberately NOT switched on for web by that binding; it is keyed on the explicit Session.from_web_chat flag, never on an empty origin_channel, because origin_channel names an inbound chat adapter and the email poller, alert review, the CLI, the MCP server, the scheduler and the unattended workflows all leave it empty while legitimately recording linkage. scheduled_actions rows also lose their session_id without the binding. The digest additionally names recently closed alerts in an 'Already handled' tail so the Executive can say an item is already cleared instead of sending the principal to dismiss it again; those ids are NOT added to the trusted set.
route — the tool exists for the chat-driven path that the model
self-detects from natural-language approval. The same feedback loop as
the HTTP ack applies: a `dismissed` on a watch-sourced alert lowers
diff --git a/packages/core/openexecutive/architecture/prebuilt/lifecycle.json b/packages/core/openexecutive/architecture/prebuilt/lifecycle.json
index 6f084507..ae40be74 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 posts to `POST /chat` (`openexecutive.api.routes.chat`). The turn carries a `<current_speaker>` hint resolved from the caller's `person_id`, 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.\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.\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.\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.\n5. **Synthesis** — the Executive feeds the tool_results back to Claude and streams one coherent reply; a `thinking` keepalive covers the specialist round.\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** — any side-effecting tool call surfaces an `action_taken` chip; the stream closes with a `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. 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 now 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.",
+ "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 posts to `POST /chat` (`openexecutive.api.routes.chat`). The turn carries a `<current_speaker>` hint resolved from the caller's `person_id`, 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.\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.\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.\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.\n5. **Synthesis** — the Executive feeds the tool_results back to Claude and streams one coherent reply; a `thinking` keepalive covers the specialist round.\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** — any side-effecting tool call surfaces an `action_taken` chip; the stream closes with a `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 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` — that names an inbound chat adapter, and the email poller, alert review, the CLI and the unattended workflows all leave it empty while legitimately recording linkage. `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.",
"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-09-18T20:54:42.334412+00:00"
}
diff --git a/packages/core/openexecutive/architecture/prebuilt/today.json b/packages/core/openexecutive/architecture/prebuilt/today.json
index ebabbd50..9ff210a3 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>`).\n\n`GET /today` returns `TodayResponse` assembled by `_build_today()`, which is synchronous and caller-agnostic:\n\n- **`departments`** — per-department goal health, rolling up each department's goal counts (`total`, `at_risk`, `off_track`) plus its awaiting-workflow count, and `attention_goals`: the actual off-track/at-risk goals (worst first, capped at 3) with `key_result`, `current`, `target`, and `status`, so the briefing's Department card shows *which* goal is off and how far without a click. Empty for healthy/inactive departments.\n- **`people`** — an attention-ranked roster. Each person carries `awaiting_action` count, soonest SLA, a `status` (`on_leave` / `needs_reply` / `awaiting` / `clear`), reachability, `overdue`, a server `priority` sort key, and a cached one-line `insight`. Sorted by `(-priority, full_name)`.\n- **`proposals`** — the *live* unread alerts (workflow approvals, triage-classified inbound, Executive signals, flagged artifacts, and gated calendar bookings): unread, inside their category TTL, not snoozed — see *Alert lifecycle* below. Each carries `score`, `category` (`action` vs `monitoring`), `surfaced_reason` from `openexecutive.briefing.ranking`, the lifecycle fields (`occurrence_count`, `last_seen_at`, `last_reviewed_at`, `review_verdict`, `review_note`, `recommended_move`, `why_now`, `due_at`, `superseded_count`, `suggested_workflow`), and `decision_instance_id` (set only when the proposal is backed by a decision-ledger row — a calendar booking awaiting approval). The UI splits them into 'mine' vs 'across the team' using `caller_person_id`. For decision-backed proposals the card's Approve/Reject call the `/decisions` endpoints (which book or cancel the event server-side and clear the alert) instead of the ack-and-hand-off-to-chat flow — so meeting bookings are reviewed in the briefing itself rather than on a separate page.\n- **`narrative`** — a per-viewer Executive-voice header synthesized by `synthesize_briefing_narrative`; the principal gets the whole-company scope, teammates a role-scoped one. In the web UI each bullet of this narrative is a click target: clicking one hands off to chat (the same `onContinue` path as the proposal cards) seeded to discuss that item. The Executive recognizes it because every chat turn now carries a `<briefing>` digest of open alerts (see Memory). That digest (`briefing.context.format_open_alerts_for_prompt`) is capped at 30 items; when the board is longer the header says so explicitly and tells the Executive to point at this page for the rest — it previously presented the capped list as the complete board, so the Executive described a slice as everything that was open (#136). Chat adapters get the digest too, but Slack gates it to the principal's DMs: the board is company-wide and must not be pulled into a shared channel. The `[alert_id]` at the start of each line is also what `ack_alert` trusts, because an id quoted inside an alert's own body came from inbound mail or chat and is attacker-controlled. This page's `[Discuss mode — alert_id=N]` handoff primer is a pointer to which item is under discussion, not authority on its own: the server accepts it only if that id is on the live board too. Two things enforce that. Every field the digest interpolates — headline, body, suggested action, tags, review note — is collapsed to a single line, since a newline in any of them would forge a whole extra `[N]` line and with it a fabricated instruction to clear someone else's alert. And the server records the live board it derived, so `ack_alert` refuses any id outside it — on **every** session, not just the chat adapters. The recorded set is the whole live board, not just the rows the digest printed, so a card past the render cap stays ackable. The control stops invented, closed, snoozed and expired ids; it does not stop the model being argued into acking the wrong *live* card. That check used to run only when `origin_channel` was set, which the browser never sets, so the one surface where the principal actually reads their board had no check at all and the model could ack any id, including one quoted out of an alert body by the Discuss handoff. Rendering the block and recording its ids now happen together in `briefing.context.render_and_trust`, which both the web chat route and the channel adapters call: render without recording and the tool refuses everything, record without rendering and the model gets reach it was never shown. A turn that was shown nothing trusts nothing. The digest also carries a short **already handled** tail — recently acked / dismissed / resolved rows, named but deliberately NOT trusted for acking — because a card cleared on the page minutes ago is otherwise simply absent from chat: asked to \"record that as fixed\", the Executive could not tell a settled item from one it had never heard of, and sent the principal back to dismiss a card that was already gone. That tail renders even when nothing is open, which is exactly when it matters. Note it is a different window from the `handled_overnight` rail above: that one runs since the last delivered morning brief, while the chat tail looks back 14 days (matching the action-alert TTL, so it still covers an item cleared late in its life), so chat can name a settled item the rail no longer shows. The narrative is held to what is **live**, and to what it is actually for. The `alert_raised` source is dropped from the activity it reasons over (`_build_activity(..., include_alert_raised=False)`): a closed alert reads as work the principal already settled, and a *live* one is worse than redundant — `lifecycle.is_live` is the very predicate behind `list_live_alerts`, so every live raise is already a proposal card below the header, which the prompt forbids re-listing. The `/today/activity` rail keeps the whole source, because a raise really happened. The activity block is only labelled \"since last brief\" when the caller bounded it with `since` (the standalone briefs do; the header does not), since calling an unbounded history rail a delta made the header present weeks-old rows as overnight news. When the viewer's slice holds nothing that wants a decision — no action proposal, no at-risk/off-track department, nobody awaiting — the regen skips the model call entirely and writes the fixed quiet line (`Quiet right now — nothing pressing.`, or `… nothing needs you.` for a teammate). **The cache key is a hash of the rendered context itself** (`today._narrative_context` builds it once and both the hot path and the background task key off that one string, which is also handed to the model verbatim). That makes the key a function of the model's input: everything the prompt renders is covered, and nothing it omits can trigger a regeneration. Keying on hand-picked fields broke one half or the other each time — headlines alone left the rendered activity block uncovered, while the proposals' review fields are never rendered by this header yet are rewritten with fresh prose by every `alerts.review` pass, so they regenerated each viewer's narrative several times a day to re-synthesize identical input. A quiet board keys off a fixed sentinel instead, so a moving rail cannot re-key an entry whose text is constant. Together: on a fully dismissed board every other input was empty, the rail became the only context, and the model synthesized a confident header out of closed items.\n- **`in_flight`** / **`awaiting`** — upcoming Executive commitments and people we are waiting on.\n- **`handled_overnight`** — the autonomous moves the Executive *completed* since the last delivered morning brief: the alert review's (routed, nudged, escalated, drafted, merged, closed) plus the research watch policy's (`watching` — a watch added on its own because it was grounded in company data; `stopped_watching` — a research watch auto-disabled as noisy or dead; no alert id, re-enable from `/watchlist`). A `changed` verdict (the review rewrote an open alert's headline / body / severity) is deliberately **not** here: the alert is still open in \"Needs you\" and its card carries the note, so the brief reports it under \"what changed\" (a REWRITTEN block) rather than as done. Each row is structured, not just a sentence: `kind`, the audit `summary` (nudge bookkeeping marker stripped), `at`, `alert_id`, `event_type` (for a pre-filtered `/audit` deep link), `headline` (the alert's headline at move time; a watch's slug), `target` (person name for routed / nudged, survivor headline for merged, new severity for escalated, draft title, workflow name), `detail` (the cited evidence or the watch policy's reason), `outcome` (`resolved` | `dismissed` for a close, `proposed` for a route that went through the authority gate), `evidence_ref` (S1 / R2 / A3), `superseded_by_alert_id`, and `status` — the alert's lifecycle state **now** (`open` = live in the queue per `lifecycle.is_live` | `resolved` | `dismissed` | `expired` | `merged` | `acked` | `inactive` for snoozed / past-TTL rows), looked up per row so a close the principal already undid renders as reopened instead of offering a second Undo, and a \"still open\" jump link only appears when there is a card to land on. The morning brief also carries a one-line count of research watch suggestions waiting on `/watchlist`.\n\nThe route resolves the caller from `x-caller-email`, then attaches the viewer-scoped narrative in a `BackgroundTask` so the request never blocks on an LLM call. `GET /today/activity` returns the recent self-initiated action rail — merged from fired scheduled actions (DMs, follow-ups, nudges, cadences), logged decisions, saved advice, completed workflow runs (briefings/check-ins/research), kicked-off initiatives, resolved gated decisions, and raised alerts, so it reflects all of the Executive's activity rather than just dispatched messages. The Pulse page (`/memories`) polls it (limit 100) every ~20s so new events stream into the 'Recent activity' card, which scrolls internally at a fixed height instead of growing the page. The `morning_brief` workflow calls `_build_today()` directly to build the standalone DM (via a different, enumerated prompt). `GET /morning-brief` is a deprecated alias.\n\n## Alert lifecycle & the Executive review\n\nAlerts used to be write-once: raised, then never looked at again, so the \"Needs you\" queue grew without bound and the briefs re-listed it daily. Three things now keep it live:\n\n- **Time-to-live** (`openexecutive.alerts.lifecycle`). Action items expire after `ALERT_TTL_DAYS_ACTION` (14 d), unrouted low/medium monitoring signals after `ALERT_TTL_DAYS_MONITORING` (3 d). Every surface reads `list_live_alerts` (the same predicate the scheduler's 15-minute sweep persists as status `expired`), so `/today` is right even before the sweep runs. Artifacts and decision-backed alerts are exempt. `POST /alerts/{id}/reopen` is the Undo.\n- **Coalescing** (`alerts.pipeline` + `store.coalesce_alert`). A repeat of an open alert with the same `(source, dedup_key)` updates that row — `occurrence_count`, `last_seen_at`, severity max — instead of stacking a second card, and only re-pings when severity rose to high/urgent. Monitoring alerts carry a stable `watch:<slug>` key, so one watch means one card.\n- **The review** (`openexecutive.alerts.review`, heartbeat `alert_review_scan`, every 6 h and right before the morning brief). For each open alert the Executive sees what changed since it was raised — newer signals from the same watch, related alerts, activity since, the roster with SLAs, department authority — and returns a verdict (relevant / changed / resolved / stale) plus a recommended move. Deterministic policy then acts: **route** (assign + DM the owner; `propose_via_alert` for propose-only departments), **nudge**, **escalate** (severity + `due_at` + DM the principal only), **draft** (`draft_artifact`), **suggest a workflow** (a link, never a run), **merge** (`superseded_by_alert_id`), or **resolve** — only on high confidence citing a server-minted evidence ref (a newer signal, a related alert, an activity item shown for that alert); free text never closes a card, and anything weaker is annotated `likely_stale`, demoted 30 ranking points, and left for one click. Everything that came from outside is rendered as inert data inside the review prompt, so an injected email body cannot steer the batch. Board / comp / legal matters only ever go to a scope-holder or the principal and keep their text. Route and escalate are idempotent across passes, every DM carries an \"[Alert review] Re: …\" header, outbound moves are capped per pass, passes are single-flight, `ALERT_REVIEW_ENABLED=false` stops every caller, every move is audited with its evidence and prior state, and a distinct `resolved` status keeps Executive closes separate from `ack` (user approved).\n\nOn the page, cards read as decisions: the one-line \"what changed since you last looked\" (`review_note`) leads, the recommended move is the primary control (Nudge <owner> → chat; Run <workflow> → `/jobs/<name>`), with chips for age, seen ×N, why-now / due, folded-in and draft-ready, a \"Reviewed <ago>\" footer, and an amber Likely-stale treatment with one-click Dismiss. \"Needs you\" shows *Start here* + 8 cards + \"Show N more\", a \"Dismiss N older than 7 days\" footer (explicit ids to `POST /alerts/bulk-ack` — never a server-side age sweep, which would hit teammates' routed items), and \"Re-check relevance\" (`POST /alerts/review`). The handled rail (anchor of the \"Executive handled N overnight\" pill) is deliberately one sentence by default: a first-person heading built from counts only — \"Since your last brief: N off your plate (closes still standing, and merges whose survivor is not itself listed; a merge into a listed survivor counts on that survivor's row), N in others' hands (routed / nudged), N waiting on you (escalated)\", plus \"N drafts ready\", \"N workflows suggested\", \"N watch changes\", \"N other moves\" (a kind the UI does not know) and \"N back on your plate\" (a close that is open again) when present — with the rows behind a \"details\" disclosure, and nothing rendered at all when the grouped rows are empty. The pure logic (grouping, headline, links) lives in `packages/ui/src/lib/handled.ts` and is covered by `npm test`. Expanded, it shows one first-person row per alert (\"Resolved *X* — evidence\", \"Dismissed *X* as stale — evidence\", \"Handed *X* to Dana Kim\" / \"Proposed *X* to Dana Kim (awaiting their approval)\", \"Chased Dana Kim on *X*\", \"Raised *X* to high\", \"Drafted *T* from *X*\", \"Folded *X* into *Y*\", \"Started watching *slug*\"), escalations first; rows sharing an alert collapse to the newest move with the others as an \"also …\" trailer — a close always keeps the visible slot (it carries Undo), otherwise an escalation beats routed / nudged / drafted; a merge whose survivor is listed becomes \"N duplicates folded in\" on the survivor. Every row links its `evidence_ref` (or \"evidence\") to `/audit?event_type=…&q=…` (the audit page pre-fills those filters from the query string), a still-open row jumps to its card (`#alert-<id>`), drafted rows link `/artifacts`, watch rows `/watchlist`. Undo is offered only while the close still stands (`status` not `open`); a reverted close shows \"Reopened\". Dismissing a watch-sourced alert lowers that watch's `trust_score` (which discounts ranking and is shown to the review as evidence); the ack body may carry `mute_topic`.\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>`).\n\n`GET /today` returns `TodayResponse` assembled by `_build_today()`, which is synchronous and caller-agnostic:\n\n- **`departments`** — per-department goal health, rolling up each department's goal counts (`total`, `at_risk`, `off_track`) plus its awaiting-workflow count, and `attention_goals`: the actual off-track/at-risk goals (worst first, capped at 3) with `key_result`, `current`, `target`, and `status`, so the briefing's Department card shows *which* goal is off and how far without a click. Empty for healthy/inactive departments.\n- **`people`** — an attention-ranked roster. Each person carries `awaiting_action` count, soonest SLA, a `status` (`on_leave` / `needs_reply` / `awaiting` / `clear`), reachability, `overdue`, a server `priority` sort key, and a cached one-line `insight`. Sorted by `(-priority, full_name)`.\n- **`proposals`** — the *live* unread alerts (workflow approvals, triage-classified inbound, Executive signals, flagged artifacts, and gated calendar bookings): unread, inside their category TTL, not snoozed — see *Alert lifecycle* below. Each carries `score`, `category` (`action` vs `monitoring`), `surfaced_reason` from `openexecutive.briefing.ranking`, the lifecycle fields (`occurrence_count`, `last_seen_at`, `last_reviewed_at`, `review_verdict`, `review_note`, `recommended_move`, `why_now`, `due_at`, `superseded_count`, `suggested_workflow`), and `decision_instance_id` (set only when the proposal is backed by a decision-ledger row — a calendar booking awaiting approval). The UI splits them into 'mine' vs 'across the team' using `caller_person_id`. For decision-backed proposals the card's Approve/Reject call the `/decisions` endpoints (which book or cancel the event server-side and clear the alert) instead of the ack-and-hand-off-to-chat flow — so meeting bookings are reviewed in the briefing itself rather than on a separate page.\n- **`narrative`** — a per-viewer Executive-voice header synthesized by `synthesize_briefing_narrative`; the principal gets the whole-company scope, teammates a role-scoped one. In the web UI each bullet of this narrative is a click target: clicking one hands off to chat (the same `onContinue` path as the proposal cards) seeded to discuss that item. The Executive recognizes it because every chat turn now carries a `<briefing>` digest of open alerts (see Memory). That digest (`briefing.context.format_open_alerts_for_prompt`) is capped at 30 items; when the board is longer the header says so explicitly and tells the Executive to point at this page for the rest — it previously presented the capped list as the complete board, so the Executive described a slice as everything that was open (#136). Chat adapters get the digest too, but Slack gates it to the principal's DMs: the board is company-wide and must not be pulled into a shared channel. The `[alert_id]` at the start of each line is also what `ack_alert` trusts, because an id quoted inside an alert's own body came from inbound mail or chat and is attacker-controlled. This page's `[Discuss mode — alert_id=N]` handoff primer is a pointer to which item is under discussion, not authority on its own: the server accepts it only if that id is on the live board too. Two things enforce that. Every field the digest interpolates — headline, body, suggested action, tags, review note — is collapsed to a single line, since a newline in any of them would forge a whole extra `[N]` line and with it a fabricated instruction to clear someone else's alert. And the server records the live board it derived, so `ack_alert` refuses any id outside it — on **every** session, not just the chat adapters. The recorded set is the whole live board, not just the rows the digest printed, so a card past the render cap stays ackable. The control stops invented, closed, snoozed and expired ids; it does not stop the model being argued into acking the wrong *live* card. That check used to run only when `origin_channel` was set, which the browser never sets, so the one surface where the principal actually reads their board had no check at all and the model could ack any id, including one quoted out of an alert body by the Discuss handoff. Rendering the block and recording its ids now happen together in `briefing.context.render_and_trust`, which both the web chat route and the channel adapters call: render without recording and the tool refuses everything, record without rendering and the model gets reach it was never shown. A turn that was shown nothing trusts nothing. Recording it is only half the wiring: the tool reads the board off the turn's session through a ContextVar, and the chat route binds that session for the whole SSE body (`set_session`, next to `set_turn`). Bound from inside the Executive's own generator instead, it survives exactly one stream step — `asyncio.wait_for` runs each step in a fresh Task with a copy of the context — and the tool-call loop, which runs later, sees nothing. That shipped, and every web ack was refused on cards that were open the whole time. The digest also carries a short **already handled** tail — recently acked / dismissed / resolved rows, named but deliberately NOT trusted for acking — because a card cleared on the page minutes ago is otherwise simply absent from chat: asked to \"record that as fixed\", the Executive could not tell a settled item from one it had never heard of, and sent the principal back to dismiss a card that was already gone. That tail renders even when nothing is open, which is exactly when it matters. Note it is a different window from the `handled_overnight` rail above: that one runs since the last delivered morning brief, while the chat tail looks back 14 days (matching the action-alert TTL, so it still covers an item cleared late in its life), so chat can name a settled item the rail no longer shows. The narrative is held to what is **live**, and to what it is actually for. The `alert_raised` source is dropped from the activity it reasons over (`_build_activity(..., include_alert_raised=False)`): a closed alert reads as work the principal already settled, and a *live* one is worse than redundant — `lifecycle.is_live` is the very predicate behind `list_live_alerts`, so every live raise is already a proposal card below the header, which the prompt forbids re-listing. The `/today/activity` rail keeps the whole source, because a raise really happened. The activity block is only labelled \"since last brief\" when the caller bounded it with `since` (the standalone briefs do; the header does not), since calling an unbounded history rail a delta made the header present weeks-old rows as overnight news. When the viewer's slice holds nothing that wants a decision — no action proposal, no at-risk/off-track department, nobody awaiting — the regen skips the model call entirely and writes the fixed quiet line (`Quiet right now — nothing pressing.`, or `… nothing needs you.` for a teammate). **The cache key is a hash of the rendered context itself** (`today._narrative_context` builds it once and both the hot path and the background task key off that one string, which is also handed to the model verbatim). That makes the key a function of the model's input: everything the prompt renders is covered, and nothing it omits can trigger a regeneration. Keying on hand-picked fields broke one half or the other each time — headlines alone left the rendered activity block uncovered, while the proposals' review fields are never rendered by this header yet are rewritten with fresh prose by every `alerts.review` pass, so they regenerated each viewer's narrative several times a day to re-synthesize identical input. A quiet board keys off a fixed sentinel instead, so a moving rail cannot re-key an entry whose text is constant. Together: on a fully dismissed board every other input was empty, the rail became the only context, and the model synthesized a confident header out of closed items.\n- **`in_flight`** / **`awaiting`** — upcoming Executive commitments and people we are waiting on.\n- **`handled_overnight`** — the autonomous moves the Executive *completed* since the last delivered morning brief: the alert review's (routed, nudged, escalated, drafted, merged, closed) plus the research watch policy's (`watching` — a watch added on its own because it was grounded in company data; `stopped_watching` — a research watch auto-disabled as noisy or dead; no alert id, re-enable from `/watchlist`). A `changed` verdict (the review rewrote an open alert's headline / body / severity) is deliberately **not** here: the alert is still open in \"Needs you\" and its card carries the note, so the brief reports it under \"what changed\" (a REWRITTEN block) rather than as done. Each row is structured, not just a sentence: `kind`, the audit `summary` (nudge bookkeeping marker stripped), `at`, `alert_id`, `event_type` (for a pre-filtered `/audit` deep link), `headline` (the alert's headline at move time; a watch's slug), `target` (person name for routed / nudged, survivor headline for merged, new severity for escalated, draft title, workflow name), `detail` (the cited evidence or the watch policy's reason), `outcome` (`resolved` | `dismissed` for a close, `proposed` for a route that went through the authority gate), `evidence_ref` (S1 / R2 / A3), `superseded_by_alert_id`, and `status` — the alert's lifecycle state **now** (`open` = live in the queue per `lifecycle.is_live` | `resolved` | `dismissed` | `expired` | `merged` | `acked` | `inactive` for snoozed / past-TTL rows), looked up per row so a close the principal already undid renders as reopened instead of offering a second Undo, and a \"still open\" jump link only appears when there is a card to land on. The morning brief also carries a one-line count of research watch suggestions waiting on `/watchlist`.\n\nThe route resolves the caller from `x-caller-email`, then attaches the viewer-scoped narrative in a `BackgroundTask` so the request never blocks on an LLM call. `GET /today/activity` returns the recent self-initiated action rail — merged from fired scheduled actions (DMs, follow-ups, nudges, cadences), logged decisions, saved advice, completed workflow runs (briefings/check-ins/research), kicked-off initiatives, resolved gated decisions, and raised alerts, so it reflects all of the Executive's activity rather than just dispatched messages. The Pulse page (`/memories`) polls it (limit 100) every ~20s so new events stream into the 'Recent activity' card, which scrolls internally at a fixed height instead of growing the page. The `morning_brief` workflow calls `_build_today()` directly to build the standalone DM (via a different, enumerated prompt). `GET /morning-brief` is a deprecated alias.\n\n## Alert lifecycle & the Executive review\n\nAlerts used to be write-once: raised, then never looked at again, so the \"Needs you\" queue grew without bound and the briefs re-listed it daily. Three things now keep it live:\n\n- **Time-to-live** (`openexecutive.alerts.lifecycle`). Action items expire after `ALERT_TTL_DAYS_ACTION` (14 d), unrouted low/medium monitoring signals after `ALERT_TTL_DAYS_MONITORING` (3 d). Every surface reads `list_live_alerts` (the same predicate the scheduler's 15-minute sweep persists as status `expired`), so `/today` is right even before the sweep runs. Artifacts and decision-backed alerts are exempt. `POST /alerts/{id}/reopen` is the Undo.\n- **Coalescing** (`alerts.pipeline` + `store.coalesce_alert`). A repeat of an open alert with the same `(source, dedup_key)` updates that row — `occurrence_count`, `last_seen_at`, severity max — instead of stacking a second card, and only re-pings when severity rose to high/urgent. Monitoring alerts carry a stable `watch:<slug>` key, so one watch means one card.\n- **The review** (`openexecutive.alerts.review`, heartbeat `alert_review_scan`, every 6 h and right before the morning brief). For each open alert the Executive sees what changed since it was raised — newer signals from the same watch, related alerts, activity since, the roster with SLAs, department authority — and returns a verdict (relevant / changed / resolved / stale) plus a recommended move. Deterministic policy then acts: **route** (assign + DM the owner; `propose_via_alert` for propose-only departments), **nudge**, **escalate** (severity + `due_at` + DM the principal only), **draft** (`draft_artifact`), **suggest a workflow** (a link, never a run), **merge** (`superseded_by_alert_id`), or **resolve** — only on high confidence citing a server-minted evidence ref (a newer signal, a related alert, an activity item shown for that alert); free text never closes a card, and anything weaker is annotated `likely_stale`, demoted 30 ranking points, and left for one click. Everything that came from outside is rendered as inert data inside the review prompt, so an injected email body cannot steer the batch. Board / comp / legal matters only ever go to a scope-holder or the principal and keep their text. Route and escalate are idempotent across passes, every DM carries an \"[Alert review] Re: …\" header, outbound moves are capped per pass, passes are single-flight, `ALERT_REVIEW_ENABLED=false` stops every caller, every move is audited with its evidence and prior state, and a distinct `resolved` status keeps Executive closes separate from `ack` (user approved).\n\nOn the page, cards read as decisions: the one-line \"what changed since you last looked\" (`review_note`) leads, the recommended move is the primary control (Nudge <owner> → chat; Run <workflow> → `/jobs/<name>`), with chips for age, seen ×N, why-now / due, folded-in and draft-ready, a \"Reviewed <ago>\" footer, and an amber Likely-stale treatment with one-click Dismiss. \"Needs you\" shows *Start here* + 8 cards + \"Show N more\", a \"Dismiss N older than 7 days\" footer (explicit ids to `POST /alerts/bulk-ack` — never a server-side age sweep, which would hit teammates' routed items), and \"Re-check relevance\" (`POST /alerts/review`). The handled rail (anchor of the \"Executive handled N overnight\" pill) is deliberately one sentence by default: a first-person heading built from counts only — \"Since your last brief: N off your plate (closes still standing, and merges whose survivor is not itself listed; a merge into a listed survivor counts on that survivor's row), N in others' hands (routed / nudged), N waiting on you (escalated)\", plus \"N drafts ready\", \"N workflows suggested\", \"N watch changes\", \"N other moves\" (a kind the UI does not know) and \"N back on your plate\" (a close that is open again) when present — with the rows behind a \"details\" disclosure, and nothing rendered at all when the grouped rows are empty. The pure logic (grouping, headline, links) lives in `packages/ui/src/lib/handled.ts` and is covered by `npm test`. Expanded, it shows one first-person row per alert (\"Resolved *X* — evidence\", \"Dismissed *X* as stale — evidence\", \"Handed *X* to Dana Kim\" / \"Proposed *X* to Dana Kim (awaiting their approval)\", \"Chased Dana Kim on *X*\", \"Raised *X* to high\", \"Drafted *T* from *X*\", \"Folded *X* into *Y*\", \"Started watching *slug*\"), escalations first; rows sharing an alert collapse to the newest move with the others as an \"also …\" trailer — a close always keeps the visible slot (it carries Undo), otherwise an escalation beats routed / nudged / drafted; a merge whose survivor is listed becomes \"N duplicates folded in\" on the survivor. Every row links its `evidence_ref` (or \"evidence\") to `/audit?event_type=…&q=…` (the audit page pre-fills those filters from the query string), a still-open row jumps to its card (`#alert-<id>`), drafted rows link `/artifacts`, watch rows `/watchlist`. Undo is offered only while the close still stands (`status` not `open`); a reverted close shows \"Reopened\". Dismissing a watch-sourced alert lowers that watch's `trust_score` (which discounts ranking and is shown to the review as evidence); the ack body may carry `mute_topic`.\n\n## Multi-client practice section\n\nIn multi-client practice mode (2+ client slots — see the Client Companies section), the response gains an additive `practice_clients` list: rollup cards for the **parked** clients (overdue follow-ups, awaiting replies, unread alerts, onboarding due soon, renewal countdowns), each stamped with the save point its data reflects. Single-company installs always receive an empty list and the UI renders nothing.",
"mermaid": "flowchart TD\n REQ[\"GET /today\"]\n BUILD[\"_build_today()\"]\n DEPTS[\"departments<br/>(per-dept goal health)\"]\n ROSTER[\"people<br/>(attention-ranked roster)\"]\n PROPS[\"proposals<br/>(unread alerts, routed)\"]\n INFLIGHT[\"in_flight<br/>(pending follow-ups / nudges)\"]\n AWAIT[\"awaiting<br/>(replies we await)\"]\n NARR[\"viewer-scoped narrative (BackgroundTask)\"]\n MB[\"morning_brief workflow\"]\n REQ --> BUILD\n BUILD --> DEPTS\n BUILD --> ROSTER\n BUILD --> PROPS\n BUILD --> INFLIGHT\n BUILD --> AWAIT\n REQ -->|\"resolve caller, attach\"| NARR\n MB -->|\"calls directly for standalone DM\"| BUILD\n class REQ entry\n class BUILD compute\n class DEPTS storage\n class ROSTER storage\n class PROPS storage\n class INFLIGHT storage\n class AWAIT storage\n class NARR compute\n class MB compute",
"generated_at": "2026-09-18T20:28:52.031310+00:00"
}
diff --git a/packages/core/openexecutive/orchestrator/schedule_tools.py b/packages/core/openexecutive/orchestrator/schedule_tools.py
index 979c558e..9d9b98f9 100644
--- a/packages/core/openexecutive/orchestrator/schedule_tools.py
+++ b/packages/core/openexecutive/orchestrator/schedule_tools.py
@@ -16,11 +16,12 @@ so there is no `send_email` wrapper here.
from __future__ import annotations
import base64
+import contextlib
import contextvars
import copy
import json
import logging
-from collections.abc import Awaitable, Callable
+from collections.abc import Awaitable, Callable, Iterator
from datetime import UTC, datetime, timedelta
from typing import Any
@@ -34,6 +35,46 @@ current_session: contextvars.ContextVar[Any] = contextvars.ContextVar(
)
+def set_session(session: Any) -> Iterator[None]:
+ """Bind ``current_session`` for the duration of the ``with`` block.
+
+ Bind this around the *whole* stream, from outside the Executive's async
+ generator — not with a bare ``current_session.set()`` inside it.
+
+ `Executive.stream_chat` does call `current_session.set(session)` at its
+ top, and that is enough for the callers that drive it with a plain
+ ``async for`` (the adapters' `.chat()` wrapper, the CLI, tests). It is NOT
+ enough for the SSE chat route, which drives the generator one step at a
+ time under ``asyncio.wait_for(stream.__anext__(), ...)``. `wait_for` wraps
+ each step in a fresh Task that *copies* the context, so a `set()` made
+ inside the generator mutates a throwaway copy and is gone by the next
+ resume: step one sees the session, every step after it sees ``None``.
+ The tool-call loop runs on those later steps, so every handler reading
+ `current_session` got ``None`` on web — silently.
+
+ That cost a production incident. `ack_alert` reads the turn's trusted
+ alert board off the session; with ``None`` it fell back to an empty set
+ and refused every ack the principal asked for, on the one surface they
+ actually use. The same ``None`` also blanks the `session_id` on
+ `scheduled_actions` rows and disables `schedule_followup`'s
+ seen-channel_refs anti-spam gate, which only fires when it can see a
+ session.
+
+ Save/restore rather than ``Token.reset()``, for the same reason
+ `audit.context.set_turn` does it: the Token variant raises ``ValueError:
+ <Token …> was created in a different Context`` when ``__exit__`` runs in a
+ different Context than ``__enter__`` — exactly what task-hopping SSE
+ drivers produce. Save/restore is Context-independent.
+ """
+ prior = current_session.get()
+ current_session.set(session)
+ try:
+ yield
+ finally:
+ current_session.set(prior)
+
+
def _record_send_to_activity(
*,
channel: str,
@@ -154,15 +195,39 @@ def _record_outbound_context(
"""Persist an outbound→inbound DM linkage so the recipient's reply can be
hydrated with the originating conversation's context.
- Only writes when a live session is active (``current_session`` is set):
- proactive scheduler/cadence sends have no originating conversation to
- reconnect a reply to, so they intentionally create no linkage. Best-effort
- — any failure here must never break the send the caller just completed.
+ Only writes when a live session is active (``current_session`` is set), and
+ not for browser turns. Best-effort — any failure here must never break the
+ send the caller just completed.
+
+ The browser exclusion is deliberate and narrow. This linkage is read back
+ by `inbound_hydration`, which quotes the originating conversation into the
+ turn that handles a recipient's REPLY — a turn whose user content that
+ recipient authored. Until `current_session` was bound for the whole SSE
+ body (see `set_session`) this function never saw a web session at all, so
+ web sends created no linkage; fixing that binding would have switched the
+ flow on for the principal's broadest surface as a silent side effect.
+ Whether the principal's private web conversation may surface that way is a
+ product decision, so it is held here rather than carried in unannounced.
+
+ It is keyed on ``from_web_chat``, NOT on an empty ``origin_channel``.
+ Those are not the same set: ``origin_channel`` names an inbound chat
+ adapter, and the email poller, alert review's outbound session, the CLI,
+ the MCP server, the scheduler and the unattended workflows all leave it
+ empty while legitimately recording linkage — the email path in particular
+ both writes it here and reads it back through `hydrate_user_message`.
+ Keying on the empty string would silently break every one of them.
"""
try:
session = current_session.get()
if session is None:
return
+ # `is True`, not truthiness: only a session that genuinely declares
+ # itself a browser turn suppresses linkage. Duck-typed and mocked
+ # session objects auto-vivify unknown attributes into truthy values,
+ # and silently dropping linkage is the worse failure direction — a
+ # lost reply thread is invisible, an extra row is not.
+ if getattr(session, "from_web_chat", False) is True:
+ return
originating_session_id = getattr(session, "session_id", None)
recipient_person_id = _resolve_recipient_person_id(channel, channel_ref)
from openexecutive.memory.episodic import insert_outbound_context
diff --git a/packages/core/openexecutive/orchestrator/session.py b/packages/core/openexecutive/orchestrator/session.py
index 81d14697..57405329 100644
--- a/packages/core/openexecutive/orchestrator/session.py
+++ b/packages/core/openexecutive/orchestrator/session.py
@@ -25,6 +25,13 @@ class Session:
# channel can resolve it. Inbound vocabulary — see `normalize_channel`.
origin_channel: str = ""
origin_channel_ref: str = ""
+ # True only for a session minted by the web chat route. `origin_channel`
+ # cannot stand in for this: it names an INBOUND CHAT ADAPTER, and the email
+ # poller, alert review, the CLI, the MCP server, the scheduler and the
+ # unattended workflows all leave it empty while being nothing like a
+ # browser turn. Anything that wants to treat browser turns differently has
+ # to ask for them by name.
+ from_web_chat: bool = False
# The rostered Person behind this conversation, when one is resolved. The
# adapters already pass this to `Executive.chat(person_id=...)`; holding it
# on the session too lets tool handlers running mid-turn tell "the approver
diff --git a/packages/core/tests/unit/test_chat_route_alert_trust.py b/packages/core/tests/unit/test_chat_route_alert_trust.py
index 8b43ff99..20d5b016 100644
--- a/packages/core/tests/unit/test_chat_route_alert_trust.py
+++ b/packages/core/tests/unit/test_chat_route_alert_trust.py
@@ -160,3 +160,132 @@ def test_turn_start_clears_a_stale_trusted_set(env: Path, monkeypatch: pytest.Mo
_ = resp.text
assert _only_session().trusted_alert_ids == set()
+
+
+# --------------------------------------------------------------------- #
+# What `ack_alert` actually reads
+#
+# Every test above asserts `session.trusted_alert_ids` — the attribute. That
+# attribute was correct all along. `ack_alert` does not read it directly; it
+# reads `current_session.get()`, and on the SSE path that returned None for
+# every step after the first, so the tool fell back to an empty set and
+# refused every ack. Asserting the attribute cannot see that gap. These drive
+# the real route and assert what the tool resolves, from a LATER stream step.
+# --------------------------------------------------------------------- #
+
+
+def _post_with_tool_call_on_step(
+ step: int, tool_input: dict[str, Any], monkeypatch: pytest.MonkeyPatch
+) -> list[str]:
+ """Drive the real route with a stub that calls `ack_alert` mid-stream.
+
+ `step` is the 0-based yield index the tool call is made from. Step 0 is
+ the only one a `current_session.set()` inside the executive's own
+ generator survives to, so `step >= 1` is what reproduces production.
+ """
+ from openexecutive.orchestrator import executive as exec_mod
+ from openexecutive.orchestrator.schedule_tools import (
+ current_session,
+ handle_ack_alert,
+ )
+
+ results: list[str] = []
+
+ class _ToolCallingExecutive:
+ _THINKING = exec_mod.Executive._THINKING
+
+ def __init__(self, **_kwargs: Any) -> None:
+ pass
+
+ async def stream_chat(self, **kwargs: Any) -> AsyncIterator[str]:
+ # Faithful to the real `Executive.stream_chat`, which binds the
+ # session with a bare `set()` at its top. That is what makes the
+ # bug step-dependent: this binding survives into step 0 and is
+ # discarded with the per-step Task that made it, so step 1 onward
+ # sees None unless the ROUTE bound it from outside.
+ current_session.set(kwargs.get("session"))
+ for i in range(step + 2):
+ if i == step:
+ results.append(await handle_ack_alert(tool_input))
+ yield f"chunk-{i}"
+
+ async def stream_chat_with_committee(self, **kwargs: Any) -> AsyncIterator[str]:
+ async for chunk in self.stream_chat(**kwargs):
+ yield chunk
+
+ monkeypatch.setattr(exec_mod, "Executive", _ToolCallingExecutive)
+ _post()
+ return results
+
+
[email protected]("step", [0, 1, 3])
+def test_ack_alert_resolves_the_session_on_every_stream_step(
+ step: int, env: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """The regression. `_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 bare `current_session.set()`
+ inside the executive's generator is gone by step 1. The tool-call loop
+ runs on those later steps, so on the live tenant every ack the principal
+ asked for was refused with "not among the open items you were shown this
+ turn", on a card that was open the whole time.
+
+ Parametrized over the step deliberately: a test that only ever acked on
+ step 0 passes against the bug.
+ """
+ people_store.upsert_person(full_name="Alex", is_principal=True)
+ live = alert_store.insert_alert(
+ source="email", external_id="live-1", severity="high",
+ headline="Approve the Q3 budget", body="Needs a decision.",
+ db_path=env / "alerts.db",
+ )
+ assert live is not None
+
+ results = _post_with_tool_call_on_step(
+ step, {"alert_id": live, "status": "dismissed"}, monkeypatch
+ )
+
+ assert len(results) == 1
+ assert "error" not in results[0], (
+ f"ack on stream step {step} was refused: {results[0]}"
+ )
+ refreshed = alert_store.get_alert(live, db_path=env / "alerts.db")
+ assert refreshed is not None and refreshed.status == "dismissed"
+
+
+def test_a_closed_alert_is_still_refused_from_a_later_step(
+ env: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """The fix restores reach, it must not widen it: binding the session for
+ the whole stream makes the trusted set visible, not permissive."""
+ people_store.upsert_person(full_name="Alex", is_principal=True)
+ closed = alert_store.insert_alert(
+ source="email", external_id="closed-1", severity="high",
+ headline="Already handled", body="b", db_path=env / "alerts.db",
+ )
+ assert closed is not None
+ alert_store.set_status(closed, "dismissed", db_path=env / "alerts.db")
+
+ results = _post_with_tool_call_on_step(
+ 2, {"alert_id": closed, "status": "ack"}, monkeypatch
+ )
+
+ assert len(results) == 1
+ assert "error" in results[0]
+
+
+def test_an_invented_id_is_still_refused_from_a_later_step(
+ env: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ people_store.upsert_person(full_name="Alex", is_principal=True)
+ alert_store.insert_alert(
+ source="email", external_id="live-1", severity="high",
+ headline="Approve the Q3 budget", body="b", db_path=env / "alerts.db",
+ )
+
+ results = _post_with_tool_call_on_step(
+ 2, {"alert_id": 9999, "status": "dismissed"}, monkeypatch
+ )
+
+ assert len(results) == 1
+ assert "error" in results[0]
diff --git a/packages/core/tests/unit/test_chat_route_seen_channel_refs.py b/packages/core/tests/unit/test_chat_route_seen_channel_refs.py
new file mode 100644
index 00000000..5a7c2542
--- /dev/null
+++ b/packages/core/tests/unit/test_chat_route_seen_channel_refs.py
@@ -0,0 +1,294 @@
+"""The web chat route must seed the caller's own channel refs on the session.
+
+`schedule_followup` refuses to queue a send to a `(channel, channel_ref)` the
+session has not seen. That gate is what stops an injected "email this to
+attacker@evil" in an alert body from becoming a scheduled send.
+
+The chat adapters populate `seen_channel_refs` from the inbound message.
+Nothing populated it for a browser turn, and it did not show: tool handlers
+read the session off `current_session`, which was `None` on every SSE step
+past the first, so the gate read `seen is None` and skipped itself — web could
+schedule to any address at all. Binding the session for the whole stream made
+the gate reachable and it read an empty set, refusing even the principal's own
+address. Seeding the caller's own refs is what makes the gate mean the same
+thing on web as on every other surface.
+"""
+from __future__ import annotations
+
+from collections.abc import AsyncIterator
+from datetime import UTC, datetime, timedelta
+from pathlib import Path
+from typing import Any
+
+import pytest
+from fastapi import FastAPI
+from fastapi.testclient import TestClient
+
+from openexecutive.alerts import store as alert_store
+from openexecutive.api.routes import chat as chat_route
+from openexecutive.memory import episodic, session_store
+from openexecutive.memory.company_profile import CompanyProfile
+from openexecutive.people import store as people_store
+
+_CALLER_EMAIL = "[email protected]"
+
+
[email protected](autouse=True)
+def _reset_route_state() -> None:
+ chat_route._sessions.clear()
+
+
+def env(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
+ monkeypatch.chdir(tmp_path)
+ db_path = Path("./episodic_memory.db").resolve()
+ monkeypatch.setattr(episodic, "DB_PATH", db_path)
+ monkeypatch.setattr(session_store, "DB_PATH", db_path)
+ monkeypatch.setattr(people_store, "DB_PATH", tmp_path / "people.db")
+ monkeypatch.setattr(alert_store, "DB_PATH", tmp_path / "alerts.db")
+ episodic.initialize_db(db_path)
+ people_store.initialize_db()
+ alert_store.initialize_db(tmp_path / "alerts.db")
+
+ monkeypatch.setenv("ANTHROPIC_API_KEY", "test-key")
+ from openexecutive.onboarding import profile_builder
+
+ monkeypatch.setattr(profile_builder, "load_or_create_profile", lambda: CompanyProfile())
+
+ from openexecutive.knowledge import retriever as retriever_mod
+
+ monkeypatch.setattr(retriever_mod, "retrieve", lambda **_: "")
+
+ people_store.upsert_person(
+ full_name="Alex", is_principal=True, email=_CALLER_EMAIL
+ )
+ return tmp_path
+
+
+def _schedule_from_stream_step(
+ channel_ref: str, monkeypatch: pytest.MonkeyPatch
+) -> str:
+ """Drive the real route; call `schedule_followup` from a later stream step."""
+ from openexecutive.orchestrator import executive as exec_mod
+ from openexecutive.orchestrator.schedule_tools import (
+ current_session,
+ handle_schedule_followup,
+ )
+
+ run_at = (datetime.now(UTC) + timedelta(days=1)).isoformat()
+ results: list[str] = []
+
+ class _Stub:
+ _THINKING = exec_mod.Executive._THINKING
+
+ def __init__(self, **_kwargs: Any) -> None:
+ pass
+
+ async def stream_chat(self, **kwargs: Any) -> AsyncIterator[str]:
+ current_session.set(kwargs.get("session"))
+ for i in range(4):
+ if i == 2:
+ results.append(await handle_schedule_followup({
+ "channel": "email",
+ "channel_ref": channel_ref,
+ "run_at": run_at,
+ "intent": "remind me",
+ }))
+ yield f"chunk-{i}"
+
+ async def stream_chat_with_committee(self, **kwargs: Any) -> AsyncIterator[str]:
+ async for chunk in self.stream_chat(**kwargs):
+ yield chunk
+
+ monkeypatch.setattr(exec_mod, "Executive", _Stub)
+ app = FastAPI()
+ app.include_router(chat_route.router)
+ client = TestClient(app)
+ resp = client.post("/chat", json={"message": "remind me tomorrow at 9"})
+ assert resp.status_code == 200
+ _ = resp.text
+ assert len(results) == 1
+ return results[0]
+
+
+def test_caller_can_schedule_to_their_own_address(
+ env: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """"Remind me tomorrow at 9am" — the whole point of the feature."""
+ result = _schedule_from_stream_step(_CALLER_EMAIL, monkeypatch)
+
+ assert "error" not in result, result
+ assert '"status": "scheduled"' in result
+
+
+def test_an_address_the_caller_never_used_is_refused(
+ env: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """Alerts are minted from inbound mail, so an alert body can ask the
+ Executive to schedule a send to an address the principal never chose.
+ Before the session was bound for the whole stream this was ALLOWED on
+ web — the gate saw no session and skipped itself."""
+ result = _schedule_from_stream_step("[email protected]", monkeypatch)
+
+ assert "error" in result
+ assert "not seen in this session" in result
+
+
+def test_the_session_carries_the_callers_refs(
+ env: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ _schedule_from_stream_step(_CALLER_EMAIL, monkeypatch)
+
+ assert len(chat_route._sessions) == 1
+ session = next(iter(chat_route._sessions.values()))
+ assert ("email", _CALLER_EMAIL) in session.seen_channel_refs
+
+
+def test_seeding_survives_an_unresolvable_caller(
+ env: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """A lookup failure must not take down the turn — it just seeds nothing,
+ which leaves the gate at its safe default of refusing."""
+ monkeypatch.setattr(
+ chat_route, "_resolve_caller_person_id", lambda _request: None
+ )
+
+ result = _schedule_from_stream_step(_CALLER_EMAIL, monkeypatch)
+
+ assert "not seen in this session" in result
+
+
+# --------------------------------------------------------------------- #
+# Outbound reply-linkage stays off for web
+#
+# `_record_outbound_context` writes a row so a recipient's REPLY can be
+# hydrated with the originating conversation. `inbound_hydration` quotes that
+# conversation into the turn handling the reply — a turn whose user content
+# the recipient authored. Before the session was bound for the whole stream
+# this never fired on web (the function read `current_session` and got None).
+# Binding it correctly would have switched that on for the principal's
+# broadest surface as a silent side effect. It stays off pending its own
+# decision.
+# --------------------------------------------------------------------- #
+
+
+def _send_from_stream_step(
+ monkeypatch: pytest.MonkeyPatch, *, origin_channel: str = ""
+) -> list[Any]:
+ from openexecutive.orchestrator import executive as exec_mod
+ from openexecutive.orchestrator import schedule_tools
+
+ recorded: list[Any] = []
+ # `_record_outbound_context` imports this inside its own body, so the
+ # module-path patch is the one that takes. Patching a `schedule_tools`
+ # attribute would be dead — the name does not exist there.
+ monkeypatch.setattr(
+ "openexecutive.memory.episodic.insert_outbound_context",
+ lambda **kw: recorded.append(kw),
+ )
+
+ class _Stub:
+ _THINKING = exec_mod.Executive._THINKING
+
+ def __init__(self, **_kwargs: Any) -> None:
+ pass
+
+ async def stream_chat(self, **kwargs: Any) -> AsyncIterator[str]:
+ session = kwargs.get("session")
+ session.origin_channel = origin_channel
+ schedule_tools.current_session.set(session)
+ for i in range(4):
+ if i == 2:
+ schedule_tools._record_outbound_context(
+ channel="email",
+ channel_ref="[email protected]",
+ text="here is the summary",
+ )
+ yield f"chunk-{i}"
+
+ async def stream_chat_with_committee(self, **kwargs: Any) -> AsyncIterator[str]:
+ async for chunk in self.stream_chat(**kwargs):
+ yield chunk
+
+ monkeypatch.setattr(exec_mod, "Executive", _Stub)
+ app = FastAPI()
+ app.include_router(chat_route.router)
+ client = TestClient(app)
+ resp = client.post("/chat", json={"message": "email the vendor"})
+ assert resp.status_code == 200
+ _ = resp.text
+ return recorded
+
+
+def test_a_web_send_records_no_reply_linkage(
+ env: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ assert _send_from_stream_step(monkeypatch) == []
+
+
+ "origin_channel",
+ ["", "slack", "telegram"],
+ ids=["no-adapter-channel", "slack", "telegram"],
+)
+def test_a_non_web_send_still_records_reply_linkage(
+ origin_channel: str, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """The guard must key on `from_web_chat`, not on an empty `origin_channel`.
+
+ `origin_channel` names an INBOUND CHAT ADAPTER. The email poller, alert
+ review's outbound session, the CLI, the MCP server, the scheduler and the
+ unattended workflows all leave it empty while legitimately recording
+ linkage — the email path both writes it here and reads it back through
+ `hydrate_user_message`. An earlier draft of this guard keyed on the empty
+ string and silently broke every one of them; the first parameter here is
+ that regression.
+ """
+ from openexecutive.orchestrator import schedule_tools
+ from openexecutive.orchestrator.session import Session
+
+ recorded: list[Any] = []
+ monkeypatch.setattr(
+ "openexecutive.memory.episodic.insert_outbound_context",
+ lambda **kw: recorded.append(kw),
+ )
+ # Built the way every non-web caller builds it: from_web_chat left False.
+ session = Session(session_id="poller-1", origin_channel=origin_channel)
+ token = schedule_tools.current_session.set(session)
+ try:
+ schedule_tools._record_outbound_context(
+ channel="email", channel_ref="[email protected]", text="fyi",
+ )
+ finally:
+ schedule_tools.current_session.reset(token)
+
+ assert len(recorded) == 1, (
+ f"origin_channel={origin_channel!r} must still record linkage"
+ )
+ assert recorded[0]["originating_session_id"] == "poller-1"
+
+
+def test_a_web_session_is_marked_as_such(env: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ """The guard depends on this flag, so pin that the route sets it."""
+ _schedule_from_stream_step(_CALLER_EMAIL, monkeypatch)
+
+ session = next(iter(chat_route._sessions.values()))
+ assert session.from_web_chat is True
+
+
+def test_a_scheduled_action_from_web_carries_the_session_id(
+ env: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """The other symptom of the unbound session, and the one that made the
+ original incident hard to trace: rows landed with `session_id` NULL, so
+ the audit view could not connect a scheduled send to the turn that asked
+ for it."""
+ from openexecutive.memory.episodic import list_scheduled_actions
+
+ result = _schedule_from_stream_step(_CALLER_EMAIL, monkeypatch)
+ assert "error" not in result, result
+
+ session = next(iter(chat_route._sessions.values()))
+ rows = list_scheduled_actions(db_path=Path("./episodic_memory.db").resolve())
+ assert len(rows) == 1
+ assert rows[0].originating_session_id == session.session_id