AI-powered virtual executive team — a single coherent executive persona backed by 8 specialist agents (FastAPI + Next.js).
Hold the briefing narrative to what is actually live
Rufus3e2e7276ae6e
diff --git a/packages/core/openexecutive/api/routes/today.py b/packages/core/openexecutive/api/routes/today.pyindex d80bb0c3..05979458 100644--- a/packages/core/openexecutive/api/routes/today.py+++ b/packages/core/openexecutive/api/routes/today.py@@ -910,13 +910,25 @@ def _payload_headline(payload_json: str | None) -> str | None:return None-def _build_activity(limit: int, since: datetime | None = None) -> ActivityResponse:+def _build_activity(+ limit: int,+ since: datetime | None = None,+ *,+ live_alerts_only: bool = False,+) -> ActivityResponse:"""Aggregate recent self-initiated Executive activity across sources.``since`` bounds the feed to items at/after that instant (the briefs passthe 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.+Sources, all pulled from the shared SQLite database:• scheduled_actions with status='done' — fired follow-ups, nudges,cadences, workflow resumes. Internal channels and the nudge_scan@@ -1057,17 +1069,24 @@ def _build_activity(limit: int, since: datetime | None = None) -> ActivityResponat=instance.resolved_at or instance.created_at,))- # Operational alerts the Executive raised. All statuses are 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`. 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.+ # Operational alerts the Executive raised. For the rail, all statuses are+ # 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.+ # 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.+ from openexecutive.alerts import lifecycle as alert_lifecycle++ now_for_alerts = datetime.now(UTC)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):+ continueitems.append(ActivityItem(kind="alert_raised",summary=alert.headline,@@ -1209,6 +1228,55 @@ def _narrative_inputs()+# Quiet-day lines, one per narrative scope. They match the wording the+# synthesis prompts tell the model to emit on a quiet day, so a short-circuited+# narrative is indistinguishable from a model-produced one.+_QUIET_PRINCIPAL = "Quiet right now — nothing pressing."+_QUIET_VIEWER = "Quiet right now — nothing needs you."+++def _narrative_activity(viewer: PersonBriefItem | None, scoped: bool) -> list[dict[str, Any]]:+ """The activity list the narrative reasons over, for BOTH the hash and the+ synthesis.++ 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.++ Closed alerts are dropped (`live_alerts_only`) — the narrative describes+ what is live, not what once was.+ """+ activity = [+ item.model_dump()+ for item in _build_activity(20, live_alerts_only=True).items+ ]+ if scoped and viewer is not None:+ # Teammate view: keep only activity in their departments.+ vdepts = set(viewer.department_slugs)+ activity = [a for a in activity if a.get("department") in vdepts]+ return activity+++def _nothing_needs_attention(today_data: dict[str, Any]) -> bool:+ """True when the viewer's slice holds nothing that wants a decision.++ The header's job is to synthesize what needs attention. With no action+ proposals, no at-risk/off-track department and nobody awaiting, there is+ nothing to synthesize — and handing the model only the history rail makes+ it manufacture urgency out of settled items. Callers emit a fixed quiet+ line instead of spending a model call.+ """+ if today_data.get("proposals"):+ return False+ if any(+ d.get("at_risk_count", 0) or d.get("off_track_count", 0)+ for d in today_data.get("departments", [])+ ):+ return False+ return not any(p.get("awaiting_count", 0) for p in today_data.get("people", []))++def _attach_narrative(response: TodayResponse,*,@@ -1220,9 +1288,13 @@ def _attach_narrative((the deprecated alias) serves cache-only without scheduling regen."""from openexecutive.briefing import narrative_cache- scope, today_data, _desc, _viewer = _narrative_inputs(response, caller_person_id)+ scope, today_data, desc, viewer = _narrative_inputs(response, caller_person_id)try:- nhash = narrative_cache.build_narrative_input_hash(today_data, scope=scope)+ nhash = narrative_cache.build_narrative_input_hash(+ today_data,+ scope=scope,+ activity=_narrative_activity(viewer, desc is not None),+ )cached = narrative_cache.get(scope)if cached is not None:response.narrative = cached.narrative_text@@ -1263,26 +1335,30 @@ async def _regen_briefing_narrative("regen; skipping write", expected_scope, scope,)return- activity = [item.model_dump() for item in _build_activity(20).items]- if viewer_desc is not None and viewer is not None:- # Teammate view: keep only activity in their departments.- vdepts = set(viewer.department_slugs)- activity = [a for a in activity if a.get("department") in vdepts]- 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,- ),- timeout=25.0,- )+ activity = _narrative_activity(viewer, viewer_desc is not None)+ if _nothing_needs_attention(today_data):+ # 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_PRINCIPAL+ else:+ 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,+ ),+ timeout=25.0,+ )except Exception:logger.exception("today: briefing narrative regen failed")returnif not text:return- input_hash = narrative_cache.build_narrative_input_hash(today_data, scope=scope)+ input_hash = narrative_cache.build_narrative_input_hash(+ today_data, scope=scope, activity=activity+ )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 151c74a3..84928be2 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 + scope + UTC date + `NARRATIVE_PROMPT_VERSION`, the last so a prompt rewrite invalidates every cached narrative on the next view). 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). 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 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/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 fc5766aa..329b44ea 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.\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**. 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.","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 55bcd2b4..a3d652b0 100644--- a/packages/core/openexecutive/briefing/narrative.py+++ b/packages/core/openexecutive/briefing/narrative.py@@ -226,7 +226,19 @@ def render_briefing_context(parts.append("")if activity:- parts.append("OE ACTIVITY SINCE LAST BRIEF (most recent first):")+ # Only the standalone briefs pass `since`, and only they bound the+ # activity list to it — so only they may call it a delta. The /today+ # header gets whatever the rail holds, which can predate the last+ # brief entirely; labelling that "since last brief" made the header+ # report weeks-old rows as overnight news.+ if since is not None:+ parts.append("OE ACTIVITY SINCE LAST BRIEF (most recent first):")+ else:+ parts.append(+ "RECENT OE ACTIVITY (most recent first) — this is a history "+ "rail, NOT a delta: the principal may have seen these already, "+ "so never describe them as new or as having just happened:"+ )for item in activity[:15]:parts.append(f"- [{item.get('at', '')[:10]}] {item.get('kind', 'action')}: "diff --git a/packages/core/openexecutive/briefing/narrative_cache.py b/packages/core/openexecutive/briefing/narrative_cache.pyindex 8329fb20..53932947 100644--- a/packages/core/openexecutive/briefing/narrative_cache.py+++ b/packages/core/openexecutive/briefing/narrative_cache.py@@ -87,21 +87,31 @@ def initialize_db(db_path: Path | None = None) -> None:# into the input hash so a prompt change invalidates every cached narrative on# the next view — otherwise a wording fix wouldn't surface until the underlying# state changed (or the daily date rollover).-NARRATIVE_PROMPT_VERSION = "3"+NARRATIVE_PROMPT_VERSION = "4"def build_narrative_input_hash(- today_data: dict[str, Any], scope: str = DEFAULT_SCOPE+ today_data: dict[str, Any],+ scope: str = DEFAULT_SCOPE,+ activity: list[dict[str, Any]] | None = None,) -> 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, 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.+ 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."""proposals = [(p.get("headline", ""), p.get("category", ""))@@ -117,6 +127,12 @@ 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,@@ -124,6 +140,7 @@ 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_briefing_context_render.py b/packages/core/tests/unit/test_briefing_context_render.pyindex 1a90832e..2432e773 100644--- a/packages/core/tests/unit/test_briefing_context_render.py+++ b/packages/core/tests/unit/test_briefing_context_render.py@@ -125,3 +125,24 @@ def test_eod_context_lists_rewritten_open_items() -> None:text = _render_eod_context(period_label="p", today_data=today, activity=[], since=since)assert "REWRITTEN BY THE EXECUTIVE TODAY" in textassert "- item 4 — two offers now expiring Friday" in text+++def test_activity_label_claims_a_delta_only_when_bounded() -> None:+ """Only the standalone briefs pass `since`, and only they bound activity to+ it. The /today header gets the unbounded history rail, so calling that+ block "since last brief" made the header report old rows as overnight news.+ """+ activity = [{"at": "2026-09-20", "kind": "alert_raised", "summary": "old news"}]++ bounded = render_briefing_context(+ period_label="p", today_data=_today(), activity=activity,+ since=datetime.now(UTC) - timedelta(hours=24),+ )+ assert "OE ACTIVITY SINCE LAST BRIEF" in bounded++ unbounded = render_briefing_context(+ period_label="p", today_data=_today(), activity=activity, since=None,+ )+ assert "OE ACTIVITY SINCE LAST BRIEF" not in unbounded+ assert "RECENT OE ACTIVITY" in unbounded+ assert "NOT a delta" in unboundeddiff --git a/packages/core/tests/unit/test_today_route.py b/packages/core/tests/unit/test_today_route.pyindex ccd4d343..1819de82 100644--- a/packages/core/tests/unit/test_today_route.py+++ b/packages/core/tests/unit/test_today_route.py@@ -46,6 +46,19 @@ def _setup_isolated_db(db: Path, monkeypatch: pytest.MonkeyPatch) -> None:dept_store.seed_default_departments(db_path=db)+def _seed_live_action_alert(db: Path, headline: str = "Approve the Q3 budget") -> None:+ """One live, unrouted, action-category alert — enough to make the board+ non-quiet so the narrative takes the synthesizer path."""+ alert_store.insert_alert(+ source="system",+ external_id=f"live-{headline[:12]}",+ severity="high",+ headline=headline,+ body="Needs a decision.",+ db_path=db,+ )++def _make_client() -> TestClient:app = FastAPI()app.include_router(today_route.router)@@ -101,6 +114,11 @@ def test_today_departments_have_fields(client: TestClient) -> None:# --------------------------------------------------------------------------- #def test_morning_brief_alias_returns_same_body(client: TestClient) -> None:+ # Warm the narrative cache first: the very first /today hit is cold+ # (narrative null) and its background task populates the cache, so+ # comparing a cold call against a warm one would diff on `narrative`+ # alone. The alias contract is about the rest of the body.+ client.get("/today")today = client.get("/today").json()legacy = client.get("/morning-brief").json()assert today == legacy@@ -503,6 +521,7 @@ def test_insight_served_from_cache(tmp_path: Path, monkeypatch: pytest.MonkeyPatdef test_morning_brief_alias_unaffected_by_async_today(client: TestClient) -> None:"""The sync /morning-brief alias must keep returning the same body asthe now-async /today (both serve insight=None on a cold cache)."""+ client.get("/today") # warm the narrative cache — see the alias test aboveassert client.get("/today").json() == client.get("/morning-brief").json()@@ -897,6 +916,10 @@ def test_narrative_regenerated_in_background(populated and the next request serves it."""db = tmp_path / "regen.db"_setup_isolated_db(db, monkeypatch)+ # A live action proposal, so the board is NOT quiet and the synthesizer+ # actually runs (an empty board short-circuits to the fixed quiet line+ # without a model call — see test_empty_board_skips_the_model_call).+ _seed_live_action_alert(db)async def _synth(**_kwargs: object) -> str:return "**What changed:** nothing dramatic."@@ -1172,6 +1195,7 @@ def test_unrostered_viewer_gets_whole_company_narrative(whole-company (principal-scope) narrative."""db = tmp_path / "unrostered.db"_setup_isolated_db(db, monkeypatch)+ _seed_live_action_alert(db) # non-quiet board, so the synthesizer runsasync def _synth(**kw: object) -> str:return "principal-brief" if kw.get("viewer") is None else "teammate-brief"@@ -1255,25 +1279,21 @@ def test_teammate_with_no_routed_proposals_quiet_path(full_name="Dan", role="CFO", email="[email protected]",department_slugs=["finance"], db_path=db,)- captured: dict[str, list[str]] = {}+ calls = {"n": 0}- async def _synth(**kw: object) -> str:- viewer = kw.get("viewer")- today_data = kw.get("today_data") or {}- if viewer:- captured["proposals"] = [- p["headline"] for p in today_data.get("proposals", []) # type: ignore[union-attr]- ]- return "Quiet right now — nothing needs you."- return "principal"+ async def _synth(**_kw: object) -> str:+ calls["n"] += 1+ return "should not be reached"monkeypatch.setattr(briefing_narrative, "synthesize_briefing_narrative", _synth)c = _make_client()c.get("/today", headers={"x-caller-email": "[email protected]"})narr = c.get("/today", headers={"x-caller-email": "[email protected]"}).json()["narrative"]- assert captured["proposals"] == [] # empty slice — nothing routed to them+ # Nothing is routed to Dan, so his slice is empty — the fixed quiet line is+ # written directly and no model call is spent on it.assert narr == "Quiet right now — nothing needs you."+ assert calls["n"] == 0def test_narrative_input_is_company_action_no_monitoring(@@ -1569,3 +1589,133 @@ def test_handled_overnight_rows_are_structured_and_track_current_status(watching = rows["stock-acme"]assert watching["kind"] == "watching" and watching["alert_id"] is Noneassert watching["detail"] == "competitor ticker named on Sales" and watching["status"] == ""+++# --------------------------------------------------------------------------- #+# Briefing-narrative accuracy: the header must describe what is LIVE.+#+# Regression set for the incident where a tenant's board was fully dismissed+# yet the header still led with three closed items. Three independent defects+# combined: closed alerts stayed in the activity feed, that feed was unbounded+# but labelled "since last brief", and the cache hash ignored activity — so+# once proposals hit zero the hash was constant and the text froze for a day.+# --------------------------------------------------------------------------- #++def test_activity_keeps_closed_alerts_for_the_rail(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ """The /today/activity rail is a history feed: a dismissed alert still+ represents a real raise event and must stay."""+ db = tmp_path / "rail.db"+ _setup_isolated_db(db, monkeypatch)+ aid = alert_store.insert_alert(+ source="system", external_id="closed-1", severity="high",+ headline="Since-settled thing", body="b", db_path=db,+ )+ assert aid is not None+ alert_store.set_status(aid, "dismissed", db_path=db)++ headlines = [i.summary for i in today_route._build_activity(20).items]+ assert "Since-settled thing" in headlines+++def test_activity_drops_closed_alerts_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."""+ db = tmp_path / "narr-activity.db"+ _setup_isolated_db(db, monkeypatch)+ closed = alert_store.insert_alert(+ source="system", external_id="closed-2", severity="high",+ headline="Already handled", body="b", db_path=db,+ )+ assert closed is not None+ alert_store.set_status(closed, "dismissed", db_path=db)+ alert_store.insert_alert(+ source="system", external_id="open-2", severity="high",+ headline="Still open", body="b", db_path=db,+ )++ 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+++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+++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+++def test_empty_board_skips_the_model_call(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ """The core regression: with everything dismissed, the header must say it+ is quiet rather than synthesizing a story out of the history rail."""+ db = tmp_path / "empty-board.db"+ _setup_isolated_db(db, monkeypatch)+ dismissed = alert_store.insert_alert(+ source="system", external_id="dismissed-1", severity="urgent",+ headline="St. Albans reconciliation gap", body="b", db_path=db,+ )+ assert dismissed is not None+ alert_store.set_status(dismissed, "dismissed", db_path=db)++ calls = {"n": 0}++ async def _synth(**_kw: object) -> str:+ calls["n"] += 1+ return "**Bottom line:** St. Albans is on fire."++ monkeypatch.setattr(briefing_narrative, "synthesize_briefing_narrative", _synth)++ c = _make_client()+ assert c.get("/today").json()["proposals"] == []+ narr = c.get("/today").json()["narrative"]+ assert narr == "Quiet right now — nothing pressing."+ assert calls["n"] == 0+ assert "St. Albans" not in (narr or "")+++def test_live_board_still_synthesizes(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ """The quiet short-circuit must not swallow a real board."""+ db = tmp_path / "live-board.db"+ _setup_isolated_db(db, monkeypatch)+ _seed_live_action_alert(db)++ calls = {"n": 0}++ async def _synth(**_kw: object) -> str:+ calls["n"] += 1+ return "**Bottom line:** the budget needs you."++ monkeypatch.setattr(briefing_narrative, "synthesize_briefing_narrative", _synth)++ c = _make_client()+ c.get("/today")+ assert c.get("/today").json()["narrative"] == "**Bottom line:** the budget needs you."+ assert calls["n"] == 1