Skip to content

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

118 KB
Raw Blame
"""GET /today — live dashboard summary for the UI.

Returns a JSON snapshot of:
  • departments — one entry per department with Goal health summary and
    awaiting workflow count
  • people — compact roster with awaiting-action counts and next-SLA time
  • proposals — every unread alert (workflow approvals, triage-classified
    inbound, Executive create_alert calls). The UI splits this into
    "Needs you" vs "Across the team" using caller_person_id plus a
    "principal owns unrouted" rule for alerts with no routed_to_person_id.

The legacy path `/morning-brief` is kept as a deprecated alias for one release
so older UI builds and bookmarked URLs keep working.

GET /today/activity returns the Executive's recent self-initiated activity —
fired scheduled_actions (DMs sent, follow-ups dispatched, cadences run),
plus decisions and advice the system has logged. Powers the "Recent
activity" rail on the briefing-first landing.

GET /today/top-three and GET /today/weekly-review feed two solo-only
Briefing cards — today's top three (as the morning brief picks them) and the
latest completed weekly review — for the principal alone; null in team mode
and for anyone else.
"""
from __future__ import annotations

import asyncio
import json
import logging
from datetime import UTC, datetime, timedelta, tzinfo
from typing import TYPE_CHECKING, Any, Literal

from fastapi import APIRouter, BackgroundTasks, HTTPException, Query, Request, Response
from pydantic import BaseModel, Field

from openexecutive.briefing.value_summary import ValueSummary
from openexecutive.clients.cockpit import ClientCockpitCard, format_practice_for_today

if TYPE_CHECKING:
    from openexecutive.alerts.models import Alert
    from openexecutive.briefing.reader import Reader
    from openexecutive.departments.models import Goal
    from openexecutive.people.models import Person

logger = logging.getLogger(__name__)

# A person whose cached insight note is stale and needs background regen:
# (person, signals-dict, input-hash). Built in `_build_today`, consumed by
# `_regen_stale_insights` after the response is sent.
StaleInsight = tuple["Person", dict[str, Any], str]

# Most attention-worthy (off-track/at-risk) goals shown inline on a Department
# card before the card defers the rest to the department page.
_DEPT_ATTENTION_GOAL_CAP = 3
# The briefing row that holds the goals with no department (slug ""). It is
# shaped like a department so every reader of `departments` (the narrative,
# the header, the digest, the fingerprint) counts its at-risk goals too.
UNASSIGNED_GOALS_TITLE = "Other goals"

router = APIRouter()


# --------------------------------------------------------------------------- #
# Response models
# --------------------------------------------------------------------------- #

class GoalBrief(BaseModel):
    """A single attention-worthy goal, surfaced inline on the briefing's
    Department card so the principal sees *which* goal is off and how far —
    `current` vs `target` — without opening the department."""

    key_result: str
    current: str
    target: str
    status: str  # "at_risk" | "off_track" (the only statuses surfaced here)
    # Who the goal is on: its own owner, else the department's lead, else the
    # principal (``departments.goals.effective_owner_id``). Additive.
    owner_id: int | None = None
    owner_name: str = ""


class DepartmentBriefItem(BaseModel):
    # "" for the row of goals with no department (UNASSIGNED_GOALS_TITLE).
    slug: str
    title: str
    authority_level: str
    goal_count: int
    at_risk_count: int
    off_track_count: int
    awaiting_count: int
    # The off-track/at-risk goals themselves (worst first), capped, so the card
    # is insightful at rest. Empty for healthy/inactive departments. Additive —
    # defaults to empty so older clients and test mocks keep working.
    attention_goals: list[GoalBrief] = Field(default_factory=list)


class PersonBriefItem(BaseModel):
    id: int
    full_name: str
    role: str
    is_principal: bool
    preferred_channel: str
    awaiting_count: int
    soonest_sla_at: str | None
    # Enrichment — attention, recency, and routing signals the brief surfaces
    # so the roster is more than a name list. All additive; consumers that
    # only read the original fields (e.g. workflows/morning_brief.py) are
    # unaffected.
    status: str  # on_leave | needs_reply | awaiting | clear
    awaiting_reply_count: int  # open commitments we're waiting on THEM to answer
    oldest_awaiting_reply_at: str | None
    on_leave_until: str | None
    reachable_now: bool
    next_window_at: str | None
    authority_scope: list[str]
    department_slugs: list[str]
    last_contact_at: str | None
    overdue: bool  # any SLA / awaited-reply past its deadline → UI red emphasis
    priority: int  # server-computed sort key; higher = needs attention sooner
    insight: str | None  # utility-fast note, served from cache (None until warm)


class RosterRequestCard(BaseModel):
    """What a roster-request card shows (all server-derived; ``display_name``
    is what the sender called themselves, sanitised and unverified)."""

    id: int
    channel: str
    channel_ref: str
    display_name: str
    profile_email: str | None
    on_company_domain: bool
    suggested_kind: str | None
    suggested_person_id: int | None
    suggested_person_name: str | None
    message_count: int
    ack_sent: bool
    first_seen_at: str
    previews: list[str]


def _roster_request_card(topic_tags: list[str]) -> RosterRequestCard | None:
    """The card for a ``roster_request:{id}`` alert whose request is still
    pending, else None. Never raises."""
    from openexecutive.people import roster_requests as rr

    request_id = rr.parse_alert_tag(topic_tags)
    if request_id is None:
        return None
    try:
        req = rr.get_request(request_id)
        if req is None or req.status != "pending":
            return None
        from openexecutive.people.store import get_person

        suggested = (
            get_person(req.suggested_person_id) if req.suggested_person_id is not None else None
        )
        return RosterRequestCard(
            id=req.id,
            channel=req.channel,
            channel_ref=req.channel_ref,
            display_name=req.display_name,
            profile_email=req.profile_email,
            on_company_domain=req.on_company_domain,
            suggested_kind=req.suggested_kind,
            suggested_person_id=suggested.id if suggested is not None else None,
            suggested_person_name=suggested.full_name if suggested is not None else None,
            message_count=req.message_count,
            ack_sent=req.ack_sent_at is not None,
            first_seen_at=req.first_seen_at,
            previews=rr.previews(req.id),
        )
    except Exception:
        logger.warning("today: roster request card failed", exc_info=True)
        return None


class ProposalItem(BaseModel):
    alert_id: int
    headline: str
    # Full intent text behind the proposal. `headline` is a 160-char
    # excerpt used as the card title; `body` is the untruncated text
    # the UI seeds into the chat handoff so the Executive has the
    # full context when the user taps the card.
    body: str
    routed_to_person_id: int | None
    suggested_action: str
    created_at: str
    topic_tags: list[str]
    # Presentation signals (see openexecutive.briefing.ranking). `score` is
    # an attention sort key (higher leads); `category` is "action" (a human
    # should look) or "monitoring" (passive watchlist/external noise the UI
    # can collapse so it stops crowding the "Needs you" queue).
    score: int = 0
    category: str = "action"
    # Why this item is in "Needs you" rather than Monitoring — set only when
    # an external/watchlist signal was pulled into the action lane by its
    # severity (large stock move, etc.). Null for everything else; the UI
    # renders it as a small note so the promotion reads as deliberate.
    surfaced_reason: str | None = None
    # Set when this proposal is backed by a decision_instance (a gated
    # calendar booking awaiting approval). The UI routes Approve/Reject to
    # the /decisions endpoints (which book/cancel server-side) instead of the
    # ack-and-handoff-to-chat flow. Null for ordinary alert-backed proposals.
    decision_instance_id: int | None = None
    # A scheduled run that failed (workflows/failure_alerts.py): the run the
    # card's Run again queues once more. None on every other card.
    failed_run_id: str | None = None
    # Set when this card is a roster request ("who is this new sender?",
    # people.roster_requests): the UI answers it at /people/requests/{id}
    # (add / same person as / ignore) instead of ack-and-chat. Private to the
    # principal, like the request.
    roster_request: RosterRequestCard | None = None
    # Lifecycle signals (alerts/lifecycle.py, alerts/review.py). Coalescing:
    # how many times this situation re-fired and when it was last seen.
    occurrence_count: int = 1
    last_seen_at: str | None = None
    # The Executive's latest review of this item: verdict ('' | relevant |
    # changed | likely_stale | drafted | routed | merged; closed rows carry
    # resolved | stale but never reach this list), a one-line "what changed
    # since you last looked", the next move the card should lead with, a
    # short "why now", and a deadline when one exists.
    last_reviewed_at: str | None = None
    review_verdict: str = ""
    review_note: str = ""
    recommended_move: str = ""
    why_now: str = ""
    due_at: str | None = None
    # Rows the review folded into this one (merge).
    superseded_count: int = 0
    # Registry workflow the review suggested as the next step ('' = none).
    suggested_workflow: str = ""
    # Drafted artifacts only (source='artifact'): the format, so the card can
    # badge it and link to /artifacts, and the link target for 'link' ones.
    # `body` already carries a Markdown rendering for every format.
    artifact_format: str | None = None
    artifact_url: str | None = None


def _proposal_body(alert: Alert) -> str:
    """Markdown the card and the chat handoff can show, for any alert.

    Artifact bodies are stored per format (HTML, sheet JSON…); everything
    else is already the text to show.
    """
    if alert.source != "artifact":
        return alert.body or alert.headline
    from openexecutive.orchestrator.artifact_formats import get_format

    return get_format(alert.artifact_format).display(alert.body or "") or alert.headline


def _as_int(raw: Any) -> int | None:
    try:
        return int(raw) if raw is not None else None
    except (TypeError, ValueError):
        return None


def _alert_status_now(alert_id: int | None, now: datetime) -> str:
    """Current lifecycle state of the alert a handled row touched.

    ``open`` means exactly "in the /today queue right now" (`lifecycle.is_live`:
    unread, inside its TTL, not snoozed) — the only state where a "still open"
    jump link has a card to land on and where a close row can be read as
    undone. ``acked`` is the principal's own approval (not an Undo target),
    ``inactive`` a snoozed / TTL-expired row the sweep has not closed yet.
    """
    if alert_id is None:
        return ""
    try:
        from openexecutive.alerts import lifecycle
        from openexecutive.alerts.store import get_alert

        alert = get_alert(alert_id)
    except Exception:
        logger.debug("today: alert status lookup failed for %s", alert_id, exc_info=True)
        return ""
    if alert is None:
        return ""
    if alert.superseded_by_alert_id is not None:
        return "merged"
    if alert.status in {"resolved", "dismissed", "expired"}:
        return alert.status
    if alert.status == "ack":
        return "acked"
    return "open" if lifecycle.is_live(alert, now) else "inactive"


# Which audit-details keys fill a handled row's `target` and `detail`, per
# kind. `headline` defaults to the alert headline; watch rows use the slug.
_HANDLED_TARGET_KEY: dict[str, str] = {
    "routed": "target_person_name",
    "nudged": "target_person_name",
    "escalated": "new_severity",
    "drafted": "draft_title",
    "merged": "superseded_by_headline",
    "suggested_workflow": "workflow_name",
}
_HANDLED_DETAIL_KEYS: dict[str, tuple[str, ...]] = {
    "closed": ("evidence",),
    "escalated": ("evidence",),
    "watching": ("rationale", "reason"),
    "stopped_watching": ("rationale", "reason"),
}
_WATCH_KINDS = frozenset({"watching", "stopped_watching"})


def _handled_outcome(kind: str, details: dict[str, Any]) -> str:
    """resolved | dismissed for a close, proposed for a gated route, else ''."""
    if kind == "closed":
        return str(details.get("new_status") or "")
    if kind == "routed" and details.get("proposed"):
        return "proposed"
    return ""


def _handled_item(h: dict[str, Any], now: datetime) -> HandledItem:
    """One structured rail row from a `brief_state.handled_since` entry."""
    kind = str(h["kind"])
    raw_details = h.get("details")
    details: dict[str, Any] = raw_details if isinstance(raw_details, dict) else {}
    alert_id = _as_int(h.get("alert_id"))
    headline = details.get("slug") if kind in _WATCH_KINDS else details.get("headline")
    target_key = _HANDLED_TARGET_KEY.get(kind)
    target = details.get(target_key) if target_key else None
    detail = next(
        (str(details[k]) for k in _HANDLED_DETAIL_KEYS.get(kind, ()) if details.get(k)), ""
    )
    return HandledItem(
        kind=kind,
        summary=str(h["summary"]),
        at=str(h["at"]),
        alert_id=alert_id,
        event_type=str(h.get("event_type") or ""),
        headline=str(headline) if headline else None,
        target=str(target) if target else None,
        detail=detail,
        outcome=_handled_outcome(kind, details),
        evidence_ref=str(details.get("evidence_ref") or ""),
        superseded_by_alert_id=_as_int(details.get("superseded_by_alert_id")),
        status=_alert_status_now(alert_id, now),
    )


def _handled_overnight(now: datetime, *, include_private: bool = False) -> list[HandledItem]:
    """What the alert review completed since the last delivered morning brief.
    Rows private to the principal only for the principal's own view."""
    try:
        from openexecutive.briefing import brief_state

        since = brief_state.since_for("principal_brief_morning", now=now)
        handled = brief_state.handled_since(since, limit=20, include_private=include_private)
        return [_handled_item(h, now) for h in handled]
    except Exception:
        logger.debug("today: handled_overnight unavailable", exc_info=True)
        return []


