AI-powered virtual executive team — a single coherent executive persona backed by 8 specialist agents (FastAPI + Next.js).
Drop the alert source from the narrative feed; keep activity out of the hash
Rufusd671d7103cee
diff --git a/packages/core/openexecutive/api/routes/today.py b/packages/core/openexecutive/api/routes/today.pyindex 6e1bb017..d60801bc 100644--- a/packages/core/openexecutive/api/routes/today.py+++ b/packages/core/openexecutive/api/routes/today.py@@ -914,7 +914,7 @@ def _build_activity(limit: int,since: datetime | None = None,*,- live_alerts_only: bool = False,+ include_alert_raised: bool = True,) -> ActivityResponse:"""Aggregate recent self-initiated Executive activity across sources.@@ -922,12 +922,15 @@ def _build_activity(the previous delivery time so "what changed" is a real delta); the poolis widened so a busy history cannot starve the window.- ``live_alerts_only`` drops ``alert_raised`` rows whose alert is no longer- live (acked, dismissed, resolved, snoozed, past TTL). The rail wants the- full history — a raise really happened even if the card is gone — but the- briefing narrative does not: fed closed alerts it re-reports settled items- as live, and on an empty board they become the *only* input, so the header- describes a queue that no longer exists.+ ``include_alert_raised=False`` omits the ``alert_raised`` source entirely.+ The rail wants it — a raise really happened, even if the card is gone — but+ the briefing narrative wants neither half of it. A *closed* alert read as+ live work the principal had already settled. 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, and+ the header prompt forbids re-listing the cards. Dropping the source is also+ why this is not a post-pull filter: ``recent_alerts`` would otherwise burn+ the whole pool on closed rows and starve the live ones out of the feed.Sources, all pulled from the shared SQLite database:• scheduled_actions with status='done' — fired follow-ups, nudges,@@ -945,7 +948,6 @@ def _build_activity(Items are merged, sorted by timestamp DESC, and capped at `limit`.The caller is expected to clamp `limit` (the route does this)."""- from openexecutive.alerts import lifecycle as alert_lifecyclefrom openexecutive.alerts import store as alerts_storefrom openexecutive.memory import decision_ledgerfrom openexecutive.memory.episodic import (@@ -1074,18 +1076,15 @@ def _build_activity(# included on purpose: this is a historical "what happened" feed (like# decisions / advice, which have no status), so an alert later read or# dismissed still represents a real raise event at its `created_at`. The- # narrative passes `live_alerts_only` to opt out — see the docstring.+ # narrative opts the whole source out — see the docstring.# Decision-scheduling alerts are excluded in SQL (not after the pull, so# they can't starve real alerts out of the pool) — they are the companion# alert for a gated booking, already represented by the `decision_resolved`# rows above (and as a live proposal while pending), so surfacing them here# would double-count.- now_for_alerts = datetime.now(UTC)- for alert in alerts_store.recent_alerts(+ for alert in (alerts_store.recent_alerts(limit=pool, exclude_source=decision_ledger.DECISION_ALERT_SOURCE,- ):- if live_alerts_only and not alert_lifecycle.is_live(alert, now_for_alerts):- continue+ ) if include_alert_raised else []):items.append(ActivityItem(kind="alert_raised",summary=alert.headline,@@ -1230,25 +1229,28 @@ def _narrative_inputs(def _narrative_activity(viewer: PersonBriefItem | None, viewer_desc: dict[str, str] | None) -> list[dict[str, Any]]:- """The activity list the narrative reasons over, for BOTH the hash and the- synthesis.+ """The activity list the narrative reasons over.- Shared on purpose: the hot path hashes this to decide staleness and the- background task feeds it to the model. If the two ever computed it- differently, every request would either regenerate forever or never- regenerate at all.+ Background task only — deliberately NOT part of the cache hash. Hashing it+ looked like the fix for a frozen header, but it has no floor: the 20-row+ window moves on almost every DM, decision, advice row and completed+ workflow, so every viewer's narrative would regenerate (a real model call+ each) on nearly any Executive action. `_nothing_needs_attention` is what+ actually keeps a frozen header from recurring, and the hash now tracks the+ proposal fields that genuinely change what the narrative would say.- Closed alerts are dropped (`live_alerts_only`) — the narrative describes- what is live, not what once was.+ ``alert_raised`` is excluded (see `_build_activity`): live raises are the+ proposal cards, which the header must not re-list, and closed ones are+ settled work.``viewer_desc`` is `_narrative_inputs`' third element: non-None only for anon-principal teammate, whose feed is narrowed to their own departments.- Taken as-is rather than as a bool so both call sites pass what they already- hold instead of each re-deriving the same condition.+ Taken as-is rather than as a bool so the call site passes what it already+ holds instead of re-deriving the same condition."""activity = [item.model_dump()- for item in _build_activity(20, live_alerts_only=True).items+ for item in _build_activity(20, include_alert_raised=False).items]if viewer_desc is not None and viewer is not None:# Teammate view: keep only activity in their departments.@@ -1289,11 +1291,7 @@ 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,- activity=_narrative_activity(viewer, desc),- )+ nhash = narrative_cache.build_narrative_input_hash(today_data, scope=scope)cached = narrative_cache.get(scope)if cached is not None:response.narrative = cached.narrative_text@@ -1359,9 +1357,7 @@ async def _regen_briefing_narrative(if not text:return- input_hash = narrative_cache.build_narrative_input_hash(- today_data, scope=scope, activity=activity- )+ input_hash = narrative_cache.build_narrative_input_hash(today_data, 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 84928be2..bcce1a02 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 IN the hash, and the hot path and the background regen both derive it from the same helper (`today._narrative_activity`) — omitting it was a silent staleness bug: with no proposals, no at-risk department and nobody awaiting, every remaining input lived in activity, so the hash was constant and the header could not regenerate inside a UTC day; computing it two different ways instead would either regenerate on every request or never. The narrative's activity is built with `live_alerts_only=True`, so alerts that are acked / dismissed / resolved / snoozed / past TTL are dropped (the `/today/activity` rail keeps them — a raise really happened), and `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. 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(..., live_alerts_only=True)` additionally drops `alert_raised` rows whose alert is no longer live; 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). 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/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 329b44ea..c44d21da 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**. The activity it reasons over is built with `live_alerts_only`, so an alert that was acked, dismissed, resolved, snoozed or aged past its TTL drops out — the `/today/activity` rail still shows it, because a raise really happened, but the header must not re-report a settled item as current. The activity block is also only labelled \"since last brief\" when the caller actually 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). Those three rules are one bug fix: on a fully dismissed board every other input was empty, so 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 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.","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_cache.py b/packages/core/openexecutive/briefing/narrative_cache.pyindex 53932947..084a0733 100644--- a/packages/core/openexecutive/briefing/narrative_cache.py+++ b/packages/core/openexecutive/briefing/narrative_cache.py@@ -91,30 +91,42 @@ NARRATIVE_PROMPT_VERSION = "4"def build_narrative_input_hash(- today_data: dict[str, Any],- scope: str = DEFAULT_SCOPE,- activity: list[dict[str, Any]] | None = None,+ today_data: dict[str, Any], 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 — proposal- headlines, at-risk department counts, who's awaiting, and the activity- rows the narrative reasons over — 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.-- ``activity`` must be the SAME list the synthesis is fed — callers get both- from ``today._narrative_activity``. Omitting it was a silent staleness bug:- on a board with no proposals, no at-risk department and nobody awaiting,- every remaining input lived in ``activity``, so the hash was constant and- the narrative could never regenerate within a UTC day no matter what the- Executive did.+ 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."""proposals = [- (p.get("headline", ""), p.get("category", ""))+ (+ 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 "",+ )for p in today_data.get("proposals", [])]depts = [@@ -127,12 +139,6 @@ def build_narrative_input_hash(for p in today_data.get("people", [])if p.get("awaiting_count", 0))- # Keyed by kind + summary, never by timestamp, so an unchanged rail does- # not churn the cache the way a stamp would.- activity_key = sorted(- (str(a.get("kind", "")), str(a.get("summary", ""))[:120])- for a in (activity or [])- )payload = {"scope": scope,"prompt_version": NARRATIVE_PROMPT_VERSION,@@ -140,7 +146,6 @@ def build_narrative_input_hash("proposals": proposals,"depts": depts,"awaiting": awaiting,- "activity": activity_key,}blob = json.dumps(payload, sort_keys=True, default=str)return hashlib.sha256(blob.encode("utf-8")).hexdigest()diff --git a/packages/core/tests/unit/test_today_route.py b/packages/core/tests/unit/test_today_route.pyindex 79cc691f..7dcd888a 100644--- a/packages/core/tests/unit/test_today_route.py+++ b/packages/core/tests/unit/test_today_route.py@@ -1634,11 +1634,15 @@ def test_activity_keeps_closed_alerts_for_the_rail(assert "Since-settled thing" in headlines-def test_activity_drops_closed_alerts_for_the_narrative(+def test_activity_drops_the_alert_source_for_the_narrative(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:- """`live_alerts_only` drops them, so the narrative cannot re-report a- settled item as live. Live alerts are kept."""+ """`include_alert_raised=False` drops the whole source.++ Closed alerts would be re-reported as live work; LIVE ones are already+ proposal cards (`is_live` is the `list_live_alerts` predicate) and the+ header prompt forbids re-listing cards. Other sources are untouched.+ """db = tmp_path / "narr-activity.db"_setup_isolated_db(db, monkeypatch)closed = alert_store.insert_alert(@@ -1651,37 +1655,59 @@ def test_activity_drops_closed_alerts_for_the_narrative(source="system", external_id="open-2", severity="high",headline="Still open", body="b", db_path=db,)+ episodic.store_decision("finance", "Cut burn to 400k", db_path=db)++ items = today_route._build_activity(20, include_alert_raised=False).items+ summaries = [i.summary for i in items]+ assert "Already handled" not in summaries+ assert "Still open" not in summaries+ assert "alert_raised" not in [i.kind for i in items]+ 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": [],+ }++ base = narrative_cache.build_narrative_input_hash(board())+ for field, value in (+ ("review_verdict", "changed"),+ ("review_note", "two offers now expire Friday"),+ ("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+++def test_narrative_hash_is_stable_across_activity_churn(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ """Activity is deliberately NOT hashed.- live = [i.summary for i in today_route._build_activity(20, live_alerts_only=True).items]- assert "Already handled" not in live- assert "Still open" in live-+ 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.+ """+ db = tmp_path / "hash-stable.db"+ _setup_isolated_db(db, monkeypatch)-def test_narrative_hash_moves_when_only_activity_changes() -> None:- """The hash must cover activity. Without this, a board with no proposals,- no at-risk department and nobody awaiting produced a constant hash, so the- narrative could never regenerate inside a UTC day."""- empty_board: dict[str, object] = {"proposals": [], "departments": [], "people": []}- before = narrative_cache.build_narrative_input_hash(- empty_board, activity=[{"kind": "alert_raised", "summary": "one"}]- )- after = narrative_cache.build_narrative_input_hash(- empty_board, activity=[{"kind": "alert_raised", "summary": "two"}]- )- assert before != after+ snapshot = today_route._build_today()+ before = narrative_cache.build_narrative_input_hash(snapshot.model_dump())+ episodic.store_decision("finance", "Cut burn to 400k", db_path=db)+ episodic.store_advice("hr", "Hire?", "Slowly", db_path=db)-def test_narrative_hash_ignores_activity_timestamps() -> None:- """Keyed on kind + summary, never the stamp — an unchanged rail must not- churn the cache (and burn a model call) on every poll."""- board: dict[str, object] = {"proposals": [], "departments": [], "people": []}- a = narrative_cache.build_narrative_input_hash(- board, activity=[{"kind": "dm_sent", "summary": "s", "at": "2026-01-01T00:00:00Z"}]- )- b = narrative_cache.build_narrative_input_hash(- board, activity=[{"kind": "dm_sent", "summary": "s", "at": "2026-06-30T12:00:00Z"}]- )- assert a == b+ 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()) == beforedef test_empty_board_skips_the_model_call(@@ -1772,15 +1798,17 @@ def test_viewer_slice_scopes_proposals_to_the_teammate(assert sliced["people"] == [] # the principal-only section is dropped-def test_closed_alerts_never_reach_the_synthesizer(+def test_alert_raises_never_reach_the_synthesizer(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:- """End-to-end: on a NON-quiet board the model still must not be told about- a dismissed alert.-- The quiet short-circuit cannot be what saves us here — a live proposal- keeps the board active — so this proves `live_alerts_only` actually- survives the trip through `_regen_briefing_narrative`.+ """End-to-end on a NON-quiet board: no `alert_raised` row reaches the model.++ Closed alerts are settled work. LIVE ones are worse than redundant —+ `lifecycle.is_live` is the predicate behind `list_live_alerts`, so a live+ raise IS a proposal card, and the header prompt forbids re-listing cards.+ The quiet short-circuit cannot be what saves us here: a live proposal keeps+ the board active, so this proves the exclusion survives the trip through+ `_regen_briefing_narrative`."""db = tmp_path / "e2e-live-only.db"_setup_isolated_db(db, monkeypatch)@@ -1791,6 +1819,9 @@ def test_closed_alerts_never_reach_the_synthesizer()assert dismissed is not Nonealert_store.set_status(dismissed, "dismissed", db_path=db)+ # A non-alert activity row, so "no alert_raised" is proved against a+ # non-empty feed rather than passing vacuously on an empty one.+ episodic.store_decision("finance", "Cut burn to 400k", db_path=db)seen: dict[str, list[str]] = {}@@ -1799,6 +1830,7 @@ def test_closed_alerts_never_reach_the_synthesizer(seen["summaries"] = [str(a.get("summary", "")) for a in activity # type: ignore[union-attr]]+ seen["kinds"] = [str(a.get("kind", "")) for a in activity] # type: ignore[union-attr]return "**Bottom line:** the budget needs you."monkeypatch.setattr(briefing_narrative, "synthesize_briefing_narrative", _synth)@@ -1807,4 +1839,7 @@ def test_closed_alerts_never_reach_the_synthesizer(c.get("/today")assert "St. Albans reconciliation gap" not in seen["summaries"]- assert "Approve the Q3 budget" in seen["summaries"]+ # The live one is excluded too — it is already a card below the header.+ assert "Approve the Q3 budget" not in seen["summaries"]+ assert "decision_logged" in seen["kinds"] # feed is non-empty+ assert "alert_raised" not in seen["kinds"]