AI-powered virtual executive team — a single coherent executive persona backed by 8 specialist agents (FastAPI + Next.js).
Key the narrative cache on the rendered context itself
Rufus83a9cd2f54a2
diff --git a/packages/core/openexecutive/api/routes/today.py b/packages/core/openexecutive/api/routes/today.pyindex d60801bc..93c7c7fd 100644--- a/packages/core/openexecutive/api/routes/today.py+++ b/packages/core/openexecutive/api/routes/today.py@@ -1278,6 +1278,35 @@ def _nothing_needs_attention(today_data: dict[str, Any]) -> bool:return not any(p.get("awaiting_count", 0) for p in today_data.get("people", []))+def _narrative_context(+ today_data: dict[str, Any],+ viewer: PersonBriefItem | None,+ viewer_desc: dict[str, str] | None,+) -> tuple[str, list[dict[str, Any]] | None]:+ """``(context, activity)`` — the exact user turn the model would receive.++ The single source both the cache key and the model call come from, so the+ key can never be computed over something the model did not see.++ On a quiet board it returns `narrative_cache.QUIET_CONTEXT` and no+ activity: the narrative is a fixed line there, so the key must not depend+ on the rail, and building the rail would be wasted work (it is a+ seven-source SQL union) on a request whose answer is a constant.+ """+ from openexecutive.briefing import narrative_cache+ from openexecutive.briefing.narrative import render_briefing_context++ if _nothing_needs_attention(today_data):+ return narrative_cache.QUIET_CONTEXT, None+ activity = _narrative_activity(viewer, viewer_desc)+ context = render_briefing_context(+ period_label=datetime.now(UTC).strftime("%Y-%m-%d"),+ today_data=today_data,+ activity=activity,+ )+ return context, activity++def _attach_narrative(response: TodayResponse,*,@@ -1291,7 +1320,8 @@ def _attach_narrative(scope, today_data, desc, viewer = _narrative_inputs(response, caller_person_id)try:- nhash = narrative_cache.build_narrative_input_hash(today_data, scope=scope)+ context, _activity = _narrative_context(today_data, viewer, desc)+ nhash = narrative_cache.build_narrative_input_hash(context, scope=scope)cached = narrative_cache.get(scope)if cached is not None:response.narrative = cached.narrative_text@@ -1336,18 +1366,20 @@ async def _regen_briefing_narrative("regen; skipping write", expected_scope, scope,)return- activity = _narrative_activity(viewer, viewer_desc)- if _nothing_needs_attention(today_data):+ context, activity = _narrative_context(today_data, viewer, viewer_desc)+ if context == narrative_cache.QUIET_CONTEXT:# Nothing awaits a decision — skip the model call entirely and# write the fixed quiet line. Still cached (below) so the hot path# sees a fresh hash instead of re-scheduling this task forever.text = QUIET_VIEWER if viewer_desc is not None else QUIET_PRINCIPALelse:- period_label = datetime.now(UTC).strftime("%Y-%m-%d")text = await asyncio.wait_for(synthesize_briefing_narrative(- today_data=today_data, activity=activity,- period_label=period_label, viewer=viewer_desc,+ today_data=today_data, activity=activity or [],+ period_label=datetime.now(UTC).strftime("%Y-%m-%d"),+ viewer=viewer_desc,+ # Hand the model the very string that was hashed.+ rendered_context=context,),timeout=25.0,)@@ -1357,7 +1389,7 @@ async def _regen_briefing_narrative(if not text:return- input_hash = narrative_cache.build_narrative_input_hash(today_data, scope=scope)+ input_hash = narrative_cache.build_narrative_input_hash(context, scope=scope)narrative_cache.put(narrative_cache.BriefingNarrative(scope=scope,input_hash=input_hash,diff --git a/packages/core/openexecutive/architecture/architecture-facts.yaml b/packages/core/openexecutive/architecture/architecture-facts.yamlindex bcce1a02..435b9670 100644--- a/packages/core/openexecutive/architecture/architecture-facts.yaml+++ b/packages/core/openexecutive/architecture/architecture-facts.yaml@@ -1465,8 +1465,8 @@ scheduler:today:module: openexecutive.api.routes.todayendpoints:- - "GET /today — JSON aggregation. Returns TodayResponse(departments, people, proposals, narrative, in_flight, awaiting, caller_person_id). `departments` rolls up each department's goal counts (total, at_risk, off_track) and awaiting workflow count, PLUS `attention_goals` — the actual off_track/at_risk Goal rows themselves (worst first, capped at 3), each carrying `key_result`, `current`, `target`, and `status`, so the briefing's Department card is insightful at rest (shows which goal is off and how far) instead of a count you must click into; empty for healthy/inactive departments and additive (older clients ignore it). `people` is an attention-ranked roster: each person carries the original preferred channel, awaiting-action count and soonest SLA PLUS enrichment signals — `status` (on_leave | needs_reply | awaiting | clear), `awaiting_reply_count`/`oldest_awaiting_reply_at` (open scheduled_action commitments we're waiting on THEM to answer, mirroring the nudge engine's awaiting_response_since set), `on_leave_until`, `reachable_now`/`next_window_at` (from people.channel availability windows), `authority_scope`, `department_slugs`, `last_contact_at` (most recent done outbound assigned to them), `overdue` (any SLA or awaited reply past deadline), `priority` (server sort key — overdue replies/work float to top, on-leave sinks), and `insight` (a one-line utility-fast note, see people.insights — null until the background cache warms). Rows are returned sorted by (-priority, full_name). `proposals` is the org-wide set of ALL unread alerts (workflow approvals, triage-classified inbound, Executive-created operational signals, and research artifacts the Executive flagged for review via `draft_artifact` — source=`artifact`, tagged `artifact`, which the UI renders as a Markdown document card rather than a terse proposal — and which also persist into the dedicated Artifacts section (`/artifacts`) so they remain browsable after they leave this unread queue — anything in the alerts table with status='unread'); the UI splits it into 'mine' vs 'across the team' using `caller_person_id` plus a 'principal owns unrouted' rule (alerts with `routed_to_person_id == null` fall to the principal's queue by default). Each proposal also carries presentation signals from `openexecutive.briefing.ranking`: `score` (attention sort key — severity-weighted, with a bonus for routed alerts) and `category` ('action' = a human should look, vs 'monitoring' = passive watchlist/external signals that are unrouted and not high/urgent), plus `surfaced_reason` (a short human note, null for most items) — set only when an external/watchlist signal was pulled into the 'action' lane *by its severity* (the high/urgent escape hatch in `categorize`, e.g. a ≥5% stock move), so the UI can render a per-item explanation of why a normally-Monitoring signal is in 'Needs you'. A proposal also carries `decision_instance_id` (parsed from a `decision_instance:{id}` topic tag), non-null only for gated calendar bookings surfaced from the decision ledger (source=`decision_scheduling`); the UI routes those cards' Approve/Reject to the /decisions endpoints (which book or cancel server-side and clear this alert) instead of the ack-and-hand-off-to-chat flow, so meeting bookings are reviewed in the briefing itself (the standalone proposals page was removed). `_build_today` sorts action items first (by score), monitoring last; the UI collapses the 'monitoring' tail into a separate section so it stops crowding the 'Needs you' queue. `narrative` is a PER-VIEWER Executive-voice 'what's going on' header (see `openexecutive.briefing.narrative` + `today._attach_narrative`). It is a SYNTHESIS, not a re-list: the actionable items render as cards below it, so the narrative gives the connective tissue a list can't (how items relate, what's most urgent and why, the single recommended focus) and deliberately does NOT enumerate a 'Needs you' section that would duplicate the cards. The principal and any unrostered/unresolved caller get the whole-company synthesis (cache scope `principal`) over ALL action-category proposals (mine + across the team; monitoring/watchlist noise is excluded) plus company-wide at-risk depts + activity; each non-principal teammate gets a role-scoped synthesis (cache scope `person:<id>`) over ONLY the action items routed to them + their departments' goal health + their department activity, written in their perspective. Synthesized by `synthesize_briefing_narrative`, which also produces the standalone morning_brief DM but via a DIFFERENT prompt (`standalone=True` → an enumerated brief with a 'Needs you' section, since the DM has no cards beside it to carry the list; the EoD digest still has its own prompt); the /today header path uses the synthesis prompt and never re-lists. Served from the per-scope `briefing_narrative` cache (`openexecutive.briefing.narrative_cache`, keyed by a hash of the viewer's scoped state + the activity rows the narrative reasons over + scope + UTC date + `NARRATIVE_PROMPT_VERSION`, the last so a prompt rewrite invalidates every cached narrative on the next view). Activity is deliberately NOT in the hash: the 20-row rail moves on almost every DM, decision, advice row and completed workflow, so hashing it regenerates every viewer's narrative — one model call each — on nearly any Executive action, with no floor. The hash instead tracks each proposal's review fields (review_verdict / review_note / why_now / recommended_move / due_at) beside its headline, because the review rewrites those IN PLACE while keeping the headline, which is the staleness that actually changes what the header would say. The narrative's activity is built with `include_alert_raised=False`, dropping that source entirely: closed alerts read as settled work, and live ones are already the proposal cards (`is_live` IS the `list_live_alerts` predicate) that the header prompt forbids re-listing — the `/today/activity` rail keeps them. It is a source opt-out rather than a post-pull filter so `recent_alerts` cannot burn its pool on closed rows. `render_briefing_context` only labels that block 'SINCE LAST BRIEF' when the caller bounded it with `since`; an unbounded rail is labelled 'RECENT OE ACTIVITY' and explicitly marked as not a delta. When the viewer's slice has no action proposal, no at-risk/off-track department and nobody awaiting, the regen writes a fixed quiet line and spends NO model call — that, not the hash, is what keeps a frozen header from recurring. Together these stop a fully-dismissed board from yielding a confident header synthesized entirely out of closed items. Served from cache on the hot path and regenerated per-viewer in a FastAPI BackgroundTask when that viewer's hash moves; null on a cold cache. `in_flight` is the Executive's upcoming user-facing commitments — pending scheduled_actions (follow-ups, nudges) from `episodic.list_pending_scheduled_actions` (excludes the `__internal__` channel and `nudge_scan` heartbeat, the same set the activity feed hides), each with the resolved recipient `target` (person name via the shared channel→name lookup, or department/raw ref), `kind`, `run_at`, and `overdue` (run_at already passed). `awaiting` is the people we're waiting on a reply from, derived from the same open-commitment set behind each person's `awaiting_reply_count` (name, role, count, oldest_at, overdue), sorted most-overdue/oldest first. Together they power the briefing's 'In flight' section so cross-team work in progress is visible without opening the Scheduled Actions page. Both are additive and default to empty. `caller_person_id` is the signed-in caller resolved from `x-caller-email` via chat._resolve_caller_person_id; null when no caller could be resolved (unrostered signed-in user, or a CLI hit without the header). The route is async: it serves insight notes from the person_insights cache and, after resolving the caller, attaches the viewer-scoped narrative via `_attach_narrative`, scheduling regeneration of stale entries as FastAPI BackgroundTasks so the request never blocks on an LLM call. `_build_today()` stays synchronous and caller-agnostic — no insight regen and NO narrative (that is attached per-viewer by the endpoints) — for the morning_brief workflow and the deprecated /morning-brief alias that call it directly; the alias resolves the caller and serves the cached narrative but cannot schedule a regen."- - "GET /today/activity?limit=N — Returns ActivityResponse(items). Each item is one recent self-initiated Executive action — a fired scheduled_action (DM dispatched, follow-up fired, cadence run, paused workflow resumed) or an extracted decision/advice row. Items carry `kind` (coarse classifier the UI maps to verb + icon — dm_sent, email_sent, nudge_sent, cadence_sent, workflow_resumed, proposal_routed, decision_logged, advice_given, workflow_done, initiative_started, decision_resolved, alert_raised, or action for unclassified), `summary`, `actor` (always Executive for now), `target` (channel ref / person, or null), `department`, and `at` (ISO timestamp). Sources merged — `scheduled_actions` with status=done (excluding `nudge_scan` heartbeat and `__internal__` channel), `decisions`, `advice_given`, completed `workflow_runs` (status=done — briefings/check-ins/research, bucketed at `updated_at`), `initiatives` (kicked-off projects, at `created_at`), resolved `decision_instances` (terminal gated-decision outcomes — approved/rejected/reversed, at `resolved_at`; pending ones stay in `proposals`, not the rail), and `alerts` raised (excluding source=`decision_scheduling`, which is the companion alert for a gated booking already represented by its `decision_resolved` row). `_build_activity(..., include_alert_raised=False)` omits this source entirely; the rail never passes it (history is the point there), the briefing narrative always does. This broadens the feed beyond the original messaging-heavy three sources so it reflects all self-initiated Executive activity, not just dispatched messages. Actions on `propose_only` departments are reclassified to `proposal_routed` because the runner marks them done without dispatching (the proposal is surfaced via /today's `proposals` field; the activity rail shows it as 'proposed to <approver>' rather than implying a DM was sent). Sorted by `at DESC`, then capped at `limit` (default 20, clamped to 1..100 via FastAPI Query validation — 422 on out-of-range). The Pulse page polls this endpoint (limit=100) every ~20s so new activity streams into the 'Recent activity' card without a reload; the card scrolls internally at a fixed max-height rather than growing the page."+ - "GET /today — JSON aggregation. Returns TodayResponse(departments, people, proposals, narrative, in_flight, awaiting, caller_person_id). `departments` rolls up each department's goal counts (total, at_risk, off_track) and awaiting workflow count, PLUS `attention_goals` — the actual off_track/at_risk Goal rows themselves (worst first, capped at 3), each carrying `key_result`, `current`, `target`, and `status`, so the briefing's Department card is insightful at rest (shows which goal is off and how far) instead of a count you must click into; empty for healthy/inactive departments and additive (older clients ignore it). `people` is an attention-ranked roster: each person carries the original preferred channel, awaiting-action count and soonest SLA PLUS enrichment signals — `status` (on_leave | needs_reply | awaiting | clear), `awaiting_reply_count`/`oldest_awaiting_reply_at` (open scheduled_action commitments we're waiting on THEM to answer, mirroring the nudge engine's awaiting_response_since set), `on_leave_until`, `reachable_now`/`next_window_at` (from people.channel availability windows), `authority_scope`, `department_slugs`, `last_contact_at` (most recent done outbound assigned to them), `overdue` (any SLA or awaited reply past deadline), `priority` (server sort key — overdue replies/work float to top, on-leave sinks), and `insight` (a one-line utility-fast note, see people.insights — null until the background cache warms). Rows are returned sorted by (-priority, full_name). `proposals` is the org-wide set of ALL unread alerts (workflow approvals, triage-classified inbound, Executive-created operational signals, and research artifacts the Executive flagged for review via `draft_artifact` — source=`artifact`, tagged `artifact`, which the UI renders as a Markdown document card rather than a terse proposal — and which also persist into the dedicated Artifacts section (`/artifacts`) so they remain browsable after they leave this unread queue — anything in the alerts table with status='unread'); the UI splits it into 'mine' vs 'across the team' using `caller_person_id` plus a 'principal owns unrouted' rule (alerts with `routed_to_person_id == null` fall to the principal's queue by default). Each proposal also carries presentation signals from `openexecutive.briefing.ranking`: `score` (attention sort key — severity-weighted, with a bonus for routed alerts) and `category` ('action' = a human should look, vs 'monitoring' = passive watchlist/external signals that are unrouted and not high/urgent), plus `surfaced_reason` (a short human note, null for most items) — set only when an external/watchlist signal was pulled into the 'action' lane *by its severity* (the high/urgent escape hatch in `categorize`, e.g. a ≥5% stock move), so the UI can render a per-item explanation of why a normally-Monitoring signal is in 'Needs you'. A proposal also carries `decision_instance_id` (parsed from a `decision_instance:{id}` topic tag), non-null only for gated calendar bookings surfaced from the decision ledger (source=`decision_scheduling`); the UI routes those cards' Approve/Reject to the /decisions endpoints (which book or cancel server-side and clear this alert) instead of the ack-and-hand-off-to-chat flow, so meeting bookings are reviewed in the briefing itself (the standalone proposals page was removed). `_build_today` sorts action items first (by score), monitoring last; the UI collapses the 'monitoring' tail into a separate section so it stops crowding the 'Needs you' queue. `narrative` is a PER-VIEWER Executive-voice 'what's going on' header (see `openexecutive.briefing.narrative` + `today._attach_narrative`). It is a SYNTHESIS, not a re-list: the actionable items render as cards below it, so the narrative gives the connective tissue a list can't (how items relate, what's most urgent and why, the single recommended focus) and deliberately does NOT enumerate a 'Needs you' section that would duplicate the cards. The principal and any unrostered/unresolved caller get the whole-company synthesis (cache scope `principal`) over ALL action-category proposals (mine + across the team; monitoring/watchlist noise is excluded) plus company-wide at-risk depts + activity; each non-principal teammate gets a role-scoped synthesis (cache scope `person:<id>`) over ONLY the action items routed to them + their departments' goal health + their department activity, written in their perspective. Synthesized by `synthesize_briefing_narrative`, which also produces the standalone morning_brief DM but via a DIFFERENT prompt (`standalone=True` → an enumerated brief with a 'Needs you' section, since the DM has no cards beside it to carry the list; the EoD digest still has its own prompt); the /today header path uses the synthesis prompt and never re-lists. Served from the per-scope `briefing_narrative` cache (`openexecutive.briefing.narrative_cache`, keyed by a hash of the viewer's scoped state + the activity rows the narrative reasons over + scope + UTC date + `NARRATIVE_PROMPT_VERSION`, the last so a prompt rewrite invalidates every cached narrative on the next view). The key is a hash of the RENDERED context string itself (`today._narrative_context` builds it once; the hot path hashes it, the background task hands that same string to the model as `rendered_context`). So the key is a function of the model's input: everything the prompt renders is covered, nothing it omits can cause a regeneration, and both properties survive edits to `render_briefing_context` with no field list to maintain. Hand-picked field lists broke one half or the other each time — proposal headlines alone left the rendered activity block uncovered (the header then described a rail that had moved on), while the proposals' review fields (review_verdict / review_note / why_now / recommended_move / due_at) are NEVER rendered by this header (the `since is None` branch prints headline[:160] and nothing else) yet `alerts.review` rewrites them with fresh LLM prose on every pass INCLUDING its 'still relevant, nothing changed' path, so keying on them regenerated every viewer's narrative several times a day to re-synthesize byte-identical input. A quiet board keys off the fixed `narrative_cache.QUIET_CONTEXT` sentinel and builds no activity at all, so a moving rail cannot re-key an entry whose text is a constant. The narrative's activity is built with `include_alert_raised=False`, dropping that source entirely: closed alerts read as settled work, and live ones are already the proposal cards (`is_live` IS the `list_live_alerts` predicate) that the header prompt forbids re-listing — the `/today/activity` rail keeps them. It is a source opt-out rather than a post-pull filter so `recent_alerts` cannot burn its pool on closed rows. `render_briefing_context` only labels that block 'SINCE LAST BRIEF' when the caller bounded it with `since`; an unbounded rail is labelled 'RECENT OE ACTIVITY' and explicitly marked as not a delta. When the viewer's slice has no action proposal, no at-risk/off-track department and nobody awaiting, the regen writes a fixed quiet line and spends NO model call — that, not the hash, is what keeps a frozen header from recurring. Together these stop a fully-dismissed board from yielding a confident header synthesized entirely out of closed items. Served from cache on the hot path and regenerated per-viewer in a FastAPI BackgroundTask when that viewer's hash moves; null on a cold cache. `in_flight` is the Executive's upcoming user-facing commitments — pending scheduled_actions (follow-ups, nudges) from `episodic.list_pending_scheduled_actions` (excludes the `__internal__` channel and `nudge_scan` heartbeat, the same set the activity feed hides), each with the resolved recipient `target` (person name via the shared channel→name lookup, or department/raw ref), `kind`, `run_at`, and `overdue` (run_at already passed). `awaiting` is the people we're waiting on a reply from, derived from the same open-commitment set behind each person's `awaiting_reply_count` (name, role, count, oldest_at, overdue), sorted most-overdue/oldest first. Together they power the briefing's 'In flight' section so cross-team work in progress is visible without opening the Scheduled Actions page. Both are additive and default to empty. `caller_person_id` is the signed-in caller resolved from `x-caller-email` via chat._resolve_caller_person_id; null when no caller could be resolved (unrostered signed-in user, or a CLI hit without the header). The route is async: it serves insight notes from the person_insights cache and, after resolving the caller, attaches the viewer-scoped narrative via `_attach_narrative`, scheduling regeneration of stale entries as FastAPI BackgroundTasks so the request never blocks on an LLM call. `_build_today()` stays synchronous and caller-agnostic — no insight regen and NO narrative (that is attached per-viewer by the endpoints) — for the morning_brief workflow and the deprecated /morning-brief alias that call it directly; the alias resolves the caller and serves the cached narrative but cannot schedule a regen."+ - "GET /today/activity?limit=N — Returns ActivityResponse(items). Each item is one recent self-initiated Executive action — a fired scheduled_action (DM dispatched, follow-up fired, cadence run, paused workflow resumed) or an extracted decision/advice row. Items carry `kind` (coarse classifier the UI maps to verb + icon — dm_sent, email_sent, nudge_sent, cadence_sent, workflow_resumed, proposal_routed, decision_logged, advice_given, workflow_done, initiative_started, decision_resolved, alert_raised, or action for unclassified), `summary`, `actor` (always Executive for now), `target` (channel ref / person, or null), `department`, and `at` (ISO timestamp). Sources merged — `scheduled_actions` with status=done (excluding `nudge_scan` heartbeat and `__internal__` channel), `decisions`, `advice_given`, completed `workflow_runs` (status=done — briefings/check-ins/research, bucketed at `updated_at`), `initiatives` (kicked-off projects, at `created_at`), resolved `decision_instances` (terminal gated-decision outcomes — approved/rejected/reversed, at `resolved_at`; pending ones stay in `proposals`, not the rail), and `alerts` raised (excluding source=`decision_scheduling`, which is the companion alert for a gated booking already represented by its `decision_resolved` row). `_build_activity(..., include_alert_raised=False)` omits this source entirely. The rail keeps it (history is the point there); only the briefing narrative opts out. This broadens the feed beyond the original messaging-heavy three sources so it reflects all self-initiated Executive activity, not just dispatched messages. Actions on `propose_only` departments are reclassified to `proposal_routed` because the runner marks them done without dispatching (the proposal is surfaced via /today's `proposals` field; the activity rail shows it as 'proposed to <approver>' rather than implying a DM was sent). Sorted by `at DESC`, then capped at `limit` (default 20, clamped to 1..100 via FastAPI Query validation — 422 on out-of-range). The Pulse page polls this endpoint (limit=100) every ~20s so new activity streams into the 'Recent activity' card without a reload; the card scrolls internally at a fixed max-height rather than growing the page."- "GET /today/activity/daily?days=N — Returns DailyActivityResponse(days), the per-day counts behind the Pulse page's 'heartbeat' heatmap (the GitHub-contributions-style grid at `/memories`). Same source set and exclusions as /today/activity — the union of `decisions`, `advice_given`, status=done `scheduled_actions` (excluding the `nudge_scan` heartbeat and `__internal__` channel), completed `workflow_runs`, `initiatives`, resolved `decision_instances`, and `alerts` — but bucketed by calendar day (UTC) in `episodic.count_activity_by_day` rather than returned as individual items — decisions/advice by their `timestamp`, fired actions by `run_at` (fire time, not `created_at` queue time, so a cadence queued the night before counts on the day it fires), workflow runs by `updated_at` (completion), initiatives by `created_at`, resolved decisions by `resolved_at`, alerts by `created_at`. The `workflow_runs` and `alerts` tables are owned by other stores (not `episodic.initialize_db`), so each UNION arm is included only when its table exists — `count_activity_by_day` checks `sqlite_master` and still counts the sources episodic owns on a DB initialised by episodic alone. The response is DENSE: every calendar day in the window is present (count 0 when nothing fired), oldest→newest, so the UI renders a gap-free grid without client-side fill. `days` defaults to 90, clamped to 1..365 via FastAPI Query validation (422 on out-of-range). Read-only, unauthenticated (matches /today/activity and /memories/*), uncached."- GET /morning-brief — deprecated alias for GET /today, kept for one release for older UI builds and bookmarks. Sends a Deprecation header with a Sunset date.lifecycle: |diff --git a/packages/core/openexecutive/architecture/prebuilt/today.json b/packages/core/openexecutive/architecture/prebuilt/today.jsonindex c44d21da..054b7a89 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 one of only two trusted sources for `ack_alert` — the other being this page's `[Discuss mode — alert_id=N]` handoff primer — because an id quoted inside an alert's own body came from inbound mail or chat and is attacker-controlled. 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 digest reports which ids it named, so a chat session records them and `ack_alert` refuses anything else. 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 also 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. And 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), which is what keeps a frozen header from recurring. Activity is deliberately **not** in the cache hash: the 20-row window moves on almost every DM, decision and completed workflow, so hashing it would regenerate every viewer's narrative — one model call each — on nearly any Executive action. The hash instead tracks each proposal's review fields (`review_verdict`, `review_note`, `why_now`, `recommended_move`, `due_at`) alongside its headline, because the review rewrites those in place while keeping the headline. 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 one of only two trusted sources for `ack_alert` — the other being this page's `[Discuss mode — alert_id=N]` handoff primer — because an id quoted inside an alert's own body came from inbound mail or chat and is attacker-controlled. 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 digest reports which ids it named, so a chat session records them and `ack_alert` refuses anything else. 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/briefing/narrative.py b/packages/core/openexecutive/briefing/narrative.pyindex 5f527398..7a6b1d42 100644--- a/packages/core/openexecutive/briefing/narrative.py+++ b/packages/core/openexecutive/briefing/narrative.py@@ -273,10 +273,13 @@ async def synthesize_briefing_narrative(since: datetime | None = None,handled: list[dict[str, Any]] | None = None,pending_watch_suggestions: int = 0,+ rendered_context: str | None = None,) -> str:"""Synthesize the briefing narrative. Returns Markdown, or "" when empty.Prompt selection:+ ``rendered_context`` overrides the context render (see below).+- ``standalone=True`` → the enumerated whole-company DM brief(morning_brief): a self-contained message with no cards beside it, soit lists what needs attention. (`viewer` is ignored.)@@ -298,7 +301,11 @@ async def synthesize_briefing_narrative(system = _viewer_system_prompt(viewer["name"], viewer["role"])else:system = BRIEFING_NARRATIVE_SYSTEM- user_content = render_briefing_context(+ # `rendered_context` lets a caller hand in the exact block it already+ # rendered. The /today header path does, because it hashes that string as+ # its cache key — re-rendering here could quietly drift from what was+ # hashed and leave the cache keyed on something the model never saw.+ user_content = rendered_context if rendered_context is not None else render_briefing_context(period_label=period_label, today_data=today_data, activity=activity,since=since, handled=handled,pending_watch_suggestions=pending_watch_suggestions,diff --git a/packages/core/openexecutive/briefing/narrative_cache.py b/packages/core/openexecutive/briefing/narrative_cache.pyindex 084a0733..160a48ec 100644--- a/packages/core/openexecutive/briefing/narrative_cache.py+++ b/packages/core/openexecutive/briefing/narrative_cache.py@@ -22,7 +22,6 @@ from collections.abc import Generatorfrom contextlib import contextmanagerfrom datetime import UTC, datetimefrom pathlib import Path-from typing import Anyfrom pydantic import BaseModel@@ -90,62 +89,55 @@ def initialize_db(db_path: Path | None = None) -> None:NARRATIVE_PROMPT_VERSION = "4"+# Stands in for the rendered context when nothing on the viewer's board wants+# a decision. The narrative is then a fixed line and no model call happens, so+# the key must NOT depend on anything volatile: hashing the real context there+# would re-key on every activity row and re-write the identical quiet line+# forever.+QUIET_CONTEXT = "<nothing-needs-attention>"++def build_narrative_input_hash(- today_data: dict[str, Any], scope: str = DEFAULT_SCOPE+ rendered_context: str, scope: str = DEFAULT_SCOPE) -> str:- """Stable hash of the briefing state the narrative is derived from.-- Keyed on the signals that should trigger a re-write — each proposal's- headline, category AND the review fields that change what the narrative- would say about it, at-risk department counts, and who's awaiting — plus- the UTC date so the narrative refreshes at least daily even if nothing- structural changed, plus the viewer `scope` so two viewers whose slices- happen to coincide still cache under distinct keys, plus- NARRATIVE_PROMPT_VERSION so a prompt rewrite invalidates the cache.- Deliberately ignores volatile fields (timestamps, ids) so identical- content doesn't churn the cache.-- The review fields matter because the alert review rewrites an open alert's- note, why-now, recommended move or deadline IN PLACE, keeping the headline:- on headline alone the header kept describing the pre-rewrite situation.-- Activity is deliberately NOT hashed. It looked like the fix for a frozen- header, but the 20-row window moves on almost every DM, decision, advice- row and completed workflow, so hashing it regenerates every viewer's- narrative — a real model call each — on nearly any Executive action, with- no floor. `today._nothing_needs_attention` is what keeps a frozen header- from recurring: the state that froze it (nothing on the board) is now- answered by a deterministic quiet line instead of a model call.+ """Hash of the EXACT user-turn context the model will be given.++ The one invariant that keeps this cache honest: **the key is a function of+ the model's input.** Anything the prompt renders is covered; anything it+ does not render cannot trigger a regeneration. Both properties are free,+ and they survive future edits to `render_briefing_context` without anyone+ remembering to update a field list here.++ Two earlier designs each broke one half of that, in opposite directions:++ * Keying on proposal headlines alone left the rendered activity block+ uncovered, so the header could describe a rail that had moved on.+ * Keying on the proposals' review fields (`review_verdict`, `review_note`,+ `why_now`, `recommended_move`, `due_at`) covered data the /today header+ never renders at all — it prints `headline[:160]` and nothing else — while+ `alerts.review` rewrites those fields with fresh LLM prose on EVERY pass,+ including its "still relevant, nothing changed" path. That regenerated+ every viewer's narrative several times a day to re-synthesize byte-+ identical input.++ ``scope`` keeps two viewers whose contexts coincide under distinct keys,+ ``NARRATIVE_PROMPT_VERSION`` invalidates every entry when a prompt is+ reworded, and the UTC date gives a daily floor (it is also inside the+ rendered context's PERIOD line, but the quiet sentinel has no such line)."""- proposals = [- (- p.get("headline", ""),- p.get("category", ""),- p.get("review_verdict", ""),- str(p.get("review_note", ""))[:120],- str(p.get("why_now", ""))[:120],- p.get("recommended_move", ""),- p.get("due_at", "") or "",+ if not isinstance(rendered_context, str):+ # This used to take the `today_data` dict. A dict is JSON-serialisable,+ # so a stale caller would hash silently and key the entry on something+ # the model never saw — a wrong cache that looks like a working one.+ raise TypeError(+ "build_narrative_input_hash takes the RENDERED context string "+ f"(see today._narrative_context), not {type(rendered_context).__name__}")- for p in today_data.get("proposals", [])- ]- depts = [- (d.get("slug", ""), d.get("at_risk_count", 0), d.get("off_track_count", 0))- for d in today_data.get("departments", [])- if d.get("at_risk_count", 0) or d.get("off_track_count", 0)- ]- awaiting = sorted(- p.get("id", 0)- for p in today_data.get("people", [])- if p.get("awaiting_count", 0)- )payload = {"scope": scope,"prompt_version": NARRATIVE_PROMPT_VERSION,"date": datetime.now(UTC).strftime("%Y-%m-%d"),- "proposals": proposals,- "depts": depts,- "awaiting": awaiting,+ "context": rendered_context,}blob = json.dumps(payload, sort_keys=True, default=str)return hashlib.sha256(blob.encode("utf-8")).hexdigest()@@ -197,6 +189,7 @@ def utc_now_iso() -> str:__all__ = ["DEFAULT_SCOPE",+ "QUIET_CONTEXT","BriefingNarrative","build_narrative_input_hash","get",diff --git a/packages/core/tests/unit/test_briefing_narrative_cache.py b/packages/core/tests/unit/test_briefing_narrative_cache.pyindex 7cebdbb6..37115be4 100644--- a/packages/core/tests/unit/test_briefing_narrative_cache.py+++ b/packages/core/tests/unit/test_briefing_narrative_cache.py@@ -40,36 +40,59 @@ def test_put_upserts_on_scope(tmp_path: Path) -> None:assert got is not None and got.narrative_text == "v2" and got.input_hash == "h2"+def _ctx(today_data: dict, activity: list | None = None) -> str:+ from openexecutive.briefing.narrative import render_briefing_context++ return render_briefing_context(+ period_label="2026-09-20", today_data=today_data, activity=activity or [],+ )++def test_hash_stable_for_same_state() -> None:data = {"proposals": [{"headline": "A", "category": "action"}],- "departments": [{"slug": "fin", "at_risk_count": 1, "off_track_count": 0}],- "people": [{"id": 3, "awaiting_count": 2}],+ "departments": [{"title": "Fin", "slug": "fin", "at_risk_count": 1,+ "off_track_count": 0, "awaiting_count": 0}],+ "people": [{"id": 3, "full_name": "Dana", "role": "CFO", "awaiting_count": 2}],}- assert narrative_cache.build_narrative_input_hash(data) == \- narrative_cache.build_narrative_input_hash(dict(data))+ assert narrative_cache.build_narrative_input_hash(_ctx(data)) == \+ narrative_cache.build_narrative_input_hash(_ctx(dict(data)))def test_hash_changes_when_proposals_change() -> None:base = {"proposals": [{"headline": "A", "category": "action"}], "departments": [], "people": []}changed = {"proposals": [{"headline": "B", "category": "action"}], "departments": [], "people": []}- assert narrative_cache.build_narrative_input_hash(base) != \- narrative_cache.build_narrative_input_hash(changed)+ assert narrative_cache.build_narrative_input_hash(_ctx(base)) != \+ narrative_cache.build_narrative_input_hash(_ctx(changed))def test_hash_differs_by_scope() -> None:# Same content, different viewer → distinct cache keys (no cross-user reuse).- data = {"proposals": [], "departments": [], "people": []}- assert narrative_cache.build_narrative_input_hash(data, "principal") != \- narrative_cache.build_narrative_input_hash(data, "person:5")+ ctx = _ctx({"proposals": [], "departments": [], "people": []})+ assert narrative_cache.build_narrative_input_hash(ctx, "principal") != \+ narrative_cache.build_narrative_input_hash(ctx, "person:5")def test_hash_ignores_volatile_fields() -> None:- # created_at / alert_id / score should not churn the hash — only headline- # + category feed it.+ # created_at / alert_id / score are not rendered into the header context,+ # so they cannot churn the key. This now holds by construction — the key is+ # a hash of the rendered context — rather than by a hand-maintained field+ # list that had to be remembered.a = {"proposals": [{"headline": "A", "category": "action", "created_at": "2026-01-01", "score": 40}],"departments": [], "people": []}b = {"proposals": [{"headline": "A", "category": "action", "created_at": "2026-12-31", "score": 99}],"departments": [], "people": []}- assert narrative_cache.build_narrative_input_hash(a) == \- narrative_cache.build_narrative_input_hash(b)+ assert narrative_cache.build_narrative_input_hash(_ctx(a)) == \+ narrative_cache.build_narrative_input_hash(_ctx(b))+++def test_hash_refuses_a_today_data_dict() -> None:+ """The signature changed from the `today_data` dict to the rendered string.+ A dict is JSON-serialisable, so without this guard a stale caller would+ hash silently and key the entry on input the model never saw."""+ import pytest++ with pytest.raises(TypeError, match="RENDERED context string"):+ narrative_cache.build_narrative_input_hash(+ {"proposals": [], "departments": [], "people": []} # type: ignore[arg-type]+ )diff --git a/packages/core/tests/unit/test_today_route.py b/packages/core/tests/unit/test_today_route.pyindex 7dcd888a..6b883585 100644--- a/packages/core/tests/unit/test_today_route.py+++ b/packages/core/tests/unit/test_today_route.py@@ -59,6 +59,19 @@ def _seed_live_action_alert(db: Path, headline: str = "Approve the Q3 budget") -)+def _current_narrative_hash() -> str:+ """The principal-scope key exactly as `_attach_narrative` computes it.++ Derived through `_narrative_context` rather than rebuilt by hand: the key+ is a hash of the rendered model input, so a test that assembled it another+ way would drift from production the moment the renderer changed.+ """+ snapshot = today_route._build_today()+ scope, data, desc, viewer = today_route._narrative_inputs(snapshot, None)+ context, _ = today_route._narrative_context(data, viewer, desc)+ return narrative_cache.build_narrative_input_hash(context, scope=scope)++def _make_client() -> TestClient:app = FastAPI()app.include_router(today_route.router)@@ -901,8 +914,7 @@ def test_narrative_served_from_cache(db = tmp_path / "narr.db"_setup_isolated_db(db, monkeypatch)- snapshot = today_route._build_today()- nhash = narrative_cache.build_narrative_input_hash(snapshot.model_dump())+ nhash = _current_narrative_hash()narrative_cache.put(narrative_cache.BriefingNarrative(scope=narrative_cache.DEFAULT_SCOPE,@@ -959,8 +971,7 @@ def test_fresh_cache_does_not_trigger_regen(db = tmp_path / "fresh.db"_setup_isolated_db(db, monkeypatch)- snapshot = today_route._build_today()- nhash = narrative_cache.build_narrative_input_hash(snapshot.model_dump())+ nhash = _current_narrative_hash()narrative_cache.put(narrative_cache.BriefingNarrative(scope=narrative_cache.DEFAULT_SCOPE, input_hash=nhash,@@ -1665,49 +1676,109 @@ def test_activity_drops_the_alert_source_for_the_narrative(assert "Cut burn to 400k" in summaries # other sources survive-def test_narrative_hash_moves_when_a_proposal_is_rewritten_in_place() -> None:- """The alert review rewrites an open alert's note / why-now / move / due- date while KEEPING its headline. On headline alone the header went on- describing the pre-rewrite situation until the UTC date rolled over."""- def board(**review: object) -> dict[str, object]:- return {- "proposals": [{"headline": "Vendor renewal", "category": "action", **review}],- "departments": [], "people": [],- }+def _ctx(today_data: dict, activity: list | None = None) -> str:+ from openexecutive.briefing.narrative import render_briefing_context++ return render_briefing_context(+ period_label="2026-09-20", today_data=today_data, activity=activity or [],+ )+++def test_narrative_hash_covers_everything_the_prompt_renders() -> None:+ """The invariant: the cache key is a hash of the MODEL'S INPUT.++ So anything `render_briefing_context` emits must move the key — including+ the activity block, which is rendered and was previously uncovered.+ """+ base = {+ "proposals": [{"headline": "Vendor renewal", "category": "action"}],+ "departments": [], "people": [],+ }+ h = narrative_cache.build_narrative_input_hash(_ctx(base))++ moved = {**base, "proposals": [{"headline": "Vendor renewal II", "category": "action"}]}+ assert narrative_cache.build_narrative_input_hash(_ctx(moved)) != h++ with_dept = {**base, "departments": [+ {"title": "Finance", "slug": "finance", "at_risk_count": 1,+ "off_track_count": 0, "awaiting_count": 0},+ ]}+ assert narrative_cache.build_narrative_input_hash(_ctx(with_dept)) != h++ # The activity block is rendered, so it must be covered.+ with_activity = narrative_cache.build_narrative_input_hash(+ _ctx(base, [{"at": "2026-09-20", "kind": "dm_sent", "summary": "Nudged Dana"}])+ )+ assert with_activity != h- base = narrative_cache.build_narrative_input_hash(board())++def test_narrative_hash_ignores_what_the_prompt_never_renders() -> None:+ """The other half of the invariant, and the expensive half.++ The /today header renders `headline[:160]` and nothing else per proposal.+ `alerts.review` rewrites review_note / why_now / recommended_move with+ fresh LLM prose on EVERY pass — including its "still relevant, nothing+ changed" path — several times a day. Keying on those regenerated every+ viewer's narrative just to re-synthesize byte-identical input.+ """+ def board(**review: object) -> dict:+ proposal = today_route.ProposalItem(+ alert_id=1, headline="Vendor renewal", body="b",+ routed_to_person_id=None, suggested_action="",+ created_at="2026-09-20T00:00:00Z", topic_tags=[], category="action",+ **review, # type: ignore[arg-type]+ )+ return {"proposals": [proposal.model_dump()], "departments": [], "people": []}++ base = narrative_cache.build_narrative_input_hash(_ctx(board()))for field, value in (- ("review_verdict", "changed"),- ("review_note", "two offers now expire Friday"),+ ("review_verdict", "relevant"),+ ("review_note", "reworded by the review, same situation"),("why_now", "counterparty deadline"),("recommended_move", "escalate"),("due_at", "2026-09-21T00:00:00Z"),):- assert narrative_cache.build_narrative_input_hash(board(**{field: value})) != base, field+ assert narrative_cache.build_narrative_input_hash(+ _ctx(board(**{field: value}))+ ) == base, field-def test_narrative_hash_is_stable_across_activity_churn(+def test_quiet_board_hash_is_stable_across_activity_churn(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:- """Activity is deliberately NOT hashed.+ """On a quiet board the text is a constant, so the key must be too.- The 20-row rail moves on almost every DM, decision, advice row and- completed workflow. Hashing it would regenerate every viewer's narrative —- a real model call each — on nearly any Executive action, and on a quiet- board it would re-write the identical quiet line forever.+ Otherwise every rail movement re-keys an entry whose content cannot+ change, and each GET /today schedules a background task to rewrite the+ identical quiet line — forever."""db = tmp_path / "hash-stable.db"_setup_isolated_db(db, monkeypatch)- snapshot = today_route._build_today()- before = narrative_cache.build_narrative_input_hash(snapshot.model_dump())+ def rail() -> list[tuple[str, str]]:+ return [(i.kind, i.summary) for i in today_route._build_activity(20).items]++ def key() -> str:+ snap = today_route._build_today()+ scope, data, desc, viewer = today_route._narrative_inputs(snap, None)+ ctx, _ = today_route._narrative_context(data, viewer, desc)+ assert ctx == narrative_cache.QUIET_CONTEXT+ return narrative_cache.build_narrative_input_hash(ctx, scope=scope)++ before, rail_before = key(), rail()episodic.store_decision("finance", "Cut burn to 400k", db_path=db)episodic.store_advice("hr", "Hire?", "Slowly", db_path=db)- after_snapshot = today_route._build_today()- assert [i.kind for i in today_route._build_activity(20).items] # rail did move- assert narrative_cache.build_narrative_input_hash(after_snapshot.model_dump()) == before+ # The rail genuinely moved — asserted by diffing it and by naming the rows+ # just written. A bare "is non-empty" check would pass even if both writes+ # silently failed.+ rail_after = rail()+ assert rail_after != rail_before+ assert ("decision_logged", "Cut burn to 400k") in rail_after+ assert ("advice_given", "Slowly") in rail_after++ assert key() == beforedef test_empty_board_skips_the_model_call(