def _watch_trust_by_slug(alerts: list[Any]) -> dict[str, float]:
    """``{watch slug: trust_score}`` for every watch referenced by ``alerts``.

    One lookup per distinct slug so ranking can discount watches the
    principal keeps dismissing. Never raises — a missing monitoring store
    just yields an empty map (no discount).
    """
    from openexecutive.briefing.ranking import watch_slug_from_tags

    slugs = {
        slug for a in alerts
        if (slug := watch_slug_from_tags(list(getattr(a, "topic_tags", []) or []))) is not None
    }
    if not slugs:
        return {}
    try:
        from openexecutive.monitoring import store as monitoring_store

        out: dict[str, float] = {}
        for slug in slugs:
            item = monitoring_store.get_watchlist_item_by_slug(slug)
            if item is not None:
                out[slug] = float(getattr(item, "trust_score", 1.0))
        return out
    except Exception:
        logger.debug("today: watch trust lookup failed", exc_info=True)
        return {}


def _parse_decision_instance_id(topic_tags: list[str]) -> int | None:
    """Extract the decision_instance id from a ``decision_instance:{id}`` tag.

    Returns None when the tag is absent or its suffix isn't an integer.
    """
    from openexecutive.memory.decision_ledger import DECISION_INSTANCE_TAG_PREFIX

    for tag in topic_tags:
        if tag.startswith(DECISION_INSTANCE_TAG_PREFIX):
            suffix = tag[len(DECISION_INSTANCE_TAG_PREFIX):]
            try:
                return int(suffix)
            except ValueError:
                # Malformed suffix — keep scanning in case a later tag is valid.
                continue
    return None


class InFlightItem(BaseModel):
    """An Executive commitment the briefing surfaces as 'about to happen'.

    A user-facing pending scheduled_action — a follow-up it will run or a
    nudge it will send. `target` is the resolved recipient name (or
    department / raw channel ref); `overdue` is True when run_at has already
    passed (the scheduler hasn't fired it yet).
    """

    action_id: int
    intent: str
    run_at: str
    kind: str
    channel: str
    target: str | None
    department: str | None
    overdue: bool


class AwaitingItem(BaseModel):
    """A person we're waiting on — the 'awaiting others' half of in-flight.

    Derived from the same open-commitment set that powers each person's
    `awaiting_reply_count`/`overdue` enrichment, surfaced as its own list so
    the briefing can show "we're chasing X" without scanning the roster.
    """

    person_id: int
    full_name: str
    role: str
    awaiting_count: int
    oldest_at: str | None
    overdue: bool


class HandledItem(BaseModel):
    kind: str
    summary: str
    at: str
    # The alert the move touched, when known — lets the UI offer Undo
    # (POST /alerts/{id}/reopen) right next to the "handled" row.
    alert_id: int | None = None
    # Structured view of the same audit row so the rail can render "who /
    # what / why" instead of one truncated sentence. All additive; `summary`
    # stays the fallback line.
    # Raw audit event type, for a pre-filtered /audit deep link.
    event_type: str = ""
    # The alert's headline when the move was made (a watch's slug for the
    # watching / stopped_watching kinds).
    headline: str | None = None
    # Who or what the move went to: a person's name (routed / nudged), the
    # survivor headline (merged), the new severity (escalated), the draft
    # title (drafted) or the workflow name (suggested_workflow).
    target: str | None = None
    # The "why": the cited evidence (closed / escalated) or the watch
    # policy's reason (watching / stopped_watching).
    detail: str = ""
    # Finer than `kind`: "resolved" | "dismissed" for a close (a dismissal is
    # a judgment call and must read differently), "proposed" for a route
    # that went through the authority gate instead of a DM, else "".
    outcome: str = ""
    # Server-minted evidence ref a close cited (S1 / R2 / A3), else "".
    evidence_ref: str = ""
    # The survivor a merge folded this alert into, for collapsing the pair.
    superseded_by_alert_id: int | None = None
    # The alert's status NOW: "open" (live in the /today queue) | "resolved" |
    # "dismissed" | "expired" | "merged" | "acked" (principal approved it) |
    # "inactive" (snoozed / past TTL, unswept); "" when there is no alert. The
    # rail is rebuilt from the audit log on every fetch, so this is what tells
    # the UI a close was already undone (offer "Reopened", not another Undo)
    # and whether a "still open" link has a card to land on.
    status: str = ""


class FirstWeekFinding(BaseModel):
    title: str
    summary: str


class FirstWeekCardModel(BaseModel):
    """Home's first-week card (``briefing.first_week.first_week_card``)."""

    needs_goal: bool = False
    findings: list[FirstWeekFinding] = Field(default_factory=list)
    brief_tomorrow: bool = False


class HeldBackItem(BaseModel):
    """Lines grounding left out of one of the principal's briefs (the
    "Left out of your brief" block on Home, which the brief's note names)."""

    event_id: int
    # "morning brief" / "end-of-day digest"
    surface: str
    at: str
    lines: list[str]


class PointSource(BaseModel):
    """What a Right now point is about, when Home can open it: an email in
    the reader's own inbox (``kind`` "mail": its ids, and its reply card
    when one is open) or a card in Needs you (``kind`` "alert")."""

    kind: Literal["mail", "alert"]
    message_id: str | None = None
    thread_id: str | None = None
    decision_id: int | None = None
    alert_id: int | None = None


class NarrativePoint(BaseModel):
    """One point of Right now (the /today header): its Markdown, when it
    first appeared today (ISO-8601 UTC), and what it is about."""

    text: str
    since: str | None = None
    source: PointSource | None = None


def _point_source(raw: dict[str, Any] | None) -> PointSource | None:
    """A stored point source as the API shows it; None when unreadable."""
    if not raw:
        return None
    try:
        return PointSource.model_validate(raw)
    except ValueError:
        return None


class NarrativeProgress(BaseModel):
    """What a Right now being written is doing, for the page to show in its
    place: ``reading`` what moved (mail, calendar, Needs you), ``writing``
    the header, ``checking`` each point cites something that moved. Plus how
    many emails from people they deal with came to the principal's own inbox
    since the served header was written (``since``), when there is one."""

    step: Literal["reading", "writing", "checking"]
    new_mail: int = 0
    since: str | None = None


class MorningBriefItem(BaseModel):
    """Today's delivered morning brief, for Right now's "Earlier today" link."""

    at: str
    text: str


class CalendarNextItem(BaseModel):
    """A meeting still ahead today, for Right now's calendar list. ``start``
    is ISO-8601 UTC; None with ``all_day``."""

    title: str
    start: str | None = None
    all_day: bool = False


class TodayResponse(BaseModel):
    departments: list[DepartmentBriefItem]
    people: list[PersonBriefItem]
    proposals: list[ProposalItem]
    # Executive-voice narrative header — "here's what's going on" — served
    # from `briefing.narrative_cache` and regenerated off the hot path. None
    # until the first background generation has run (or on a cold cache).
    narrative: str | None = None
    # When the served narrative was written (ISO-8601 UTC), and whether a
    # fresher one is being written right now. The UI shows "Updated …" from
    # the first and re-polls /today while the second is true, so a new
    # narrative lands without a reload. Additive; None / False on a cold cache.
    narrative_generated_at: str | None = None
    narrative_stale: bool = False
    # While ``narrative_stale``: what the rewrite is doing, so the page shows
    # that instead of the header it replaces. Additive; None otherwise.
    narrative_progress: NarrativeProgress | None = None
    # The same narrative split for Home's Right now card
    # (``briefing.right_now``): the bold opener, the points with when each
    # first appeared today, and the Move today line. Plus when this reader
    # last looked, so the page can say what is new since. Additive.
    narrative_lead: str | None = None
    narrative_points: list[NarrativePoint] = Field(default_factory=list)
    narrative_move: str | None = None
    narrative_seen_at: str | None = None
    # When the served header was last found current (ISO-8601 UTC): now,
    # when nothing it reads has moved since it was written, so a quiet
    # header says "Checked 2:20 PM" rather than the hour it was written.
    # None while a fresher one is being written. Additive.
    narrative_checked_at: str | None = None
    # The principal's own: mail to their own inbox today from people they
    # don't deal with (strangers, bulk mail), as short "Name: subject"
    # labels (a few) and how many there were. Right now's "Also in" line,
    # never a point. Additive; empty / 0 for anyone else.
    inbox_also: list[str] = Field(default_factory=list)
    inbox_also_total: int = 0
    # The principal's own: today's delivered morning brief and the meetings
    # still ahead today. Additive; None / empty for anyone else.
    morning_brief: MorningBriefItem | None = None
    calendar_next: list[CalendarNextItem] = Field(default_factory=list)
    # In-flight work the Executive will do soon (pending follow-ups / nudges)
    # and people we're awaiting a reply from. Both additive, default empty.
    in_flight: list[InFlightItem] = []
    awaiting: list[AwaitingItem] = []
    # Multi-client practice mode only (2+ client slots): rollup cards for the
    # PARKED clients — overdue follow-ups, awaiting replies, renewals — so the
    # operator sees the whole practice from the active client's brief.
    # Additive, default empty (single-company installs ⇒ no section).
    practice_clients: list[ClientCockpitCard] = []
    # The signed-in caller resolved to a Person id via x-caller-email,
    # so the UI can split `proposals` into "routed to me" vs "across the
    # team" without leaking identity to the client. Null when no caller
    # could be resolved (unrostered signed-in user, or a CLI hit with
    # no header). See chat._resolve_caller_person_id.
    caller_person_id: int | None = None
    # Autonomous alert-review moves since the last delivered morning brief
    # (routed / nudged / escalated / drafted / merged / closed), newest first
    # — the "Executive handled N overnight" pill. Additive, default empty.
    handled_overnight: list[HandledItem] = Field(default_factory=list)
    # What grounding held back from the principal's briefs in the last day.
    # Set by GET /today for the principal alone, after the narrative inputs
    # are taken, so the held lines never reach a prompt.
    held_back: list[HeldBackItem] = Field(default_factory=list)
    # The install's first week (``briefing.first_week``), for the principal:
    # Home shows the first-week card instead of calling the day quiet.
    first_week: bool = False
    first_week_card: FirstWeekCardModel | None = None


class ActivityItem(BaseModel):
    """One row in the Executive's recent self-initiated activity feed.

    `kind` is a coarse classification — UI uses it to pick an icon / verb.
    `summary` is the human-readable one-liner. `target` names who or what
    the action was directed at (a Person, a channel, a department), or
    None when not applicable. `at` is an ISO timestamp.
    """

    kind: str
    summary: str
    actor: str
    target: str | None
    department: str | None
    at: str
    # A finished run's line on what came of it (`workflows.run_outcome`),
    # and the artifact id of its write-up when it kept one (`run:<id>`).
    detail: str | None = None
    artifact_id: str | None = None


class ActivityResponse(BaseModel):
    items: list[ActivityItem]


class DailyActivityCount(BaseModel):
    """One day in the Pulse heartbeat heatmap. `date` is YYYY-MM-DD (UTC)."""

    date: str
    count: int


class DailyActivityResponse(BaseModel):
    """Dense per-day activity counts for the last N days, oldest → newest.

    Every calendar day in the window is present (count 0 when nothing fired),
    so the UI can render a gap-free contribution grid without client-side fill.
    """

    days: list[DailyActivityCount]


# --------------------------------------------------------------------------- #
# Builder
# --------------------------------------------------------------------------- #

def _person_status(*, on_leave: bool, awaiting_reply: int, awaiting: int) -> str:
    """Single headline status for a person, highest-attention first."""
    if on_leave:
        return "on_leave"
    if awaiting_reply > 0:
        return "needs_reply"
    if awaiting > 0:
        return "awaiting"
    return "clear"


def _parse_aware(iso: str | None) -> datetime | None:
    """Parse an ISO timestamp to an aware UTC datetime, or None.

    Some on-disk timestamps (workflow `awaiting_until`, scheduled_action
    `awaiting_response_since`) are stored as a bare `.isoformat()` and can be
    timezone-naive. Assume UTC for those — mirroring nudge_engine._coerce_aware
    — so comparisons against `datetime.now(UTC)` neither raise TypeError (which
    would 500 the whole /today request) nor silently drop the signal.
    """
    if not iso:
        return None
    try:
        dt = datetime.fromisoformat(iso)
    except (ValueError, TypeError):
        return None
    return dt if dt.tzinfo is not None else dt.replace(tzinfo=UTC)


def _is_past(iso: str | None, now: datetime) -> bool:
    """True if an ISO timestamp is in the past. Malformed/empty → False."""
    dt = _parse_aware(iso)
    return dt is not None and dt < now


def _reply_overdue(oldest_iso: str | None, sla_hours: int, now: datetime) -> bool:
    """True if an awaited reply has gone unanswered past the person's SLA."""
    dt = _parse_aware(oldest_iso)
    return dt is not None and (now - dt) > timedelta(hours=sla_hours)


def _person_priority(
    *,
    on_leave: bool,
    awaiting: int,
    awaiting_overdue: bool,
    awaiting_reply: int,
    reply_overdue: bool,
    is_principal: bool,
) -> int:
    """Sort key — higher floats to the top of the roster. Overdue work and
    awaited replies dominate; on-leave sinks; principal breaks ties."""
    score = 0
    if reply_overdue:
        score += 60
    elif awaiting_reply > 0:
        score += 40
    if awaiting_overdue:
        score += 30
    elif awaiting > 0:
        score += 20
    if on_leave:
        score -= 40
    if is_principal:
        score += 1
    return score


def _build_today(
    stale_out: list[StaleInsight] | None = None,
    *,
    include_private: bool = False,
    viewer: Any = None,
) -> TodayResponse:
    """Assemble the live dashboard snapshot.

    Stays synchronous so the deprecated /morning-brief alias and the
    morning_brief workflow (which call this directly) need no changes; the LLM
    insight notes are served from cache here and regenerated off the hot path.
    When `stale_out` is provided, people whose cached note is missing/stale are
    appended for the caller to regenerate in the background — only when the
    roster has more than one person (the UI shows no People sidebar for one).

    The briefing narrative is NOT attached here — it is per-viewer (see
    `_attach_narrative`), so the caller-aware endpoints attach it after
    resolving the viewer from `x-caller-email`.
    """
    from openexecutive.departments.store import list_departments
    from openexecutive.memory.episodic import (
        last_contact_at_by_person,
        list_awaiting_replies_by_person,
    )
    from openexecutive.people import insights, insights_cache
    from openexecutive.people.channel import is_reachable_now, next_window_for
    from openexecutive.people.store import list_people
    from openexecutive.workflows.persistence import list_awaiting_runs

    now = datetime.now(UTC)
    depts = list_departments()
    people = list_people()
    awaiting_runs = list_awaiting_runs()
    awaiting_replies = list_awaiting_replies_by_person()
    last_contact = last_contact_at_by_person()

    pid_to_awaiting: dict[int, int] = {}
    pid_to_soonest: dict[int, str] = {}
    for run in awaiting_runs:
        pid = run.get("awaiting_person_id")
        if pid is not None:
            pid_to_awaiting[pid] = pid_to_awaiting.get(pid, 0) + 1
            until = run.get("awaiting_until") or ""
            if until and (pid not in pid_to_soonest or until < pid_to_soonest[pid]):
                pid_to_soonest[pid] = until

    dept_awaiting: dict[str, int] = {}
    for run in awaiting_runs:
        raw_state = run.get("state_json") or "{}"
        try:
            state = json.loads(raw_state)
        except (json.JSONDecodeError, TypeError):
            state = {}
        slug = state.get("department", "")
        if slug:
            dept_awaiting[slug] = dept_awaiting.get(slug, 0) + 1

    from openexecutive.departments.goals import list_goal_views

    try:
        views = list_goal_views()
    except Exception:
        logger.warning("today: goal owners unreadable", exc_info=True)
        views = []
    owner_by_goal = {v.goal.id: (v.owner_id, v.owner_name) for v in views}

    def _brief_row(
        slug: str, title: str, authority_level: str, goals: list[Goal]
    ) -> DepartmentBriefItem:
        # Surface the actual problem goals inline on the card — off_track
        # (worse) before at_risk, capped so a department with many goals can't
        # blow out the card. Goals already loaded, so no extra query. The id
        # tiebreaker makes intra-tier order deterministic regardless of how
        # the goals were loaded (today it's ORDER BY id; this pins it).
        attention = sorted(
            (g for g in goals if g.status in ("off_track", "at_risk")),
            key=lambda g: (0 if g.status == "off_track" else 1, g.id or 0),
        )[:_DEPT_ATTENTION_GOAL_CAP]
        return DepartmentBriefItem(
            slug=slug,
            title=title,
            authority_level=authority_level,
            goal_count=len(goals),
            at_risk_count=sum(1 for g in goals if g.status == "at_risk"),
            off_track_count=sum(1 for g in goals if g.status == "off_track"),
            awaiting_count=dept_awaiting.get(slug, 0) if slug else 0,
            attention_goals=[
                GoalBrief(
                    key_result=g.key_result,
                    current=g.current,
                    target=g.target,
                    status=g.status,
                    owner_id=owner_by_goal.get(g.id, (None, ""))[0],
                    owner_name=owner_by_goal.get(g.id, (None, ""))[1],
                )
                for g in attention
            ],
        )

    dept_items = [
        _brief_row(ds.config.slug, ds.config.title, ds.config.authority_level.value, ds.goals)
        for ds in depts
    ]
    unassigned = [v.goal for v in views if not v.goal.department_slug]
    if unassigned:
        dept_items.append(_brief_row("", UNASSIGNED_GOALS_TITLE, "", unassigned))

    # Per-person insight notes only earn their model call when the brief has a
    # roster to show: the UI renders the People sidebar only for more than one
    # person, so a one-person install (solo, or a team before anyone is added)
    # would pay a daily LLM + peer-memory call for a note nobody sees. Decided
    # before the loop; cached notes are still served either way.
    collect_stale = stale_out is not None and len(people) > 1

    person_items = []
    # Per-person reply-overdue, kept separately from PersonBriefItem.overdue
    # (which also folds in workflow-SLA overdue) so the `awaiting` list — which
    # is specifically "we're waiting on their REPLY" — flags only late replies.
    reply_overdue_by_pid: dict[int, bool] = {}
    for person in people:
        pid = person.id or 0
        awaiting = pid_to_awaiting.get(pid, 0)
        soonest_sla_at = pid_to_soonest.get(pid)
        reply_count, oldest_reply = awaiting_replies.get(pid, (0, None))

        on_leave = person.on_leave_until is not None and now.date() <= person.on_leave_until
        reachable = is_reachable_now(person, now=now)
        next_window = None if reachable else next_window_for(person, after=now)
        awaiting_overdue = _is_past(soonest_sla_at, now)
        reply_overdue = _reply_overdue(oldest_reply, person.response_sla_hours, now)
        reply_overdue_by_pid[pid] = reply_overdue
        authority = [s.value for s in person.authority_scope]

        status = _person_status(on_leave=on_leave, awaiting_reply=reply_count, awaiting=awaiting)
        priority = _person_priority(
            on_leave=on_leave,
            awaiting=awaiting,
            awaiting_overdue=awaiting_overdue,
            awaiting_reply=reply_count,
            reply_overdue=reply_overdue,
            is_principal=person.is_principal,
        )

        signals: dict[str, Any] = {
            "role": person.role,
            "is_principal": person.is_principal,
            "status": status,
            "awaiting_count": awaiting,
            "soonest_sla_at": soonest_sla_at,
            "awaiting_reply_count": reply_count,
            "oldest_awaiting_reply_at": oldest_reply,
            "overdue": awaiting_overdue or reply_overdue,
            "on_leave_until": person.on_leave_until.isoformat() if person.on_leave_until else None,
            "reachable_now": reachable,
            "next_window_at": next_window.isoformat() if next_window else None,
            "authority_scope": authority,
            "department_slugs": person.department_slugs,
            "last_contact_at": last_contact.get(pid),
        }

        # Insight: serve from cache; collect stale entries for background regen.
        # Skip unsaved people (no stable id to key the cache on).
        insight: str | None = None
        if pid:
            input_hash = insights.build_insight_input_hash(signals)
            cached = insights_cache.get(pid)
            if cached is not None and cached.input_hash == input_hash:
                insight = cached.insight_text
            elif collect_stale and stale_out is not None:
                stale_out.append((person, signals, input_hash))

        person_items.append(PersonBriefItem(
            id=pid,
            full_name=person.full_name,
            role=person.role,
            is_principal=person.is_principal,
            preferred_channel=person.preferred_channel,
            awaiting_count=awaiting,
            soonest_sla_at=soonest_sla_at,
            status=status,
            awaiting_reply_count=reply_count,
            oldest_awaiting_reply_at=oldest_reply,
            on_leave_until=signals["on_leave_until"],
            reachable_now=reachable,
            next_window_at=signals["next_window_at"],
            authority_scope=authority,
            department_slugs=person.department_slugs,
            last_contact_at=last_contact.get(pid),
            overdue=awaiting_overdue or reply_overdue,
            priority=priority,
            insight=insight,
        ))

    # Attention-worthy people first; stable name order within a priority band.
    person_items.sort(key=lambda p: (-p.priority, p.full_name))

    from openexecutive.alerts import lifecycle as lifecycle_module
    from openexecutive.alerts.lifecycle import list_live_alerts
    from openexecutive.alerts.store import count_superseded_by
    from openexecutive.briefing.ranking import score_and_categorize
    from openexecutive.workflows.failure_alerts import SOURCE as FAILED_RUN_SOURCE
    from openexecutive.workflows.failure_alerts import failed_run_id

    # Live = unread AND inside its TTL AND not snoozed — the read-side twin of
    # the scheduler's expiry sweep, so the page is right before the sweep runs.
    # A drafted artifact's card only for its owner (`viewer`, the caller of
    # GET /today); every other build (the brief, the digest, the reflection,
    # a cached narrative) leaves them all out.
    raw_alerts = list_live_alerts(
        limit=lifecycle_module.BOARD_LIMIT, now=now, viewer=viewer
    )
    if not include_private:
        # Alerts private to the principal (mail from one of their contacts,
        # a meeting with one) appear only on the principal's own /today —
        # never for a teammate, and never in the morning brief, the
        # end-of-day digest or the reflection, which all read this default.
        from openexecutive.alerts.models import is_private_alert

        raw_alerts = [a for a in raw_alerts if not is_private_alert(a)]
    superseded_counts = count_superseded_by()
    trust_by_slug = _watch_trust_by_slug(raw_alerts)
    proposal_items = []
    for alert in raw_alerts:
        # Surface every unread alert as a briefing action item, including
        # alerts with no routed_to_person_id. Previously these were
        # invisible — the Executive's create_alert tool calls (from
        # inbound triage, operational signals, etc.) produced rows that
        # landed in the table but never showed up in the briefing. The
        # UI splits "Needs you" vs "Across the team" using caller +
        # principal-owns-unrouted; everything stays one queue.
        #
        # Score + categorize so the UI can lead with genuinely-actionable
        # items and collapse low-signal monitoring noise.
        item_score, item_category, item_reason = score_and_categorize(
            alert, trust_by_slug=trust_by_slug, now=now
        )
        proposal_items.append(ProposalItem(
            alert_id=alert.id or 0,
            headline=alert.headline,
            body=_proposal_body(alert),
            routed_to_person_id=alert.routed_to_person_id,
            suggested_action=alert.suggested_action,
            created_at=alert.created_at,
            topic_tags=alert.topic_tags or [],
            score=item_score,
            category=item_category,
            surfaced_reason=item_reason,
            decision_instance_id=_parse_decision_instance_id(alert.topic_tags or []),
            failed_run_id=(
                failed_run_id(alert.topic_tags or [])
                if alert.source == FAILED_RUN_SOURCE
                else None
            ),
            roster_request=(
                _roster_request_card(alert.topic_tags or [])
                if alert.source == "roster_request" else None
            ),
            occurrence_count=alert.occurrence_count,
            last_seen_at=alert.last_seen_at,
            last_reviewed_at=alert.last_reviewed_at,
            review_verdict=alert.review_verdict,
            review_note=alert.review_note,
            recommended_move=alert.recommended_move,
            why_now=alert.why_now,
            due_at=alert.due_at,
            superseded_count=superseded_counts.get(alert.id or -1, 0),
            suggested_workflow=alert.suggested_workflow,
            artifact_format=alert.artifact_format if alert.source == "artifact" else None,
            artifact_url=alert.artifact_url if alert.source == "artifact" else None,
        ))

    # Action items first (sharpest by score), monitoring noise after; ties
    # broken by recency (most recent first). Two-pass stable sort: order by
    # created_at DESC first, then by (category, -score) — Python's stable
    # sort preserves the recency order within equal category/score bands.
    # The UI further splits action items into "Needs you" / "Across the
    # team" and collapses the monitoring tail.
    proposal_items.sort(key=lambda p: p.created_at, reverse=True)
    proposal_items.sort(key=lambda p: (0 if p.category == "action" else 1, -p.score))

    response = TodayResponse(
        departments=dept_items,
        people=person_items,
        proposals=proposal_items,
        handled_overnight=_handled_overnight(now, include_private=include_private),
    )

    # In-flight commitments (pending follow-ups / nudges) + people we're
    # awaiting a reply from. Both reuse data already loaded above, so this
    # adds one cheap query (pending actions) and no extra LLM work. The
    # narrative hash above ignores these keys, so populating them here does
    # not affect narrative freshness.
    from openexecutive.memory.episodic import list_pending_scheduled_actions

    pid_to_name = {p.id: p.full_name for p in people if p.id}
    channel_lookup = _build_channel_lookup()
    in_flight_items: list[InFlightItem] = []
    try:
        for action in list_pending_scheduled_actions():
            target: str | None = None
            if action.assigned_to_person_id is not None:
                target = pid_to_name.get(action.assigned_to_person_id)
            if target is None:
                target = _resolve_channel_target(
                    channel_lookup, action.channel, action.channel_ref or ""
                )
            in_flight_items.append(InFlightItem(
                action_id=action.id or 0,
                intent=action.intent_text,
                run_at=action.run_at,
                kind=action.kind,
                channel=action.channel,
                target=target,
                department=action.department or None,
                overdue=_is_past(action.run_at, now),
            ))
    except Exception:
        logger.exception("today: in-flight scheduled actions read failed")

    awaiting_items = [
        AwaitingItem(
            person_id=p.id,
            full_name=p.full_name,
            role=p.role,
            awaiting_count=p.awaiting_reply_count,
            oldest_at=p.oldest_awaiting_reply_at,
            # Reply-specific overdue (not the person's combined SLA overdue),
            # since this list is about late *replies*.
            overdue=reply_overdue_by_pid.get(p.id, p.overdue),
        )
        for p in person_items
        if p.awaiting_reply_count > 0
    ]
    # Most-overdue first; within a group, those with a known oldest-awaited
    # timestamp (oldest first) ahead of any with none.
    awaiting_items.sort(
        key=lambda a: (not a.overdue, a.oldest_at is None, a.oldest_at or "")
    )

    response.in_flight = in_flight_items
    response.awaiting = awaiting_items

    # Parked clients in multi-client practice mode. The helper returns [] for
    # single-company installs (0–1 slots) and swallows its own errors.
    from openexecutive.config import get_settings as _get_settings

    response.practice_clients = format_practice_for_today(_get_settings())

    return response


def _classify_scheduled_action(kind: str, channel: str) -> str:
    """Map a fired scheduled_action to a UI-friendly activity kind.

    Mirrors the kind/channel taxonomy declared in
    openexecutive.memory.episodic.ScheduledAction. Unknown combinations
    fall back to "action" rather than raising — the activity feed is
    best-effort and should keep rendering even if a new kind is added
    that this code hasn't been taught about.
    """
    if kind == "proactive_nudge":
        return "nudge_sent"
    if kind == "dept_cadence":
        return "cadence_sent"
    if kind == "awaiting_human":
        return "workflow_resumed"
    if channel in ("slack_dm", "discord_dm"):
        return "dm_sent"
    if channel == "email":
        return "email_sent"
    if channel == "telegram":
        return "dm_sent"
    return "action"


def _build_channel_lookup() -> dict[tuple[str, str], str]:
    """Map (channel, channel_ref) → person.full_name for the whole roster.

    Lets the activity rail and the in-flight list say "DM Jordan Avery"
    instead of leaking a raw Discord/Slack/Telegram id. Built once per
    request by the caller.
    """
    from openexecutive.people import registry as people_registry

    lookup: dict[tuple[str, str], str] = {}
    for person in people_registry.list_people():
        if person.discord_user_id:
            lookup[("discord_dm", person.discord_user_id)] = person.full_name
        if person.slack_user_id:
            lookup[("slack_dm", person.slack_user_id)] = person.full_name
        if person.telegram_chat_id:
            lookup[("telegram", person.telegram_chat_id)] = person.full_name
        for address in [person.email, *person.email_aliases]:
            if address:
                lookup[("email", address.lower())] = person.full_name
    return lookup


def _resolve_channel_target(
    lookup: dict[tuple[str, str], str], channel: str, channel_ref: str
) -> str | None:
    """Resolve a (channel, channel_ref) to a person name, or the raw ref.

    Email channel_refs sometimes carry a "|thread_id" suffix (written by the
    scheduler runner) — strip it before the email lookup.
    """
    if not channel_ref:
        return None
    key_ref = (
        channel_ref.split("|", 1)[0].strip().lower()
        if channel == "email"
        else channel_ref
    )
    return lookup.get((channel, key_ref), channel_ref)


# Held Take the lead actions (orchestrator.take_the_lead.DECISION_CLASS).
TAKE_THE_LEAD_CLASS = "take_the_lead_action"
DEPARTMENT_ACTION_CLASS = "department_action"

# Terminal decision-instance status → human verb for the activity rail.
_DECISION_STATUS_LABEL = {
    "approved_unchanged": "Approved",
    "approved_with_edit": "Approved (edited)",
    "rejected": "Rejected",
    "auto_no_response": "Expired (no response)",
    "reversed": "Reversed",
    "executed": "Executed",
    "failed": "Failed",
    "closed_externally": "Closed",
}


def _payload_is_private(payload_json: str | None) -> bool:
    """Whether a decision payload is private to the principal (a booking with
    one of their contacts — see ``calendar_tools``)."""
    try:
        data = json.loads(payload_json or "")
    except (json.JSONDecodeError, TypeError):
        return False
    return isinstance(data, dict) and data.get("private") is True


def _payload_headline(payload_json: str | None) -> str | None:
    """Best-effort human label from a decision payload JSON blob.

    Decision payloads aren't a fixed shape, so probe the common human-readable
    keys in priority order; return None if none are present or the blob is not
    parseable, so the caller can fall back to the decision_class.
    """
    if not payload_json:
        return None
    try:
        data = json.loads(payload_json)
    except (json.JSONDecodeError, TypeError):
        return None
    if not isinstance(data, dict):
        return None
    for key in ("summary", "title", "headline", "name"):
        value = data.get(key)
        if isinstance(value, str) and value.strip():
            return value.strip()
    return None


def _app_action_summary(instance: Any) -> str | None:
    """What a card left from chat (``orchestrator.app_control``) did, in its
    own words ("Deleted the department “Finance”"), or what it would have
    done ("Turned down: Delete the department “Finance”"). "" for a card on
    something private to its person (left off the feed); None for any other
    decision class. Its payload's title is only the item's name, so the
    generic "Approved: Finance" read as the Executive approving a decision."""
    from openexecutive.orchestrator.app_control import DECISION_CLASS

    if instance.decision_class != DECISION_CLASS:
        return None
    final = _payload_dict(instance.final_payload_json)
    proposed = _payload_dict(instance.proposed_payload_json)
    if not _team_visible_app_action(str(proposed.get("action") or "")):
        return ""  # names something private (a chat, a file, a memory): left out
    did = final.get("did")
    if isinstance(did, str) and did.strip() and instance.status in _APPROVED_STATUSES:
        return f"{did.strip()} (asked for in chat, approved on its card)"
    card = final.get("card") or proposed.get("card") or proposed.get("title") or "a change from chat"
    if instance.status in _APPROVED_STATUSES:
        verb = "Done"
    else:
        verb = {"rejected": "Turned down", "failed": "Didn't go through"}.get(instance.status, "Not done")
    return f"{verb}: {str(card).strip()}"


_APPROVED_STATUSES = frozenset({"approved_unchanged", "approved_with_edit", "executed"})

# Cards whose item the whole team may see by name (``app_control_catalog``);
# the rest (a chat's title, a file, a memory) stay off this shared feed.
_TEAM_VISIBLE_APP_ACTIONS = frozenset({"add_department", "rename_department", "delete_department"})


def _team_visible_app_action(action_name: str) -> bool:
    return action_name in _TEAM_VISIBLE_APP_ACTIONS


def _payload_dict(payload_json: str | None) -> dict[str, Any]:
    try:
        data = json.loads(payload_json or "")
    except (json.JSONDecodeError, TypeError):
        return {}
    return data if isinstance(data, dict) else {}


# The Executive's own daily rhythm runs. Each lands as a dated
# "workflow_done: Executive Reflection 2026-09-28" row every day: fine on the
# rail, but noise to the header and the briefs (and the dated title moved the
# brief's "unchanged" fingerprint every day, so it never suppressed).
RHYTHM_WORKFLOWS: frozenset[str] = frozenset({
    "morning_brief", "end_of_day_digest", "executive_reflection", "weekly_review",
})


def _build_activity(
    limit: int,
    since: datetime | None = None,
    *,
    include_alert_raised: bool = True,
    exclude_workflows: frozenset[str] = frozenset(),
) -> ActivityResponse:
    """Aggregate recent self-initiated Executive activity across sources.

    ``since`` bounds the feed to items at/after that instant (the briefs pass
    the previous delivery time so "what changed" is a real delta); the pool
    is widened so a busy history cannot starve the window.

    ``exclude_workflows`` drops completed runs of those workflow names (the
    header and the briefs pass ``RHYTHM_WORKFLOWS``).

    ``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,
        cadences, workflow resumes. Internal channels and the nudge_scan
        heartbeat are filtered out (no user-visible side effect).
      • decisions — items the extractor recorded the user committed to.
      • advice_given — strategic advice the system rendered worth keeping.
      • workflow_runs with status='done' — briefings, department check-ins,
        research runs the Executive completed on its own initiative.
      • initiatives — projects the Executive kicked off / is tracking.
      • decision_instances that reached a terminal state — gated proposals
        approved / rejected / reversed (the autonomy gate outcomes).
      • alerts — operational signals the Executive raised.

    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 store as alerts_store
    from openexecutive.memory import decision_ledger
    from openexecutive.memory.episodic import (
        get_recent_advice,
        get_recent_decisions,
        get_recent_initiatives,
        list_scheduled_actions,
    )
    from openexecutive.workflows import persistence as wf_persistence

    items: list[ActivityItem] = []

    # Pull a generous pool from each source so the post-merge sort
    # produces a representative top-N; the route clamps `limit` itself.
    pool = max(limit * 3, 30) if since is None else max(limit * 5, 50)

    # Resolve channel_ref → person.full_name once per request so the
    # activity rail can say "DM'd Jordan Avery" instead of leaking the
    # raw Discord/Slack/Telegram id.
    channel_lookup = _build_channel_lookup()

    def _resolve_target(channel: str, channel_ref: str) -> str | None:
        return _resolve_channel_target(channel_lookup, channel, channel_ref)

    # Departments in propose_only mode get marked done by the runner
    # WITHOUT dispatching (scheduler/runner.py:135). The action shows up
    # in the activity feed because status=done, but no DM actually went
    # out — labelling those as "DM'd" is misleading. Override the kind
    # so the UI renders them with a different verb ("Proposed to …").
    from openexecutive.departments import store as dept_store
    propose_only_depts = {
        d.config.slug
        for d in dept_store.list_departments()
        if d.config.authority_level == "propose_only"
    }

    from openexecutive.alerts.models import is_private_alert, visible_alert

    for action in list_scheduled_actions(status="done", limit=pool, exclude_internal=True):
        if action.kind == "nudge_scan" or action.channel == "__internal__":
            continue
        # `created_at` is when the action was queued, not when it fired.
        # For ad-hoc follow-ups these are typically minutes apart, but
        # long-running cadences/nudges can have `run_at` days after
        # `created_at`. There is no `done_at` column today; switching
        # to `run_at` would be more truthful for fired actions but is
        # a wider schema change to defer.
        kind = _classify_scheduled_action(action.kind, action.channel)
        if action.department and action.department in propose_only_depts:
            kind = "proposal_routed"
        items.append(ActivityItem(
            kind=kind,
            summary=action.intent_text,
            actor="Executive",
            target=_resolve_target(action.channel, action.channel_ref or ""),
            department=action.department or None,
            at=action.created_at,
        ))

    for decision in get_recent_decisions(limit=pool):
        items.append(ActivityItem(
            kind="decision_logged",
            summary=decision.summary,
            actor="Executive",
            target=None,
            department=decision.department or None,
            at=decision.timestamp,
        ))

    for advice in get_recent_advice(limit=pool):
        items.append(ActivityItem(
            kind="advice_given",
            summary=advice.advice_summary,
            actor="Executive",
            target=None,
            department=advice.department or None,
            at=advice.timestamp,
        ))

    # Completed workflow runs — briefings, department check-ins, research runs
    # the Executive finished on its own. The status filter is pushed into SQL
    # (not applied after the pull) so a backlog of running/awaiting runs can't
    # starve the done ones out of the pool. Bucket at `updated_at` (completion).
    # Team runs only: the rail is shown to everyone, and a run someone started
    # by hand is theirs alone (`persistence.run_visible_to`).
    # Rows say what the work was and what came of it (`run_outcome`), never
    # the run's log title ("Executive Research (periodic)").
    from openexecutive.workflows import run_outcome

    for run in wf_persistence.list_runs(
        status="done", limit=pool, visible_to=None, with_body=True,
    ):
        if run.get("workflow_name") in exclude_workflows:
            continue
        items.append(ActivityItem(
            kind="workflow_done",
            summary=run_outcome.plain_name(run),
            actor="Executive",
            target=None,
            department=None,
            at=run["updated_at"],
            detail=run_outcome.outcome_line(run),
            artifact_id=run_outcome.write_up_id(run),
        ))

    # Initiatives the Executive kicked off / is tracking. `created_at` marks
    # when it started; a non-active status is appended so the row reads true.
    for initiative in get_recent_initiatives(limit=pool):
        summary = initiative.title
        if initiative.status and initiative.status != "active":
            summary = f"{summary} ({initiative.status})"
        items.append(ActivityItem(
            kind="initiative_started",
            summary=summary,
            actor="Executive",
            target=None,
            department=initiative.department or None,
            at=initiative.created_at,
        ))

    # Gated decisions that reached a terminal state (approved / rejected /
    # reversed / …). The pending ones are surfaced as proposals, not activity.
    for instance in decision_ledger.list_recent_resolved(limit=pool):
        if _payload_is_private(instance.proposed_payload_json):
            continue  # a meeting with one of the principal's contacts
        if instance.decision_class == TAKE_THE_LEAD_CLASS:
            continue  # its card quotes the message: the Take the lead rows below say what it did
        if instance.decision_class == DEPARTMENT_ACTION_CLASS:
            continue  # it quotes a teammate's conversation; the audit log keeps who approved it
        label = _DECISION_STATUS_LABEL.get(instance.status, "Resolved")
        app_action = _app_action_summary(instance)
        if app_action == "":
            continue
        if app_action is not None:
            items.append(ActivityItem(
                kind="decision_resolved",
                summary=app_action,
                actor="Executive",
                target=None,
                department=instance.department or None,
                at=instance.resolved_at or instance.created_at,
            ))
            continue
        detail = (
            _payload_headline(instance.final_payload_json)
            or _payload_headline(instance.proposed_payload_json)
            or instance.decision_class.replace("_", " ")
        )
        items.append(ActivityItem(
            kind="decision_resolved",
            summary=f"{label}: {detail}",
            actor="Executive",
            target=None,
            department=instance.department or None,
            at=instance.resolved_at or instance.created_at,
        ))

    # Take the lead as the Executive: what it did on its own, and what it
    # did once someone approved it (orchestrator.take_the_lead). Named, never
    # quoted: this feed is the whole team's.
    from openexecutive.orchestrator import take_the_lead

    try:
        led = take_the_lead.done([take_the_lead.SCOPE_EXECUTIVE], days=30, limit=pool)
    except Exception:
        logger.warning("activity: couldn't read Take the lead's rows", exc_info=True)
        led = []
    for row in led:
        if row.status not in ("done", "approved"):
            continue
        items.append(ActivityItem(
            kind="took_the_lead",
            summary=row.summary if row.status == "done" else f"{row.summary} (after a yes)",
            actor="Executive",
            target=None,
            department=None,
            at=row.at,
        ))

    # 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 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.
    for alert in (alerts_store.recent_alerts(
        limit=pool, exclude_source=decision_ledger.DECISION_ALERT_SOURCE,
    ) if include_alert_raised else []):
        if is_private_alert(alert) or not visible_alert(alert, None):
            continue  # the rail is shown to everyone
        items.append(ActivityItem(
            kind="alert_raised",
            summary=alert.headline,
            actor="Executive",
            target=None,
            department=None,
            at=alert.created_at,
        ))

    if since is not None:
        items = [
            i for i in items
            if (at := _parse_aware(i.at)) is not None and at >= since
        ]
    items.sort(key=lambda i: i.at, reverse=True)
    return ActivityResponse(items=items[:limit])


def _build_daily_activity(days: int) -> DailyActivityResponse:
    """Dense per-day activity counts for the Pulse heartbeat heatmap.

    Delegates the bucketing to `episodic.count_activity_by_day` (sparse: only
    days with activity), then fills every calendar day in the window so the
    grid has no holes. Window = the last `days` days inclusive of today (UTC),
    returned oldest → newest. The caller clamps `days`.
    """
    from openexecutive.memory.episodic import count_activity_by_day

    counts = dict(count_activity_by_day(days))
    start = datetime.now(UTC).date() - timedelta(days=days - 1)
    out: list[DailyActivityCount] = []
    for offset in range(days):
        date = (start + timedelta(days=offset)).isoformat()
        out.append(DailyActivityCount(date=date, count=counts.get(date, 0)))
    return DailyActivityResponse(days=out)


# --------------------------------------------------------------------------- #
# Endpoints
# --------------------------------------------------------------------------- #

async def _regen_stale_insights(stale: list[StaleInsight]) -> None:
    """Regenerate and cache insight notes off the request hot path.

    Runs as a FastAPI background task after the response is sent. Each person
    is generated concurrently and guarded so one slow/failed model call can
    neither hang the batch nor surface to the user.
    """
    from openexecutive.people import insights, insights_cache

    async def _one(person: Person, signals: dict[str, Any], input_hash: str) -> None:
        try:
            text = await asyncio.wait_for(
                insights.generate_person_insight(person, signals),
                timeout=25.0,
            )
        except Exception:
            logger.exception("today: insight regen failed for person_id=%s", person.id)
            return
        if text and person.id:
            insights_cache.put(insights_cache.PersonInsight(
                person_id=person.id,
                input_hash=input_hash,
                insight_text=text,
                generated_at=insights_cache.utc_now_iso(),
            ))

    await asyncio.gather(*(_one(p, s, h) for p, s, h in stale))


# --------------------------------------------------------------------------- #
# Per-viewer briefing narrative
# --------------------------------------------------------------------------- #

def _viewer_for(
    response: TodayResponse, caller_person_id: int | None
) -> PersonBriefItem | None:
    """The PersonBriefItem for the resolved caller, or None."""
    if caller_person_id is None:
        return None
    return next((p for p in response.people if p.id == caller_person_id), None)


def _action_proposals(
    proposals: list[ProposalItem], *, include_private: bool = False
) -> list[ProposalItem]:
    """Action-category proposals only — drops monitoring/watchlist noise.

    The narrative is a SYNTHESIS (not a re-list of the cards), so it should
    reason over the signal — decisions/approvals — and ignore the passive
    monitoring items the UI collapses into its own section.

    A private alert (``alerts.models.PRIVATE_ALERT_TAG``) is kept only with
    ``include_private``: the principal's own scope, which no one else is
    served. The shared ``company`` scope an unresolved caller reads, and a
    teammate's, are written from what everyone may see.
    """
    from openexecutive.alerts.models import is_private_alert

    # A roster-request card names a stranger by the name they gave: it stays
    # a card and never reaches the narrative model.
    return [
        p for p in proposals
        if p.category == "action" and (include_private or not is_private_alert(p))
        and p.roster_request is None
    ]


# How recent a monitoring signal must be to reach the header's EXTERNAL block.
_EXTERNAL_WINDOW = timedelta(hours=24)
_EXTERNAL_MAX = 5


def _fresh_external(
    proposals: list[ProposalItem], *, include_private: bool, now: datetime
) -> list[ProposalItem]:
    """Monitoring signals raised in the last day, newest first. They never
    count as needing attention on their own; they only give the header the
    outside world when something else is going on."""
    from openexecutive.alerts.models import is_private_alert

    fresh = [
        p for p in proposals
        if p.category == "monitoring"
        and (include_private or not is_private_alert(p))
        and (at := _parse_aware(p.created_at)) is not None
        and now - at <= _EXTERNAL_WINDOW
    ]
    fresh.sort(key=lambda p: p.created_at, reverse=True)
    return fresh[:_EXTERNAL_MAX]


def _viewer_slice(response: TodayResponse, viewer: PersonBriefItem) -> dict[str, Any]:
    """A `today_data`-shaped dict scoped to one non-principal teammate:
    the action items routed to THEM + their departments' goal health. Mirrors
    the UI's 'routed to me' split; the principal-only 'people waiting on you'
    section is dropped (empty people list)."""
    depts = set(viewer.department_slugs)
    proposals = [
        p for p in _action_proposals(response.proposals)
        if p.routed_to_person_id == viewer.id
    ]
    departments = [d for d in response.departments if d.slug and d.slug in depts]
    # Of the goals with no department, only the ones on this teammate.
    for d in response.departments:
        if d.slug:
            continue
        mine = [g for g in d.attention_goals if g.owner_id == viewer.id]
        if mine:
            departments.append(d.model_copy(update={
                "goal_count": len(mine),
                "at_risk_count": sum(1 for g in mine if g.status == "at_risk"),
                "off_track_count": sum(1 for g in mine if g.status == "off_track"),
                "attention_goals": mine,
            }))
    return {
        "departments": [d.model_dump() for d in departments],
        "people": [],
        "proposals": [p.model_dump() for p in proposals],
    }


def _narrative_inputs(
    response: TodayResponse, caller_person_id: int | None
) -> tuple[str, dict[str, Any], dict[str, str] | None, PersonBriefItem | None]:
    """Resolve (cache scope, scoped today_data, viewer descriptor, viewer row).

    Three scopes:
      * ``principal`` (DEFAULT_SCOPE) — the resolved principal. Their own, so
        it may carry what is private to them (their contacts' mail and
        alerts); nobody else is ever served it.
      * ``company`` — any caller that resolved to no roster row. The
        whole-company synthesis written from what everyone may see.
      * ``person:<id>`` — a non-principal teammate: a role-scoped slice.
    """
    from openexecutive.briefing import narrative_cache

    viewer = _viewer_for(response, caller_person_id)
    if viewer is None or viewer.is_principal:
        # Whole-company synthesis: feed all ACTION proposals (mine + across the
        # team) so the narrative can connect them, minus monitoring noise.
        # At-risk depts / activity stay company-wide.
        own = viewer is not None
        data = response.model_dump()
        data["proposals"] = [
            p.model_dump()
            for p in _action_proposals(response.proposals, include_private=own)
        ]
        data["external"] = [
            p.model_dump()
            for p in _fresh_external(
                response.proposals, include_private=own, now=datetime.now(UTC)
            )
        ]
        scope = narrative_cache.DEFAULT_SCOPE if own else narrative_cache.COMPANY_SCOPE
        return scope, data, None, viewer
    return (
        f"person:{caller_person_id}",
        _viewer_slice(response, viewer),
        {"name": viewer.full_name, "role": viewer.role},
        viewer,
    )


def _narrative_activity(
    viewer: PersonBriefItem | None, viewer_desc: dict[str, str] | None
) -> list[dict[str, Any]]:
    """The activity list the narrative reasons over.

    It is rendered into the context, so it is covered by the cache key like
    everything else the model sees (``narrative_cache.build_narrative_input_
    hash`` hashes the rendered context). On a quiet board it is never built:
    `_narrative_context` short-circuits to the fixed quiet line first, so the
    rail's churn cannot trigger model calls on a board with nothing on it.

    ``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 a
    non-principal teammate, whose feed is narrowed to their own departments.
    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, include_alert_raised=False, exclude_workflows=RHYTHM_WORKFLOWS,
        ).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]
    return activity


def _nothing_needs_attention(today_data: dict[str, Any], mode: str = "team") -> 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. Solo never renders who is
    awaiting (the Executive coordinates nobody but the principal there), so
    it does not count here either.
    """
    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
    if mode == "solo":
        # Solo's own open items (DUE THIS WEEK) want attention too.
        return not today_data.get("due_soon")
    return not any(p.get("awaiting_count", 0) for p in today_data.get("people", []))


def _with_due_soon(
    today_data: dict[str, Any],
    mode: str,
    viewer_desc: dict[str, str] | None,
    scope: str | None = None,
) -> dict[str, Any]:
    """``today_data`` plus ``due_soon``: the principal's open loops due this
    week or overdue (``open_loops.principal_due_soon``), for their own
    whole-business view only: in solo, and in a team on the principal's own
    scope (Right now names what came due today). Rendered into the context,
    so the cache key moves when one is added, closed or falls due. A copy;
    anything else is returned untouched."""
    from openexecutive.briefing import narrative_cache

    if viewer_desc is not None or (mode != "solo" and scope != narrative_cache.DEFAULT_SCOPE):
        return today_data
    from openexecutive.attunement.open_loops import principal_due_soon

    return {**today_data, "due_soon": principal_due_soon()}


# How far back the header's live blocks reach: the principal's local day, or
# the last 12 hours when that is longer (so at 07:00 last night's mail is
# still "going on").
_LIVE_MIN_LOOKBACK = timedelta(hours=12)


def _live_start(now: datetime, tz: tzinfo) -> datetime:
    """Where Right now's live window starts: local midnight, or
    ``_LIVE_MIN_LOOKBACK`` before the current hour when that is earlier."""
    hour = now.astimezone(tz).replace(minute=0, second=0, microsecond=0)
    return min(hour.replace(hour=0), hour - _LIVE_MIN_LOOKBACK)


def _header_live(include_private: bool, now: datetime | None = None) -> tuple[Any, str, str]:
    """``(signals, window words, NOW label)`` for a whole-company header.

    The window start and the NOW line are keyed to the current local HOUR,
    so the rendered context (and the cache key over it) moves at most once
    an hour on time alone, plus whenever something new lands. The calendar
    is placed at the real time (a meeting that ended at 10:15 is gone at
    10:40), which moves the key only when a meeting starts or ends. The calendar is the cached
    read (``live_signals.refresh_calendar``, refreshed by the scheduler);
    this never calls out.
    """
    from openexecutive.briefing.live_signals import gather_live_signals
    from openexecutive.memory.workspace_settings import get_user_timezone

    now = now or datetime.now(UTC)
    tz = get_user_timezone()
    hour = now.astimezone(tz).replace(minute=0, second=0, microsecond=0)
    start = _live_start(now, tz)
    window = "today so far" if start == hour.replace(hour=0) else f"since {start:%a %H:%M}"
    now_label = f"{hour:%A %d %B}, between {hour:%H}:00 and {(hour + timedelta(hours=1)):%H}:00 local time"
    signals = gather_live_signals(
        start.astimezone(UTC), now=now, include_private=include_private,
    )
    return signals, window, now_label


# `_narrative_context(reader=…)` left out: look the reader up there.
_LOOKUP = object()


def _narrative_context(
    today_data: dict[str, Any],
    viewer: PersonBriefItem | None,
    viewer_desc: dict[str, str] | None,
    mode: str = "team",
    scope: str | None = None,
    reader: Reader | None | object = _LOOKUP,
    sources_out: dict[str, dict[str, Any]] | None = None,
) -> tuple[str, list[dict[str, Any]] | None]:
    """``(context, activity)`` — the exact user turn the model would receive.

    ``reader`` is who the header is written for (``_narrative_reader``); the
    regeneration resolves it once and hands the same one to the post-check.
    ``sources_out``, when given, is filled with Right now's tag → item map
    (``HeaderContext.sources``), so a point can be opened from Home.

    The single source both the cache key and the model call come from, so the
    key can never be computed over something the model did not see.

    The whole-company scopes (``principal`` / ``company``) get Right now's
    context (`_header_context`, ``briefing.header_context``): what moved
    today, tagged, with the live blocks (`_header_live`) private only in the
    principal's own scope. A teammate's header keeps the older render.

    On a quiet board it returns a fixed context (`narrative_cache.
    QUIET_CONTEXT`, or `NOTHING_MOVED_CONTEXT` for the header when items are
    open but none moved today) and no activity: the narrative is a fixed
    line there, so the key must not depend on anything volatile.
    """
    from openexecutive.briefing import narrative_cache
    from openexecutive.briefing.narrative import render_briefing_context

    today_data = _with_due_soon(today_data, mode, viewer_desc, scope)
    resolved = _narrative_reader(scope, viewer) if reader is _LOOKUP else reader
    if viewer_desc is None:
        return _header_context(today_data, viewer, mode, scope, resolved, sources_out)  # type: ignore[arg-type]
    if _nothing_needs_attention(today_data, mode):
        return narrative_cache.QUIET_CONTEXT, None
    activity = _narrative_activity(viewer, viewer_desc)
    context = render_briefing_context(
        period_label=narrative_cache.local_today(),
        today_data=today_data,
        activity=activity,
        mode=mode,
        brief_requests=False,
        reader=resolved,  # type: ignore[arg-type]
    )
    return context, activity


def _header_context(
    today_data: dict[str, Any],
    viewer: PersonBriefItem | None,
    mode: str,
    scope: str | None,
    reader: Reader | None,
    sources_out: dict[str, dict[str, Any]] | None = None,
) -> tuple[str, list[dict[str, Any]] | None]:
    """Right now's context for a whole-company scope
    (``briefing.header_context``). With nothing moved today it is one of the
    two fixed contexts (``QUIET_CONTEXT``: nothing open either;
    ``NOTHING_MOVED_CONTEXT``: open items, none of them new), so the header
    is a fixed line and no model call happens. A calendar alone does not
    count as moved, on purpose: Right now lists the meetings still ahead
    (``calendar_next``) under that line, so a meetings-only day costs no
    model call."""
    from openexecutive.briefing import brief_requests, narrative_cache
    from openexecutive.briefing.header_context import HeaderContext, render_header_context
    from openexecutive.memory.facts import render_facts_for_prompt
    from openexecutive.memory.workspace_settings import get_user_timezone

    own = scope == narrative_cache.DEFAULT_SCOPE
    live, _window, now_label = _header_live(include_private=own)
    tz: tzinfo
    try:
        tz = get_user_timezone()
    except Exception:
        logger.exception("today: reading the user's time zone failed; Right now uses UTC")
        tz = UTC
    # What the Executive said in a chat it would do and couldn't: news on
    # the day it was saved, an open item after that.
    raise_lines: list[str] = []
    raise_older: list[str] = []
    leave_out = ""
    if own:
        raise_lines, raise_older, leave_out = brief_requests.raise_split(tz)
    standing_facts = render_facts_for_prompt()

    def render(activity: list[dict[str, Any]]) -> HeaderContext:
        return render_header_context(
            period_label=narrative_cache.local_today(),
            today_data=today_data,
            live=live,
            activity=activity,
            mode=mode,
            now_label=now_label,
            tz=tz,
            standing_facts=standing_facts,
            raise_lines=raise_lines,
            raise_older=raise_older,
            leave_out_block=leave_out,
            reader=reader,
        )

    # Rendered first without the rail: on a board with nothing open and
    # nothing moved, the answer is the fixed quiet line and the rail (a
    # seven-source SQL union) is never built. Work finished today alone does
    # not make a header there.
    ctx = render([])
    open_items = (
        not _nothing_needs_attention(today_data, mode)
        or bool(today_data.get("due_soon"))
        or bool(today_data.get("in_flight"))
    )
    if not ctx.moved and not open_items:
        return narrative_cache.QUIET_CONTEXT, None
    activity = _narrative_activity(viewer, None)
    ctx = render(activity)
    if not ctx.moved:
        return narrative_cache.NOTHING_MOVED_CONTEXT, None
    if sources_out is not None:
        sources_out.update(ctx.sources)
    return ctx.text, activity


def _narrative_reader(scope: str | None, viewer: PersonBriefItem | None) -> Reader | None:
    """Who a scope's header is written for: the teammate on their own scope,
    else the principal. The whole-company scope (no signed-in caller) uses
    the same prompt as the principal's, which narrates the principal's day,
    so it is written to them too, from the shared rows only."""
    from openexecutive.briefing.reader import person_reader, principal_reader

    if viewer is not None and scope is not None and scope.startswith("person:"):
        return person_reader(viewer.id)
    return principal_reader()


# One regeneration per scope at a time. Every stale view schedules one, and
# the scheduler's tick does too, so without this a busy page stacks model
# calls that all write the same row. A trigger that finds one running is not
# dropped: it marks the scope pending, and the running one goes round once
# more when it ends (it built its context before that trigger's news landed).
_regen_locks: dict[str, asyncio.Lock] = {}
_regen_pending: set[str] = set()

# After a regeneration fails (model error, 25 s timeout, empty text) nothing
# is cached, so every view would report the header stale and spend another
# model call. For this long after a failure no view or tick starts one, and
# the page is told nothing is coming, so it drops its "Catching up…" line.
_REGEN_FAILURE_BACKOFF = timedelta(minutes=5)
_regen_failed_at: dict[str, datetime] = {}
# Scope → the step a running rewrite is on (``NarrativeProgress.step``).
_regen_step: dict[str, str] = {}


def _in_failure_backoff(scope: str, now: datetime | None = None) -> bool:
    failed = _regen_failed_at.get(scope)
    return failed is not None and (now or datetime.now(UTC)) - failed < _REGEN_FAILURE_BACKOFF


def _regen_lock(scope: str) -> asyncio.Lock:
    lock = _regen_locks.get(scope)
    if lock is None:
        lock = _regen_locks[scope] = asyncio.Lock()
    return lock


# A stale header older than this is not served: the rewrite runs at least
# hourly (the NOW line moves the key), so one this old means it has been
# failing, and its "next meeting" or "due in an hour" no longer holds.
_STALE_HEADER_MAX_AGE = timedelta(hours=2)


def _header_outdated(written: datetime, now: datetime, *, quotes_calendar: bool) -> bool:
    """Whether a header written at ``written`` can no longer be shown as now:
    it is over ``_STALE_HEADER_MAX_AGE`` old, or (``quotes_calendar``: the
    principal's own header) a meeting on today's cached calendar started or
    ended since it was written, so it may call that meeting next or say there
    is time to prepare. Only asked of a stale header, whose rewrite is
    already scheduled. Never raises."""
    if now - written > _STALE_HEADER_MAX_AGE:
        return True
    if not quotes_calendar:
        return False
    from openexecutive.briefing.live_signals import cached_calendar
    from openexecutive.memory.workspace_settings import get_user_timezone

    try:
        events = cached_calendar(now, get_user_timezone()) or []
        return any(
            edge is not None and written < edge <= now
            for e in events
            if not e.all_day
            for edge in (e.start, e.end)
        )
    except Exception:
        logger.exception("today: checking the header against the calendar failed")
        return False


def _attach_narrative(
    response: TodayResponse,
    *,
    caller_person_id: int | None,
    background_tasks: BackgroundTasks | None,
) -> None:
    """Serve the viewer's cached narrative onto `response`, scheduling a
    background regeneration when it's missing/stale. `background_tasks=None`
    (the deprecated alias) serves cache-only without scheduling regen.

    Sets ``narrative_generated_at`` and ``narrative_stale`` so the page can
    say how old the text is and re-poll until the regeneration lands. A row
    written on an earlier local day is never served as today's: the page
    shows nothing until today's is written (a few seconds) rather than
    yesterday's read as if it were current, and the same goes for a stale
    one a meeting has started or ended since, or that is hours old
    (``_header_outdated``): it may still call a finished call next."""
    from openexecutive.briefing import narrative_cache
    from openexecutive.memory.workspace_settings import get_workspace

    scope, today_data, desc, viewer = _narrative_inputs(response, caller_person_id)
    try:
        mode = get_workspace().mode
        context, _activity = _narrative_context(today_data, viewer, desc, mode, scope)
        nhash = narrative_cache.build_narrative_input_hash(context, scope=scope, mode=mode)
        cached = narrative_cache.get(scope)
        is_stale = cached is None or cached.input_hash != nhash
        age_s: int | None = None
        if cached is not None:
            written = _parse_aware(cached.generated_at)
            if (
                written is not None
                and narrative_cache.local_today(written) == narrative_cache.local_today()
                and not (is_stale and _header_outdated(
                    written, datetime.now(UTC),
                    quotes_calendar=scope == narrative_cache.DEFAULT_SCOPE,
                ))
            ):
                response.narrative = cached.narrative_text
                response.narrative_generated_at = cached.generated_at
                if not is_stale:
                    response.narrative_checked_at = narrative_cache.utc_now_iso()
                age_s = int((datetime.now(UTC) - written).total_seconds())
                _attach_right_now(response, scope, cached.narrative_text, cached.generated_at)
        scheduled = is_stale and background_tasks is not None and not _in_failure_backoff(scope)
        if scheduled:
            assert background_tasks is not None
            background_tasks.add_task(_regen_briefing_narrative, caller_person_id, scope)
        response.narrative_stale = scheduled
        if scheduled:
            response.narrative_progress = _narrative_progress(scope, cached)
        logger.info(
            "today: narrative served scope=%s age_s=%s stale=%s regen_scheduled=%s",
            scope, age_s, is_stale, scheduled,
        )
    except Exception:
        logger.exception("today: briefing narrative attach failed (scope=%s)", scope)


def _narrative_progress(scope: str, cached: Any, now: datetime | None = None) -> NarrativeProgress:
    """Where the rewrite of ``scope``'s header is (``reading`` until it
    starts), and for the principal how many emails came to their own inbox
    since ``cached`` was written. Never raises."""
    from openexecutive.briefing import narrative_cache

    step = _regen_step.get(scope)
    progress = NarrativeProgress(step="writing" if step == "writing" else "checking" if step == "checking" else "reading")
    written = _parse_aware(cached.generated_at) if cached is not None else None
    if written is None or narrative_cache.local_today(written) != narrative_cache.local_today():
        return progress
    progress.since = cached.generated_at
    if scope != narrative_cache.DEFAULT_SCOPE:
        return progress
    try:
        from openexecutive.briefing.live_signals import own_inbox
        from openexecutive.memory.workspace_settings import get_user_timezone

        mail = own_inbox(written, get_user_timezone(), now or datetime.now(UTC))
        progress.new_mail = mail.total  # from people they deal with, not yet answered
    except Exception:
        logger.exception("today: counting new mail for Right now failed")
    return progress


def _attach_right_now(response: TodayResponse, scope: str, text: str, written_at: str) -> None:
    """Split the served narrative for Home's Right now card. A point with no
    recorded time (a header written before times were kept) takes the
    header's own time."""
    from openexecutive.briefing import narrative_cache, right_now

    parts = right_now.split_narrative(text)
    day = narrative_cache.local_today()
    times = right_now.point_times(scope, day)
    sources = right_now.point_sources(scope, day)
    response.narrative_lead = parts.lead
    response.narrative_move = parts.move
    response.narrative_points = [
        NarrativePoint(
            text=p,
            since=times.get(right_now.point_key(p), written_at),
            source=_point_source(sources.get(right_now.point_key(p))),
        )
        for p in parts.points
    ]
    # Only a rostered reader's own scope has a last look (see /today/seen).
    if scope != narrative_cache.COMPANY_SCOPE:
        response.narrative_seen_at = right_now.seen_at(scope)
    if scope == narrative_cache.DEFAULT_SCOPE:
        _attach_inbox_also(response)


def _attach_inbox_also(response: TodayResponse, now: datetime | None = None) -> None:
    """The principal's "Also in" line: today's mail to their own inbox from
    people they don't deal with. Never raises."""
    from openexecutive.briefing.live_signals import own_inbox
    from openexecutive.memory.workspace_settings import get_user_timezone

    now = now or datetime.now(UTC)
    try:
        tz = get_user_timezone()
        mail = own_inbox(_live_start(now, tz).astimezone(UTC), tz, now)
    except Exception:
        logger.exception("today: reading the own inbox for Right now failed")
        return
    response.inbox_also = list(mail.others)
    response.inbox_also_total = mail.others_total


async def _regen_briefing_narrative(
    caller_person_id: int | None, expected_scope: str
) -> None:
    """Regenerate and cache the viewer's briefing narrative off the hot path.

    Runs as a FastAPI background task after the response is sent, and from
    the scheduler's tick (`refresh_principal_narrative`). Rebuilds the
    snapshot — with the principal's private rows only for their own scope —
    derives the viewer's scope / scoped slice / perspective, synthesizes via
    the shared synthesizer, and caches under the viewer's scope. Guarded so a
    slow/failed model call can never surface to the user, and serialized per
    scope so concurrent triggers do not stack model calls: a trigger that
    finds one running skips (the running one writes the fresh state).

    `expected_scope` is the scope resolved on the hot path; if the viewer's
    scope changed in between (e.g. the person was deleted, collapsing them to
    the company scope) we skip the write rather than churn / overwrite a
    different scope's cache entry.
    """
    if _in_failure_backoff(expected_scope):
        return
    lock = _regen_lock(expected_scope)
    if lock.locked():
        _regen_pending.add(expected_scope)
        logger.info(
            "today: narrative regen already running scope=%s — queued one more pass",
            expected_scope,
        )
        return
    async with lock:
        try:
            # At most one extra pass: a trigger that arrived mid-run may carry
            # news the running pass never saw. The pass is cheap when nothing
            # moved (it returns before the model call when the key matches).
            for _ in range(2):
                _regen_pending.discard(expected_scope)
                _regen_step[expected_scope] = "reading"
                ok = await _regen_briefing_narrative_locked(caller_person_id, expected_scope)
                if not ok:
                    _regen_failed_at[expected_scope] = datetime.now(UTC)
                    _regen_pending.discard(expected_scope)
                    return
                _regen_failed_at.pop(expected_scope, None)
                if expected_scope not in _regen_pending:
                    return
        finally:
            _regen_step.pop(expected_scope, None)


async def _regen_briefing_narrative_locked(
    caller_person_id: int | None, expected_scope: str
) -> bool:
    """One pass. False only when the model could not write a header (an
    error, a timeout, empty text) — the caller backs off; a skipped write or
    an unchanged key is not a failure."""
    import time

    from openexecutive.briefing import narrative_cache
    from openexecutive.briefing.header_context import keep_cited_points, tags_in
    from openexecutive.briefing.narrative import (
        NOTHING_NEW,
        QUIET_PRINCIPAL,
        QUIET_VIEWER,
        REWRITE_TIMEOUT_S,
        synthesize_briefing_narrative,
    )
    from openexecutive.memory.workspace_settings import get_workspace

    started = time.monotonic()
    # The new points that need the principal, by key (right_now_ping).
    important: set[str] = set()
    # Tag → item for the lines Home can open, and point key → item.
    sources: dict[str, dict[str, Any]] = {}
    pointed: dict[str, dict[str, Any]] = {}
    try:
        mode = get_workspace().mode
        snapshot = _build_today(include_private=expected_scope == narrative_cache.DEFAULT_SCOPE)
        scope, today_data, viewer_desc, viewer = _narrative_inputs(
            snapshot, caller_person_id
        )
        if scope != expected_scope:
            logger.info(
                "today: narrative scope changed (%s → %s) between serve and "
                "regen; skipping write", expected_scope, scope,
            )
            return True
        reader = _narrative_reader(scope, viewer)
        context, activity = _narrative_context(
            today_data, viewer, viewer_desc, mode, scope, reader=reader, sources_out=sources,
        )
        input_hash = narrative_cache.build_narrative_input_hash(context, scope=scope, mode=mode)
        cached = narrative_cache.get(scope)
        if cached is not None and cached.input_hash == input_hash:
            return True  # another trigger already wrote this exact state
        if context == narrative_cache.QUIET_CONTEXT:
            # Nothing awaits a decision — skip the model call entirely and
            # write the fixed quiet line. Still cached (below) so the hot path
            # sees a fresh hash instead of re-scheduling this task forever.
            text = QUIET_VIEWER if viewer_desc is not None else QUIET_PRINCIPAL
        elif context == narrative_cache.NOTHING_MOVED_CONTEXT:
            # Open items, none new today: Needs you below is the whole story.
            text = NOTHING_NEW
        else:
            _regen_step[expected_scope] = "writing"
            text = await asyncio.wait_for(
                synthesize_briefing_narrative(
                    today_data=today_data, activity=activity or [],
                    period_label=narrative_cache.local_today(),
                    viewer=viewer_desc,
                    # Hand the model the very string that was hashed.
                    rendered_context=context,
                    mode=mode,
                    reader=reader,
                ),
                # 25 s for the draft, plus the rewrite's own budget.
                timeout=25.0 + REWRITE_TIMEOUT_S,
            )
            _regen_step[expected_scope] = "checking"
            if viewer_desc is None and text:
                from openexecutive.briefing.header_context import point_sources
                from openexecutive.briefing.right_now import point_key as key_of

                pointed = {key_of(p): src for p, src in point_sources(text, sources)}
                if scope == narrative_cache.DEFAULT_SCOPE:
                    from openexecutive.briefing.header_context import (
                        needs_you_tags,
                        point_citations,
                    )
                    from openexecutive.briefing.right_now import point_key

                    needs_you = needs_you_tags(context)
                    important = {point_key(p) for p, cited in point_citations(text) if cited & needs_you}
                # Right now: a point must cite a line of what moved today.
                # A draft with nothing left is still cached (as the fixed
                # line), or every view would pay for the same draft again.
                text = keep_cited_points(text, tags_in(context)) or NOTHING_NEW
    except Exception:
        logger.exception("today: briefing narrative regen failed (scope=%s)", expected_scope)
        return False

    if not text:
        logger.warning("today: narrative regen returned no text (scope=%s) — not cached", scope)
        return False
    written_at = narrative_cache.utc_now_iso()
    narrative_cache.put(narrative_cache.BriefingNarrative(
        scope=scope,
        input_hash=input_hash,
        narrative_text=text,
        generated_at=written_at,
    ))
    from openexecutive.briefing import right_now

    recorded = right_now.record_points(scope, text, written_at)
    right_now.record_sources(scope, written_at, pointed)
    if scope == narrative_cache.DEFAULT_SCOPE and recorded.new:
        from openexecutive.briefing.right_now_ping import maybe_ping

        ping = await maybe_ping(recorded.new, important, earlier_today=_written_earlier_today(cached))
        logger.info("today: right now ping %s", ping.status)
    logger.info(
        "today: narrative regenerated scope=%s ms=%d quiet=%s context_chars=%d",
        scope, int((time.monotonic() - started) * 1000),
        context in (narrative_cache.QUIET_CONTEXT, narrative_cache.NOTHING_MOVED_CONTEXT), len(context),
    )
    return True


def _written_earlier_today(cached: Any) -> bool:
    """Whether the header being replaced was written today, the quiet line
    included: the first header of the day is the morning's, which the brief
    covers, so it pings nobody."""
    from openexecutive.briefing import narrative_cache

    written = _parse_aware(cached.generated_at) if cached is not None else None
    return written is not None and narrative_cache.local_today(written) == narrative_cache.local_today()


async def refresh_principal_narrative() -> bool:
    """Bring the principal's header up to date without anyone opening the page.

    Called from the scheduler's tick: refreshes the calendar read the header
    quotes and the principal's unanswered sent mail (``briefing.waiting_on``), and settles the chat drafts it counts, then regenerates the principal's narrative only when its key
    moved (new mail, something stuck, a proposal, the hour). True when a
    regeneration ran. Never raises.
    """
    from openexecutive.briefing import narrative_cache, waiting_on
    from openexecutive.briefing.live_signals import refresh_calendar, settle_principal_drafts
    from openexecutive.memory.workspace_settings import get_workspace
    from openexecutive.people.store import find_principal_person

    try:
        principal = find_principal_person()
        if principal is None or principal.id is None:
            return False
        # Independent reads, so a slow mailbox delays none of the others.
        await asyncio.gather(refresh_calendar(), waiting_on.refresh(), settle_principal_drafts())
        mode = get_workspace().mode
        snapshot = _build_today(include_private=True)
        scope, today_data, desc, viewer = _narrative_inputs(snapshot, principal.id)
        if scope != narrative_cache.DEFAULT_SCOPE:
            return False
        context, _activity = _narrative_context(today_data, viewer, desc, mode, scope)
        nhash = narrative_cache.build_narrative_input_hash(context, scope=scope, mode=mode)
        cached = narrative_cache.get(scope)
        if (cached is not None and cached.input_hash == nhash) or _in_failure_backoff(scope):
            return False
        await _regen_briefing_narrative(principal.id, scope)
        return True
    except Exception:
        logger.exception("today: principal narrative refresh failed")
        return False


# How often the principal opening the page settles their chat drafts (and
# rewrites the header when that moved it). The scheduler's own pass runs only
# every BRIEFING_NARRATIVE_REFRESH_MINUTES in daytime, and not at all when
# they turned that background job off; without this a draft they sent from
# their mailbox kept being called unsent on the page in between.
_VIEW_SETTLE_EVERY = timedelta(minutes=2)
_view_settled_at: datetime | None = None


def _maybe_settle_on_view(background_tasks: BackgroundTasks, now: datetime | None = None) -> bool:
    """Queue ``refresh_principal_narrative`` after the response, at most once
    per ``_VIEW_SETTLE_EVERY``. True when queued."""
    global _view_settled_at
    now = now or datetime.now(UTC)
    if _view_settled_at is not None and now - _view_settled_at < _VIEW_SETTLE_EVERY:
        return False
    _view_settled_at = now
    background_tasks.add_task(refresh_principal_narrative)
    return True


def _is_principal(caller_person_id: int | None) -> bool:
    """Whether the resolved caller is the principal. Fails closed."""
    from openexecutive.people.store import is_principal_or_self

    try:
        return is_principal_or_self(caller_person_id, None)
    except Exception:
        logger.exception("today: principal check failed — private alerts stay hidden")
        return False


@router.get("/today", response_model=TodayResponse, tags=["today"])
async def get_today(request: Request, background_tasks: BackgroundTasks) -> TodayResponse:
    stale: list[StaleInsight] = []
    from openexecutive.api.routes.chat import _resolve_caller_person_id
    from openexecutive.orchestrator.artifact_records import viewer_for_person

    caller = _resolve_caller_person_id(request)
    principal = _is_principal(caller)
    response = _build_today(
        stale_out=stale,
        include_private=principal,
        viewer=viewer_for_person(caller),
    )
    response.caller_person_id = caller
    if stale:
        background_tasks.add_task(_regen_stale_insights, stale)
    _attach_narrative(
        response,
        caller_person_id=response.caller_person_id,
        background_tasks=background_tasks,
    )
    if principal:
        _maybe_settle_on_view(background_tasks)
        response.held_back = _held_back(datetime.now(UTC))
        response.first_week_card = _first_week_card()
        response.first_week = response.first_week_card is not None
        response.morning_brief = _morning_brief_today()
        response.calendar_next = _calendar_next(datetime.now(UTC))
    return response


@router.post("/today/seen", tags=["today"])
async def mark_today_seen(request: Request) -> dict[str, str | None]:
    """The reader looked at Right now: the next view counts its points as new
    only when they appeared after this. Stored per narrative scope, the same
    scope ``GET /today`` serves this caller; an unrostered caller's shared
    scope keeps none."""
    from openexecutive.api.routes.chat import _resolve_caller_person_id
    from openexecutive.briefing import narrative_cache, right_now
    from openexecutive.people.store import get_person

    caller = _resolve_caller_person_id(request)
    if caller is None or get_person(caller) is None:
        # The shared `company` scope is read by every unrostered caller, so a
        # look there is nobody's in particular: not recorded.
        return {"seen_at": None}
    scope = narrative_cache.DEFAULT_SCOPE if _is_principal(caller) else f"person:{caller}"
    return {"seen_at": right_now.mark_seen(scope)}


def _morning_brief_today() -> MorningBriefItem | None:
    """Today's delivered morning brief, or None. Never raises."""
    from openexecutive.briefing import brief_state, narrative_cache
    from openexecutive.workflows.morning_brief import BRIEF_KIND

    try:
        last = brief_state.last_delivered(BRIEF_KIND)
        written = _parse_aware(last.generated_at) if last else None
        if last is None or written is None or not last.narrative_text.strip():
            return None
        if narrative_cache.local_today(written) != narrative_cache.local_today():
            return None
        return MorningBriefItem(at=last.generated_at, text=last.narrative_text)
    except Exception:
        logger.exception("today: morning brief read failed")
        return None


# Right now lists at most this many of the meetings still ahead today.
_CALENDAR_NEXT_MAX = 3


def _calendar_next(now: datetime) -> list[CalendarNextItem]:
    """The meetings still ahead today from the cached calendar read (never
    calls out): the one in progress and the next ones, then all-day events."""
    from openexecutive.briefing.live_signals import cached_calendar
    from openexecutive.memory.workspace_settings import get_user_timezone

    try:
        events = cached_calendar(now, get_user_timezone()) or []
        items: list[CalendarNextItem] = []
        timed = sorted(
            (e for e in events if not e.all_day and e.start is not None and e.end is not None),
            key=lambda e: e.start,
        )
        for e in timed:
            # Over (a zero-length one once it starts); one in progress stays.
            over = e.start < now if e.end == e.start else e.end <= now
            if over:
                continue
            items.append(CalendarNextItem(title=e.title, start=e.start.astimezone(UTC).isoformat()))
        # All-day events fill what room the meetings leave, so a day of
        # them never hides the next meeting.
        items += [CalendarNextItem(title=e.title, all_day=True) for e in events if e.all_day]
    except Exception:
        logger.exception("today: calendar read failed")
        return []
    return items[:_CALENDAR_NEXT_MAX]


def _first_week_card() -> FirstWeekCardModel | None:
    from dataclasses import asdict

    from openexecutive.briefing.first_week import first_week_card

    card = first_week_card()
    return FirstWeekCardModel.model_validate(asdict(card)) if card else None


# How far back Home lists what grounding left out of the briefs: today's
# morning brief and last night's digest.
_HELD_BACK_WINDOW = timedelta(hours=24)


def _held_back(now: datetime) -> list[HeldBackItem]:
    from openexecutive.briefing.grounding import recent_held_back

    since = (now - _HELD_BACK_WINDOW).isoformat()
    return [
        HeldBackItem(event_id=h.event_id, surface=h.surface, at=h.at, lines=h.lines)
        for h in recent_held_back(since=since)
    ]


@router.get("/today/activity", response_model=ActivityResponse, tags=["today"])
def get_today_activity(
    request: Request,
    limit: int = Query(20, ge=1, le=100),
) -> ActivityResponse:
    """Recent self-initiated Executive activity for the briefing rail.

    Default limit 20, clamped to [1, 100]. Sources: fired scheduled_actions,
    decisions, advice. See `_build_activity` for the merge rules. On top,
    the caller's own replies and follow-ups Handle it for me sent as them
    (``actor`` "you"): theirs alone, never in the shared feed.
    """
    # FastAPI's Query(ge=, le=) does the clamping/422 for out-of-range.
    # Defensive secondary check in case the signature changes later.
    if limit < 1 or limit > 100:
        raise HTTPException(status_code=400, detail="limit must be in [1, 100]")
    built = _build_activity(limit)
    mine = [*_sent_as_caller(request), *_contacts_kept_for_caller(request)]
    if not mine:
        return built
    merged = sorted([*built.items, *mine], key=lambda i: i.at, reverse=True)
    return ActivityResponse(items=merged[:limit])


def _contacts_kept_for_caller(request: Request) -> list[ActivityItem]:
    """One line a day on what the Executive changed in the contacts, for the
    principal alone (contacts are theirs). Counts only. Best effort."""
    from openexecutive.api.routes.people import caller_is_principal
    from openexecutive.people import contact_changes

    try:
        if not caller_is_principal(request):
            return []
        days = contact_changes.counts_by_day()
    except Exception:
        logger.warning("activity: couldn't read the contact changes", exc_info=True)
        return []
    items: list[ActivityItem] = []
    for _day, added, updated, latest in days:
        parts = [f"{added} added"] if added else []
        if updated:
            parts.append(f"{updated} updated")
        items.append(ActivityItem(
            kind="contacts_kept",
            summary="Kept your contacts up to date",
            detail=", ".join(parts),
            actor="executive",
            target=None,
            department=None,
            at=latest,
        ))
    return items


def _sent_as_caller(request: Request) -> list[ActivityItem]:
    """What Handle it for me sent as the caller this week. Best effort."""
    from openexecutive.api.routes.chat import _resolve_caller_person_id
    from openexecutive.delegation import handle_it

    try:
        person_id = _resolve_caller_person_id(request)
        if person_id is None:
            return []
        found = handle_it.handled(person_id)
    except Exception:
        logger.warning("activity: couldn't read what was sent as the caller", exc_info=True)
        return []
    return [
        ActivityItem(
            kind="sent_as_you",
            summary=h.summary if h.source == "invite" and h.summary else (
                f"{'Followed up with' if h.source == 'follow_up' else 'Replied to'} "
                f"{h.to_name or h.to_email}: {h.subject}"
            ),
            actor="you",
            target=h.to_name or h.to_email,
            department=None,
            at=h.sent_at,
        )
        for h in found
    ]


@router.get(
    "/today/activity/daily",
    response_model=DailyActivityResponse,
    tags=["today"],
)
def get_today_activity_daily(
    days: int = Query(90, ge=1, le=365),
) -> DailyActivityResponse:
    """Per-day activity counts for the Pulse heartbeat heatmap.

    Default 90 days, clamped to [1, 365]. Returns a dense list (every calendar
    day present, count 0 when nothing fired), oldest → newest. Same source set
    and exclusions as `GET /today/activity` — see `_build_daily_activity`.
    """
    # Query(ge=, le=) clamps to 422; defensive check mirrors get_today_activity.
    if days < 1 or days > 365:
        raise HTTPException(status_code=400, detail="days must be in [1, 365]")
    return _build_daily_activity(days)


class BriefDeliveryNotice(BaseModel):
    """The latest brief that didn't reach the owner, for the notice above the
    Briefing."""

    brief: str  # "morning brief" or "end-of-day digest"
    at: str  # when it ran (ISO)
    problem: str
    fix: str
    # Whether it was written, so it can still be read on the Artifacts page.
    readable: bool


def _brief_delivery_notice() -> BriefDeliveryNotice | None:
    from openexecutive.briefing.brief_state import (
        brief_name,
        current_problem,
        describe_problem,
        last_delivery_outcome,
    )
    from openexecutive.config import get_settings
    from openexecutive.scheduler.runner import mail_gateway_problem, principal_delivery_plan

    # With the scheduler off no brief is coming; the Setup status page says so.
    if not get_settings().scheduler_enabled:
        return None
    last = last_delivery_outcome()
    if last is None:
        return None
    principal, plan = principal_delivery_plan()
    blocked = mail_gateway_problem(principal)
    reason = current_problem(
        last, has_owner=principal is not None, can_deliver=bool(plan),
        gateway_down=blocked is not None,
    )
    if reason is None:
        return None
    problem, fix = describe_problem(
        reason, blocked if reason == "gateway_down" else last.detail
    )
    return BriefDeliveryNotice(
        brief=brief_name(last.kind),
        at=last.at.isoformat(),
        problem=problem,
        fix=fix,
        readable=last.reason != "not_written",
    )


@router.get(
    "/today/brief-delivery",
    response_model=BriefDeliveryNotice | None,
    tags=["today"],
)
async def get_brief_delivery(request: Request) -> BriefDeliveryNotice | None:
    """The latest morning brief or end-of-day digest that didn't reach the
    owner and still has a problem to fix, or null. Only the owner is told:
    anyone else gets null, since it is about the owner's channels."""
    from openexecutive.api.routes.chat import _caller_is_principal_or_unclaimed

    if not await asyncio.to_thread(_caller_is_principal_or_unclaimed, request):
        return None
    return await asyncio.to_thread(_brief_delivery_notice)


@router.get("/today/value", response_model=ValueSummary, tags=["today"])
async def get_today_value(
    request: Request,
    period: str = Query("month", pattern="^(month|week)$"),
    offset: int = Query(0, ge=0, le=24),
) -> ValueSummary:
    """What the Executive did for the owner this calendar month or week
    (``offset`` periods back), with the period before beside each count and
    the finished reports (``briefing.value_summary``). Every number is counted from the record,
    none is written by a model. The owner's alone: it counts their private
    rows, so anyone else gets 403."""
    from openexecutive.api.routes.people import caller_is_principal
    from openexecutive.briefing.value_summary import summarize

    if not await asyncio.to_thread(caller_is_principal, request):
        raise HTTPException(status_code=403, detail="Only the owner sees this summary")
    return await asyncio.to_thread(summarize, "week" if period == "week" else "month", offset)


# --------------------------------------------------------------------------- #
# Solo Briefing cards: today's top three and the latest weekly review
# --------------------------------------------------------------------------- #


class TopThreeItem(BaseModel):
    """One of today's three, as the solo morning brief lists it
    (``briefing.top_three``)."""

    key: str
    kind: str  # "commitment" | "goal" | "project"
    text: str
    why: str
    # A free block today in the user's zone ("10:00–11:00") when a calendar
    # was read on a business day; "" when no block is left for it; null when
    # no calendar was read (none connected, a failure, a weekend).
    slot: str | None = None


class TopThreeToday(BaseModel):
    items: list[TopThreeItem]


class WeeklyReviewSummary(BaseModel):
    """The latest completed weekly review, for the solo Briefing's card."""

    run_id: str
    completed_at: str  # ISO — when the run finished
    period: str  # "Week of Sep 21"; "" when the review has no title line
    # Next week's top three, as written (plain text, list markers removed).
    top_three: list[str]
    # Stands in when top_three is empty: the review's own note, or its
    # first lines.
    excerpt: str


def _solo_principal_view(request: Request) -> bool:
    """Whether this caller gets the solo Briefing's own cards: the workspace
    is solo and the caller is the principal by the rule for starting a
    principal-only run (``workflows._caller_is_the_principal``) — their own
    email on the roster, or no caller header; never "nobody is principal
    yet". Team mode reads no roster."""
    from openexecutive.api.routes.workflows import _caller_is_the_principal
    from openexecutive.memory.workspace_settings import effective_workspace_mode

    if effective_workspace_mode() != "solo":
        return False
    return _caller_is_the_principal(request)


@router.get(
    "/today/top-three",
    response_model=TopThreeToday | None,
    tags=["today"],
)
async def get_top_three(request: Request) -> TopThreeToday | None:
    """Solo only: today's top three for the principal — the same items, order
    and free slot the morning brief lists, from the same inputs
    (``open_loops.principal_due_soon`` → ``top_three.build_top_three``). Null
    in team mode and for anyone else. Kept off ``GET /today`` so the
    Briefing never waits on the calendar read (one call, 4 s cap; no
    calendar or a failure means no slots)."""
    if not await asyncio.to_thread(_solo_principal_view, request):
        return None
    from openexecutive.attunement.open_loops import principal_due_soon
    from openexecutive.briefing.top_three import build_top_three

    due_soon = await asyncio.to_thread(principal_due_soon)
    items, _calendar = await build_top_three(due_soon)
    return TopThreeToday(items=[TopThreeItem(**item) for item in items])


def _latest_weekly_review() -> WeeklyReviewSummary | None:
    from openexecutive.workflows.persistence import get_run, list_runs
    from openexecutive.workflows.weekly_review import WeeklyReviewWorkflow, summarize_review

    try:
        latest = list_runs(
            workflow_name=WeeklyReviewWorkflow.name, status="done", limit=1, visible_to=None
        )
        run = get_run(latest[0]["run_id"]) if latest else None
    except Exception:
        logger.warning("today: weekly review runs unreadable", exc_info=True)
        return None
    if run is None:
        return None
    return WeeklyReviewSummary(
        run_id=str(run["run_id"]),
        completed_at=str(run["updated_at"]),
        **summarize_review(str(run.get("artifact") or "")),
    )


@router.get(
    "/today/weekly-review",
    response_model=WeeklyReviewSummary | None,
    tags=["today"],
)
async def get_weekly_review(request: Request) -> WeeklyReviewSummary | None:
    """Solo only: the latest completed weekly review — its run id, when it
    finished, and next week's top three (or a short excerpt) — so a
    principal no channel reaches still sees it. Null with no completed run,
    in team mode and for anyone but the principal."""
    if not await asyncio.to_thread(_solo_principal_view, request):
        return None
    return await asyncio.to_thread(_latest_weekly_review)


@router.get(
    "/morning-brief",
    response_model=TodayResponse,
    tags=["today"],
    deprecated=True,
    summary="Deprecated alias for GET /today",
)
def get_morning_brief(request: Request, response: Response) -> TodayResponse:
    response.headers["Deprecation"] = "true"
    response.headers["Sunset"] = "Sat, 22 Aug 2026 00:00:00 GMT"
    response.headers["Link"] = '</today>; rel="successor-version"'
    from openexecutive.api.routes.chat import _resolve_caller_person_id
    from openexecutive.orchestrator.artifact_records import viewer_for_person

    caller = _resolve_caller_person_id(request)
    payload = _build_today(
        include_private=_is_principal(caller), viewer=viewer_for_person(caller)
    )
    payload.caller_person_id = caller
    # Serve the viewer's cached narrative (cache-only — this deprecated alias
    # has no BackgroundTasks to schedule a regen).
    _attach_narrative(
        payload, caller_person_id=payload.caller_person_id, background_tasks=None
    )
    return payload