AI-powered virtual executive team — a single coherent executive persona backed by 8 specialist agents (FastAPI + Next.js).
feat(alerts): lifecycle foundation — expiry, coalescing, change-aware briefs, feedback loop
Rufusbec8300eb8ae
diff --git a/.env.example b/.env.exampleindex 8c162be7..8664a555 100644--- a/.env.example+++ b/.env.example@@ -227,3 +227,33 @@ OUTBOUND_RESPECT_QUIET_HOURS=true # honor recipient availability windows# NOTION_API_KEY=# NOTION_SYNC_INTERVAL_MINUTES=60# NOTION_MAX_PAGES_PER_SCAN=40++# Alert lifecycle — keeps the briefing's "Needs you" queue and the daily+# briefs from going stale (alerts/lifecycle.py, alerts/review.py). Defaults+# shown; all optional. An unread alert older than its category TTL is+# expired by a scheduler sweep (reversible: POST /alerts/{id}/reopen).+# Monitoring = unrouted low/medium watchlist signals; action = everything a+# human should look at. 0 disables expiry for that category.+ALERT_TTL_DAYS_MONITORING=3+ALERT_TTL_DAYS_ACTION=14+# Executive alert review: every ALERT_REVIEW_INTERVAL_HOURS (and right+# before the morning brief) the Executive re-examines open alerts with+# evidence and, within department authority, routes + DMs the owner,+# nudges, escalates to the principal, drafts an artifact, folds+# duplicates, or resolves with evidence (only on high confidence). Every+# move is audited and reversible. ALERT_REVIEW_MAX_MOVES_PER_SCAN=0 keeps+# the review but makes it annotate-only (no DMs / drafts).+ALERT_REVIEW_ENABLED=true+ALERT_REVIEW_INTERVAL_HOURS=6+ALERT_REVIEW_MIN_AGE_HOURS=2+ALERT_REVIEW_MAX_PER_SCAN=25+ALERT_REVIEW_MAX_MOVES_PER_SCAN=10+# Daily briefs: when nothing changed since the last delivered brief, send a+# one-line "nothing new" instead of re-synthesising the same list.+PRINCIPAL_BRIEF_SUPPRESS_UNCHANGED=true+# Stop re-chasing the same stalled item forever (delivered nudges per item;+# 0 disables the cap).+NUDGE_MAX_PER_SCOPE=3+# Force a research-council re-run at most this often when internal state is+# unchanged (was daily; a daily forced run re-filed the same findings).+WATCHLIST_RESEARCH_MAX_STALENESS_HOURS=168diff --git a/CHANGELOG.md b/CHANGELOG.mdindex f2ede920..47ff47f2 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,7 +7,71 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]+### Added+- **Self-maintaining alert feed.** Alerts get a per-category time-to-live+ (`ALERT_TTL_DAYS_ACTION=14`, `ALERT_TTL_DAYS_MONITORING=3`); a scheduler+ sweep expires past-TTL rows (audited, reversible via+ `POST /alerts/{id}/reopen`) and every surface reads the same live view.+ A repeat of an open alert with the same `(source, dedup_key)` now+ coalesces into the existing card (`occurrence_count`, `last_seen_at`)+ instead of stacking, and only re-pings when severity rose to high/urgent;+ monitoring alerts carry a stable `watch:<slug>` key so one watch means+ one card. A distinct `resolved` status keeps Executive closes separate+ from `ack` (user approved).+- **Executive alert review** (`alert_review_scan`, every 6 h and right before+ the morning brief): re-examines each open alert with evidence — newer+ signals from the same watch, related alerts, activity since, the roster+ with SLAs, department authority — and, through deterministic policy,+ routes + DMs the owner (`propose_via_alert` for propose-only departments),+ nudges, escalates to the principal with a deadline, drafts an artifact,+ suggests a workflow, folds duplicates, or resolves with evidence (high+ confidence only, citing a server-minted evidence ref — free text never+ closes a card; otherwise annotates "likely stale"). Alert text is rendered+ as inert data inside the review prompt (injection boundary); board / comp /+ legal matters only ever go to a scope-holder or the principal and keep+ their text; route/escalate are idempotent across passes; DMs carry an+ "[Alert review] Re: …" header. Capped per pass+ (`ALERT_REVIEW_MAX_MOVES_PER_SCAN`), single-flight, off for every caller+ with `ALERT_REVIEW_ENABLED=false`, every move audited with its evidence and+ prior state, every close reversible. `POST /alerts/review` runs it on+ demand.+- Briefing cards read as decisions: what changed since you last looked, the+ recommended move as the primary control, why-now / due chips, provenance+ (age, seen ×N), "N folded in", a "Handled overnight" rail with Undo, an+ "Executive handled N overnight" pill, a capped "Needs you" list with+ Show more, "Dismiss older than 7 days" (explicit ids), "Re-check+ relevance", and "Mute this topic" on dismiss.+- `POST /alerts/bulk-ack`, `POST /alerts/{id}/reopen`, `POST /alerts/review`.+- Dismissing a watch-sourced alert lowers that watch's `trust_score` (and+ bumps `dismiss_count`); approving recovers it. Trust now discounts the+ ranking and is shown to the review as evidence.+### Changed+- Daily briefs are bounded to "since the last delivered brief": what's new,+ what the Executive handled overnight, who we're waiting on, one top call,+ and a one-line carried-over count. An unchanged day sends+ "Nothing new since yesterday's brief — N items still waiting on you." and+ skips the model call (`PRINCIPAL_BRIEF_SUPPRESS_UNCHANGED`; `force_full`+ on a manual run bypasses it). The EoD digest now excludes monitoring noise.+- The daily reflection sees yesterday's standup and is told not to repeat+ it; the watchlist research council's forced re-run moves from daily to+ weekly (`WATCHLIST_RESEARCH_MAX_STALENESS_HOURS=168`); stalled-workflow+ nudges stop after `NUDGE_MAX_PER_SCOPE=3` per item.+- Alerts created by the Executive's `create_alert` tool now land with their+ `routed_to_person_id` and `department:<slug>` tag (previously every+ triage-born alert fell to the principal as "unrouted").++### Upgrading+- All schema changes are additive columns with defaults (`alerts` table);+ rolling the image back is safe. No config changes are required.+- After upgrading, the first scheduler sweep expires alerts past their TTL+ (audited as `alert_sweep`, reversible with `reopen`); raise+ `ALERT_TTL_DAYS_*` (or set `0`) beforehand to keep an old backlog. The+ review job starts acting within `ALERT_REVIEW_MIN_AGE_HOURS` (2 h) — set+ `ALERT_REVIEW_ENABLED=false` to turn it off, or+ `ALERT_REVIEW_MAX_MOVES_PER_SCAN=0` to keep it annotate-only.+- Briefs get shorter and send a one-liner on unchanged days+ (`PRINCIPAL_BRIEF_SUPPRESS_UNCHANGED=false` restores daily full briefs).- `docker/docker-compose.yml` now binds the API to `127.0.0.1:8000` instead ofevery host interface. The UI reaches the API over the compose network, sonothing in the stack needed the public port. If you were calling `:8000`diff --git a/CLAUDE.md b/CLAUDE.mdindex 105c0329..9db97871 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -174,6 +174,19 @@ See `.env.example`. Required: `ANTHROPIC_API_KEY`. Optional integrations: `SLACK> interactive setup prompt. `npm run build` (`next build`) is the UI's> lint/type gate.+> **Audit-log test pollution:** `audit.log_event` writes to the default+> `./episodic_memory.db` unless the test isolates it. A test module that+> exercises audited code (alerts review, sweeps) without monkeypatching+> `openexecutive.audit.log_event` (or the audit logger's DB) leaks rows that+> break *other* modules' assertions only in a full run (e.g. the brief's+> "handled overnight" block). Patch it in an autouse fixture, and delete a+> stray `packages/core/episodic_memory.db` (gitignored) if one appears.++> **Known-red on `main`:** `tests/integration/test_chat_committee.py::+> test_chat_with_committee_streams_phases_and_revised_text` fails on the+> base commit independently of local changes; deselect it when comparing+> full-suite runs.+```bash# Unit tests (no API calls)pytest packages/core/tests/unit/ -vdiff --git a/docs/deployment.md b/docs/deployment.mdindex e462b992..289b2169 100644--- a/docs/deployment.md+++ b/docs/deployment.md@@ -188,7 +188,9 @@ docker compose exec api sqlite3 /data/episodic_memory.db \**Rollback** is an image-tag rollback: redeploy the previous tag. The volume isnot versioned with the image, so a release that migrates schema forward is notundone by rolling the image back — check what changed under `*/store.py` before-relying on it.+relying on it. Additive column migrations (the common case — every column has a+default and older builds name their columns explicitly) are safe to roll back+over; a rolled-back build simply ignores the newer columns.**Backups.** There is no snapshot cron in this repo. `/data/episodic_memory.db`is the irreplaceable part (Chroma rebuilds from source documents), so back it updiff --git a/packages/core/openexecutive/alerts/lifecycle.py b/packages/core/openexecutive/alerts/lifecycle.pynew file mode 100644index 00000000..d6f58e7c--- /dev/null+++ b/packages/core/openexecutive/alerts/lifecycle.py@@ -0,0 +1,311 @@+"""Alert lifecycle: time-to-live, the "live" read view, and the expiry sweep.++An alert used to leave the ``unread`` queue only when a human acked or+dismissed it, so the briefing's "Needs you" list grew without bound and the+daily briefs re-listed the same rows every day. This module gives every alert+a deterministic lifetime and one read helper every surface shares:++- :func:`ttl_days_for` — per-category TTL (monitoring vs action), from+ settings; ``None`` for sources that own their own lifecycle (artifacts+ persist in the gallery, decision-backed alerts end via approve/reject).+- :func:`is_expired` — pure predicate over an ``Alert`` + ``now``.+- :func:`list_live_alerts` — ``unread`` rows that are neither past their TTL+ nor snoozed. ``/today``, the chat ``<briefing>`` block, the briefs and the+ reflection all read through this, so the page is correct even before the+ sweep has run.+- :func:`expire_stale_alerts` — the sweep the scheduler runs every 15 minutes+ (and once at startup): flips past-TTL ``unread`` rows to ``expired`` and+ audits the batch. ``expired`` is just "not unread": the activity feed and+ the artifacts gallery keep showing the rows, and ``POST /alerts/{id}/reopen``+ brings one back.++Kept free of briefing/route imports at module level (only lazy imports inside+functions) so ``alerts.store`` stays a leaf and this module can be imported by+the scheduler, the routes and the workflows alike.+"""+from __future__ import annotations++import logging+from datetime import UTC, datetime, timedelta+from pathlib import Path++from openexecutive.alerts.models import Alert++logger = logging.getLogger(__name__)++EXPIRED_STATUS = "expired"+RESOLVED_STATUS = "resolved"++# Rows one sweep examines. Larger than any realistic unread backlog so a+# single pass converges; a bigger one just takes a second tick.+_SWEEP_PAGE = 5000++# Sources whose rows have their own lifecycle and must never be expired,+# closed or routed by the automatic machinery: artifacts persist in the+# gallery until archived; decision-backed alerts end via /decisions.+TTL_EXEMPT_SOURCES: frozenset[str] = frozenset({"artifact", "decision_scheduling"})+++def parse_aware(iso: str | None) -> datetime | None:+ """Parse an ISO timestamp to an aware UTC datetime, or ``None``.++ Naive timestamps (a bare ``.isoformat()``) are assumed UTC, mirroring+ ``api/routes/today._parse_aware`` so comparisons against+ ``datetime.now(UTC)`` never raise.+ """+ if not iso:+ return None+ try:+ dt = datetime.fromisoformat(iso)+ except (ValueError, TypeError):+ return None+ if dt.tzinfo is None:+ dt = dt.replace(tzinfo=UTC)+ return dt.astimezone(UTC)+++def _ttl_settings() -> tuple[int, int]:+ """Return ``(monitoring_days, action_days)`` from settings.++ Falls back to the documented defaults when settings cannot be built (a+ bare test DB with no env), so a lifecycle read never raises.+ """+ try:+ from openexecutive.config import get_settings++ s = get_settings()+ return int(s.alert_ttl_days_monitoring), int(s.alert_ttl_days_action)+ except Exception:+ return 3, 14+++def ttl_days_for(alert: Alert, *, monitoring_days: int, action_days: int) -> int | None:+ """Days an alert may sit ``unread`` before it expires; ``None`` = never.++ ``0`` (or a negative value) for a category disables expiry for it — the+ knob an operator uses to keep an old backlog when upgrading.+ """+ if alert.source in TTL_EXEMPT_SOURCES:+ return None+ from openexecutive.briefing.ranking import categorize++ category = categorize(+ source=alert.source,+ severity=alert.severity,+ routed_to_person_id=alert.routed_to_person_id,+ topic_tags=alert.topic_tags or [],+ )+ days = monitoring_days if category == "monitoring" else action_days+ return days if days > 0 else None+++def is_expired(+ alert: Alert,+ now: datetime | None = None,+ *,+ monitoring_days: int | None = None,+ action_days: int | None = None,+) -> bool:+ """True when ``alert`` is older than its category TTL."""+ if monitoring_days is None or action_days is None:+ m, a = _ttl_settings()+ monitoring_days = m if monitoring_days is None else monitoring_days+ action_days = a if action_days is None else action_days+ days = ttl_days_for(alert, monitoring_days=monitoring_days, action_days=action_days)+ if days is None:+ return False+ # A situation that keeps re-firing stays live: the age anchor is the+ # later of created_at and last_seen_at (coalescing bumps the latter).+ anchor = parse_aware(alert.created_at)+ seen = parse_aware(getattr(alert, "last_seen_at", None))+ if seen is not None and (anchor is None or seen > anchor):+ anchor = seen+ if anchor is None:+ return False+ now = now or datetime.now(UTC)+ return anchor + timedelta(days=days) <= now+++def _is_snoozed(alert: Alert, now: datetime) -> bool:+ until = parse_aware(getattr(alert, "snoozed_until", None))+ return until is not None and until > now+++def is_live(alert: Alert, now: datetime | None = None) -> bool:+ """Would this row show in the live queue right now? (unread, inside its+ TTL, not snoozed.) The single predicate every surface and the sweep share."""+ now = now or datetime.now(UTC)+ return alert.status == "unread" and not is_expired(alert, now) and not _is_snoozed(alert, now)+++def list_live_alerts(+ limit: int = 100,+ db_path: Path | None = None,+ *,+ now: datetime | None = None,+) -> list[Alert]:+ """``unread`` alerts that are still live: not past TTL, not snoozed.++ Newest first, like ``store.list_alerts``. This is the read every+ user-facing surface shares; the sweep merely persists what this view+ already hides, so the two can never disagree.+ """+ from openexecutive.alerts.store import list_alerts++ now = now or datetime.now(UTC)+ monitoring_days, action_days = _ttl_settings()+ # Over-fetch: the page is newest-first, but snoozed rows and (between+ # sweeps) freshly-expired rows are interleaved with live ones, so a+ # `limit`-sized page could come back short.+ rows = list_alerts(status="unread", limit=max(limit * 3, limit + 50), db_path=db_path)+ live = [+ a for a in rows+ if not is_expired(a, now, monitoring_days=monitoring_days, action_days=action_days)+ and not _is_snoozed(a, now)+ ]+ return live[:limit]+++def expire_stale_alerts(+ now: datetime | None = None,+ db_path: Path | None = None,+) -> int:+ """Flip every past-TTL ``unread`` alert to ``expired``. Returns the count.++ Audited as ``alert_sweep`` (actor ``scheduler``) whenever at least one row+ changed, with the ids so the reopen path is one click away. Never raises:+ a sweep failure is logged and reported as ``0`` so the scheduler tick+ continues.+ """+ from openexecutive.alerts.store import bulk_set_status, list_alerts++ now = now or datetime.now(UTC)+ try:+ monitoring_days, action_days = _ttl_settings()+ rows = list_alerts(status="unread", limit=_SWEEP_PAGE, db_path=db_path)+ expired_ids = [+ a.id for a in rows+ if a.id is not None+ and is_expired(a, now, monitoring_days=monitoring_days, action_days=action_days)+ ]+ if not expired_ids:+ return 0+ count = len(bulk_set_status(+ EXPIRED_STATUS, alert_ids=expired_ids, only_status="unread", db_path=db_path+ ))+ except Exception:+ logger.exception("alerts.lifecycle: expiry sweep failed")+ return 0++ if count:+ try:+ from openexecutive.audit import log_event as audit_log++ audit_log(+ "alert_sweep",+ f"Expired {count} stale alert(s) past TTL",+ actor="scheduler",+ details={+ "count": count,+ "alert_ids": expired_ids[:50],+ "ttl_days_monitoring": monitoring_days,+ "ttl_days_action": action_days,+ },+ )+ except Exception:+ logger.exception("alerts.lifecycle: audit log failed")+ return count+++def mute_pattern_for(alert: Alert) -> str | None:+ """The topic pattern "mute this topic" should add for an alert.++ Prefers the watch slug (``external:<slug>``), then a ``department:``+ tag, then the first topic tag. ``None`` when the alert carries no tags.+ """+ from openexecutive.briefing.ranking import watch_slug_from_tags++ tags = list(alert.topic_tags or [])+ slug = watch_slug_from_tags(tags)+ if slug is not None:+ return f"external:{slug}"+ for tag in tags:+ if tag.startswith("department:"):+ return tag+ return tags[0] if tags else None+++def record_ack_feedback(alert: Alert, status: str) -> None:+ """Teach the source of an alert from the principal's verdict.++ ``dismissed`` on a watch-sourced alert lowers that watch's trust score+ (and bumps its dismiss_count); ``ack`` recovers it a little. Other+ sources have no feedback sink yet. Never raises.+ """+ from openexecutive.briefing.ranking import watch_slug_from_tags++ slug = watch_slug_from_tags(list(alert.topic_tags or []))+ if slug is None:+ return+ try:+ from openexecutive.monitoring import store as monitoring_store++ if status == "dismissed":+ monitoring_store.record_dismissal(slug)+ elif status == "ack":+ monitoring_store.record_confirmation(slug)+ except Exception:+ logger.debug("alerts.lifecycle: ack feedback failed for %s", slug, exc_info=True)+++_MUTE_MIN_CHARS = 4+++def mute_pattern_allowed(alert: Alert, pattern: str) -> bool:+ """A mute added from a card must be specific: one of that alert's own+ tags, or an ``external:`` / ``department:`` scoped pattern of at least+ ``_MUTE_MIN_CHARS`` characters. Mutes are substring matches over every+ future alert's tags, so ``"e"`` would silence the company."""+ p = pattern.strip().lower()+ if len(p) < _MUTE_MIN_CHARS:+ return False+ tags = {t.lower() for t in (alert.topic_tags or [])}+ if p in tags:+ return True+ return p.startswith(("external:", "department:")) and len(p.split(":", 1)[1]) >= 2+++def apply_mute_request(alert: Alert, mute_topic: str | bool | None) -> str | None:+ """Handle the optional ``mute_topic`` on a dismiss: an explicit pattern,+ or ``True`` to derive one from the alert's tags. Returns the pattern+ added, or ``None`` (also when the pattern is too broad to allow)."""+ if not mute_topic:+ return None+ pattern = mute_topic if isinstance(mute_topic, str) else mute_pattern_for(alert)+ if not pattern or not mute_pattern_allowed(alert, pattern):+ return None+ from openexecutive.alerts.store import add_mute++ try:+ add_mute(pattern)+ except Exception:+ logger.exception("alerts.lifecycle: add_mute failed for %r", pattern)+ return None+ return pattern+++__all__ = [+ "EXPIRED_STATUS",+ "apply_mute_request",+ "mute_pattern_allowed",+ "mute_pattern_for",+ "record_ack_feedback",+ "RESOLVED_STATUS",+ "TTL_EXEMPT_SOURCES",+ "expire_stale_alerts",+ "is_expired",+ "is_live",+ "list_live_alerts",+ "parse_aware",+ "ttl_days_for",+]diff --git a/packages/core/openexecutive/alerts/models.py b/packages/core/openexecutive/alerts/models.pyindex 42166b87..70ecfafc 100644--- a/packages/core/openexecutive/alerts/models.py+++ b/packages/core/openexecutive/alerts/models.py@@ -46,6 +46,13 @@ class AlertEvent(BaseModel):channel: str | None = Noneuser: str | None = Nonetitle: str | None = None # for documents+ # Producer-supplied dedup key that overrides the triage model's own+ # (monitoring sets ``watch:<slug>`` so one watch = one open alert).+ dedup_hint: str = ""+ # Person the alert should be routed to (assigned_to_person_id from the+ # Executive's create_alert tool). Lands on the row so the "principal+ # owns unrouted" rule stops sweeping every triage-born alert to them.+ routed_to_person_id: int | None = Noneclass TriageDecision(BaseModel):@@ -86,7 +93,11 @@ class Alert(BaseModel):channels_attempted: list[str] = Field(default_factory=list)channels_delivered: list[str] = Field(default_factory=list)dedup_key: str = ""- status: str = "unread" # unread | read | ack | dismissed+ # unread | read | ack | dismissed | resolved | expired. `ack` means the+ # user approved (the Executive executes the suggested action);+ # `resolved` means the Executive's review closed it with evidence;+ # `expired` means the lifecycle sweep aged it out (alerts/lifecycle.py).+ status: str = "unread"created_at: str# Phase 4: person the alert is routed to for approval. NULL means the# alert is general (not routed to a specific approver).@@ -95,6 +106,28 @@ class Alert(BaseModel):# timestamp means the artifact was archived (hidden from the default list# but restorable). Only meaningful for source='artifact' rows.archived_at: str | None = None+ # Lifecycle (alerts/lifecycle.py + alerts/review.py). All additive with+ # defaults so rows written by older builds read back unchanged.+ # Coalescing: a repeat of an open alert bumps these instead of stacking.+ last_seen_at: str | None = None+ occurrence_count: int = 1+ # Executive review verdict: '' | relevant | changed | likely_stale |+ # drafted | routed | merged, plus resolved | stale on rows the review+ # closed; `review_note` is the one-line "what changed since+ # you last looked"; `recommended_move` the next move the card leads with;+ # `why_now` a short urgency note; `due_at` an ISO 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+ # Set on a row folded into another (merge): the surviving alert's id.+ superseded_by_alert_id: int | None = None+ # Hidden from the live queue until this ISO timestamp (snooze).+ snoozed_until: str | None = None+ # Registry workflow the review suggested as the next step ('' = none).+ suggested_workflow: str = ""class UserPreferences(BaseModel):diff --git a/packages/core/openexecutive/alerts/pipeline.py b/packages/core/openexecutive/alerts/pipeline.pyindex a3149207..caf06a80 100644--- a/packages/core/openexecutive/alerts/pipeline.py+++ b/packages/core/openexecutive/alerts/pipeline.py@@ -27,6 +27,34 @@ _recent_event_ts: deque[float] = deque(maxlen=_RATE_LIMIT_PER_MIN)_rate_lock = threading.Lock()+# Severities that justify re-dispatching a coalesced alert (a repeat that+# escalated the open situation into "look now" territory).+_REDISPATCH_SEVERITIES = frozenset({"high", "urgent"})+++def _person_id_from_event(event: AlertEvent) -> int | None:+ """Routing target: ONLY the explicit ``routed_to_person_id`` field.++ ``event.user`` is deliberately not parsed: integrations fill it with a+ sender's self-chosen display name (Telegram, Google Chat), so a+ ``person:<id>`` there would let an outsider pick the routing target.+ The create_alert tool sets the explicit field itself.+ """+ return event.routed_to_person_id+++def _with_department_tag(tags: list[str], channel: str | None) -> list[str]:+ """Carry a ``department:<slug>`` routing hint into the row's tags."""+ chan = (channel or "").strip()+ if not chan.startswith("department:"):+ return list(tags)+ slug = chan.split(":", 1)[1].strip().lower()+ if not slug:+ return list(tags)+ tag = f"department:{slug}"+ return list(tags) if tag in tags else [*tags, tag]++def _rate_limited() -> bool:"""Returns True when the per-minute cap has been hit."""now = time.monotonic()@@ -116,6 +144,53 @@ async def evaluate_and_dispatch(decision.channels, decision.severity, prefs)+ # A producer that knows the stable identity of the situation (a watch+ # slug) wins over the model's free-text key.+ dedup_key = event.dedup_hint or decision.dedup_key+ topic_tags = _with_department_tag(decision.topic_tags, event.channel)+ routed_to = _person_id_from_event(event)++ # A replay of the SAME upstream event (webhook retry, re-poll) is a+ # no-op, exactly as before: the (source, external_id) row already exists.+ if event.external_id and store.get_alert_by_external(+ event.source, event.external_id, db_path=path+ ) is not None:+ logger.info(+ "alerts.pipeline duplicate suppressed source=%s ext_id=%s",+ event.source, event.external_id,+ )+ return decision, None++ # Coalesce a repeat of an open alert into the existing row instead of+ # stacking another card — and stay quiet unless the repeat is graver+ # (a 2% move followed by a 10% crash must still ping).+ coalesced = store.coalesce_alert(+ source=event.source,+ dedup_key=dedup_key,+ severity=decision.severity.value,+ body=decision.body,+ db_path=path,+ )+ if coalesced is not None:+ existing_id, raised = coalesced+ logger.info(+ "alerts.pipeline coalesced source=%s ext_id=%s into alert=%d raised=%s",+ event.source, event.external_id, existing_id, raised,+ )+ if not (raised and decision.severity.value in _REDISPATCH_SEVERITIES):+ return decision, None+ alert = store.get_alert(existing_id, db_path=path)+ if alert is None:+ return decision, None+ await dispatcher.dispatch_all(+ alert,+ effective_channels,+ db_path=path,+ department_slug=decision.department_slug,+ broadcast_integration=decision.broadcast_integration,+ )+ return decision, existing_id+alert_id = store.insert_alert(source=event.source,external_id=event.external_id,@@ -123,8 +198,9 @@ async def evaluate_and_dispatch(headline=decision.headline or (event.subject or event.title or event.source),body=decision.body,suggested_action=decision.suggested_action,- topic_tags=decision.topic_tags,- dedup_key=decision.dedup_key,+ topic_tags=topic_tags,+ dedup_key=dedup_key,+ routed_to_person_id=routed_to,db_path=path,)if alert_id is None:diff --git a/packages/core/openexecutive/alerts/store.py b/packages/core/openexecutive/alerts/store.pyindex 5c2e3cdd..6abfa80c 100644--- a/packages/core/openexecutive/alerts/store.py+++ b/packages/core/openexecutive/alerts/store.py@@ -71,6 +71,19 @@ def initialize_db(db_path: Path | None = None) -> None:("routed_to_person_id", "INTEGER"),# Artifacts gallery soft-delete: NULL = active, ISO ts = archived.("archived_at", "TEXT"),+ # Lifecycle (alerts/lifecycle.py, alerts/review.py). NOT NULL+ # columns carry a DEFAULT — SQLite requires it on ADD COLUMN.+ ("last_seen_at", "TEXT"),+ ("occurrence_count", "INTEGER NOT NULL DEFAULT 1"),+ ("last_reviewed_at", "TEXT"),+ ("review_verdict", "TEXT NOT NULL DEFAULT ''"),+ ("review_note", "TEXT NOT NULL DEFAULT ''"),+ ("recommended_move", "TEXT NOT NULL DEFAULT ''"),+ ("why_now", "TEXT NOT NULL DEFAULT ''"),+ ("due_at", "TEXT"),+ ("superseded_by_alert_id", "INTEGER"),+ ("snoozed_until", "TEXT"),+ ("suggested_workflow", "TEXT NOT NULL DEFAULT ''"),):if col not in existing:try:@@ -250,6 +263,304 @@ def set_status(alert_id: int, status: str, db_path: Path | None = None) -> bool:return cursor.rowcount > 0+# --- Lifecycle helpers (alerts/lifecycle.py, alerts/review.py, routes) ---++# Cap on ids per bulk UPDATE (SQLite's default variable limit is 32,766); the+# HTTP route caps its own `alert_ids` at 500, the sweep may need more.+_BULK_MAX_IDS = 5000+# Statuses `reopen_alert` may bring back: the closes the lifecycle / review+# / dismiss paths produce. `ack` (user approved and the Executive executed)+# is not an Undo target.+_REOPENABLE_STATUSES = ("resolved", "expired", "dismissed")+++def coalesce_alert(+ *,+ source: str,+ dedup_key: str,+ severity: str,+ body: str,+ db_path: Path | None = None,+) -> tuple[int, bool] | None:+ """Fold a repeat of an open alert into the existing row.++ When an ``unread`` alert with the same ``(source, dedup_key)`` exists,+ bump ``occurrence_count`` and ``last_seen_at``, refresh ``body`` (the+ newest wording of the same situation), and raise ``severity`` if the+ repeat is graver — never lower it. Returns ``(alert_id, severity_raised)``+ on a hit, ``None`` when there is nothing to coalesce into (empty key, or no+ open row) so the caller inserts a fresh alert.++ Uses the ``idx_alerts_dedup`` index; the newest open match wins if a key+ was somehow reused.+ """+ from openexecutive.alerts.models import SEVERITY_RANK++ if not dedup_key or not _resolve_db_path(db_path).exists():+ return None+ with _get_conn(db_path) as conn:+ # Take the write lock up front so two concurrent repeats cannot both+ # miss the row (read-then-update race) or overwrite each other's body.+ conn.execute("BEGIN IMMEDIATE")+ row = conn.execute(+ "SELECT id, severity FROM alerts "+ "WHERE source = ? AND dedup_key = ? AND status = 'unread' "+ "ORDER BY created_at DESC LIMIT 1",+ (source, dedup_key),+ ).fetchone()+ if row is None:+ return None+ current_rank = SEVERITY_RANK.get(str(row["severity"]), 0)+ new_rank = SEVERITY_RANK.get(severity, 0)+ raised = new_rank > current_rank+ effective = severity if raised else str(row["severity"])+ conn.execute(+ "UPDATE alerts SET last_seen_at = ?, "+ "occurrence_count = COALESCE(occurrence_count, 1) + 1, "+ "body = ?, severity = ? WHERE id = ?",+ (_now(), body, effective, int(row["id"])),+ )+ return int(row["id"]), raised+++def bulk_set_status(+ status: str,+ *,+ alert_ids: list[int] | None = None,+ before: str | None = None,+ category: str | None = None,+ only_status: str | None = "unread",+ exclude_sources: tuple[str, ...] = (),+ db_path: Path | None = None,+) -> list[int]:+ """Set ``status`` on many alerts at once. Returns the ids updated.++ Selects candidates by explicit ``alert_ids`` and/or ``created_at <+ before`` (ISO), restricted to ``only_status`` (default ``unread``; pass+ ``None`` for any) and excluding ``exclude_sources``. ``category``+ (``"action"`` / ``"monitoring"``) is applied in Python via+ ``briefing.ranking.categorize`` so the bulk path and ``/today`` agree on+ what counts as monitoring noise. With neither ``alert_ids`` nor ``before``+ nothing is touched (a bulk call must always carry a selector).+ """+ if alert_ids is None and before is None:+ return []+ if not _resolve_db_path(db_path).exists():+ return []+ clauses: list[str] = []+ params: list[object] = []+ if only_status:+ clauses.append("status = ?")+ params.append(only_status)+ if before is not None:+ # Same age anchor as the TTL: a situation that keeps re-firing is+ # not "old" just because its first occurrence was.+ clauses.append("COALESCE(last_seen_at, created_at) < ?")+ params.append(before)+ if alert_ids is not None:+ if not alert_ids:+ return []+ # Bound the IN list well under SQLite's variable limit.+ alert_ids = list(alert_ids)[:_BULK_MAX_IDS]+ clauses.append(f"id IN ({','.join('?' * len(alert_ids))})")+ params.extend(int(i) for i in alert_ids)+ for src in exclude_sources:+ clauses.append("source != ?")+ params.append(src)+ where = " AND ".join(clauses)+ with _get_conn(db_path) as conn:+ conn.execute("BEGIN IMMEDIATE") # select + update under one write lock+ rows = conn.execute(f"SELECT * FROM alerts WHERE {where}", params).fetchall()+ targets = [_row_to_alert(r) for r in rows]+ if category:+ from openexecutive.briefing.ranking import categorize++ targets = [+ a for a in targets+ if categorize(+ source=a.source, severity=a.severity,+ routed_to_person_id=a.routed_to_person_id,+ topic_tags=a.topic_tags or [],+ ) == category+ ]+ ids = [a.id for a in targets if a.id is not None][:_BULK_MAX_IDS]+ if not ids:+ return []+ status_guard = " AND status = ?" if only_status else ""+ guard_params: list[object] = [only_status] if only_status else []+ conn.execute(+ f"UPDATE alerts SET status = ? WHERE id IN ({','.join('?' * len(ids))}){status_guard}",+ (status, *ids, *guard_params),+ )+ return ids+++def update_alert_content(+ alert_id: int,+ *,+ headline: str | None = None,+ body: str | None = None,+ severity: str | None = None,+ db_path: Path | None = None,+) -> bool:+ """Rewrite headline / body / severity in place (a ``changed`` verdict)."""+ sets: list[str] = []+ params: list[object] = []+ if headline is not None:+ sets.append("headline = ?")+ params.append(headline[:200])+ if body is not None:+ sets.append("body = ?")+ params.append(body)+ if severity is not None:+ sets.append("severity = ?")+ params.append(severity)+ if not sets or not _resolve_db_path(db_path).exists():+ return False+ params.append(alert_id)+ with _get_conn(db_path) as conn:+ cursor = conn.execute(+ f"UPDATE alerts SET {', '.join(sets)} WHERE id = ?", params+ )+ return cursor.rowcount > 0+++def set_review(+ alert_id: int,+ *,+ verdict: str,+ note: str = "",+ recommended_move: str = "",+ why_now: str = "",+ due_at: str | None = None,+ reviewed_at: str | None = None,+ suggested_workflow: str = "",+ db_path: Path | None = None,+) -> bool:+ """Stamp the Executive's latest review verdict on an alert."""+ if not _resolve_db_path(db_path).exists():+ return False+ with _get_conn(db_path) as conn:+ cursor = conn.execute(+ "UPDATE alerts SET last_reviewed_at = ?, review_verdict = ?, "+ "review_note = ?, recommended_move = ?, why_now = ?, due_at = ?, "+ "suggested_workflow = ? WHERE id = ?",+ (+ reviewed_at or _now(), verdict[:32], note[:400],+ recommended_move[:32], why_now[:160], due_at,+ suggested_workflow[:64], alert_id,+ ),+ )+ return cursor.rowcount > 0+++def update_alert_routing(+ alert_id: int, person_id: int | None, db_path: Path | None = None+) -> bool:+ """Assign (or clear) the person an alert is routed to."""+ if not _resolve_db_path(db_path).exists():+ return False+ with _get_conn(db_path) as conn:+ cursor = conn.execute(+ "UPDATE alerts SET routed_to_person_id = ? WHERE id = ?",+ (person_id, alert_id),+ )+ return cursor.rowcount > 0+++def mark_superseded(+ alert_id: int, by_alert_id: int, db_path: Path | None = None+) -> bool:+ """Fold ``alert_id`` into ``by_alert_id``: the merged row is dismissed and+ points at the survivor, whose ``occurrence_count`` absorbs it."""+ if alert_id == by_alert_id or not _resolve_db_path(db_path).exists():+ return False+ with _get_conn(db_path) as conn:+ conn.execute("BEGIN IMMEDIATE")+ survivor = conn.execute(+ "SELECT 1 FROM alerts WHERE id = ?", (by_alert_id,)+ ).fetchone()+ if survivor is None:+ return False+ merged = conn.execute(+ "SELECT occurrence_count FROM alerts WHERE id = ? AND status = 'unread'",+ (alert_id,),+ ).fetchone()+ if merged is None:+ return False+ absorbed = int(merged["occurrence_count"] or 1)+ conn.execute(+ "UPDATE alerts SET superseded_by_alert_id = ?, status = 'dismissed' "+ "WHERE id = ? AND status = 'unread'",+ (by_alert_id, alert_id),+ )+ conn.execute(+ "UPDATE alerts SET occurrence_count = COALESCE(occurrence_count, 1) + ?, "+ "last_seen_at = ? WHERE id = ?",+ (absorbed, _now(), by_alert_id),+ )+ return True+++def count_superseded_by(db_path: Path | None = None) -> dict[int, int]:+ """``{survivor_id: number of rows folded into it}`` in one query."""+ if not _resolve_db_path(db_path).exists():+ return {}+ with _get_conn(db_path) as conn:+ rows = conn.execute(+ "SELECT superseded_by_alert_id AS sid, COUNT(*) AS n FROM alerts "+ "WHERE superseded_by_alert_id IS NOT NULL GROUP BY superseded_by_alert_id"+ ).fetchall()+ return {int(r["sid"]): int(r["n"]) for r in rows}+++def reopen_alert(+ alert_id: int, db_path: Path | None = None, *, exclude_sources: tuple[str, ...] = ()+) -> bool:+ """Bring a ``resolved`` / ``expired`` / ``dismissed`` alert back to ``unread``.++ The Undo for every autonomous close. Clears the review stamps (verdict,+ note, move, why-now, deadline, last_reviewed_at) and any supersede link+ so the row is judged afresh on the very next pass, stamps `last_seen_at`+ = now so a row older than its TTL is live again rather than re-expired+ on the next sweep, and hands back the occurrence count a merge had+ folded into the survivor. Returns+ False when the row is missing, already ``unread``, ``ack``'d (approved+ and executed — not an Undo target) or from an excluded source+ (artifacts / decision-backed alerts have their own lifecycle).+ """+ if not _resolve_db_path(db_path).exists():+ return False+ clauses = [f"status IN ({','.join('?' * len(_REOPENABLE_STATUSES))})"]+ params: list[object] = [*_REOPENABLE_STATUSES]+ for src in exclude_sources:+ clauses.append("source != ?")+ params.append(src)+ with _get_conn(db_path) as conn:+ conn.execute("BEGIN IMMEDIATE")+ row = conn.execute(+ f"SELECT superseded_by_alert_id, occurrence_count FROM alerts "+ f"WHERE id = ? AND {' AND '.join(clauses)}",+ (alert_id, *params),+ ).fetchone()+ if row is None:+ return False+ if row["superseded_by_alert_id"] is not None:+ conn.execute(+ "UPDATE alerts SET occurrence_count = MAX(1, COALESCE(occurrence_count, 1) - ?) "+ "WHERE id = ?",+ (int(row["occurrence_count"] or 1), int(row["superseded_by_alert_id"])),+ )+ conn.execute(+ "UPDATE alerts SET status = 'unread', review_verdict = '', "+ "review_note = '', recommended_move = '', why_now = '', due_at = NULL, "+ "last_reviewed_at = NULL, superseded_by_alert_id = NULL, "+ "snoozed_until = NULL, suggested_workflow = '', last_seen_at = ? WHERE id = ?",+ (_now(), alert_id),+ )+ return True++def get_alert_by_external(source: str, external_id: str, db_path: Path | None = None) -> Alert | None:diff --git a/packages/core/openexecutive/api/routes/alerts.py b/packages/core/openexecutive/api/routes/alerts.pyindex cf8377a2..4b27875c 100644--- a/packages/core/openexecutive/api/routes/alerts.py+++ b/packages/core/openexecutive/api/routes/alerts.py@@ -1,28 +1,164 @@from __future__ import annotations+from typing import Literal+from fastapi import APIRouter, HTTPExceptionfrom pydantic import BaseModel, Field-from openexecutive.alerts import store+from openexecutive.alerts import lifecycle, storefrom openexecutive.alerts.models import Alert# The standalone alerts UI (panel, live toast stream, mute/severity settings,# feedback) was removed — those items now surface only through the briefing-# (`/today`), which reads `store.list_alerts` directly. The alert ingestion →-# triage → storage pipeline is unchanged; this router only exposes the one-# endpoint the briefing still calls: acking a proposal to groom the queue.+# (`/today`), which reads the live alert view (alerts/lifecycle.py). The+# ingestion → triage → storage pipeline is unchanged; this router exposes the+# queue-grooming endpoints the briefing calls: single ack, bulk ack, reopen+# (the Undo for every autonomous close / expiry) and an on-demand run of the+# Executive's relevance review.router = APIRouter()class AckBody(BaseModel):status: str = Field(..., pattern="^(read|ack|dismissed)$")+ # Optional on a dismiss: a topic pattern to mute (see alerts/preferences+ # matches_mute), or true to derive one from the alert's own tags+ # (`external:<watch slug>` / `department:<slug>` / first tag).+ mute_topic: str | bool | None = None@router.post("/alerts/{alert_id}/ack", response_model=Alert)def ack_alert(alert_id: int, body: AckBody) -> Alert:+ existing = store.get_alert(alert_id)+ if existing is None:+ raise HTTPException(status_code=404, detail="Alert not found")if not store.set_status(alert_id, body.status):raise HTTPException(status_code=404, detail="Alert not found")+ # Feedback loop: a dismiss on a watch-sourced alert lowers that watch's+ # trust score; an approval recovers it. Optional mute on dismiss. Only+ # on a real transition — re-posting the same status teaches nothing.+ if existing.status != body.status:+ lifecycle.record_ack_feedback(existing, body.status)+ if body.status == "dismissed":+ lifecycle.apply_mute_request(existing, body.mute_topic)+ updated = store.get_alert(alert_id)+ if updated is None:+ raise HTTPException(status_code=404, detail="Alert not found")+ return updated+++class BulkAckBody(BaseModel):+ status: str = Field(..., pattern="^(ack|dismissed)$")+ # Explicit ids (what the UI sends — it knows which cards the caller owns)+ # and/or an age cutoff for ops / API use.+ alert_ids: list[int] | None = Field(default=None, max_length=500)+ # At least one day: a 0-day sweep would close the whole company queue,+ # including items routed to other people.+ older_than_days: int | None = Field(default=None, ge=1)+ category: Literal["action", "monitoring"] | None = None+++class BulkAckResponse(BaseModel):+ count: int++[email protected]("/alerts/bulk-ack", response_model=BulkAckResponse)+def bulk_ack_alerts(body: BulkAckBody) -> BulkAckResponse:+ if body.alert_ids is None and body.older_than_days is None:+ raise HTTPException(+ status_code=400, detail="alert_ids or older_than_days is required"+ )+ before: str | None = None+ if body.older_than_days is not None:+ from datetime import UTC, datetime, timedelta++ before = (datetime.now(UTC) - timedelta(days=body.older_than_days)).isoformat()+ targets = {+ a.id: a+ for a in (store.get_alert(i) for i in (body.alert_ids or [])[:500])+ if a is not None+ }+ updated_ids = store.bulk_set_status(+ body.status,+ alert_ids=body.alert_ids,+ before=before,+ category=body.category,+ exclude_sources=tuple(lifecycle.TTL_EXEMPT_SOURCES),+ )+ count = len(updated_ids)+ # Same feedback loop as a single ack, for the rows we can attribute.+ for alert_id in updated_ids:+ alert = targets.get(alert_id) or store.get_alert(alert_id)+ if alert is not None:+ lifecycle.record_ack_feedback(alert, body.status)+ if count:+ from openexecutive.audit import log_event as audit_log++ audit_log(+ "alerts_bulk_ack",+ f"Bulk {body.status}: {count} alert(s)",+ actor="user",+ details={+ "status": body.status,+ "count": count,+ "alert_ids": (body.alert_ids or [])[:100],+ "older_than_days": body.older_than_days,+ "category": body.category,+ },+ )+ return BulkAckResponse(count=count)++[email protected]("/alerts/{alert_id}/reopen", response_model=Alert)+def reopen_alert(alert_id: int) -> Alert:+ """Undo for a close / dismiss / expiry: back to ``unread``, verdict cleared."""+ existing = store.get_alert(alert_id)+ if existing is None:+ raise HTTPException(status_code=404, detail="Alert not found")+ prior = existing.status+ if not store.reopen_alert(+ alert_id, exclude_sources=tuple(lifecycle.TTL_EXEMPT_SOURCES)+ ):+ raise HTTPException(+ status_code=409,+ detail="Only resolved, expired or dismissed alerts can be reopened",+ )+ from openexecutive.audit import log_event as audit_log++ audit_log(+ "alert_reopened",+ f"Reopened alert {alert_id}: {prior} → unread",+ actor="user",+ details={"alert_id": alert_id, "from_status": prior},+ )updated = store.get_alert(alert_id)if updated is None:raise HTTPException(status_code=404, detail="Alert not found")return updated+++class ReviewResponse(BaseModel):+ reviewed: int+ closed: int+ changed: int+ routed: int+ nudged: int+ escalated: int+ drafted: int+ merged: int+ suggested: int+ annotated: int++[email protected]("/alerts/review", response_model=ReviewResponse)+async def review_alerts() -> ReviewResponse:+ """Run the Executive's relevance review on demand ("Re-check now").++ Ignores the per-alert review interval so every live alert past the+ minimum age is re-examined; the per-pass caps, the per-alert move+ idempotency, the single-flight lock and `ALERT_REVIEW_ENABLED` all+ still apply (a disabled review returns zero counts).+ """+ from openexecutive.alerts.review import run_alert_review++ summary = await run_alert_review(reason="manual", ignore_interval=True)+ return ReviewResponse(**summary.as_dict())diff --git a/packages/core/openexecutive/api/routes/today.py b/packages/core/openexecutive/api/routes/today.pyindex 2ae11c3e..9fb6aa03 100644--- a/packages/core/openexecutive/api/routes/today.py+++ b/packages/core/openexecutive/api/routes/today.py@@ -135,6 +135,76 @@ class ProposalItem(BaseModel):# 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+ # 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 = ""+++def _handled_overnight(now: datetime) -> list[HandledItem]:+ """What the alert review did since the last delivered morning brief."""+ try:+ from openexecutive.briefing import brief_state++ since = brief_state.since_for("principal_brief_morning", now=now)+ items: list[HandledItem] = []+ for h in brief_state.handled_since(since, limit=20):+ raw_id = h.get("alert_id")+ try:+ alert_id = int(raw_id) if raw_id is not None else None+ except (TypeError, ValueError):+ alert_id = None+ items.append(HandledItem(+ kind=str(h["kind"]), summary=str(h["summary"]), at=str(h["at"]), alert_id=alert_id,+ ))+ return items+ 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:@@ -190,6 +260,15 @@ class AwaitingItem(BaseModel):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++class TodayResponse(BaseModel):departments: list[DepartmentBriefItem]people: list[PersonBriefItem]@@ -220,6 +299,10 @@ class TodayResponse(BaseModel):# 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)class ActivityItem(BaseModel):@@ -347,7 +430,6 @@ def _build_today(`_attach_narrative`), so the caller-aware endpoints attach it afterresolving the viewer from `x-caller-email`."""- from openexecutive.alerts.store import list_alertsfrom openexecutive.departments.store import list_departmentsfrom openexecutive.memory.episodic import (last_contact_at_by_person,@@ -501,9 +583,15 @@ def _build_today(# 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.lifecycle import list_live_alerts+ from openexecutive.alerts.store import count_superseded_byfrom openexecutive.briefing.ranking import score_and_categorize- raw_alerts = list_alerts(status="unread", limit=100)+ # 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.+ raw_alerts = list_live_alerts(limit=100, now=now)+ 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@@ -516,7 +604,9 @@ def _build_today(## 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)+ 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,@@ -529,6 +619,16 @@ def _build_today(category=item_category,surfaced_reason=item_reason,decision_instance_id=_parse_decision_instance_id(alert.topic_tags or []),+ 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,))# Action items first (sharpest by score), monitoring noise after; ties@@ -544,6 +644,7 @@ def _build_today(departments=dept_items,people=person_items,proposals=proposal_items,+ handled_overnight=_handled_overnight(now),)# In-flight commitments (pending follow-ups / nudges) + people we're@@ -716,9 +817,13 @@ def _payload_headline(payload_json: str | None) -> str | None:return None-def _build_activity(limit: int) -> ActivityResponse:+def _build_activity(limit: int, since: datetime | None = None) -> 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.+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@@ -749,7 +854,7 @@ def _build_activity(limit: int) -> ActivityResponse:# 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)+ 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@@ -879,6 +984,11 @@ def _build_activity(limit: int) -> ActivityResponse: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])diff --git a/packages/core/openexecutive/architecture/architecture-facts.yaml b/packages/core/openexecutive/architecture/architecture-facts.yamlindex 520e94a0..a2befe9d 100644--- a/packages/core/openexecutive/architecture/architecture-facts.yaml+++ b/packages/core/openexecutive/architecture/architecture-facts.yaml@@ -86,6 +86,9 @@ system:- External-monitor adapters are read-only — they never write to upstream systems. The whole `monitoring/` subsystem is observation-only; surfacing happens through the alert pipeline, never via a direct upstream side-effect.- External signals never auto-execute on the principal's behalf. Every signal that surfaces is proposed via the alert pipeline (and thus subject to triage / mute / severity gates); the scheduler never dispatches an outbound message directly off a signal.- An external signal whose `dedup_key` already exists is dropped at ingest via the UNIQUE(dedup_key) constraint on `external_signals`. Adapter retries / re-polls cannot multiply alerts for the same upstream event.+ - Alerts have a lifetime. Every user-facing surface (`/today`, the chat `<briefing>` block, the briefs, the reflection) reads `alerts.lifecycle.list_live_alerts` — unread, inside its category TTL, not snoozed — and the scheduler sweep persists the same predicate as status `expired`. `artifact` and `decision_scheduling` rows are exempt (own lifecycle). Every autonomous close is reversible via `POST /alerts/{id}/reopen`.+ - A repeat of an open alert with the same `(source, dedup_key)` coalesces into the existing row (`alerts.store.coalesce_alert`) rather than inserting a second card, and does not re-dispatch unless severity rose into high/urgent. Monitoring alerts carry a producer-supplied `watch:<slug>` key so one watch = one open card.+ - The alert review model (`agents.alert_review`) never mutates state. `alerts.review.apply_verdict` is the only writer: it closes only on a high-confidence `resolved`/`stale` verdict with named evidence, routes only to a person on the roster slice it showed the model (scope-holders or the principal for board/comp/legal matters), runs department moves through `departments.authority.gate_action` (propose-only → `propose_via_alert`, never a third-party DM), caps outbound moves per pass, and audits every move with its evidence and prior state. Status `resolved` (Executive closed) is distinct from `ack` (user approved).caching:block_layout: |@@ -325,7 +328,119 @@ routing:("Approved proposal #N" / "Dismissed proposal #N"). The button-drivenApprove / Dismiss path on the briefing page still acks via the HTTProute — the tool exists for the chat-driven path that the model- self-detects from natural-language approval.+ self-detects from natural-language approval. The same feedback loop as+ the HTTP ack applies: a `dismissed` on a watch-sourced alert lowers+ that watch's `trust_score` (`monitoring.store.record_dismissal`); an+ `ack` recovers it a little.+ alert_lifecycle: |+ `openexecutive.alerts.lifecycle` gives every alert a lifetime and one+ shared read view. TTL per category — `ALERT_TTL_DAYS_ACTION` (14) for+ anything a human should look at, `ALERT_TTL_DAYS_MONITORING` (3) for+ unrouted low/medium watchlist signals (`briefing.ranking.categorize`+ decides), computed from `created_at` at read/sweep time (no stored+ expiry, so a setting change applies to existing rows; 0 = never).+ The age anchor is the later of `created_at` and `last_seen_at`, so a+ situation that keeps re-firing (coalescing) stays live.+ `list_live_alerts` = unread ∧ inside TTL ∧ `snoozed_until` null/past+ (`snoozed_until` is a column only — nothing writes it yet; snooze UI is+ a follow-up); `is_live(alert, now)` is the same predicate for one row;+ `/today`, `briefing.context`, the briefs and the reflection all read it.+ `expire_stale_alerts` (called by the scheduler loop every 15 min and once+ at boot, `runner._maybe_sweep_alerts`) flips past-TTL rows to `expired`+ and audits `alert_sweep`. `artifact` and `decision_scheduling` rows are+ exempt. Additive `alerts` columns: `last_seen_at`, `occurrence_count`+ (coalescing), `last_reviewed_at`, `review_verdict`, `review_note`,+ `recommended_move`, `why_now`, `due_at`, `superseded_by_alert_id`,+ `snoozed_until`, `suggested_workflow` (review). Store helpers:+ `coalesce_alert`, `bulk_set_status`, `update_alert_content`,+ `set_review`, `update_alert_routing`, `mark_superseded`,+ `count_superseded_by`, `reopen_alert`. Routes (`api/routes/alerts.py`):+ `POST /alerts/{id}/ack` (now accepts `mute_topic`: a pattern or `true`+ to derive `external:<slug>` / `department:<slug>` / first tag), `POST+ /alerts/bulk-ack` (`status`, `alert_ids` and/or `older_than_days`,+ `category`; exempt sources skipped), `POST /alerts/{id}/reopen` (Undo: only `resolved` /+ `expired` / `dismissed` rows, never `ack` or exempt sources; clears every+ review stamp incl. `last_reviewed_at`, stamps `last_seen_at = now` so a+ past-TTL row is live again, and hands a merged row's occurrence count+ back to its survivor),+ `POST /alerts/review` (on-demand review, ignores the interval but not the+ kill switch, the caps, the lock or per-alert idempotency). `ack` applies+ feedback / mute only on a real status transition; `bulk-ack` caps+ `alert_ids` at 500, requires `older_than_days >= 1`, and applies the same+ watch feedback per row; `mute_topic` must be one of the alert's own tags+ or an `external:` / `department:` scoped pattern (≥ 4 chars).+ alert_review: |+ `openexecutive.alerts.review` is the Executive working the feed instead+ of just filing into it. Heartbeat kind `alert_review_scan` (channel+ `__internal__`, bootstrap + chain like `nudge_scan`, every+ `ALERT_REVIEW_INTERVAL_HOURS` = 6) plus a `pre_brief` pass from+ `_run_principal_brief` before the morning brief. Candidates: live alerts+ at least `ALERT_REVIEW_MIN_AGE_HOURS` (2) old, not reviewed inside the+ interval, not exempt, oldest first, capped at `ALERT_REVIEW_MAX_PER_SCAN`+ (25), in batches of `ALERT_REVIEW_BATCH_SIZE` (8). Evidence per alert+ (`gather_evidence`, deterministic, no tools): age, `occurrence_count`,+ prior verdict; newer `external_signals` for the same watch plus its+ `trust_score` / `dismiss_count`; related live alerts raised since (same+ source or shared tag); Executive activity since (`_build_activity(since)`);+ the roster slice (department members + routed person + principal, or+ only `legal_sign` / `board_comms` holders + principal for a sensitive+ matter — tags `board`/`comp`/`legal` or `broadcast_tools`'s privacy+ backstop); the department's authority level; registry workflows whose+ name matches the text. `agents.alert_review.AlertReviewAgent` (routing+ model, one forced `emit_alert_reviews` tool call, never raises) returns+ per alert: verdict (relevant | changed | resolved | stale), confidence,+ evidence, note (≤160), why_now (≤80), due_at, recommended_move (none |+ route | nudge | escalate | draft | suggest_workflow | merge | close),+ target_person_id, superseded_by_alert_id, rewritten headline/body/+ severity, draft_title/draft_document, workflow_name, message.+ Trust boundary: every externally-sourced field (headline, body,+ suggested_action, signal / related-alert text) is rendered through+ `_untrusted` (angle brackets → ‹ ›, control chars dropped) inside the+ `<alert>` envelope, the batch header and the prompt state it is data,+ never instructions, and each evidence item carries a server-minted ref+ (S1.. signals, R1.. related alerts, A1.. activity) the model must cite.+ `apply_verdict` policy: close → `resolved` / `dismissed` only when+ confidence is high AND `evidence_ref` names a ref that exists for THAT+ alert (free text — or an injected body saying "resolved" — never closes),+ else `review_verdict = likely_stale` (ranking demotes it 30 points, the card shows an amber+ chip + one-click Dismiss); changed → `update_alert_content` with the+ prior text in the audit row (a sensitive alert keeps its text — only+ severity moves — so a rewrite cannot launder the privacy keywords);+ route → target must be on the roster slice (which, for a sensitive+ matter, never includes a mere `routed_to_person_id`), skipped when the+ alert is already `routed` to that person;+ `gate_action(dept, "route_alert")` — `propose` ⇒ `propose_via_alert` to+ the approver, else `update_alert_routing` + DM via+ `handle_message_person` (server-side channel resolution + the outbound+ anti-spam guard, session seeded from the roster); nudge → DM the routed+ owner, capped by `NUDGE_MAX_PER_SCOPE` delivered nudges per alert+ (counted from `alert_review_nudged` audit rows); escalate → severity up+ (never down, at least `high`), `due_at` (verdict's or +24 h), DM the+ principal only — no principal ⇒ annotate, never counted as an escalation;+ skipped when already escalated (high/urgent + due_at); draft → `handle_draft_artifact` (lands as an artifact+ card), source marked `drafted`; suggest_workflow → `suggested_workflow`+ stored only when the name was offered, never runs anything; merge →+ only at high confidence, `mark_superseded` into a survivor that was SHOWN+ as a related alert and is live (`lifecycle.is_live`), absorbing the merged+ row's occurrence_count (handed back on reopen); draft → skipped when the+ source is already `drafted`; escalate → the DM goes first and only a+ delivered DM bumps severity / sets `due_at` / counts; a `_dm` that fell+ back to creating an alert ("alerted") counts as not delivered. Activity+ refs (A1..) are only minted for items that mention the alert's subject+ (`_subject_terms`), and untrusted text is collapsed to one line so a body+ cannot forge a section header;+ a standalone `close` move is ignored (closing is only ever a verdict).+ Every DM goes out as "[Alert review] Re: <headline>\n\n<text>"+ (`_dm_text`) so provenance is visible. `run_alert_review` honours+ `ALERT_REVIEW_ENABLED` for every caller (the manual endpoint does not+ bypass it) and is single-flight (`asyncio.Lock`: an overlapping+ heartbeat / pre-brief / manual pass is skipped). Outbound moves+ (route/nudge/escalate/draft) count against+ `ALERT_REVIEW_MAX_MOVES_PER_SCAN` (10; 0 = annotate-only). Audit event+ types: `alert_review` (annotation), `alert_review_closed`, `_routed`,+ `_nudged`, `_escalated`, `_drafted`, `_merged`, `_suggested_workflow`,+ `_changed` — `briefing.brief_state.handled_since` reads them for the+ brief's "Handled overnight" block and `/today.handled_overnight`.artifact_tools: |`draft_artifact(title, document, why_interesting, source_urls?,severity?)` (openexecutive.orchestrator.artifact_tools) lets the@@ -1030,13 +1145,14 @@ scheduler:- dept_cadence — internal action fired by department cadences; the runner invokes the `department_check_in` workflow and re-enqueues the next occurrence via `cadence.enqueue_next`. Pending rows are cancelled when their department is deleted, and orphaned rows (department no longer exists) are swept by `cadence.cancel_orphaned_cadences` on lifespan boot.- awaiting_human — placed by the `wait_for_human` workflow step; the run resumes when an inbound message matches.- "dynamic_workflow — cadence-fired run of a user-created (dynamic) workflow. Enqueued by `workflows.dynamic_cadence.schedule_dynamic_workflow_cadence` (channel=`__internal__`, channel_ref=the workflow name, assigned_to_person_id=the delivery recipient). The runner's `_run_dynamic_workflow` resolves the stored definition, runs the generic `DynamicWorkflow`, DMs the artifact to the recipient via `handle_message_person`, and re-chains the next occurrence — same crash-survival pattern as the principal briefs. Saving/updating/deleting/deactivating the definition reconciles its pending rows via `dynamic_cadence.cancel_cadence_rows`. See the `workflows:` → `dynamic_user_created` key."- - nudge_scan — internal heartbeat row owned by the nudge engine; the runner calls `nudge_engine.run_nudge_scan()` and chains the next tick via `nudge_engine.enqueue_next_scan()`. Bypasses outbound dispatch.+ - nudge_scan — internal heartbeat row owned by the nudge engine; the runner calls `nudge_engine.run_nudge_scan()` and chains the next tick via `nudge_engine.enqueue_next_scan()`. Bypasses outbound dispatch. Emission is also capped per `scope_key` at `NUDGE_MAX_PER_SCOPE` (default 3) delivered nudges (`episodic.count_nudges_for_scope`), so a parked item is not chased forever.+ - "alert_review_scan — internal heartbeat row owned by the Executive alert review (`alerts.review`). Bootstrapped idempotently at scheduler startup when `ALERT_REVIEW_ENABLED`, fires every `ALERT_REVIEW_INTERVAL_HOURS` (default 6); the runner calls `run_alert_review(reason='heartbeat')`, marks done, and chains the next tick — same crash-resilient shape as nudge_scan. `_run_principal_brief` also runs a `pre_brief` pass before the morning brief so the brief reflects fresh verdicts (a review failure never blocks the brief). Bypasses outbound dispatch itself; the moves it makes go through the real DM / draft handlers. See the `alert_review:` key. Not a kind but loop-level: the runner also calls `_maybe_sweep_alerts` (alert TTL expiry, `alerts.lifecycle.expire_stale_alerts`) once at boot and every 15 min at the top of the tick — BEFORE the company-profile and rotation gates, so an old backlog expires even pre-onboarding — pure DB hygiene, no heartbeat row."- proactive_nudge — per-channel nudge action emitted by `run_nudge_scan`. Carries a `scope_key` for cooldown dedup and `assigned_to_person_id` for a dispatch-time on-leave re-check that runs BEFORE the ad-hoc dispatch path: if the assignee has gone unreachable since the scan, the runner reschedules into the next available slot (clamped to fall after on_leave_until) or drops the nudge with an audit event rather than dispatching to a deaf channel.- "principal_brief_morning — Shift 3 recurring row that runs the `morning_brief` workflow and DMs the artifact to the principal via their preferred channel. Seeded once per database at scheduler startup via `seed_principal_briefs()`; each fire chains the next occurrence in `_run_principal_brief()` so the recurring rhythm survives crashes. Time-of-day reads `PRINCIPAL_BRIEF_MORNING_TIME` (HH:MM UTC, default 08:00). Single-timezone for v1."- "principal_brief_eod — same shape as morning_brief, fires once per day at `PRINCIPAL_BRIEF_EOD_TIME` (default 18:00 UTC). Runs `end_of_day_digest` workflow. Both brief kinds bypass the per-channel anti-spam guards because the principal is by definition deliverable (channel_ref=`principal`, channel=`__internal__` triggers the workflow run rather than a direct send)."- "executive_reflection — Shift 5 recurring row. Seeded alongside the principal briefs (idempotent via `_has_pending_brief`), default 07:30 UTC, override via `PRINCIPAL_REFLECTION_TIME`. The scheduler runs `_run_executive_reflection`: invokes the `executive_reflection` workflow, stores the artifact via `complete_run`, audits the outcome, then chains the next occurrence — same crash-survival pattern as principal briefs. Unlike the briefs, the artifact is NOT delivered to the principal — the morning brief that fires 30 minutes later surfaces what reflection decided via the existing /today/activity rail."- "external_monitor_scan — heartbeat owned by the external-condition monitoring layer. Default every 5 min via EXTERNAL_MONITOR_SCAN_INTERVAL_MINUTES. The runner calls `monitoring.pipeline.run_external_monitor_scan()` which walks enabled watchlist rows whose `last_polled_at` is stale enough, fires the matching adapter (vendor_status, rss, stock, the billed standing-query `query` adapter, the `edgar` SEC-filings adapter, and the stateful `page_watch` change-detector), enriches promotable signals with capture-time relevance, writes `external_signals` rows, and promotes qualifying signals into the alerts pipeline. Bypasses outbound dispatch (channel=`__internal__`, channel_ref=`external_monitor`). Chains the next tick via `enqueue_next_external_monitor_scan` after firing — same idempotent / crash-resilient pattern as `nudge_scan`."- - "watchlist_research_scan — periodic cron for the executive_research workflow (default every 120 min via WATCHLIST_RESEARCH_INTERVAL_MINUTES). The handler short-circuits when the company profile / initiatives / watchlist haven't changed since the last successful run, so quiet days cost zero tokens — except that a staleness floor (WATCHLIST_RESEARCH_MAX_STALENESS_HOURS, default 24) forces a run once that long has elapsed since the last successful run, so a static internal state can't keep the council blind to external change indefinitely. Does NOT write its own Alert — the workflow's Executive synthesis step routes findings directly via DMs / send_department_message / create_alert / add_watchlist_entry, so a separate cron Alert would duplicate the briefing. After routing, a DEDICATED watchlist-analysis pass (its own budget, separate from the routing budget) explicitly decides which findings are ongoing monitorable conditions and calls add_watchlist_entry for each; the run's markdown artifact is also persisted into the separate `recent_research` knowledge collection (keep-latest) so future runs + chat can recall it. The cron's only side-effects on success are the audit row (`watchlist_research_periodic_ran`) and whatever routing tools the synthesis fired. The scheduled-action kind keeps the legacy `watchlist_research_scan` name (matched by the env var WATCHLIST_RESEARCH_INTERVAL_MINUTES + the three audit event_types) even though the workflow itself is registered as `executive_research` — naming is mixed intentionally to avoid a migration on already-pending heartbeat rows. Bypasses outbound dispatch (channel=`__internal__`, channel_ref=`watchlist_research`)."+ - "watchlist_research_scan — periodic cron for the executive_research workflow (default every 120 min via WATCHLIST_RESEARCH_INTERVAL_MINUTES). The handler short-circuits when the company profile / initiatives / watchlist haven't changed since the last successful run, so quiet days cost zero tokens — except that a staleness floor (WATCHLIST_RESEARCH_MAX_STALENESS_HOURS, default 168 — weekly; a daily forced run re-derived the same findings from unchanged state and re-filed them as fresh alerts every morning) forces a run once that long has elapsed since the last successful run, so a static internal state can't keep the council blind to external change indefinitely. Does NOT write its own Alert — the workflow's Executive synthesis step routes findings directly via DMs / send_department_message / create_alert / add_watchlist_entry, so a separate cron Alert would duplicate the briefing. After routing, a DEDICATED watchlist-analysis pass (its own budget, separate from the routing budget) explicitly decides which findings are ongoing monitorable conditions and calls add_watchlist_entry for each; the run's markdown artifact is also persisted into the separate `recent_research` knowledge collection (keep-latest) so future runs + chat can recall it. The cron's only side-effects on success are the audit row (`watchlist_research_periodic_ran`) and whatever routing tools the synthesis fired. The scheduled-action kind keeps the legacy `watchlist_research_scan` name (matched by the env var WATCHLIST_RESEARCH_INTERVAL_MINUTES + the three audit event_types) even though the workflow itself is registered as `executive_research` — naming is mixed intentionally to avoid a migration on already-pending heartbeat rows. Bypasses outbound dispatch (channel=`__internal__`, channel_ref=`watchlist_research`)."- "notion_sync_scan — optional heartbeat (NOTION_SYNC_ENABLED, default off) that incrementally re-indexes Notion pages shared with an internal integration into the isolated `notion_wiki` collection (NOT COMPANY — synced pages are multi-writer and unreviewed). Interval NOTION_SYNC_INTERVAL_MINUTES (default 60). Caps ingest per tick via NOTION_MAX_PAGES_PER_SCAN; overflow is retried and the watermark does not advance past failed or uningested pages. Each tick reconciles: un-shared/deleted pages have files + chunks purged. Bypasses outbound dispatch (channel=`__internal__`, channel_ref=`notion_sync`). Chains the next tick via enqueue_next_notion_sync_scan. See knowledge.collections NOTION_WIKI."channel_routing: |The delivery channel is stored ON the scheduled_actions row itself@@ -1091,6 +1207,32 @@ today:- "GET /today/activity?limit=N — Returns ActivityResponse(items). Each item is one recent self-initiated Executive action — a fired scheduled_action (DM dispatched, follow-up fired, cadence run, paused workflow resumed) or an extracted decision/advice row. Items carry `kind` (coarse classifier the UI maps to verb + icon — dm_sent, email_sent, nudge_sent, cadence_sent, workflow_resumed, proposal_routed, decision_logged, advice_given, workflow_done, initiative_started, decision_resolved, alert_raised, or action for unclassified), `summary`, `actor` (always Executive for now), `target` (channel ref / person, or null), `department`, and `at` (ISO timestamp). Sources merged — `scheduled_actions` with status=done (excluding `nudge_scan` heartbeat and `__internal__` channel), `decisions`, `advice_given`, completed `workflow_runs` (status=done — briefings/check-ins/research, bucketed at `updated_at`), `initiatives` (kicked-off projects, at `created_at`), resolved `decision_instances` (terminal gated-decision outcomes — approved/rejected/reversed, at `resolved_at`; pending ones stay in `proposals`, not the rail), and `alerts` raised (excluding source=`decision_scheduling`, which is the companion alert for a gated booking already represented by its `decision_resolved` row). This broadens the feed beyond the original messaging-heavy three sources so it reflects all self-initiated Executive activity, not just dispatched messages. Actions on `propose_only` departments are reclassified to `proposal_routed` because the runner marks them done without dispatching (the proposal is surfaced via /today's `proposals` field; the activity rail shows it as 'proposed to <approver>' rather than implying a DM was sent). Sorted by `at DESC`, then capped at `limit` (default 20, clamped to 1..100 via FastAPI Query validation — 422 on out-of-range). The Pulse page polls this endpoint (limit=100) every ~20s so new activity streams into the 'Recent activity' card without a reload; the card scrolls internally at a fixed max-height rather than growing the page."- "GET /today/activity/daily?days=N — Returns DailyActivityResponse(days), the per-day counts behind the Pulse page's 'heartbeat' heatmap (the GitHub-contributions-style grid at `/memories`). Same source set and exclusions as /today/activity — the union of `decisions`, `advice_given`, status=done `scheduled_actions` (excluding the `nudge_scan` heartbeat and `__internal__` channel), completed `workflow_runs`, `initiatives`, resolved `decision_instances`, and `alerts` — but bucketed by calendar day (UTC) in `episodic.count_activity_by_day` rather than returned as individual items — decisions/advice by their `timestamp`, fired actions by `run_at` (fire time, not `created_at` queue time, so a cadence queued the night before counts on the day it fires), workflow runs by `updated_at` (completion), initiatives by `created_at`, resolved decisions by `resolved_at`, alerts by `created_at`. The `workflow_runs` and `alerts` tables are owned by other stores (not `episodic.initialize_db`), so each UNION arm is included only when its table exists — `count_activity_by_day` checks `sqlite_master` and still counts the sources episodic owns on a DB initialised by episodic alone. The response is DENSE: every calendar day in the window is present (count 0 when nothing fired), oldest→newest, so the UI renders a gap-free grid without client-side fill. `days` defaults to 90, clamped to 1..365 via FastAPI Query validation (422 on out-of-range). Read-only, unauthenticated (matches /today/activity and /memories/*), uncached."- GET /morning-brief — deprecated alias for GET /today, kept for one release for older UI builds and bookmarks. Sends a Deprecation header with a Sunset date.+ lifecycle: |+ `proposals` is now the LIVE unread set (`alerts.lifecycle.list_live_alerts`:+ unread ∧ inside TTL ∧ not snoozed — the read-side twin of the scheduler's+ expiry sweep, so the page is right before the sweep runs), never+ `expired` / `resolved` rows. Each ProposalItem additionally carries+ `occurrence_count` / `last_seen_at` (coalescing), `last_reviewed_at`,+ `review_verdict` ('' | relevant | changed | likely_stale | drafted |+ routed | merged), `review_note` (the one-line "what changed since you+ last looked"), `recommended_move`, `why_now`, `due_at`,+ `superseded_count` (rows folded into it) and `suggested_workflow`.+ `briefing.ranking.score` now subtracts 30 for `likely_stale`, adds 20+ when `due_at` is within 24 h, and discounts up to 10 by the watch's+ `trust_score` (looked up once per distinct `external:<slug>` tag).+ `TodayResponse.handled_overnight` (additive) lists the alert review's+ autonomous moves since the last delivered morning brief (`brief_state.+ handled_since`: kind, summary, at, alert_id) — the UI's "Handled+ overnight" rail (Undo → `POST /alerts/{id}/reopen`) and the "Executive+ handled N overnight" status pill. UI: cards lead with `review_note`+ (amber "Likely stale" / "Updated" / "Since you last looked"), chips for+ age, seen ×N, why-now / due, folded-in, draft-ready, a "Reviewed <ago>"+ footer, a primary move control (Nudge <owner> → chat handoff; Run+ <workflow> → /jobs/<name>); "Needs you" shows "Start here" + 8 cards ++ "Show N more", a "Dismiss N older than 7 days" footer that sends+ explicit ids to `POST /alerts/bulk-ack` (never a server-side age sweep),+ and "Re-check relevance" (`POST /alerts/review`); Monitoring gets the+ same footer at 3 days; the ack body may carry `mute_topic`.ui_route: / (Next.js app router root) — the briefing is the default landing surface. `/today` still renders the same content as a standalone route (no sidebar shell) for bookmarks and the sidebar Briefing button. The chat lives at the same root behind a `mode` toggle — entering chat from "New chat" or by selecting a session swaps the main content; clicking the sidebar brandmark or the "Briefing" sidebar button returns to the briefing. A standalone "Pulse" link (→ `/memories`, the page titled "Pulse") is pinned directly beneath Briefing in the rail, the chat-home sidebar, and the mobile bottom bar — an always-visible top-level destination rather than a Knowledge-group entry (the Knowledge group now lists "RAG" → `/knowledge` and Skills). Both navs render it from the shared `PULSE_NAV_ITEM` in `navConfig.ts`.briefing_first_landing: |The root page (`packages/ui/src/app/page.tsx`) defaults to `mode="briefing"`@@ -1444,7 +1586,19 @@ external_monitoring:`external:<source>` + `external:<watchlist_slug>` topic tag — those tags(and the source itself, via briefing.ranking `_is_external_signal`) arewhat land an unrouted low/medium signal in the briefing's Monitoring lane- rather than the "Needs you" action queue.+ rather than the "Needs you" action queue. The event also carries+ `dedup_hint="watch:<slug>"`, which `alerts.pipeline` uses as the ALERT+ dedup_key (overriding the triage model's free-text key): a repeat from+ the same watch coalesces into the open card (`occurrence_count`,+ `last_seen_at`, severity max) instead of a new one, re-pinging only when+ severity rose into high/urgent — the signal-level `dedup_key` (stock's+ UTC-date bucket, vendor_status's `<updated>`) is untouched, so every+ observation still lands in `external_signals`. Feedback: dismissing a+ watch-sourced alert (HTTP ack or the `ack_alert` tool) calls+ `store.record_dismissal(slug)` — `dismiss_count += 1`, `trust_score =+ max(0.2, trust_score × 0.8)`; an ack calls `record_confirmation`+ (+0.05, capped at 1.0). `trust_score` discounts `briefing.ranking.score`+ (up to −10) and is shown to the alert review as WATCH TRUST evidence.heartbeat:kind: external_monitor_scanchannel: __internal__@@ -1623,7 +1777,7 @@ external_monitoring:triggers:- "Manual chat — the principal asks 'what should we look into?'; the Executive calls the `run_executive_research` chat tool. The tool runs the workflow, which both researches AND routes; the chat tool returns the structured summary so the Executive can describe to the principal what it researched and what it did with each finding."- "Onboarding completion — when the wizard finishes (build_and_save_profile fires), `api/routes/onboarding._fire_post_onboarding_research` schedules the workflow as a background task. The workflow's synthesis step fires whatever routing tools it deems necessary (DMs to heads, briefing alert, watchlist additions) — the wrapper just runs the workflow with a wall-clock ceiling and creates / completes the workflow_run row."- - "Periodic cron — `watchlist_research_scan` scheduled-action kind (default every 120 min via `WATCHLIST_RESEARCH_INTERVAL_MINUTES`). Each tick computes a state fingerprint (company profile + active initiatives + watchlist slugs/targets) and SKIPS the run when nothing has changed since the last successful periodic research. Quiet days cost zero tokens; first tick after any material profile / initiative / watchlist change fires immediately. A staleness floor (`WATCHLIST_RESEARCH_MAX_STALENESS_HOURS`, default 24) overrides the skip once that many hours have elapsed since the last successful run, so a static internal state cannot keep the council blind to purely-external change forever (set <= 0 to disable). The cron does NOT write its own Alert — the workflow's synthesis step already routes findings directly. After routing, a dedicated watchlist-analysis pass (separate budget) explicitly adds ongoing monitors via add_watchlist_entry, and the run artifact is persisted into the separate `recent_research` knowledge collection (keep-latest). Cron's only side-effects on success are the `watchlist_research_periodic_ran` audit row + whatever the workflow's Executive synthesis + watchlist pass fired."+ - "Periodic cron — `watchlist_research_scan` scheduled-action kind (default every 120 min via `WATCHLIST_RESEARCH_INTERVAL_MINUTES`). Each tick computes a state fingerprint (company profile + active initiatives + watchlist slugs/targets) and SKIPS the run when nothing has changed since the last successful periodic research. Quiet days cost zero tokens; first tick after any material profile / initiative / watchlist change fires immediately. A staleness floor (`WATCHLIST_RESEARCH_MAX_STALENESS_HOURS`, default 168, i.e. weekly) overrides the skip once that many hours have elapsed since the last successful run, so a static internal state cannot keep the council blind to purely-external change forever (set <= 0 to disable). The cron does NOT write its own Alert — the workflow's synthesis step already routes findings directly. After routing, a dedicated watchlist-analysis pass (separate budget) explicitly adds ongoing monitors via add_watchlist_entry, and the run artifact is persisted into the separate `recent_research` knowledge collection (keep-latest). Cron's only side-effects on success are the `watchlist_research_periodic_ran` audit row + whatever the workflow's Executive synthesis + watchlist pass fired."skip_if_unchanged: |The periodic cron handler (`monitoring.research.scheduler.run_watchlist_research_scan`)computes a sha256 over (`CompanyProfile.to_prompt_block()`,@@ -1852,9 +2006,9 @@ workflows:- inbound_resolver — matches human replies back to paused workflow runs.- crisis_comms — drafts incident response messaging.- churn_deep_dive — structured customer-loss analysis.- - "morning_brief — Shift 3 recurring workflow. Fires once per day from the scheduler (default 08:00 UTC, override via PRINCIPAL_BRIEF_MORNING_TIME env var). Targets the principal: utility_fast model renders a ≤200-word Markdown briefing covering at-risk goals, proposals awaiting decision, OE's overnight actions, and the top call. Artifact is DM'd via the principal's preferred_channel (slack_dm → discord_dm → telegram → email fallback chain). First workflow to target the principal rather than be user-invoked."- - "end_of_day_digest — Shift 3 recurring workflow. Fires once per day from the scheduler (default 18:00 UTC, override via PRINCIPAL_BRIEF_EOD_TIME). Same shape as morning_brief but framed as a recap: what OE did today, what's still pending, what's at risk for tomorrow, one optional 'sleep on this' question."- - "executive_reflection — Shift 5 recurring workflow. Fires once per day ~30 minutes before the morning brief (default 07:30 UTC, override via PRINCIPAL_REFLECTION_TIME). The first workflow OE runs ON ITSELF — not for a department, not for the principal, but for its own org-coordination judgment. Three steps: (1) gather /today + /today/activity + recent open alerts, (2) single LLM call with the full outbound toolkit (schedule_followup, send_*_dm, send_department_message, send_company_broadcast, suggest_workflow, create_alert, etc.) bounded to ≤4 iterations — the model decides per signal whether to act now, notify the right audience via the persona's 'Choosing Who to Tell' rule, raise it for the morning brief, or ignore, (3) emit a short Markdown summary with a structured tool-call log. The artifact is stored via complete_run but NOT DM'd — the morning brief surfaces what was decided via /today/activity. This operationalizes the 'When You Notice Something on Your Own' persona section (Shift 1)."+ - "morning_brief — Shift 3 recurring workflow. Fires once per day from the scheduler (default 08:00 UTC, override via PRINCIPAL_BRIEF_MORNING_TIME env var). Targets the principal: utility_fast model renders a ≤200-word Markdown briefing. CHANGE-AWARE: the window is 'since the last DELIVERED morning brief' (`briefing.brief_state.since_for`, 24 h on a cold store, clamped to 7 d); activity comes from `_build_activity(20, since=…)`; proposals (action category only) split into NEW SINCE LAST BRIEF (enumerated, with why_now / next move) vs a one-line CARRIED OVER count (with the likely-stale count); a HANDLED OVERNIGHT block lists the alert review's autonomous moves (`brief_state.handled_since`). Section order: top call → what changed → handled overnight → needs you (new only) → waiting on → at risk. A fingerprint of the inputs (`build_brief_fingerprint`, date-free) is compared to the last delivered one: unchanged ⇒ the artifact is the one-liner 'Nothing new since yesterday's brief — N items still waiting on you.' and no model call (`PRINCIPAL_BRIEF_SUPPRESS_UNCHANGED`, bypass with `force_full=true` on a manual run). The workflow yields a `result` event `{brief_fingerprint, suppressed, since}`; only `_run_principal_brief` records the fingerprint, after a successful delivery (`brief_state.record_delivered`, stored in `briefing_narrative` under scope `brief:<kind>`). Artifact is DM'd via the principal's preferred_channel (slack_dm → discord_dm → telegram → email fallback chain)."+ - "end_of_day_digest — Shift 3 recurring workflow. Fires once per day from the scheduler (default 18:00 UTC, override via PRINCIPAL_BRIEF_EOD_TIME). Same shape as morning_brief but framed as a recap since the last DELIVERED digest (`brief_state.since_for`, 24 h on a cold store): what OE did today (activity since), alerts it handled today, what's still pending (NEW SINCE LAST BRIEF, action category only, carried-over as one line), what's at risk for tomorrow, one optional 'sleep on this' question. Same fingerprint / one-liner suppression and `force_full` as morning_brief, under scope `brief:principal_brief_eod`."+ - "executive_reflection — Shift 5 recurring workflow. Fires once per day ~30 minutes before the morning brief (default 07:30 UTC, override via PRINCIPAL_REFLECTION_TIME). The first workflow OE runs ON ITSELF — not for a department, not for the principal, but for its own org-coordination judgment. Three steps: (1) gather /today + /today/activity + recent open alerts, (2) single LLM call with the full outbound toolkit (schedule_followup, send_*_dm, send_department_message, send_company_broadcast, suggest_workflow, create_alert, etc.) bounded to ≤4 iterations — the model decides per signal whether to act now, notify the right audience via the persona's 'Choosing Who to Tell' rule, raise it for the morning brief, or ignore, (3) emit a short Markdown summary with a structured tool-call log. MEMORY: the context carries a YESTERDAY'S STANDUP block (the previous done run's artifact, capped at 1500 chars) and the prompt forbids re-acting on or re-notifying about anything listed there unless it changed; open alerts render with `alert_id`, the review verdict, note and recommended move. Reflection never closes alerts (the alert review does, with evidence) — the prompt does not instruct `ack_alert`. The artifact is stored via complete_run but NOT DM'd — the morning brief surfaces what was decided via /today/activity. This operationalizes the 'When You Notice Something on Your Own' persona section (Shift 1)."- "candidate_screen — Talent-platform (Phase 1) workflow. Screens one candidate against one executive-search engagement: loads the engagement + candidate from `talent.store`, consults the `talent` specialist for a fit assessment, parses the 0-100 fit score from the response, and persists score + summary back onto the candidate via `talent.store.record_screening` (which advances a raw `lead` to `screened`). Emits a structured `result` event plus a Markdown scorecard artifact. See the `talent:` key."- "candidate_outreach — Talent-platform (Phase 3) recruiting-automation workflow. Drafts a personalized first-touch + N follow-ups for a candidate via the `talent` specialist and schedules each touch as a REMINDER TO THE PRINCIPAL (a `scheduled_actions` row, assigned_to_person_id=principal, run_at = now + i*interval) — never a direct message to the candidate. Draft-and-approve posture: each reminder is the human checkpoint (the Executive DMs the principal the ready-to-send draft at fire time; the principal sends it manually). Deliberately uses reminders rather than a `wait_for_human` gate because gate-resume is deferred (a gate would pause and never schedule). Channel resolution maps the principal's people-channel → scheduled-actions vocabulary (slack→slack_dm etc.). See the `talent:` key."- "interview_coordination — Talent-platform (Phase 3) workflow. Designs an N-round interview loop + a candidate-facing availability-request via the `talent` specialist, then schedules ONE reminder to the principal to kick off scheduling (line up the panel, send the availability request). Never contacts the candidate directly. See the `talent:` key."diff --git a/packages/core/openexecutive/architecture/prebuilt/agents.json b/packages/core/openexecutive/architecture/prebuilt/agents.jsonindex af6507d2..c26b271a 100644--- a/packages/core/openexecutive/architecture/prebuilt/agents.json+++ b/packages/core/openexecutive/architecture/prebuilt/agents.json@@ -1,7 +1,7 @@{"section_id": "agents","title": "Agent Council",- "markdown": "The Executive (`openexecutive.orchestrator.executive.Executive`) is a single coherent persona that fans out to specialist sub-agents via Anthropic tool use. Each specialist subclasses `openexecutive.agents.base.BaseAgent`, carrying a `name`, `domain`, and `model`, and exposes `analyze(...)`, which wraps the question in user-turn context and calls Claude through the per-call provider.\n\nRouting uses one `consult_specialist` tool. Multiple parallel `tool_use` blocks in a single assistant turn fan out concurrently through `router.route_parallel`, each running its own domain-filtered ChromaDB query before the specialist sees the question. The Executive then synthesizes the returned analyses into one reply.\n\nThe ten entries in `SPECIALIST_REGISTRY` (`openexecutive.orchestrator.router`):\n\n| Key | Agent | Domain |\n| --- | --- | --- |\n| `cso` | `StrategyAgent` | strategy |\n| `cfo` | `FinanceAgent` | finance |\n| `chro` | `HRAgent` | hr |\n| `gc` | `LegalAgent` | legal |\n| `coo` | `OperationsAgent` | operations |\n| `cmo` | `MarketingAgent` | marketing |\n| `cpo` | `ProductAgent` | product |\n| `board_comms` | `BoardCommsAgent` | board |\n| `talent` | `TalentAgent` | talent |\n| `triage` | `TriageAgent` | triage |\n\nModels: specialists default to `claude-sonnet-5`; a deep-reasoning tier uses `claude-opus-5` (adaptive thinking); routing/fast classification uses `claude-haiku-4-5`. The Council's **Deep reasoning** toggle is honoured on Claude Opus/Sonnet (direct or via OpenRouter) and on any OpenRouter model whose live catalog entry supports `reasoning` (today all OpenAI, Gemini, DeepSeek and Grok entries; not Llama) — the request translator turns Anthropic adaptive thinking + effort into OpenRouter's `reasoning` parameter. It is a silent no-op on models that can't reason, and disabled for Haiku, which rejects adaptive thinking. With `OPENROUTER_ENABLED`, the Council dropdown's non-Anthropic entries come from OpenRouter's live `/models` catalog (fetched at startup, refreshed in the background, filtered to tool-capable paid text models from an allowlisted vendor set), falling back to a built-in snapshot if the fetch fails. Four Council-only agents (`quality_judge`, `utility_fast`, `research`, `fixture_generator`) are model/prompt-overridable in the UI but not callable via `consult_specialist`.\n\nMost specialists only *advise* — they return analysis the Executive synthesizes. The `talent` specialist (Head of Talent & Executive Search) additionally backs a vertical the Executive can *act* on: `orchestrator.talent_tools` gives the main tool loop read access to the live search pipeline (`list_engagements`, `list_candidates`, `get_candidate`, `match_candidates`) plus two side-effecting tools (`set_candidate_stage`, `start_talent_workflow`), so a chat turn can move a candidate or fire a screen/outreach workflow, not just opine. See the Talent section.\n\nBeyond the talent vertical, the Executive can launch *any* workflow conversationally: `orchestrator.workflow_run_tools` adds `list_workflows` (the launchable catalog with each workflow's inputs) and `run_workflow` (runs a built-in or custom workflow to completion and returns its artifact, checkpointing approval gates as `awaiting_human`). This makes the `/jobs` catalog reachable from chat — see the Workflows section.\n\nThe Executive also backs the **Ask OE** panel's form-fill tier via `orchestrator.form_tools.propose_form_values`: when a chat turn arrives with a `<page_context>` block describing a form on the user's screen, the Executive can propose values for it. The proposal is delivered to the UI as a `form_patch` SSE event and placed into the form as highlighted suggestions — the tool never saves or submits anything; the user reviews and saves manually. The tool is **always** in the tool list (tool definitions sit at the top of the cached prompt prefix, so a conditionally-present tool would invalidate the prompt cache whenever panel and non-panel turns alternate); its description restricts usage to turns that carry a form descriptor.",+ "markdown": "The Executive (`openexecutive.orchestrator.executive.Executive`) is a single coherent persona that fans out to specialist sub-agents via Anthropic tool use. Each specialist subclasses `openexecutive.agents.base.BaseAgent`, carrying a `name`, `domain`, and `model`, and exposes `analyze(...)`, which wraps the question in user-turn context and calls Claude through the per-call provider.\n\nRouting uses one `consult_specialist` tool. Multiple parallel `tool_use` blocks in a single assistant turn fan out concurrently through `router.route_parallel`, each running its own domain-filtered ChromaDB query before the specialist sees the question. The Executive then synthesizes the returned analyses into one reply.\n\nThe ten entries in `SPECIALIST_REGISTRY` (`openexecutive.orchestrator.router`):\n\n| Key | Agent | Domain |\n| --- | --- | --- |\n| `cso` | `StrategyAgent` | strategy |\n| `cfo` | `FinanceAgent` | finance |\n| `chro` | `HRAgent` | hr |\n| `gc` | `LegalAgent` | legal |\n| `coo` | `OperationsAgent` | operations |\n| `cmo` | `MarketingAgent` | marketing |\n| `cpo` | `ProductAgent` | product |\n| `board_comms` | `BoardCommsAgent` | board |\n| `talent` | `TalentAgent` | talent |\n| `triage` | `TriageAgent` | triage |\n\nModels: specialists default to `claude-sonnet-5`; a deep-reasoning tier uses `claude-opus-5` (adaptive thinking); routing/fast classification uses `claude-haiku-4-5`. The Council's **Deep reasoning** toggle is honoured on Claude Opus/Sonnet (direct or via OpenRouter) and on any OpenRouter model whose live catalog entry supports `reasoning` (today all OpenAI, Gemini, DeepSeek and Grok entries; not Llama) — the request translator turns Anthropic adaptive thinking + effort into OpenRouter's `reasoning` parameter. It is a silent no-op on models that can't reason, and disabled for Haiku, which rejects adaptive thinking. With `OPENROUTER_ENABLED`, the Council dropdown's non-Anthropic entries come from OpenRouter's live `/models` catalog (fetched at startup, refreshed in the background, filtered to tool-capable paid text models from an allowlisted vendor set), falling back to a built-in snapshot if the fetch fails. Four Council-only agents (`quality_judge`, `utility_fast`, `research`, `fixture_generator`) are model/prompt-overridable in the UI but not callable via `consult_specialist`.\n\nOne more structured-output utility agent sits beside `triage`: `openexecutive.agents.alert_review.AlertReviewAgent` (routing model, one forced `emit_alert_reviews` tool call, never raises). The alert review job hands it a batch of open alerts with evidence and gets back, per alert, a verdict (relevant / changed / resolved / stale), a confidence, the evidence it relied on, a one-line note, why-now, an optional deadline, and a recommended move (none / route / nudge / escalate / draft / suggest_workflow / merge / close) with its parameters. Like `triage`, it never mutates state — `alerts.review.apply_verdict` executes the verdicts deterministically within authority, so the model's job is judgment, not action.\n\nMost specialists only *advise* — they return analysis the Executive synthesizes. The `talent` specialist (Head of Talent & Executive Search) additionally backs a vertical the Executive can *act* on: `orchestrator.talent_tools` gives the main tool loop read access to the live search pipeline (`list_engagements`, `list_candidates`, `get_candidate`, `match_candidates`) plus two side-effecting tools (`set_candidate_stage`, `start_talent_workflow`), so a chat turn can move a candidate or fire a screen/outreach workflow, not just opine. See the Talent section.\n\nBeyond the talent vertical, the Executive can launch *any* workflow conversationally: `orchestrator.workflow_run_tools` adds `list_workflows` (the launchable catalog with each workflow's inputs) and `run_workflow` (runs a built-in or custom workflow to completion and returns its artifact, checkpointing approval gates as `awaiting_human`). This makes the `/jobs` catalog reachable from chat — see the Workflows section.\n\nThe Executive also backs the **Ask OE** panel's form-fill tier via `orchestrator.form_tools.propose_form_values`: when a chat turn arrives with a `<page_context>` block describing a form on the user's screen, the Executive can propose values for it. The proposal is delivered to the UI as a `form_patch` SSE event and placed into the form as highlighted suggestions — the tool never saves or submits anything; the user reviews and saves manually. The tool is **always** in the tool list (tool definitions sit at the top of the cached prompt prefix, so a conditionally-present tool would invalidate the prompt cache whenever panel and non-panel turns alternate); its description restricts usage to turns that carry a form descriptor.","mermaid": "flowchart TD\n User([User message]) --> Exec[\"Executive<br/>orchestrator\"]\n Exec -->|consult_specialist| Cso[\"cso: StrategyAgent\"]\n Exec -->|consult_specialist| Cfo[\"cfo: FinanceAgent\"]\n Exec -->|consult_specialist| Gc[\"gc: LegalAgent\"]\n Exec -->|consult_specialist| More[\"chro / coo / cmo / cpo<br/>board_comms / talent / triage\"]\n Cso --> Claude[\"Claude (Anthropic)\"]\n Cfo --> Claude\n Gc --> Claude\n More --> Claude\n Claude --> Exec\n class User entry\n class Exec compute\n class Cso compute\n class Cfo compute\n class Gc compute\n class More compute\n class Claude external",- "generated_at": "2026-06-11T00:00:00+00:00"+ "generated_at": "2026-09-11T19:18:55+00:00"}diff --git a/packages/core/openexecutive/architecture/prebuilt/api.json b/packages/core/openexecutive/architecture/prebuilt/api.jsonindex b07d0ee4..9f4dcdf0 100644--- a/packages/core/openexecutive/architecture/prebuilt/api.json+++ b/packages/core/openexecutive/architecture/prebuilt/api.json@@ -1,7 +1,7 @@{"section_id": "api","title": "API Reference",- "markdown": "The FastAPI surface lives in `openexecutive.api.main`, which mounts one router per topic. A shared-secret middleware gates every request via an `x-api-key` header, except `/health` and the `/webhook/*` callbacks (which carry their own verification). CORS is restricted to configured UI origins. The gate is off when `BACKEND_SHARED_SECRET` is unset — intended for local development only — so any internet-reachable deployment sets `OE_PUBLIC_DEPLOYMENT`, and `create_app()` then refuses to boot without the secret rather than serving an unauthenticated API.\n\nEndpoints grouped by router:\n\n| Router | Key endpoints | Purpose |\n|---|---|---|\n| `chat` | `POST /chat` | SSE stream of a live Executive turn. The request body optionally carries `page_context` (route, page title, guide section id, and a form descriptor with current values) — sent only by the Ask OE side panel so the Executive can explain the current page or propose form values. When the Executive calls its `propose_form_values` tool, the stream emits a `form_patch` event (`{type, form_id, fields, rationale, iteration}`) that the panel applies into the on-screen form as highlighted suggestions; the user reviews and saves through the form's normal submit path. |\n| `sessions` | `GET /sessions`, `GET /sessions/{id}/messages` | List and read saved chat sessions. |\n| `today` | `GET /today`, `GET /today/activity`, `GET /today/activity/daily` | Morning-brief aggregation, recent-action rail, and Pulse heartbeat heatmap (per-day activity counts). |\n| `people` | `GET\\|POST\\|PATCH /people`, `POST /people/{id}/archive` | Roster CRUD and scope lookups. |\n| `departments` | `GET\\|POST\\|PATCH\\|DELETE /departments`, `.../goals` | Department state and per-department goals. |\n| `talent` | `GET|POST|PATCH /engagements`, `GET|POST|PATCH /candidates`, `POST /candidates/{id}/stage`, `GET /engagements/{id}/matches`, `GET /candidates/{id}/similar`, `POST /talent/reindex`, `GET|POST|PATCH /offers`, `POST /offers/{id}/{extend,decision,archive}` | Executive-search pipeline: searches, candidates, semantic matching, and the offer lifecycle (extend/decision return the offer plus approval state, scheduled/cancelled expiry nudges, side effects, and warnings; lifecycle conflicts are 409s). |\n| `agents` | `GET /agents`, `PATCH /agents/{id}`, `POST /agents/{id}/test` | Specialist metadata and Council overrides. |\n| `personas` | `GET\\|PUT\\|POST\\|DELETE /personas` | Executive persona definitions. |\n| `alerts` | `POST /alerts/{id}/ack` | Ack a briefing proposal (`read`/`ack`/`dismissed`) to groom the queue. The ingestion → triage → storage pipeline is unchanged, but alerts now surface only through the briefing (`/today` reads them directly) — there is no list, prefs, mutes, feedback, or live-stream endpoint. |\n| `artifacts` | `GET /artifacts`, `POST /artifacts/{id}/archive` | Browsable research/document artifacts. |\n| `decisions` | `GET /decisions`, `POST /decisions/{id}/{approve,reject,cancel}`, `GET /audit/reliability` | Approval-gated decision instances (e.g. calendar bookings). A proposed booking is surfaced on the briefing as a companion alert; approve/reject/cancel here also clear that alert. Reviewed in the briefing — there is no separate proposals page. |\n| `audit` | `GET /audit/logs`, `GET /audit/logs/{id}`, `GET /audit/sessions/{id}`, `GET /audit/usage`, `POST /audit/log` | Durable audit trail of side effects. `/audit/sessions/{id}` adds a per-session token cost summary; `/audit/usage` aggregates token usage and OpenRouter cost across all sessions (totals, by day, by model). |\n| `architecture` | `GET /architecture/sections`, `.../sections/{id}` | This documentation surface. |\n| `guide` | `GET /guide/sections`, `.../sections/{id}` | Plain-language user-guide content surface — mirrors `architecture` (static, version-controlled files; no LLM on the serving path). |\n| `health` | `GET /health`, `GET /health/honcho` | Liveness probes (unauthenticated). |\n| `documents` | `POST\\|GET\\|DELETE /documents`, `GET /documents/{filename}` | Upload, list, view extracted text, and delete indexed company docs. |\n| `scheduled` | `GET\\|DELETE` scheduled actions (`?status=…&order=asc\\|desc`) | Pending and fired scheduled actions; `order` flips the `run_at` sort (asc=soonest-first for the upcoming queue, desc=most-recent-first for terminal-status history). |\n| `watchlist` | `GET\\|POST\\|PATCH\\|DELETE /watchlist` | External-monitoring watchlist + signals. |\n| `workflows` | `GET /workflows`, `POST /workflows/{name}/runs`, `GET\\|POST\\|PUT\\|DELETE /workflows/custom` | Workflow catalog, run management, and user-created (dynamic) workflow CRUD. |\n| `knowledge` | `/knowledge/builtin`, `/external`, `/search` | MBA knowledge base and external sources. |\n| `skills` | `/skills`, `/skills/search` | Skill registry CRUD and search. |\n| `evals` | `/evals/scenarios`, `/evals/runs` | Eval scenarios and run results. |\n| `memories` | `/memories/{decisions,initiatives,advice}` | Episodic-memory record management. |\n| `review` | `/review/items`, `/review/stats` | Knowledge review queue and annotations. |\n| `onboarding` | `/onboard/start`, `/onboard/answer` | Company-profile setup wizard. |\n| `company-profile` | `GET\\|PATCH /company-profile` | Structured company profile. |\n| `auth` | `GET /auth/allowed-emails` | Allowed sign-in emails. |\n| `fixtures` | `/fixtures`, `/fixtures/{name}/load` | Demo-company fixture load/reset/snapshot. |\n| `clients` | `/clients`, `/clients/generate`, `/clients/cockpit`, `/clients/save`, `/clients/{slug}/activate` | Client-company slots — multi-client mode for fractional use; create from current/blank/AI-generated intake draft (pasted notes and/or file attachments, multipart on `/clients/generate`), save-back switching, engagement metadata (PATCH), cross-client cockpit, delete. See the Client Companies section. |\n| webhooks | `POST /webhook/telegram`, `POST /webhook/google-chat` | Inbound integration callbacks (self-verified). |\n| MCP server | `POST\\|GET /mcp` | Open Executive exposed as an MCP server (Streamable-HTTP). Not a router — a mounted FastMCP sub-app. Same shared-secret gate (`x-api-key`); exposes company context as resources and the specialist council as tools. See the MCP Server section. |",+ "markdown": "The FastAPI surface lives in `openexecutive.api.main`, which mounts one router per topic. A shared-secret middleware gates every request via an `x-api-key` header, except `/health` and the `/webhook/*` callbacks (which carry their own verification). CORS is restricted to configured UI origins. The gate is off when `BACKEND_SHARED_SECRET` is unset — intended for local development only — so any internet-reachable deployment sets `OE_PUBLIC_DEPLOYMENT`, and `create_app()` then refuses to boot without the secret rather than serving an unauthenticated API.\n\nEndpoints grouped by router:\n\n| Router | Key endpoints | Purpose |\n|---|---|---|\n| `chat` | `POST /chat` | SSE stream of a live Executive turn. The request body optionally carries `page_context` (route, page title, guide section id, and a form descriptor with current values) — sent only by the Ask OE side panel so the Executive can explain the current page or propose form values. When the Executive calls its `propose_form_values` tool, the stream emits a `form_patch` event (`{type, form_id, fields, rationale, iteration}`) that the panel applies into the on-screen form as highlighted suggestions; the user reviews and saves through the form's normal submit path. |\n| `sessions` | `GET /sessions`, `GET /sessions/{id}/messages` | List and read saved chat sessions. |\n| `today` | `GET /today`, `GET /today/activity`, `GET /today/activity/daily` | Morning-brief aggregation, recent-action rail, and Pulse heartbeat heatmap (per-day activity counts). |\n| `people` | `GET\\|POST\\|PATCH /people`, `POST /people/{id}/archive` | Roster CRUD and scope lookups. |\n| `departments` | `GET\\|POST\\|PATCH\\|DELETE /departments`, `.../goals` | Department state and per-department goals. |\n| `talent` | `GET|POST|PATCH /engagements`, `GET|POST|PATCH /candidates`, `POST /candidates/{id}/stage`, `GET /engagements/{id}/matches`, `GET /candidates/{id}/similar`, `POST /talent/reindex`, `GET|POST|PATCH /offers`, `POST /offers/{id}/{extend,decision,archive}` | Executive-search pipeline: searches, candidates, semantic matching, and the offer lifecycle (extend/decision return the offer plus approval state, scheduled/cancelled expiry nudges, side effects, and warnings; lifecycle conflicts are 409s). |\n| `agents` | `GET /agents`, `PATCH /agents/{id}`, `POST /agents/{id}/test` | Specialist metadata and Council overrides. |\n| `personas` | `GET\\|PUT\\|POST\\|DELETE /personas` | Executive persona definitions. |\n| `alerts` | `POST /alerts/{id}/ack`, `POST /alerts/bulk-ack`, `POST /alerts/{id}/reopen`, `POST /alerts/review` | Groom the briefing queue. `ack` (`read`/`ack`/`dismissed`, optional `mute_topic`) also teaches a watch-sourced alert's watch (`trust_score`); `bulk-ack` takes explicit `alert_ids` and/or `older_than_days` + `category` (exempt sources skipped); `reopen` is the Undo for a `resolved` / `expired` / `dismissed` alert (never `ack` or an artifact / decision row; back to `unread` with every review stamp cleared and its TTL anchor refreshed, so it is live again even if older than its TTL); `review` runs the Executive's relevance review on demand (ignores the interval; still honours `ALERT_REVIEW_ENABLED`, the per-pass caps, the single-flight lock and per-alert idempotency) and returns the move counts. `bulk-ack` caps ids at 500, needs `older_than_days >= 1`, and applies watch feedback per row; `mute_topic` must be one of the alert's tags or a scoped `external:` / `department:` pattern. Alerts still surface only through the briefing (`/today` reads the live view) — there is no list, prefs, mutes, or live-stream endpoint. |\n| `artifacts` | `GET /artifacts`, `POST /artifacts/{id}/archive` | Browsable research/document artifacts. |\n| `decisions` | `GET /decisions`, `POST /decisions/{id}/{approve,reject,cancel}`, `GET /audit/reliability` | Approval-gated decision instances (e.g. calendar bookings). A proposed booking is surfaced on the briefing as a companion alert; approve/reject/cancel here also clear that alert. Reviewed in the briefing — there is no separate proposals page. |\n| `audit` | `GET /audit/logs`, `GET /audit/logs/{id}`, `GET /audit/sessions/{id}`, `GET /audit/usage`, `POST /audit/log` | Durable audit trail of side effects. `/audit/sessions/{id}` adds a per-session token cost summary; `/audit/usage` aggregates token usage and OpenRouter cost across all sessions (totals, by day, by model). |\n| `architecture` | `GET /architecture/sections`, `.../sections/{id}` | This documentation surface. |\n| `guide` | `GET /guide/sections`, `.../sections/{id}` | Plain-language user-guide content surface — mirrors `architecture` (static, version-controlled files; no LLM on the serving path). |\n| `health` | `GET /health`, `GET /health/honcho` | Liveness probes (unauthenticated). |\n| `documents` | `POST\\|GET\\|DELETE /documents`, `GET /documents/{filename}` | Upload, list, view extracted text, and delete indexed company docs. |\n| `scheduled` | `GET\\|DELETE` scheduled actions (`?status=…&order=asc\\|desc`) | Pending and fired scheduled actions; `order` flips the `run_at` sort (asc=soonest-first for the upcoming queue, desc=most-recent-first for terminal-status history). |\n| `watchlist` | `GET\\|POST\\|PATCH\\|DELETE /watchlist` | External-monitoring watchlist + signals. |\n| `workflows` | `GET /workflows`, `POST /workflows/{name}/runs`, `GET\\|POST\\|PUT\\|DELETE /workflows/custom` | Workflow catalog, run management, and user-created (dynamic) workflow CRUD. |\n| `knowledge` | `/knowledge/builtin`, `/external`, `/search` | MBA knowledge base and external sources. |\n| `skills` | `/skills`, `/skills/search` | Skill registry CRUD and search. |\n| `evals` | `/evals/scenarios`, `/evals/runs` | Eval scenarios and run results. |\n| `memories` | `/memories/{decisions,initiatives,advice}` | Episodic-memory record management. |\n| `review` | `/review/items`, `/review/stats` | Knowledge review queue and annotations. |\n| `onboarding` | `/onboard/start`, `/onboard/answer` | Company-profile setup wizard. |\n| `company-profile` | `GET\\|PATCH /company-profile` | Structured company profile. |\n| `auth` | `GET /auth/allowed-emails` | Allowed sign-in emails. |\n| `fixtures` | `/fixtures`, `/fixtures/{name}/load` | Demo-company fixture load/reset/snapshot. |\n| `clients` | `/clients`, `/clients/generate`, `/clients/cockpit`, `/clients/save`, `/clients/{slug}/activate` | Client-company slots — multi-client mode for fractional use; create from current/blank/AI-generated intake draft (pasted notes and/or file attachments, multipart on `/clients/generate`), save-back switching, engagement metadata (PATCH), cross-client cockpit, delete. See the Client Companies section. |\n| webhooks | `POST /webhook/telegram`, `POST /webhook/google-chat` | Inbound integration callbacks (self-verified). |\n| MCP server | `POST\\|GET /mcp` | Open Executive exposed as an MCP server (Streamable-HTTP). Not a router — a mounted FastMCP sub-app. Same shared-secret gate (`x-api-key`); exposes company context as resources and the specialist council as tools. See the MCP Server section. |","mermaid": null,- "generated_at": "2026-09-11T14:34:11Z"+ "generated_at": "2026-09-11T19:47:55+00:00"}diff --git a/packages/core/openexecutive/architecture/prebuilt/external_monitoring.json b/packages/core/openexecutive/architecture/prebuilt/external_monitoring.jsonindex 306439dc..906688e9 100644--- a/packages/core/openexecutive/architecture/prebuilt/external_monitoring.json+++ b/packages/core/openexecutive/architecture/prebuilt/external_monitoring.json@@ -1,7 +1,7 @@{"section_id": "external_monitoring","title": "External Monitoring",- "markdown": "`openexecutive.monitoring` watches the outside world on a heartbeat and turns detected changes into briefing proposals via the same alert pipeline that handles inbound email and Slack.\n\nThe `external_monitor_scan` heartbeat (`__internal__` channel, default every 5 min) walks `list_watchlist(enabled_only=True)`, skipping rows fresher than their per-source cadence floor. For each due row it fires a read-only source adapter resolved from `_REGISTRY` by `signal_type`:\n\n- `vendor_status` — Statuspage Atom/RSS incident feeds (AWS, Stripe, GitHub, …). Reads each incident's current status out of the entry body, parses `<updated>` into `published_at`, and keys its dedup on `(entry id, <updated>)`; a **seeding** source (see below).\n- `rss` — generic Atom/RSS via feedparser (changelogs, layoffs.fyi, filings). Parses each entry's `<pubDate>`/`<updated>` into `published_at`; a **seeding** source (see below).\n- `stock` — Yahoo Finance chart endpoint; fires on `abs_change_pct_gte` moves.\n- `page_watch` — change-detection on a feed-less page. Fetches via the keyless httpx fetcher by default, or via xcrawl's scrape API when the row carries `config.fetch = \"xcrawl\"` — so JS-rendered / bot-blocked pages that publish no RSS (most modern news / marketing sites) are still monitorable.\n- `edgar` and the BILLED `query` web-search adapter.\n\nEach `Signal` is trigger-filtered, severity-clamped to the row's `[floor, ceiling]`, and INSERTed into `external_signals` where `UNIQUE(dedup_key)` drops replays. Survivors pass a suppression cascade (`baseline` → `stale` → `dry_run` → `below_floor` → capture-time relevance enrichment → promote), then `promote_signal_to_alert` builds an `AlertEvent` handed to `alerts.pipeline.schedule_evaluation` and surfaced as a `/today` proposal.\n\nEvery signal carries two timestamps that are never conflated: `captured_at` (when the monitor first saw it) and `published_at` (when the upstream says it happened — RSS `<pubDate>`, EDGAR filing date; null for `stock`, `page_watch`, `query`). Two freshness gates run first in the cascade, before anything that costs an LLM call. **Baseline:** the first poll that returns entries for a row whose adapter declares `seed_on_first_poll` (`rss`, `edgar`) records every entry already in the feed — trigger misses included, so the first entry that ever matches a keyword is news and a later, wider trigger can't resurface old ones — as `suppressed_baseline`, promotes nothing, and stamps `watchlist.baselined_at`, so a new watch reports what changes from now on instead of replaying the feed's back-catalogue (the same idea as `page_watch`'s first-observation baseline). It is keyed on `baselined_at` rather than `last_polled_at`, so a failed first fetch can't forfeit it; the claim and the recording are one transaction (a compare-and-swap on the stamp plus the rows, all-or-nothing), so of two overlapping scans exactly one records the back-catalogue and a failure part-way leaves nothing behind to replay; the other scan promotes only entries dated after that stamp (undated entries count as baseline, since the feed controls the date; entries dated more than a few minutes past its own clock are deferred rather than recorded); and baseline rows don't count against `max_signals_per_scan`, so a large feed can't be half-baselined. `vendor_status` used to sit outside both gates for a structural reason: its dedup key was `sha256(slug, entry id)`, and an incident's id never changes across its updates, so any suppressed insert muted that incident for good. Keying on `(entry id, <updated>)` instead (issue #90) makes a suppression cost one *state* of an incident rather than the incident, so both gates now apply to vendor feeds too — and an incident moving Investigating → Resolved mints a new key and surfaces, while re-polling an unchanged feed still dedups. Because a history feed's archive is mostly incidents resolved months ago, the adapter also carves live news out of its own baseline: it reads each incident's current status from the entry body (Statuspage renders the newest update first as `<strong>Resolved</strong>` / `Investigating` / `Monitoring` / … — the body is parsed by a real HTML parser, off the event loop, and the reading is deliberately asymmetric: any sign that the incident is over closes it, wherever it appears, while only a marked-up label can say it is still open. Working out which update is newest turned out to be something tag soup cannot be trusted to express, and every attempt reported a long-resolved incident as live) and exempts the ones still OPEN via the optional `promote_on_baseline` hook, so a watch added during an outage reports that outage on its first poll while the resolved archive is recorded as `suppressed_baseline`. An unrecognised status counts as closed — a vendor changing feed format must not be able to promote its whole archive at HIGH, and nothing is lost, since the next `<updated>` bump surfaces normally. An exempt entry must still pass the row's trigger filter (one that misses stays in the baseline, so widening a trigger later cannot resurface it) and is still judged by the stale gate below: the exemption buys an entry past the baseline, never past its own timestamp, because \"this is live\" is a reading of vendor-controlled markup and an entry the feed dates outside the age window is not news whatever that reading says. **Stale:** a signal whose `published_at` is older than `EXTERNAL_MONITOR_MAX_SIGNAL_AGE_DAYS` (default 7; `0` disables) at capture time is recorded as `suppressed_stale` and never promoted — a January article a feed resurfaces in September is not September news. An entry dated more than `EXTERNAL_MONITOR_MAX_FUTURE_SKEW_HOURS` ahead (default 24; `0` disables; `config_json.max_future_skew_hours` overrides it per row for calendar or maintenance feeds that legitimately date entries ahead) is deferred instead: skipped for the tick and not recorded (recording would burn its dedup key and let a feed mute an announcement for good by post-dating it), with one aggregated `external_signal_deferred` audit row per poll — carrying each held-back entry's summary and link, and emitted even if the poll later raises — then judged normally once the date passes. Inside the window, the alert body handed to triage carries `Published:` and `Discovered:` lines so the item is judged on when it happened. Adapters prefer a plausible date key over one more than a day in the future (and keep the future value when every key is implausible, so the pipeline defers it rather than waving an undated entry through), and the alert body collapses whitespace in the summary so no source can forge its own labeled body line.\n\nThe `query` adapter is a special case: it emits every web hit flat-LOW (it can't judge materiality per-hit), so for query signals enrichment runs BEFORE the floor gate and `_grade_query_severity` regrades from the relevance read (≥0.8 HIGH, ≥0.5 MEDIUM, else LOW). Without this, any query watch item with a `severity_floor` above LOW would suppress every hit — which is what left the Monitoring section empty even while standing queries were returning material findings.\n\nWhich lane a proposal lands in is decided by `briefing.ranking.categorize`: an unrouted, low/medium signal from a monitoring source (`stock`, `vendor_status`, `rss`, `query`, `edgar`, `page_watch`, or any `external:*` topic tag) is `monitoring` (the collapsible Monitoring section); a routed or high/urgent one is `action` (the \"Needs you\" queue). The triage prompt's External Signals rule covers all six source kinds so it trusts the source and emits the `external:*` tags that drive this split.\n\nThe watchlist is editable from chat (`add_watchlist_entry`, `tune_watchlist_entry`) and HTTP (`/watchlist`); the `executive_research` workflow proposes what to watch. Because that workflow is LLM-driven and historically proposed feed URLs it never verified (most were dead — 404 / 403 / not-actually-a-feed), every `rss` target is validated at insert time (`monitoring.target_validation`): a URL that fetches and parses as a feed is kept; a public page that isn't a feed is converted to a scrape-backed `page_watch` when xcrawl can read it, otherwise rejected (HTTP 422 / tool error); SSRF-blocked or unparseable URLs are rejected outright and never handed to xcrawl. Non-`rss` types insert unchanged with no network I/O.\n\n### Invariants\n\n- Adapters are read-only — they never write upstream and never auto-execute.\n- Every `Signal` carries a deterministic `dedup_key` and a mandatory `provenance_url`.\n- Fetches are SSRF-guarded and bounded by `external_monitor_max_fetch_bytes`; xcrawl scrape (off by default, gated by `XCRAWL_ENABLED` + `XCRAWL_API_KEY`) is the one path that delegates the fetch to an external API.\n- Suppressed signals are still persisted so audits show the full picture.",+ "markdown": "`openexecutive.monitoring` watches the outside world on a heartbeat and turns detected changes into briefing proposals via the same alert pipeline that handles inbound email and Slack.\n\nThe `external_monitor_scan` heartbeat (`__internal__` channel, default every 5 min) walks `list_watchlist(enabled_only=True)`, skipping rows fresher than their per-source cadence floor. For each due row it fires a read-only source adapter resolved from `_REGISTRY` by `signal_type`:\n\n- `vendor_status` — Statuspage Atom/RSS incident feeds (AWS, Stripe, GitHub, …). Reads each incident's current status out of the entry body, parses `<updated>` into `published_at`, and keys its dedup on `(entry id, <updated>)`; a **seeding** source (see below).\n- `rss` — generic Atom/RSS via feedparser (changelogs, layoffs.fyi, filings). Parses each entry's `<pubDate>`/`<updated>` into `published_at`; a **seeding** source (see below).\n- `stock` — Yahoo Finance chart endpoint; fires on `abs_change_pct_gte` moves.\n- `page_watch` — change-detection on a feed-less page. Fetches via the keyless httpx fetcher by default, or via xcrawl's scrape API when the row carries `config.fetch = \"xcrawl\"` — so JS-rendered / bot-blocked pages that publish no RSS (most modern news / marketing sites) are still monitorable.\n- `edgar` and the BILLED `query` web-search adapter.\n\nEach `Signal` is trigger-filtered, severity-clamped to the row's `[floor, ceiling]`, and INSERTed into `external_signals` where `UNIQUE(dedup_key)` drops replays. Survivors pass a suppression cascade (`baseline` → `stale` → `dry_run` → `below_floor` → capture-time relevance enrichment → promote), then `promote_signal_to_alert` builds an `AlertEvent` handed to `alerts.pipeline.schedule_evaluation` and surfaced as a `/today` proposal.\n\nEvery signal carries two timestamps that are never conflated: `captured_at` (when the monitor first saw it) and `published_at` (when the upstream says it happened — RSS `<pubDate>`, EDGAR filing date; null for `stock`, `page_watch`, `query`). Two freshness gates run first in the cascade, before anything that costs an LLM call. **Baseline:** the first poll that returns entries for a row whose adapter declares `seed_on_first_poll` (`rss`, `edgar`) records every entry already in the feed — trigger misses included, so the first entry that ever matches a keyword is news and a later, wider trigger can't resurface old ones — as `suppressed_baseline`, promotes nothing, and stamps `watchlist.baselined_at`, so a new watch reports what changes from now on instead of replaying the feed's back-catalogue (the same idea as `page_watch`'s first-observation baseline). It is keyed on `baselined_at` rather than `last_polled_at`, so a failed first fetch can't forfeit it; the claim and the recording are one transaction (a compare-and-swap on the stamp plus the rows, all-or-nothing), so of two overlapping scans exactly one records the back-catalogue and a failure part-way leaves nothing behind to replay; the other scan promotes only entries dated after that stamp (undated entries count as baseline, since the feed controls the date; entries dated more than a few minutes past its own clock are deferred rather than recorded); and baseline rows don't count against `max_signals_per_scan`, so a large feed can't be half-baselined. `vendor_status` used to sit outside both gates for a structural reason: its dedup key was `sha256(slug, entry id)`, and an incident's id never changes across its updates, so any suppressed insert muted that incident for good. Keying on `(entry id, <updated>)` instead (issue #90) makes a suppression cost one *state* of an incident rather than the incident, so both gates now apply to vendor feeds too — and an incident moving Investigating → Resolved mints a new key and surfaces, while re-polling an unchanged feed still dedups. Because a history feed's archive is mostly incidents resolved months ago, the adapter also carves live news out of its own baseline: it reads each incident's current status from the entry body (Statuspage renders the newest update first as `<strong>Resolved</strong>` / `Investigating` / `Monitoring` / … — the body is parsed by a real HTML parser, off the event loop, and the reading is deliberately asymmetric: any sign that the incident is over closes it, wherever it appears, while only a marked-up label can say it is still open. Working out which update is newest turned out to be something tag soup cannot be trusted to express, and every attempt reported a long-resolved incident as live) and exempts the ones still OPEN via the optional `promote_on_baseline` hook, so a watch added during an outage reports that outage on its first poll while the resolved archive is recorded as `suppressed_baseline`. An unrecognised status counts as closed — a vendor changing feed format must not be able to promote its whole archive at HIGH, and nothing is lost, since the next `<updated>` bump surfaces normally. An exempt entry must still pass the row's trigger filter (one that misses stays in the baseline, so widening a trigger later cannot resurface it) and is still judged by the stale gate below: the exemption buys an entry past the baseline, never past its own timestamp, because \"this is live\" is a reading of vendor-controlled markup and an entry the feed dates outside the age window is not news whatever that reading says. **Stale:** a signal whose `published_at` is older than `EXTERNAL_MONITOR_MAX_SIGNAL_AGE_DAYS` (default 7; `0` disables) at capture time is recorded as `suppressed_stale` and never promoted — a January article a feed resurfaces in September is not September news. An entry dated more than `EXTERNAL_MONITOR_MAX_FUTURE_SKEW_HOURS` ahead (default 24; `0` disables; `config_json.max_future_skew_hours` overrides it per row for calendar or maintenance feeds that legitimately date entries ahead) is deferred instead: skipped for the tick and not recorded (recording would burn its dedup key and let a feed mute an announcement for good by post-dating it), with one aggregated `external_signal_deferred` audit row per poll — carrying each held-back entry's summary and link, and emitted even if the poll later raises — then judged normally once the date passes. Inside the window, the alert body handed to triage carries `Published:` and `Discovered:` lines so the item is judged on when it happened. Adapters prefer a plausible date key over one more than a day in the future (and keep the future value when every key is implausible, so the pipeline defers it rather than waving an undated entry through), and the alert body collapses whitespace in the summary so no source can forge its own labeled body line.\n\nThe `query` adapter is a special case: it emits every web hit flat-LOW (it can't judge materiality per-hit), so for query signals enrichment runs BEFORE the floor gate and `_grade_query_severity` regrades from the relevance read (≥0.8 HIGH, ≥0.5 MEDIUM, else LOW). Without this, any query watch item with a `severity_floor` above LOW would suppress every hit — which is what left the Monitoring section empty even while standing queries were returning material findings.\n\nWhich lane a proposal lands in is decided by `briefing.ranking.categorize`: an unrouted, low/medium signal from a monitoring source (`stock`, `vendor_status`, `rss`, `query`, `edgar`, `page_watch`, or any `external:*` topic tag) is `monitoring` (the collapsible Monitoring section); a routed or high/urgent one is `action` (the \"Needs you\" queue). The triage prompt's External Signals rule covers all six source kinds so it trusts the source and emits the `external:*` tags that drive this split.\n\nThe watchlist is editable from chat (`add_watchlist_entry`, `tune_watchlist_entry`) and HTTP (`/watchlist`); the `executive_research` workflow proposes what to watch. Because that workflow is LLM-driven and historically proposed feed URLs it never verified (most were dead — 404 / 403 / not-actually-a-feed), every `rss` target is validated at insert time (`monitoring.target_validation`): a URL that fetches and parses as a feed is kept; a public page that isn't a feed is converted to a scrape-backed `page_watch` when xcrawl can read it, otherwise rejected (HTTP 422 / tool error); SSRF-blocked or unparseable URLs are rejected outright and never handed to xcrawl. Non-`rss` types insert unchanged with no network I/O.\n\n### One watch, one card — and dismissals teach the watch\n\n`promote_signal_to_alert` stamps the `AlertEvent` with `dedup_hint=\"watch:<slug>\"`, which `alerts.pipeline` uses as the *alert* dedup key. A repeat from the same watch coalesces into the open card (`occurrence_count`, `last_seen_at`, severity max) rather than minting another, and re-pings only when severity rose into high/urgent — so a ticker that stays over its threshold or an incident that keeps updating no longer produces a new \"Needs you\" item every day. The signal-level `dedup_key` (stock's UTC-date bucket, vendor_status's `<updated>`) is untouched, so every observation still lands in `external_signals`. Dismissing a watch-sourced alert calls `store.record_dismissal(slug)` (`dismiss_count += 1`, `trust_score = max(0.2, trust × 0.8)`); approving calls `record_confirmation` (+0.05). `trust_score` discounts the briefing ranking and is shown to the Executive's alert review as evidence, alongside the newer signals for that watch (a \"Resolved\" incident state, a reversed move) that let it close the card with evidence.\n\n### Invariants\n\n- Adapters are read-only — they never write upstream and never auto-execute.\n- Every `Signal` carries a deterministic `dedup_key` and a mandatory `provenance_url`.\n- Fetches are SSRF-guarded and bounded by `external_monitor_max_fetch_bytes`; xcrawl scrape (off by default, gated by `XCRAWL_ENABLED` + `XCRAWL_API_KEY`) is the one path that delegates the fetch to an external API.\n- Suppressed signals are still persisted so audits show the full picture.\n- A repeat from the same watch never becomes a second open card: the alert-level `watch:<slug>` key coalesces it, and only a severity escalation re-dispatches.","mermaid": "flowchart TD\n ADD[\"add (chat tool / POST /watchlist / research)\"]\n VAL[\"target_validation: rss feed? → keep / convert→page_watch(xcrawl) / reject\"]\n WL[(\"watchlist\")]\n HB[\"external_monitor_scan heartbeat (~5 min)\"]\n AD[\"read-only adapters: vendor_status / rss / stock / query / edgar / page_watch (httpx | xcrawl)\"]\n SIG[(\"external_signals UNIQUE(dedup_key)\")]\n ENRICH[\"capture-time enrichment<br/>(relevance score + why_it_matters)\"]\n PROMO[\"promote_signal_to_alert\"]\n PIPE[\"alert pipeline (triage)\"]\n TODAY[\"/today proposals\"]\n ADD --> VAL\n VAL -->|\"insert valid rows\"| WL\n HB -->|\"walk enabled rows\"| WL\n WL -->|\"poll due rows\"| AD\n AD -->|\"emit Signal\"| SIG\n SIG -->|\"baseline / stale / dry_run / floor gates\"| ENRICH\n ENRICH -->|\"≥ relevance floor\"| PROMO\n PROMO --> PIPE\n PIPE --> TODAY\n class HB hot\n class WL storage\n class VAL compute\n class AD external\n class SIG storage\n class ENRICH compute\n class PROMO compute\n class PIPE compute\n class TODAY entry\n class ADD compute",- "generated_at": "2026-09-07T19:52:01+00:00"+ "generated_at": "2026-09-11T19:18:55+00:00"}diff --git a/packages/core/openexecutive/architecture/prebuilt/scheduler.json b/packages/core/openexecutive/architecture/prebuilt/scheduler.jsonindex 3fcf0a2a..b738fa4c 100644--- a/packages/core/openexecutive/architecture/prebuilt/scheduler.json+++ b/packages/core/openexecutive/architecture/prebuilt/scheduler.json@@ -1,7 +1,7 @@{"section_id": "scheduler","title": "Scheduler & Cadences",- "markdown": "The scheduler is an asyncio task started in the FastAPI lifespan (`openexecutive.scheduler.runner.run_scheduler`). It polls every 30s and reads due rows from `scheduled_actions` (in `episodic_memory.db`). The due query uses `claim_due_actions`, an UPDATE…RETURNING claim, so each row fires at most once per process — this assumes a single scheduler instance per database. Polls are gated on an active company profile via `_company_profile_active()`; before onboarding, due rows stay `pending`.\n\n### Cadence DSL\n\n`openexecutive.departments.cadence` supports, all in UTC:\n\n- `daily@HH:MM`\n- `weekly@DOW@HH:MM` or `weekly@DOW-HH:MM` (DOW is a 3-letter day, e.g. `weekly@thu@09:00`)\n- `quarterly@DD-HH:MM`\n\nWhen a department cadence is due, the runner invokes the `department_check_in` workflow and chains the following occurrence via `cadence.enqueue_next()`. Deleting a department cancels its pending `dept_cadence` rows, and `cancel_orphaned_cadences()` sweeps orphans on boot.\n\nUser-created (dynamic) workflows can carry the same cadence DSL. A cadence-enabled definition enqueues a `dynamic_workflow` action (`workflows.dynamic_cadence`); when due, the runner runs the stored `DynamicWorkflow`, DMs the artifact to the definition's `cadence_person_id`, and re-chains the next occurrence. Saving/updating/deleting the definition reconciles its pending `dynamic_workflow` rows.\n\n### Channel routing & nudges\n\nThe delivery channel lives on the `scheduled_actions` row (`channel` / `channel_ref`); the runner dispatches through whichever was set at enqueue time — `telegram`, `slack_dm`, `discord_dm`, `email`, or `__internal__` (workflow steps and heartbeats bypass outbound dispatch). The nudge engine (`scheduler.nudge_engine`, default 15 min) scans stalled `awaiting_human` runs, stale commitments, and idle initiatives, then emits `proactive_nudge` rows routed via `people.channel.prefer_channel_for` — honouring each Person's preferred (last-used) channel and availability windows, deferring those outside their window and skipping those with no reachable channel.\n\n### Bounded onboarding ramp drip\n\nStaff onboarding adds the `onboarding_ramp` action kind — the one *self-terminating* recurring action (every other recurring kind chains forever). `staff_onboarding.service.activate_plan` enqueues the first occurrence; on each fire the runner claims the plan's next pre-generated ramp segment via an atomic compare-and-swap on `ramp_next_index` (`store.claim_next_ramp_segment`), DMs it to the hire with `message_person`, and chains the next **business-day** occurrence ONLY while segments remain — then stops. It no-ops unless the plan has a roster `person_id` and generated `ramp_segments`.\n\n### Onboarding orchestration & check-ins\n\n`activate_plan` also enqueues two more kinds (idempotently, via `staff_onboarding.orchestration`):\n\n- `onboarding_kickoff` — one-shot, fires the next tick: a welcome notice to the hire's **department channel only when one is configured** (no accidental broadcast — routed through the privacy-gated, audited `broadcast_tools.post_department_notice`, which applies the same length cap + privacy backstop + audit trail as `send_department_message`, to the first configured Slack/Discord/Telegram channel), plus intro-1:1 nudge DMs to the manager and buddy.\n- `onboarding_checkin` — milestone check-ins at **day 7 / 30 / 60 / 90**. Each milestone is its own pre-scheduled row (no self-chaining); milestones already in the past at activation are skipped. On fire it DMs the hire + manager a check-in and advances the plan's phase deterministically (forward-only). Because `wait_for_human` resume is a Phase-7 item, replies aren't auto-resumed — they land in chat, where the Executive's onboarding tools fold them into task/plan progress.\n\n## Client rotation claim pause\n\nThe `client_rotation` kind (multi-client practice mode, opt-in via `CLIENT_ROTATION_ENABLED`) adds one loop-level behavior: while a rotation's `.rotation_in_progress` marker exists, the scheduler **skips claiming entirely** for that tick. Rotation switches the live company context between parked clients; claiming during the window would fire the just-activated client's overdue outbound follow-ups from a context nobody is watching. Everything due fires on the first tick after the original client is restored. Stale markers (crash mid-rotation) are reconciled at scheduler startup, and the rotation row is idempotently re-seeded both at boot and after every slot activation (scheduled rows swap with the client). See the Client Companies section for the rotation's full design.\n\nAn optional `notion_sync_scan` heartbeat (`NOTION_SYNC_ENABLED`, off by default) incrementally re-indexes Notion pages the workspace integration can see into the isolated `notion_wiki` collection (not COMPANY), reconciles un-shared pages, then chains the next tick.",+ "markdown": "The scheduler is an asyncio task started in the FastAPI lifespan (`openexecutive.scheduler.runner.run_scheduler`). It polls every 30s and reads due rows from `scheduled_actions` (in `episodic_memory.db`). The due query uses `claim_due_actions`, an UPDATE…RETURNING claim, so each row fires at most once per process — this assumes a single scheduler instance per database. Polls are gated on an active company profile via `_company_profile_active()`; before onboarding, due rows stay `pending`.\n\n### Cadence DSL\n\n`openexecutive.departments.cadence` supports, all in UTC:\n\n- `daily@HH:MM`\n- `weekly@DOW@HH:MM` or `weekly@DOW-HH:MM` (DOW is a 3-letter day, e.g. `weekly@thu@09:00`)\n- `quarterly@DD-HH:MM`\n\nWhen a department cadence is due, the runner invokes the `department_check_in` workflow and chains the following occurrence via `cadence.enqueue_next()`. Deleting a department cancels its pending `dept_cadence` rows, and `cancel_orphaned_cadences()` sweeps orphans on boot.\n\nUser-created (dynamic) workflows can carry the same cadence DSL. A cadence-enabled definition enqueues a `dynamic_workflow` action (`workflows.dynamic_cadence`); when due, the runner runs the stored `DynamicWorkflow`, DMs the artifact to the definition's `cadence_person_id`, and re-chains the next occurrence. Saving/updating/deleting the definition reconciles its pending `dynamic_workflow` rows.\n\n### Channel routing & nudges\n\nThe delivery channel lives on the `scheduled_actions` row (`channel` / `channel_ref`); the runner dispatches through whichever was set at enqueue time — `telegram`, `slack_dm`, `discord_dm`, `email`, or `__internal__` (workflow steps and heartbeats bypass outbound dispatch). The nudge engine (`scheduler.nudge_engine`, default 15 min) scans stalled `awaiting_human` runs, stale commitments, and idle initiatives, then emits `proactive_nudge` rows routed via `people.channel.prefer_channel_for` — honouring each Person's preferred (last-used) channel and availability windows, deferring those outside their window and skipping those with no reachable channel. Emission is capped per `scope_key` (`NUDGE_MAX_PER_SCOPE`, default 3 delivered nudges) so a parked item is not chased forever.\n\n### Alert lifecycle: expiry sweep and the review heartbeat\n\nTwo alert-maintenance jobs live here. The **expiry sweep** is loop-level, not a heartbeat row: `_maybe_sweep_alerts` runs `alerts.lifecycle.expire_stale_alerts` once at boot and every 15 minutes at the top of the tick — before the company-profile and rotation gates, so an old backlog expires even before onboarding completes, flipping `unread` alerts past their category TTL to `expired` and auditing `alert_sweep`. Pure DB hygiene, no model call, reversible via `POST /alerts/{id}/reopen`.\n\nThe **Executive alert review** is a real heartbeat — kind `alert_review_scan`, `__internal__` channel, bootstrapped idempotently at startup when `ALERT_REVIEW_ENABLED` and chained every `ALERT_REVIEW_INTERVAL_HOURS` (6) with the same crash-resilient run → mark-done → chain shape as `nudge_scan`. `_run_principal_brief` also runs a `pre_brief` pass right before the morning brief (a review failure never blocks the brief). Each pass re-examines open alerts with evidence and, within department authority and the privacy rule, routes, nudges, escalates, drafts, merges or resolves them — see the Today section for the policy. The moves go through the real handlers (`message_person`, `draft_artifact`), so the outbound anti-spam guard applies, and `ALERT_REVIEW_MAX_MOVES_PER_SCAN` bounds side effects per pass.\n\n### Bounded onboarding ramp drip\n\nStaff onboarding adds the `onboarding_ramp` action kind — the one *self-terminating* recurring action (every other recurring kind chains forever). `staff_onboarding.service.activate_plan` enqueues the first occurrence; on each fire the runner claims the plan's next pre-generated ramp segment via an atomic compare-and-swap on `ramp_next_index` (`store.claim_next_ramp_segment`), DMs it to the hire with `message_person`, and chains the next **business-day** occurrence ONLY while segments remain — then stops. It no-ops unless the plan has a roster `person_id` and generated `ramp_segments`.\n\n### Onboarding orchestration & check-ins\n\n`activate_plan` also enqueues two more kinds (idempotently, via `staff_onboarding.orchestration`):\n\n- `onboarding_kickoff` — one-shot, fires the next tick: a welcome notice to the hire's **department channel only when one is configured** (no accidental broadcast — routed through the privacy-gated, audited `broadcast_tools.post_department_notice`, which applies the same length cap + privacy backstop + audit trail as `send_department_message`, to the first configured Slack/Discord/Telegram channel), plus intro-1:1 nudge DMs to the manager and buddy.\n- `onboarding_checkin` — milestone check-ins at **day 7 / 30 / 60 / 90**. Each milestone is its own pre-scheduled row (no self-chaining); milestones already in the past at activation are skipped. On fire it DMs the hire + manager a check-in and advances the plan's phase deterministically (forward-only). Because `wait_for_human` resume is a Phase-7 item, replies aren't auto-resumed — they land in chat, where the Executive's onboarding tools fold them into task/plan progress.\n\n## Client rotation claim pause\n\nThe `client_rotation` kind (multi-client practice mode, opt-in via `CLIENT_ROTATION_ENABLED`) adds one loop-level behavior: while a rotation's `.rotation_in_progress` marker exists, the scheduler **skips claiming entirely** for that tick. Rotation switches the live company context between parked clients; claiming during the window would fire the just-activated client's overdue outbound follow-ups from a context nobody is watching. Everything due fires on the first tick after the original client is restored. Stale markers (crash mid-rotation) are reconciled at scheduler startup, and the rotation row is idempotently re-seeded both at boot and after every slot activation (scheduled rows swap with the client). See the Client Companies section for the rotation's full design.\n\nAn optional `notion_sync_scan` heartbeat (`NOTION_SYNC_ENABLED`, off by default) incrementally re-indexes Notion pages the workspace integration can see into the isolated `notion_wiki` collection (not COMPANY), reconciles un-shared pages, then chains the next tick.","mermaid": "flowchart TD\n Loop[\"run_scheduler<br/>poll every 30s\"]\n Claim[\"claim_due_actions<br/>(status=pending, by kind)\"]\n Table[(\"scheduled_actions\")]\n Dispatch[\"dispatch via row channel<br/>(ad_hoc / proactive_nudge)\"]\n Dept[\"dept_cadence →<br/>department_check_in\"]\n Nudge[\"nudge_scan →<br/>nudge_engine scan\"]\n Brief[\"principal_brief_morning / _eod →<br/>morning_brief / end_of_day_digest\"]\n Reflect[\"executive_reflection →<br/>reflection (artifact only)\"]\n ExtMon[\"external_monitor_scan →<br/>monitoring pipeline\"]\n Research[\"watchlist_research_scan →<br/>executive_research (skip-if-unchanged)\"]\n Notion[\"notion_sync_scan →<br/>isolated wiki ingest\"]\n Chain[\"enqueue_next<br/>(re-arm recurring tick)\"]\n Prefer[\"prefer_channel_for<br/>(availability + last-used)\"]\n Channels[\"Slack / Discord<br/>Telegram / Email\"]\n Principal[\"DM principal\"]\n Alerts[\"alerts pipeline → /today\"]\n Loop --> Claim\n Claim -- \"claim due rows\" --> Table\n Claim -- \"ad_hoc / proactive_nudge\" --> Dispatch\n Claim -- \"dept_cadence\" --> Dept\n Claim -- \"nudge_scan\" --> Nudge\n Claim -- \"principal_brief_*\" --> Brief\n Claim -- \"executive_reflection\" --> Reflect\n Claim -- \"external_monitor_scan\" --> ExtMon\n Claim -- \"watchlist_research_scan\" --> Research\n Claim -- \"notion_sync_scan\" --> Notion\n Nudge -- \"prefer_channel_for\" --> Prefer\n Prefer -- \"emits proactive_nudge\" --> Table\n Dispatch --> Channels\n Brief --> Principal\n ExtMon --> Alerts\n Dept --> Chain\n Nudge --> Chain\n Brief --> Chain\n Reflect --> Chain\n ExtMon --> Chain\n Research --> Chain\n Notion --> Chain\n Chain --> Table\n class Loop entry\n class Claim compute\n class Table storage\n class Dispatch compute\n class Dept compute\n class Nudge compute\n class Brief compute\n class Reflect compute\n class ExtMon compute\n class Research compute\n class Notion compute\n class Chain compute\n class Prefer compute\n class Channels external\n class Principal external\n class Alerts hot",- "generated_at": "2026-08-31T00:00:00+00:00"+ "generated_at": "2026-09-11T19:36:35+00:00"}diff --git a/packages/core/openexecutive/architecture/prebuilt/today.json b/packages/core/openexecutive/architecture/prebuilt/today.jsonindex 6024a6ae..7b4fe208 100644--- a/packages/core/openexecutive/architecture/prebuilt/today.json+++ b/packages/core/openexecutive/architecture/prebuilt/today.json@@ -1,7 +1,7 @@{"section_id": "today","title": "Today / Morning Brief",- "markdown": "`openexecutive.api.routes.today` serves the morning brief \u2014 a one-screen, read-only view of what is happening across the org. It is the default landing surface (the Next.js root renders `<Briefing>`).\n\n`GET /today` returns `TodayResponse` assembled by `_build_today()`, which is synchronous and caller-agnostic:\n\n- **`departments`** \u2014 per-department goal health, rolling up each department's goal counts (`total`, `at_risk`, `off_track`) plus its awaiting-workflow count, and `attention_goals`: the actual off-track/at-risk goals (worst first, capped at 3) with `key_result`, `current`, `target`, and `status`, so the briefing's Department card shows *which* goal is off and how far without a click. Empty for healthy/inactive departments.\n- **`people`** \u2014 an attention-ranked roster. Each person carries `awaiting_action` count, soonest SLA, a `status` (`on_leave` / `needs_reply` / `awaiting` / `clear`), reachability, `overdue`, a server `priority` sort key, and a cached one-line `insight`. Sorted by `(-priority, full_name)`.\n- **`proposals`** \u2014 all unread alerts (workflow approvals, triage-classified inbound, Executive signals, flagged artifacts, and gated calendar bookings). Each carries `score`, `category` (`action` vs `monitoring`), `surfaced_reason` from `openexecutive.briefing.ranking`, and `decision_instance_id` (set only when the proposal is backed by a decision-ledger row \u2014 a calendar booking awaiting approval). The UI splits them into 'mine' vs 'across the team' using `caller_person_id`. For decision-backed proposals the card's Approve/Reject call the `/decisions` endpoints (which book or cancel the event server-side and clear the alert) instead of the ack-and-hand-off-to-chat flow \u2014 so meeting bookings are reviewed in the briefing itself rather than on a separate page.\n- **`narrative`** \u2014 a per-viewer Executive-voice header synthesized by `synthesize_briefing_narrative`; the principal gets the whole-company scope, teammates a role-scoped one. In the web UI each bullet of this narrative is a click target: clicking one hands off to chat (the same `onContinue` path as the proposal cards) seeded to discuss that item. The Executive recognizes it because every chat turn now carries a `<briefing>` digest of open alerts (see Memory).\n- **`in_flight`** / **`awaiting`** \u2014 upcoming Executive commitments and people we are waiting on.\n- **`talent`** \u2014 the active executive-search pipeline, rolled up by `briefing.talent_digest.build_talent_brief_items`: one item per non-terminal engagement (FILLED/CANCELLED dropped) with role, department, status, candidate count, per-stage counts, and four attention signals \u2014 `offers_expiring_soon` (extended offers within 72h of `expires_at`, or past it with no decision recorded \u2014 computed straight from the offers table so a missed nudge can't make the briefing stale), `needs_screening` (leads), `offers_out` (offers), and `stalled_count` (active candidates not touched in \u22657 days). Items sort expiring \u2192 offers \u2192 stalled \u2192 leads \u2192 size. It renders as the briefing's **Executive search** card (one per search; click-to-discuss hands off to chat via the same `onContinue` path), feeds the narrative (an offer landing or a search going cold re-writes the header \u2014 the narrative cache hash folds a talent fingerprint), and the same digest's `format_talent_for_prompt` is appended to the chat `<briefing>` block so the Executive can discuss live searches by client or role. One rollup, shared by all four surfaces, so the card / header / chat never disagree. See the Talent section.\n\nThe route resolves the caller from `x-caller-email`, then attaches the viewer-scoped narrative in a `BackgroundTask` so the request never blocks on an LLM call. `GET /today/activity` returns the recent self-initiated action rail \u2014 merged from fired scheduled actions (DMs, follow-ups, nudges, cadences), logged decisions, saved advice, completed workflow runs (briefings/check-ins/research), kicked-off initiatives, resolved gated decisions, and raised alerts, so it reflects all of the Executive's activity rather than just dispatched messages. The Pulse page (`/memories`) polls it (limit 100) every ~20s so new events stream into the 'Recent activity' card, which scrolls internally at a fixed height instead of growing the page. The `morning_brief` workflow calls `_build_today()` directly to build the standalone DM (via a different, enumerated prompt). `GET /morning-brief` is a deprecated alias.\n\n## Multi-client practice section\n\nIn multi-client practice mode (2+ client slots \u2014 see the Client Companies section), the response gains an additive `practice_clients` list: rollup cards for the **parked** clients (overdue follow-ups, awaiting replies, unread alerts, onboarding due soon, renewal countdowns), each stamped with the save point its data reflects. Single-company installs always receive an empty list and the UI renders nothing.",+ "markdown": "`openexecutive.api.routes.today` serves the morning brief — a one-screen, read-only view of what is happening across the org. It is the default landing surface (the Next.js root renders `<Briefing>`).\n\n`GET /today` returns `TodayResponse` assembled by `_build_today()`, which is synchronous and caller-agnostic:\n\n- **`departments`** — per-department goal health, rolling up each department's goal counts (`total`, `at_risk`, `off_track`) plus its awaiting-workflow count, and `attention_goals`: the actual off-track/at-risk goals (worst first, capped at 3) with `key_result`, `current`, `target`, and `status`, so the briefing's Department card shows *which* goal is off and how far without a click. Empty for healthy/inactive departments.\n- **`people`** — an attention-ranked roster. Each person carries `awaiting_action` count, soonest SLA, a `status` (`on_leave` / `needs_reply` / `awaiting` / `clear`), reachability, `overdue`, a server `priority` sort key, and a cached one-line `insight`. Sorted by `(-priority, full_name)`.\n- **`proposals`** — the *live* unread alerts (workflow approvals, triage-classified inbound, Executive signals, flagged artifacts, and gated calendar bookings): unread, inside their category TTL, not snoozed — see *Alert lifecycle* below. Each carries `score`, `category` (`action` vs `monitoring`), `surfaced_reason` from `openexecutive.briefing.ranking`, the lifecycle fields (`occurrence_count`, `last_seen_at`, `last_reviewed_at`, `review_verdict`, `review_note`, `recommended_move`, `why_now`, `due_at`, `superseded_count`, `suggested_workflow`), and `decision_instance_id` (set only when the proposal is backed by a decision-ledger row — a calendar booking awaiting approval). The UI splits them into 'mine' vs 'across the team' using `caller_person_id`. For decision-backed proposals the card's Approve/Reject call the `/decisions` endpoints (which book or cancel the event server-side and clear the alert) instead of the ack-and-hand-off-to-chat flow — so meeting bookings are reviewed in the briefing itself rather than on a separate page.\n- **`narrative`** — a per-viewer Executive-voice header synthesized by `synthesize_briefing_narrative`; the principal gets the whole-company scope, teammates a role-scoped one. In the web UI each bullet of this narrative is a click target: clicking one hands off to chat (the same `onContinue` path as the proposal cards) seeded to discuss that item. The Executive recognizes it because every chat turn now carries a `<briefing>` digest of open alerts (see Memory).\n- **`in_flight`** / **`awaiting`** — upcoming Executive commitments and people we are waiting on.\n- **`handled_overnight`** — the autonomous moves the Executive's alert review made since the last delivered morning brief (routed, nudged, escalated, drafted, merged, closed, updated), each with the alert id so the UI can offer Undo.\n- **`talent`** — the active executive-search pipeline, rolled up by `briefing.talent_digest.build_talent_brief_items`: one item per non-terminal engagement (FILLED/CANCELLED dropped) with role, department, status, candidate count, per-stage counts, and four attention signals — `offers_expiring_soon` (extended offers within 72h of `expires_at`, or past it with no decision recorded — computed straight from the offers table so a missed nudge can't make the briefing stale), `needs_screening` (leads), `offers_out` (offers), and `stalled_count` (active candidates not touched in ≥7 days). Items sort expiring → offers → stalled → leads → size. It renders as the briefing's **Executive search** card (one per search; click-to-discuss hands off to chat via the same `onContinue` path), feeds the narrative (an offer landing or a search going cold re-writes the header — the narrative cache hash folds a talent fingerprint), and the same digest's `format_talent_for_prompt` is appended to the chat `<briefing>` block so the Executive can discuss live searches by client or role. One rollup, shared by all four surfaces, so the card / header / chat never disagree. See the Talent section.\n\nThe route resolves the caller from `x-caller-email`, then attaches the viewer-scoped narrative in a `BackgroundTask` so the request never blocks on an LLM call. `GET /today/activity` returns the recent self-initiated action rail — merged from fired scheduled actions (DMs, follow-ups, nudges, cadences), logged decisions, saved advice, completed workflow runs (briefings/check-ins/research), kicked-off initiatives, resolved gated decisions, and raised alerts, so it reflects all of the Executive's activity rather than just dispatched messages. The Pulse page (`/memories`) polls it (limit 100) every ~20s so new events stream into the 'Recent activity' card, which scrolls internally at a fixed height instead of growing the page. The `morning_brief` workflow calls `_build_today()` directly to build the standalone DM (via a different, enumerated prompt). `GET /morning-brief` is a deprecated alias.\n\n## Alert lifecycle & the Executive review\n\nAlerts used to be write-once: raised, then never looked at again, so the \"Needs you\" queue grew without bound and the briefs re-listed it daily. Three things now keep it live:\n\n- **Time-to-live** (`openexecutive.alerts.lifecycle`). Action items expire after `ALERT_TTL_DAYS_ACTION` (14 d), unrouted low/medium monitoring signals after `ALERT_TTL_DAYS_MONITORING` (3 d). Every surface reads `list_live_alerts` (the same predicate the scheduler's 15-minute sweep persists as status `expired`), so `/today` is right even before the sweep runs. Artifacts and decision-backed alerts are exempt. `POST /alerts/{id}/reopen` is the Undo.\n- **Coalescing** (`alerts.pipeline` + `store.coalesce_alert`). A repeat of an open alert with the same `(source, dedup_key)` updates that row — `occurrence_count`, `last_seen_at`, severity max — instead of stacking a second card, and only re-pings when severity rose to high/urgent. Monitoring alerts carry a stable `watch:<slug>` key, so one watch means one card.\n- **The review** (`openexecutive.alerts.review`, heartbeat `alert_review_scan`, every 6 h and right before the morning brief). For each open alert the Executive sees what changed since it was raised — newer signals from the same watch, related alerts, activity since, the roster with SLAs, department authority — and returns a verdict (relevant / changed / resolved / stale) plus a recommended move. Deterministic policy then acts: **route** (assign + DM the owner; `propose_via_alert` for propose-only departments), **nudge**, **escalate** (severity + `due_at` + DM the principal only), **draft** (`draft_artifact`), **suggest a workflow** (a link, never a run), **merge** (`superseded_by_alert_id`), or **resolve** — only on high confidence citing a server-minted evidence ref (a newer signal, a related alert, an activity item shown for that alert); free text never closes a card, and anything weaker is annotated `likely_stale`, demoted 30 ranking points, and left for one click. Everything that came from outside is rendered as inert data inside the review prompt, so an injected email body cannot steer the batch. Board / comp / legal matters only ever go to a scope-holder or the principal and keep their text. Route and escalate are idempotent across passes, every DM carries an \"[Alert review] Re: …\" header, outbound moves are capped per pass, passes are single-flight, `ALERT_REVIEW_ENABLED=false` stops every caller, every move is audited with its evidence and prior state, and a distinct `resolved` status keeps Executive closes separate from `ack` (user approved).\n\nOn the page, cards read as decisions: the one-line \"what changed since you last looked\" (`review_note`) leads, the recommended move is the primary control (Nudge <owner> → chat; Run <workflow> → `/jobs/<name>`), with chips for age, seen ×N, why-now / due, folded-in and draft-ready, a \"Reviewed <ago>\" footer, and an amber Likely-stale treatment with one-click Dismiss. \"Needs you\" shows *Start here* + 8 cards + \"Show N more\", a \"Dismiss N older than 7 days\" footer (explicit ids to `POST /alerts/bulk-ack` — never a server-side age sweep, which would hit teammates' routed items), and \"Re-check relevance\" (`POST /alerts/review`). The \"Handled overnight\" rail and the \"Executive handled N overnight\" pill show what the review did, with Undo. Dismissing a watch-sourced alert lowers that watch's `trust_score` (which discounts ranking and is shown to the review as evidence); the ack body may carry `mute_topic`.\n\n## Multi-client practice section\n\nIn multi-client practice mode (2+ client slots — see the Client Companies section), the response gains an additive `practice_clients` list: rollup cards for the **parked** clients (overdue follow-ups, awaiting replies, unread alerts, onboarding due soon, renewal countdowns), each stamped with the save point its data reflects. Single-company installs always receive an empty list and the UI renders nothing.","mermaid": "flowchart TD\n REQ[\"GET /today\"]\n BUILD[\"_build_today()\"]\n DEPTS[\"departments<br/>(per-dept goal health)\"]\n ROSTER[\"people<br/>(attention-ranked roster)\"]\n PROPS[\"proposals<br/>(unread alerts, routed)\"]\n INFLIGHT[\"in_flight<br/>(pending follow-ups / nudges)\"]\n AWAIT[\"awaiting<br/>(replies we await)\"]\n TALENT[\"talent<br/>(open searches, by stage)\"]\n NARR[\"viewer-scoped narrative (BackgroundTask)\"]\n MB[\"morning_brief workflow\"]\n REQ --> BUILD\n BUILD --> DEPTS\n BUILD --> ROSTER\n BUILD --> PROPS\n BUILD --> INFLIGHT\n BUILD --> AWAIT\n BUILD --> TALENT\n REQ -->|\"resolve caller, attach\"| NARR\n MB -->|\"calls directly for standalone DM\"| BUILD\n class REQ entry\n class BUILD compute\n class DEPTS storage\n class ROSTER storage\n class PROPS storage\n class INFLIGHT storage\n class AWAIT storage\n class TALENT storage\n class NARR compute\n class MB compute",- "generated_at": "2026-06-10T00:00:00+00:00"-}\ No newline at end of file+ "generated_at": "2026-09-11T19:36:35+00:00"+}diff --git a/packages/core/openexecutive/architecture/prebuilt/workflows.json b/packages/core/openexecutive/architecture/prebuilt/workflows.jsonindex 3326ed39..698b1c81 100644--- a/packages/core/openexecutive/architecture/prebuilt/workflows.json+++ b/packages/core/openexecutive/architecture/prebuilt/workflows.json@@ -1,7 +1,7 @@{"section_id": "workflows","title": "Workflows",- "markdown": "Workflows are deterministic, multi-step orchestrations. The built-ins are registered in `openexecutive.workflows.WORKFLOW_REGISTRY`; user-created (dynamic) workflows are stored as data (see below). Each follows the same contract: structured input feeds an ordered list of named steps that render a Markdown artifact, persisted via `complete_run` into `workflow_runs.artifact`. Every step emits a `WorkflowEvent` (start/progress/complete) streamed over SSE at `/workflows/{name}/runs`.\n\nThe registry holds 30 built-in workflows, plus any number of user-created ones. Representative built-ins:\n\n- `board_prep`, `quarterly_plan`, `annual_plan` \u2014 planning and governance deliverables.\n- `performance_review`, `comp_refresh`, `org_design` \u2014 people and org artifacts.\n- `crisis_comms`, `churn_deep_dive`, `competitive_teardown` \u2014 situational analyses.\n- `department_check_in` \u2014 runs on department cadence; its `goal_status` step returns structured verdicts persisted back to `department_goals.status`.\n- `offer_approval`, `new_hire_onboarding` \u2014 the talent vertical's hire-loop pair: offer package + sign-off gate, and the placed-candidate \u2192 roster-Person handoff with 30/60/90 check-ins (see [Talent](#talent)); `new_hire_onboarding` creates the roster Person that the staff-onboarding subsystem's plan delivery and ramp drip need \u2014 see [Staff Onboarding](#staff_onboarding).\n\n### Wait-for-human pause\n\n`wait_for_human` (`openexecutive/workflows/wait_for_human.py`) is a first-class step primitive that pauses a run, writes an `awaiting_human` row into `scheduled_actions`, and returns control to the user. `propose_only` departments route scheduled actions through this approval path rather than executing immediately. When the human replies on any channel, the `inbound_resolver` workflow matches the response to the paused run via its resume token, and `resumer.apply_resolution` records the decision, marks the run `resolved`, and writes an audit row. A timeout applies the step's `on_timeout` policy (escalate / auto_proceed / fail). The captured outcome surfaces on the Today dashboard.\n\nFull generator resume is **not yet implemented**: a paused run records the human's decision and stops \u2014 it does not re-enter the generator to run its remaining steps. `offer_approval` is the first *built-in* workflow to yield the gate (previously only dynamic workflows did), and it is designed around that gap: it yields its `result` and `artifact` events *before* the gate and persists the offer package onto the Offer row, so the gate's only job is to record the HIRING_SIGNOFF decision \u2014 the actual `pending_approval \u2192 extended` transition is the explicit `extend_offer` tool/route, which consults the recorded resolution.\n\n### Launching from chat\n\nWorkflows are not only reachable from the `/jobs` UI \u2014 the Executive can list and run any of them mid-conversation. `openexecutive.orchestrator.workflow_run_tools` wires two tools into the main chat loop: `list_workflows` (the launchable catalog, with each workflow's input fields) and `run_workflow` (runs one to completion and returns its Markdown artifact, using the same engine as `POST /workflows/{name}/runs`). `run_workflow` resolves both built-ins and custom workflows via `get_workflow`, validates `inputs` against the workflow's input model, persists the run (`create_run` \u2192 `complete_run` / `fail_run`), and on an approval-gate step checkpoints the run as `awaiting_human` exactly as the HTTP route does \u2014 it never hangs waiting on a human. `executive_research` is excluded (it has the dedicated `run_executive_research` tool); the principal-targeting recurring workflows (`morning_brief`, `end_of_day_digest`, `executive_reflection`) stay launchable but the tool description flags that they dispatch real messages. Talent workflows remain better served by `start_talent_workflow`. A successful run surfaces an `action_taken` chip linking to `/jobs/runs/{run_id}`.\n\n### Dynamic (user-created) workflows\n\nUsers create reusable workflows on the fly \u2014 from the executive chat or a builder UI on `/jobs` \u2014 without shipping code. A dynamic workflow is a stored JSON definition (the `dynamic_workflows` table) interpreted at runtime by one generic `DynamicWorkflow` engine (`openexecutive/workflows/dynamic.py`) that implements the same `Workflow` ABC as the built-ins, so the run path, SSE streaming, run persistence, and `/jobs/[name]` form rendering are unchanged. `get_workflow` / `list_workflows` fall through to the dynamic store after the static registry (built-ins win on a name collision).\n\nA definition declares free-text input fields and an ordered step list of three kinds: **specialist** (consult a specialist with a goal prompt, optionally grounded by RAG), **approval_gate** (a `wait_for_human` pause), and a terminal **synthesis** step that assembles the artifact. `validate_definition` enforces the structural rules: exactly one terminal synthesis step, valid specialists, `{placeholder}` tokens that reference declared input fields, rostered approval/cadence people, and a parseable cadence.\n\nAuthoring from chat uses a **draft \u2192 confirm** handshake: the Executive calls `draft_workflow` (validate; return a `confirm_token` plus a plan summary), shows the user the plan, then calls `save_workflow` with the same definition and token \u2014 a token mismatch is rejected, so the saved workflow is exactly what the user approved. The builder UI drives the `/workflows/custom` CRUD endpoints directly. An optional cadence (`daily@` / `weekly@` / `quarterly@`) re-uses the scheduler via the `dynamic_workflow` action kind, which runs the workflow on schedule and DMs the artifact to a rostered recipient. Limitation: a gate followed by further steps pauses at `awaiting_human` and does not auto-continue (generator resume is deferred upstream), so gates belong immediately before synthesis.\n\nCompleted artifacts are discoverable in the unified Artifacts section (`/artifacts`) alongside their run-detail page at `/jobs/runs/{run_id}`.\n\n## Data-driven retrospectives\n\n`engagement_value_report` introduces a new workflow pattern: instead of the user typing the substance into a form (the `investor_update` / `mbr` shape), the workflow **reads its substance from the database**. A deterministic gatherer (`clients/engagement_activity.py`) pulls the period's decisions, initiatives, advisory consultations, delivered workflow artifacts (excluding prior value reports), follow-through counts, and alerts handled \u2014 from the live DB for the active client, or a parked client slot's `state.db` opened read-only. A single board-comms call narrates those facts (the prompt forbids inventing anything not in them; an empty period skips the LLM entirely), and the artifact's lists are assembled deterministically. Built for renewal conversations \u2014 the engagement record is the evidence.",+ "markdown": "Workflows are deterministic, multi-step orchestrations. The built-ins are registered in `openexecutive.workflows.WORKFLOW_REGISTRY`; user-created (dynamic) workflows are stored as data (see below). Each follows the same contract: structured input feeds an ordered list of named steps that render a Markdown artifact, persisted via `complete_run` into `workflow_runs.artifact`. Every step emits a `WorkflowEvent` (start/progress/complete) streamed over SSE at `/workflows/{name}/runs`.\n\nThe registry holds 30 built-in workflows, plus any number of user-created ones. Representative built-ins:\n\n- `board_prep`, `quarterly_plan`, `annual_plan` — planning and governance deliverables.\n- `performance_review`, `comp_refresh`, `org_design` — people and org artifacts.\n- `crisis_comms`, `churn_deep_dive`, `competitive_teardown` — situational analyses.\n- `department_check_in` — runs on department cadence; its `goal_status` step returns structured verdicts persisted back to `department_goals.status`.\n- `offer_approval`, `new_hire_onboarding` — the talent vertical's hire-loop pair: offer package + sign-off gate, and the placed-candidate → roster-Person handoff with 30/60/90 check-ins (see [Talent](#talent)); `new_hire_onboarding` creates the roster Person that the staff-onboarding subsystem's plan delivery and ramp drip need — see [Staff Onboarding](#staff_onboarding).\n\n### Change-aware principal briefs\n\n`morning_brief` and `end_of_day_digest` are the two recurring briefs the scheduler DMs to the principal. Both are now a *delta*, not a re-list: the window is \"since the last **delivered** brief\" (`briefing.brief_state.since_for`; 24 h on a cold store, clamped to 7 days), activity comes from `_build_activity(limit, since=…)`, proposals (action category only) split into *new since last brief* — enumerated, with each item's why-now and next move — versus a one-line carried-over count, and a *handled overnight* block lists what the Executive's alert review did on its own (`brief_state.handled_since`). Section order: top call → what changed → handled overnight → needs you (new only) → waiting on → at risk. A date-free fingerprint of the inputs is compared to the last delivered one; if unchanged the artifact is the one-liner \"Nothing new since yesterday's brief — N items still waiting on you.\" and no model call is made (`PRINCIPAL_BRIEF_SUPPRESS_UNCHANGED`; `force_full=true` on a manual run bypasses it). The workflow yields a `result` event with the fingerprint; only the scheduler records it, after a successful delivery, in `briefing_narrative` under scope `brief:<kind>` — so manual runs never advance the window.\n\n`executive_reflection` now carries memory: yesterday's standup (the previous completed run's artifact) is rendered into the context and the prompt forbids re-acting on anything listed there unless it changed; open alerts render with their id, review verdict and recommended move. Reflection never closes alerts — the alert review does, with evidence.\n\n### Wait-for-human pause\n\n`wait_for_human` (`openexecutive/workflows/wait_for_human.py`) is a first-class step primitive that pauses a run, writes an `awaiting_human` row into `scheduled_actions`, and returns control to the user. `propose_only` departments route scheduled actions through this approval path rather than executing immediately. When the human replies on any channel, the `inbound_resolver` workflow matches the response to the paused run via its resume token, and `resumer.apply_resolution` records the decision, marks the run `resolved`, and writes an audit row. A timeout applies the step's `on_timeout` policy (escalate / auto_proceed / fail). The captured outcome surfaces on the Today dashboard.\n\nFull generator resume is **not yet implemented**: a paused run records the human's decision and stops — it does not re-enter the generator to run its remaining steps. `offer_approval` is the first *built-in* workflow to yield the gate (previously only dynamic workflows did), and it is designed around that gap: it yields its `result` and `artifact` events *before* the gate and persists the offer package onto the Offer row, so the gate's only job is to record the HIRING_SIGNOFF decision — the actual `pending_approval → extended` transition is the explicit `extend_offer` tool/route, which consults the recorded resolution.\n\n### Launching from chat\n\nWorkflows are not only reachable from the `/jobs` UI — the Executive can list and run any of them mid-conversation. `openexecutive.orchestrator.workflow_run_tools` wires two tools into the main chat loop: `list_workflows` (the launchable catalog, with each workflow's input fields) and `run_workflow` (runs one to completion and returns its Markdown artifact, using the same engine as `POST /workflows/{name}/runs`). `run_workflow` resolves both built-ins and custom workflows via `get_workflow`, validates `inputs` against the workflow's input model, persists the run (`create_run` → `complete_run` / `fail_run`), and on an approval-gate step checkpoints the run as `awaiting_human` exactly as the HTTP route does — it never hangs waiting on a human. `executive_research` is excluded (it has the dedicated `run_executive_research` tool); the principal-targeting recurring workflows (`morning_brief`, `end_of_day_digest`, `executive_reflection`) stay launchable but the tool description flags that they dispatch real messages. Talent workflows remain better served by `start_talent_workflow`. A successful run surfaces an `action_taken` chip linking to `/jobs/runs/{run_id}`.\n\n### Dynamic (user-created) workflows\n\nUsers create reusable workflows on the fly — from the executive chat or a builder UI on `/jobs` — without shipping code. A dynamic workflow is a stored JSON definition (the `dynamic_workflows` table) interpreted at runtime by one generic `DynamicWorkflow` engine (`openexecutive/workflows/dynamic.py`) that implements the same `Workflow` ABC as the built-ins, so the run path, SSE streaming, run persistence, and `/jobs/[name]` form rendering are unchanged. `get_workflow` / `list_workflows` fall through to the dynamic store after the static registry (built-ins win on a name collision).\n\nA definition declares free-text input fields and an ordered step list of three kinds: **specialist** (consult a specialist with a goal prompt, optionally grounded by RAG), **approval_gate** (a `wait_for_human` pause), and a terminal **synthesis** step that assembles the artifact. `validate_definition` enforces the structural rules: exactly one terminal synthesis step, valid specialists, `{placeholder}` tokens that reference declared input fields, rostered approval/cadence people, and a parseable cadence.\n\nAuthoring from chat uses a **draft → confirm** handshake: the Executive calls `draft_workflow` (validate; return a `confirm_token` plus a plan summary), shows the user the plan, then calls `save_workflow` with the same definition and token — a token mismatch is rejected, so the saved workflow is exactly what the user approved. The builder UI drives the `/workflows/custom` CRUD endpoints directly. An optional cadence (`daily@` / `weekly@` / `quarterly@`) re-uses the scheduler via the `dynamic_workflow` action kind, which runs the workflow on schedule and DMs the artifact to a rostered recipient. Limitation: a gate followed by further steps pauses at `awaiting_human` and does not auto-continue (generator resume is deferred upstream), so gates belong immediately before synthesis.\n\nCompleted artifacts are discoverable in the unified Artifacts section (`/artifacts`) alongside their run-detail page at `/jobs/runs/{run_id}`.\n\n## Data-driven retrospectives\n\n`engagement_value_report` introduces a new workflow pattern: instead of the user typing the substance into a form (the `investor_update` / `mbr` shape), the workflow **reads its substance from the database**. A deterministic gatherer (`clients/engagement_activity.py`) pulls the period's decisions, initiatives, advisory consultations, delivered workflow artifacts (excluding prior value reports), follow-through counts, and alerts handled — from the live DB for the active client, or a parked client slot's `state.db` opened read-only. A single board-comms call narrates those facts (the prompt forbids inventing anything not in them; an empty period skips the LLM entirely), and the artifact's lists are assembled deterministically. Built for renewal conversations — the engagement record is the evidence.","mermaid": "flowchart TD\n Input[\"Structured input\"]\n Steps[\"Ordered named steps\"]\n Wait[\"wait_for_human pause\"]\n Sched[\"scheduled_actions<br/>(awaiting_human)\"]\n Resolver[\"inbound_resolver<br/>+ resumer\"]\n Artifact[\"Markdown artifact<br/>(workflow_runs.artifact)\"]\n Today[\"Today / Artifacts\"]\n Input --> Steps\n Steps --> Wait\n Wait --> Sched\n Sched -- \"human reply\" --> Resolver\n Resolver -- \"resolved\" --> Steps\n Steps -- \"complete_run\" --> Artifact\n Artifact --> Today\n class Input entry\n class Steps compute\n class Wait compute\n class Sched storage\n class Resolver compute\n class Artifact storage\n class Today external",- "generated_at": "2026-06-10T00:00:00+00:00"-}\ No newline at end of file+ "generated_at": "2026-09-11T19:18:55+00:00"+}diff --git a/packages/core/openexecutive/briefing/brief_state.py b/packages/core/openexecutive/briefing/brief_state.pynew file mode 100644index 00000000..1cfcf956--- /dev/null+++ b/packages/core/openexecutive/briefing/brief_state.py@@ -0,0 +1,201 @@+"""Delivered-brief state: what the last morning/EoD brief covered.++The principal briefs used to re-list the whole unread queue every day and+call the "activity" block "since last brief" when it was really just the+latest N rows. This module gives each recurring brief kind a memory of what+was last *delivered* so the workflow can:++- bound "what changed" to the window since the previous delivery (`since`),+- split proposals into NEW (created inside that window) vs CARRIED OVER,+- list what the Executive's alert review handled inside the window, and+- skip the model call entirely when the fingerprint of the inputs is+ unchanged, sending a one-line "nothing new" instead.++Storage reuses the ``briefing_narrative`` table (``briefing/narrative_cache``)+under a ``brief:<kind>`` scope: ``input_hash`` holds the fingerprint,+``narrative_text`` the delivered artifact and ``generated_at`` the delivery+time. Scopes are only ever read by exact key, so the namespace cannot+collide with the per-viewer header cache. Only the scheduler records a+delivery (after a successful send), so manual workflow runs never advance+the window.+"""+from __future__ import annotations++import hashlib+import json+import logging+from datetime import UTC, datetime, timedelta+from typing import Any++from openexecutive.alerts.lifecycle import parse_aware+from openexecutive.briefing import narrative_cache++logger = logging.getLogger(__name__)++SCOPE_PREFIX = "brief:"+DEFAULT_WINDOW = timedelta(hours=24)++SUPPRESSED_TEMPLATE = (+ "Nothing new since yesterday's brief — {n} item{s} still waiting on you."+)++# Audit event types the alert review job emits for autonomous moves. The+# brief's "handled overnight" block is built from these (see handled_since).+REVIEW_EVENT_TYPES: tuple[str, ...] = (+ "alert_review_closed",+ "alert_review_routed",+ "alert_review_nudged",+ "alert_review_escalated",+ "alert_review_drafted",+ "alert_review_merged",+ "alert_review_suggested_workflow",+ "alert_review_changed",+)+++def scope_for(kind: str) -> str:+ return f"{SCOPE_PREFIX}{kind}"+++def last_delivered(kind: str) -> narrative_cache.BriefingNarrative | None:+ """The last delivered brief of this kind, or None on a cold store."""+ try:+ return narrative_cache.get(scope_for(kind))+ except Exception:+ logger.exception("brief_state: read failed for %s", kind)+ return None+++def since_for(kind: str, now: datetime | None = None) -> datetime:+ """Start of the "what changed" window: the previous delivery, else 24 h ago.++ Bounded to at most 7 days back so a brief that stopped firing for a while+ does not replay a month of history when it resumes.+ """+ now = now or datetime.now(UTC)+ prev = last_delivered(kind)+ delivered_at = parse_aware(prev.generated_at) if prev else None+ if delivered_at is None:+ return now - DEFAULT_WINDOW+ # Never in the future (clock skew / a scheduler `now` earlier than the+ # recorded delivery would otherwise empty the window and suppress).+ return min(now, max(delivered_at, now - timedelta(days=7)))+++def record_delivered(kind: str, fingerprint: str, text: str) -> None:+ """Persist the delivered brief so the next run can diff against it."""+ try:+ narrative_cache.put(narrative_cache.BriefingNarrative(+ scope=scope_for(kind),+ input_hash=fingerprint,+ narrative_text=text,+ generated_at=narrative_cache.utc_now_iso(),+ ))+ except Exception:+ logger.exception("brief_state: write failed for %s", kind)+++def split_proposals(+ proposals: list[dict[str, Any]], since: datetime | None+) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]:+ """``(new, carried)``: proposals created at/after ``since`` vs earlier.++ With ``since`` None everything is "new" (the legacy single-list view).+ """+ if since is None:+ return list(proposals), []+ new: list[dict[str, Any]] = []+ carried: list[dict[str, Any]] = []+ for p in proposals:+ created = parse_aware(p.get("created_at"))+ (new if created is None or created >= since else carried).append(p)+ return new, carried+++def handled_since(since: datetime, limit: int = 20) -> list[dict[str, Any]]:+ """Autonomous alert-review moves recorded in the audit log since ``since``.++ Each item: ``{"kind": event_type sans prefix, "summary": str, "at": iso,+ "alert_id": int | None}``, newest first. Empty when the audit store is unavailable.+ """+ try:+ from openexecutive.audit.logger import get_audit_logger++ logger_ = get_audit_logger()+ out: list[dict[str, Any]] = []+ for event_type in REVIEW_EVENT_TYPES:+ for ev in logger_.query(event_type=event_type, since=since.isoformat(), limit=limit):+ details = ev.details if isinstance(ev.details, dict) else {}+ out.append({+ "kind": event_type.removeprefix("alert_review_"),+ "summary": ev.summary,+ "at": ev.ts,+ "alert_id": details.get("alert_id"),+ })+ out.sort(key=lambda e: e["at"], reverse=True)+ return out[:limit]+ except Exception:+ logger.debug("brief_state: handled_since unavailable", exc_info=True)+ return []+++def build_brief_fingerprint(+ *,+ today_data: dict[str, Any],+ activity: list[dict[str, Any]],+ handled: list[dict[str, Any]],+ since: datetime | None,+) -> str:+ """Stable hash of everything the brief would say. Deliberately free of+ dates and timestamps so an unchanged day yields the same fingerprint+ tomorrow (activity is keyed by kind + summary, never by its stamp)."""+ new, carried = split_proposals(today_data.get("proposals", []), since)+ payload = {+ "new": sorted(int(p.get("alert_id", 0)) for p in new),+ "carried": sorted(int(p.get("alert_id", 0)) for p in carried),+ "likely_stale": sum(1 for p in carried if p.get("review_verdict") == "likely_stale"),+ "activity": sorted(+ (str(a.get("kind", "")), str(a.get("summary", ""))[:80]) for a in activity+ ),+ "handled": sorted((h["kind"], h["summary"][:80]) for h in handled),+ "depts": sorted(+ (d.get("slug", ""), d.get("at_risk_count", 0), d.get("off_track_count", 0))+ for d in today_data.get("departments", [])+ if d.get("at_risk_count", 0) or d.get("off_track_count", 0)+ ),+ "awaiting": sorted(+ int(p.get("id", 0)) for p in today_data.get("people", []) if p.get("awaiting_count", 0)+ ),+ }+ blob = json.dumps(payload, sort_keys=True, default=str)+ return hashlib.sha256(blob.encode("utf-8")).hexdigest()+++def suppress_unchanged_enabled() -> bool:+ """`PRINCIPAL_BRIEF_SUPPRESS_UNCHANGED`, defaulting to on when settings+ cannot be built (bare test DB with no env)."""+ try:+ from openexecutive.config import get_settings++ return bool(get_settings().principal_brief_suppress_unchanged)+ except Exception:+ return True+++def suppressed_line(n_waiting: int) -> str:+ return SUPPRESSED_TEMPLATE.format(n=n_waiting, s="" if n_waiting == 1 else "s")+++__all__ = [+ "REVIEW_EVENT_TYPES",+ "SUPPRESSED_TEMPLATE",+ "build_brief_fingerprint",+ "handled_since",+ "last_delivered",+ "record_delivered",+ "scope_for",+ "since_for",+ "split_proposals",+ "suppress_unchanged_enabled",+ "suppressed_line",+]diff --git a/packages/core/openexecutive/briefing/context.py b/packages/core/openexecutive/briefing/context.pyindex 8aa12b6b..32b48590 100644--- a/packages/core/openexecutive/briefing/context.py+++ b/packages/core/openexecutive/briefing/context.py@@ -9,7 +9,8 @@ Executive had no record of it and couldn't discuss it.This renders the current open alerts into a compact ``<briefing>`` block that thechat route injects into the **user turn** (never a cached system block, so promptcaching is unaffected). It mirrors how ``/today`` builds proposals-(`api/routes/today.py`): company-wide, ``status="unread"``.+(`api/routes/today.py`): company-wide, live ``unread`` rows (inside TTL,+not snoozed — see ``alerts.lifecycle.list_live_alerts``)."""from __future__ import annotations@@ -44,11 +45,11 @@ def format_open_alerts_for_prompt(db_path: Path | None = None, limit: int = _MAXsite. Never raises: any failure logs and returns ``""`` so a chat turn isnever blocked by an alerts-store hiccup."""- from openexecutive.alerts.store import list_alerts+ from openexecutive.alerts.lifecycle import list_live_alertsfrom openexecutive.briefing.ranking import score_and_categorizetry:- alerts = list_alerts(status="unread", limit=limit, db_path=db_path)+ alerts = list_live_alerts(limit=limit, db_path=db_path)except Exception:logger.exception("briefing_context.list_alerts_failed")return ""@@ -66,6 +67,15 @@ def format_open_alerts_for_prompt(db_path: Path | None = None, limit: int = _MAXline += f" | suggested: {alert.suggested_action.strip()}"if alert.topic_tags:line += f" | tags: {', '.join(alert.topic_tags)}"+ if alert.review_verdict:+ review = f" | review: {alert.review_verdict}"+ if alert.review_note:+ review += f" — {alert.review_note.strip()}"+ if alert.recommended_move and alert.recommended_move != "none":+ review += f" | next move: {alert.recommended_move}"+ line += review+ if alert.occurrence_count > 1:+ line += f" | seen x{alert.occurrence_count}"lines.append(line)if not lines:diff --git a/packages/core/openexecutive/briefing/narrative.py b/packages/core/openexecutive/briefing/narrative.pyindex 065fb8c5..b645dcf7 100644--- a/packages/core/openexecutive/briefing/narrative.py+++ b/packages/core/openexecutive/briefing/narrative.py@@ -16,8 +16,11 @@ Executive's voice while letting each use the right structure.from __future__ import annotationsimport logging+from datetime import UTC, datetimefrom typing import Any+from openexecutive.alerts.lifecycle import parse_aware+logger = logging.getLogger(__name__)# Cap how many open searches the narrative lists before it stops enumerating —@@ -33,17 +36,26 @@ STANDALONE_BRIEF_SYSTEM = ("You are the user's Executive. You are writing the daily brief — a short ""message the principal reads on its own (delivered as a DM; there is no ""other list beside it, so this message must stand alone). Write "- "peer-to-peer, not as a corporate broadcast.\n\n"+ "peer-to-peer, not as a corporate broadcast. The context is a DELTA since "+ "the last brief you sent, so never re-tell yesterday's news.\n\n""Output ≤200 words of Markdown with these sections, in this order, each ""only included when there is real content for it:\n"- " 1. **What changed** — anything you acted on, anyone you DM'd, any goal "- "that flipped. One bullet per item, terse.\n"- " 2. **Needs you** — proposals or decisions waiting on the principal. "- "Lead with the most time-sensitive.\n"- " 3. **At risk** — departments / goals trending off-track the principal "- "hasn't already been briefed on.\n"- " 4. **Top call** — the single decision you'd recommend the principal "- "focus on, with your suggested move.\n\n"+ " 1. **Top call** — the single decision you'd recommend the principal "+ "focus on today, with your suggested move. One or two sentences.\n"+ " 2. **What changed** — anything NEW since the last brief: a goal that "+ "flipped, a reply that landed, an external signal that moved. One bullet "+ "per item, terse.\n"+ " 3. **Handled overnight** — what you already did on your own from the "+ "HANDLED block (routed, nudged, drafted, closed with evidence). One "+ "bullet each, past tense, naming the person or item.\n"+ " 4. **Needs you** — ONLY the items under NEW SINCE LAST BRIEF, most "+ "time-sensitive first, each with its why-now when given. If the context "+ "has a CARRIED OVER line, add exactly one sentence after the list "+ "('N older items still open — see /today'); never re-list carried items.\n"+ " 5. **Waiting on** — people whose reply you're still waiting for, with "+ "how long. One line each.\n"+ " 6. **At risk** — departments / goals trending off-track the principal "+ "hasn't already been briefed on.\n\n""Skip headers entirely for sections with no content. If everything is ""genuinely quiet, output one line: 'Quiet right now — nothing pressing.'")@@ -115,14 +127,28 @@ def _viewer_system_prompt(name: str, role: str) -> str:)+def _age_days(iso: str | None, now: datetime) -> int:+ dt = parse_aware(iso)+ return max(0, (now - dt).days) if dt is not None else 0++def render_briefing_context(*,period_label: str,today_data: dict[str, Any],activity: list[dict[str, Any]],+ since: datetime | None = None,+ handled: list[dict[str, Any]] | None = None,) -> str:- """Pack the structured /today + activity inputs into a single user-turn block."""+ """Pack the structured /today + activity inputs into a single user-turn block.++ With ``since`` (the standalone briefs) proposals are split into NEW SINCE+ LAST BRIEF vs a one-line CARRIED OVER count, and ``handled`` (autonomous+ alert-review moves in the window) renders as its own block. With both+ unset the output is byte-identical to the legacy /today header context.+ """parts: list[str] = [f"PERIOD: {period_label}\n"]+ now = datetime.now(UTC)depts = today_data.get("departments", [])at_risk = [d for d in depts if d.get("at_risk_count", 0) or d.get("off_track_count", 0)]@@ -137,11 +163,40 @@ def render_briefing_context(parts.append("")proposals = today_data.get("proposals", [])- if proposals:- parts.append("PROPOSALS AWAITING DECISION:")- for p in proposals[:10]:- parts.append(f"- {p.get('headline', '')[:160]}")- parts.append("")+ if since is None:+ if proposals:+ parts.append("PROPOSALS AWAITING DECISION:")+ for p in proposals[:10]:+ parts.append(f"- {p.get('headline', '')[:160]}")+ parts.append("")+ else:+ from openexecutive.briefing.brief_state import split_proposals++ new_items, carried = split_proposals(proposals, since)+ if new_items:+ parts.append("NEEDS YOU — NEW SINCE LAST BRIEF:")+ for p in new_items[:10]:+ line = f"- {p.get('headline', '')[:160]}"+ if p.get("why_now"):+ line += f" (why now: {str(p['why_now'])[:80]})"+ move = p.get("recommended_move")+ if move and move != "none":+ line += f" [next move: {move}]"+ parts.append(line)+ parts.append("")+ if carried:+ oldest = max(_age_days(p.get("created_at"), now) for p in carried)+ stale = sum(1 for p in carried if p.get("review_verdict") == "likely_stale")+ line = f"CARRIED OVER: {len(carried)} older item(s) still open (oldest {oldest}d"+ if stale:+ line += f", {stale} flagged likely stale"+ parts.append(line + ") — see /today")+ parts.append("")+ if handled:+ parts.append("HANDLED OVERNIGHT BY THE EXECUTIVE (already done — report, don't ask):")+ for h in handled[:15]:+ parts.append(f"- [{str(h.get('at', ''))[:10]}] {h.get('kind', '')}: {str(h.get('summary', ''))[:140]}")+ parts.append("")people = today_data.get("people", [])awaiting = [p for p in people if p.get("awaiting_count", 0)]@@ -198,6 +253,8 @@ async def synthesize_briefing_narrative(period_label: str,viewer: dict[str, str] | None = None,standalone: bool = False,+ since: datetime | None = None,+ handled: list[dict[str, Any]] | None = None,) -> str:"""Synthesize the briefing narrative. Returns Markdown, or "" when empty.@@ -224,7 +281,8 @@ async def synthesize_briefing_narrative(else:system = BRIEFING_NARRATIVE_SYSTEMuser_content = render_briefing_context(- period_label=period_label, today_data=today_data, activity=activity+ period_label=period_label, today_data=today_data, activity=activity,+ since=since, handled=handled,)model = get_fast_model()response = await get_provider(model).messages_create(diff --git a/packages/core/openexecutive/briefing/ranking.py b/packages/core/openexecutive/briefing/ranking.pyindex af8ce751..d84b368b 100644--- a/packages/core/openexecutive/briefing/ranking.py+++ b/packages/core/openexecutive/briefing/ranking.py@@ -17,8 +17,11 @@ call per alert inside ``_build_today``."""from __future__ import annotations+from datetime import UTC, datetime, timedeltafrom typing import Any+from openexecutive.alerts.lifecycle import parse_aware+# Severity → base weight. Mirrors AlertSeverity ("low"/"medium"/"high"/# "urgent"); unknown strings fall back to the medium band so a new# severity never silently sinks to the bottom.@@ -127,19 +130,62 @@ def surfaced_reason(return _SURFACED_BY_SEVERITY.get(severity)+# Review-driven adjustments (alerts/review.py). An item the Executive judged+# "likely stale" sinks below live work but is never hidden; an item with a+# deadline inside a day floats up; a watch the principal keeps dismissing+# (low trust_score) is discounted so it stops crowding out signal.+_LIKELY_STALE_PENALTY = 30+_DUE_SOON_BONUS = 20+_DUE_SOON_WINDOW = timedelta(hours=24)+_LOW_TRUST_MAX_PENALTY = 10++def score(*,severity: str,routed_to_person_id: int | None,+ review_verdict: str = "",+ due_at: str | None = None,+ trust_score: float | None = None,+ now: datetime | None = None,) -> int:"""Attention sort key for the ``action`` queue (higher leads)."""base = _SEVERITY_WEIGHT.get(severity, _DEFAULT_SEVERITY_WEIGHT)if routed_to_person_id is not None:base += _ROUTED_BONUS+ if review_verdict == "likely_stale":+ base -= _LIKELY_STALE_PENALTY+ if due_at:+ due = parse_aware(due_at)+ if due is not None and due - (now or datetime.now(UTC)) <= _DUE_SOON_WINDOW:+ base += _DUE_SOON_BONUS+ if trust_score is not None:+ clamped = min(1.0, max(0.0, float(trust_score)))+ base -= int(round(_LOW_TRUST_MAX_PENALTY * (1.0 - clamped)))return base-def score_and_categorize(alert: Any) -> tuple[int, str, str | None]:+def watch_slug_from_tags(topic_tags: list[str]) -> str | None:+ """The watchlist slug carried by an ``external:<slug>`` tag, if any.++ Skips the adapter-kind tag (``external:stock``) so ``external:stock-aapl``+ resolves to ``stock-aapl``.+ """+ for tag in topic_tags:+ if not tag.startswith("external:"):+ continue+ slug = tag[len("external:"):]+ if slug and slug not in _EXTERNAL_SOURCES:+ return slug+ return None+++def score_and_categorize(+ alert: Any,+ *,+ trust_by_slug: dict[str, float] | None = None,+ now: datetime | None = None,+) -> tuple[int, str, str | None]:"""Convenience wrapper over an ``Alert``-shaped object.Reads ``source``, ``severity``, ``routed_to_person_id`` and@@ -158,8 +204,21 @@ def score_and_categorize(alert: Any) -> tuple[int, str, str | None]:routed = _get("routed_to_person_id", None)topic_tags = list(_get("topic_tags", []) or [])+ trust: float | None = None+ if trust_by_slug:+ slug = watch_slug_from_tags(topic_tags)+ if slug is not None:+ trust = trust_by_slug.get(slug)+return (- score(severity=severity, routed_to_person_id=routed),+ score(+ severity=severity,+ routed_to_person_id=routed,+ review_verdict=str(_get("review_verdict", "") or ""),+ due_at=_get("due_at", None),+ trust_score=trust,+ now=now,+ ),categorize(source=source,severity=severity,@@ -175,4 +234,10 @@ def score_and_categorize(alert: Any) -> tuple[int, str, str | None]:)-__all__ = ["categorize", "score", "score_and_categorize", "surfaced_reason"]+__all__ = [+ "categorize",+ "score",+ "score_and_categorize",+ "surfaced_reason",+ "watch_slug_from_tags",+]diff --git a/packages/core/openexecutive/config.py b/packages/core/openexecutive/config.pyindex e15e2540..5a826994 100644--- a/packages/core/openexecutive/config.py+++ b/packages/core/openexecutive/config.py@@ -602,6 +602,37 @@ class Settings(BaseSettings):# 03:30), read by the scheduler like the principal-brief times.client_rotation_enabled: bool = Field(False, alias="CLIENT_ROTATION_ENABLED")+ # Alert lifecycle (alerts/lifecycle.py). An `unread` alert older than its+ # category TTL is expired by the scheduler sweep (and hidden by the read+ # side before the sweep runs). Monitoring = unrouted low/medium watchlist+ # signals; action = everything a human should look at. 0 disables expiry+ # for that category. Artifacts and decision-backed alerts never expire.+ alert_ttl_days_monitoring: int = Field(3, alias="ALERT_TTL_DAYS_MONITORING")+ alert_ttl_days_action: int = Field(14, alias="ALERT_TTL_DAYS_ACTION")++ # Executive alert review (alerts/review.py) — a scheduler heartbeat that+ # re-examines open alerts with evidence and lets the Executive route,+ # nudge, escalate, draft, merge or resolve them within authority. Runs+ # every `interval` hours and once right before the morning brief. Only+ # alerts at least `min_age` hours old and not reviewed within the interval+ # are sent to the model; `max_per_scan` bounds the model calls and+ # `max_moves_per_scan` bounds outbound side effects (DMs, drafts) per pass+ # — 0 keeps the review but makes it annotate-only.+ alert_review_enabled: bool = Field(True, alias="ALERT_REVIEW_ENABLED")+ alert_review_interval_hours: int = Field(6, alias="ALERT_REVIEW_INTERVAL_HOURS")+ alert_review_min_age_hours: int = Field(2, alias="ALERT_REVIEW_MIN_AGE_HOURS")+ alert_review_max_per_scan: int = Field(25, alias="ALERT_REVIEW_MAX_PER_SCAN")+ alert_review_batch_size: int = Field(8, alias="ALERT_REVIEW_BATCH_SIZE")+ alert_review_max_moves_per_scan: int = Field(+ 10, alias="ALERT_REVIEW_MAX_MOVES_PER_SCAN"+ )++ # Principal briefs: when nothing changed since the last delivered brief,+ # send a one-line "nothing new" instead of re-synthesising the same list.+ principal_brief_suppress_unchanged: bool = Field(+ True, alias="PRINCIPAL_BRIEF_SUPPRESS_UNCHANGED"+ )+# Proactive nudge engine — heartbeat that scans for stalled workflows,# stale commitments, and idle initiatives and emits per-channel nudges# routed via Person.preferred_channel + availability windows.@@ -617,6 +648,9 @@ class Settings(BaseSettings):nudge_max_defer_days: int = Field(3, alias="NUDGE_MAX_DEFER_DAYS")nudge_max_per_scan: int = Field(10, alias="NUDGE_MAX_PER_SCAN")nudge_max_per_person_per_scan: int = Field(2, alias="NUDGE_MAX_PER_PERSON_PER_SCAN")+ # Stop re-chasing the same item forever: after this many delivered nudges+ # for one scope_key, the scan stops emitting for it. 0 disables the cap.+ nudge_max_per_scope: int = Field(3, alias="NUDGE_MAX_PER_SCOPE")# External-condition monitoring — heartbeat that polls source adapters# (vendor_status in PR-A; RSS + stock in PR-B) and emits external_signals@@ -709,8 +743,10 @@ class Settings(BaseSettings):# purely-external developments (a competitor move, a regulation change)# that the internal-state fingerprint can't see. Set <= 0 to disable the# floor and rely solely on skip-if-unchanged.+ # Weekly by default: a daily forced re-run re-derived the same findings+ # from unchanged state and re-filed them as fresh alerts every morning.watchlist_research_max_staleness_hours: int = Field(- 24, alias="WATCHLIST_RESEARCH_MAX_STALENESS_HOURS"+ 168, alias="WATCHLIST_RESEARCH_MAX_STALENESS_HOURS")# Notion → isolated wiki-collection sync. OFF by default. When on, adiff --git a/packages/core/openexecutive/departments/authority.py b/packages/core/openexecutive/departments/authority.pyindex cf97e906..46c1ab3b 100644--- a/packages/core/openexecutive/departments/authority.py+++ b/packages/core/openexecutive/departments/authority.py@@ -170,17 +170,23 @@ def propose_via_alert(summary: str,body: str,suggested_action: str = "",+ extra_tags: list[str] | None = None,) -> int | None:"""Persist a proposal as an alert routed to a specific Person.Returns the alert id, or None if a duplicate was suppressed.topic_tags carries both department and person identifiers so the UI- and future resolvers can filter/match without parsing the body.+ and future resolvers can filter/match without parsing the body;+ ``extra_tags`` lets a caller carry the originating alert's tags (e.g.+ a ``comp`` / ``legal`` marker) onto the proposal."""from openexecutive.alerts.store import insert_alerttopic_tags = [f"department:{department_slug}", f"person:{person_id}"]+ for tag in extra_tags or []:+ if tag not in topic_tags:+ topic_tags.append(tag)dedup_key = f"proposal:{department_slug}:{person_id}:{summary[:60]}"try:diff --git a/packages/core/openexecutive/memory/episodic.py b/packages/core/openexecutive/memory/episodic.pyindex 6ee3fa1c..b6489f2f 100644--- a/packages/core/openexecutive/memory/episodic.py+++ b/packages/core/openexecutive/memory/episodic.py@@ -983,6 +983,24 @@ def scope_key_in_use(scope_key: str, db_path: Path | None = None) -> bool:return row is not None+def count_nudges_for_scope(scope_key: str, db_path: Path | None = None) -> int:+ """Delivered (``done``) nudges ever emitted for ``scope_key``.++ Backs the per-scope cap in the nudge engine so the same stalled item is+ not chased forever; ``cancelled`` / ``failed`` rows never count.+ """+ resolved = _resolve_db_path(db_path)+ if not resolved.exists():+ return 0+ with _get_conn(resolved) as conn:+ row = conn.execute(+ "SELECT COUNT(*) AS n FROM scheduled_actions "+ "WHERE scope_key = ? AND status = 'done' AND kind = 'proactive_nudge'",+ (scope_key,),+ ).fetchone()+ return int(row["n"]) if row else 0++def recent_nudge_for_scope(scope_key: str,since: datetime,@@ -1338,7 +1356,7 @@ def list_scheduled_actions(# commitments — excluded from the briefing's "In flight" list (and mirrored by# the activity feed's own filter in api/routes/today.py:_build_activity)._INTERNAL_ACTION_CHANNEL = "__internal__"-_INTERNAL_ACTION_KINDS = frozenset({"nudge_scan"})+_INTERNAL_ACTION_KINDS = frozenset({"nudge_scan", "alert_review_scan"})def list_pending_scheduled_actions(diff --git a/packages/core/openexecutive/monitoring/pipeline.py b/packages/core/openexecutive/monitoring/pipeline.pyindex fdec241a..dc270406 100644--- a/packages/core/openexecutive/monitoring/pipeline.py+++ b/packages/core/openexecutive/monitoring/pipeline.py@@ -274,6 +274,10 @@ def _signal_to_alert_event(external_id=signal.dedup_key,subject=summary[:200],body="\n".join(parts)[:4000],+ # One watch = one open alert: repeats of the same watch coalesce+ # into the existing card (alerts.pipeline) while the signal-level+ # dedup_key keeps every observation in external_signals.+ dedup_hint=f"watch:{item.slug}",)diff --git a/packages/core/openexecutive/monitoring/store.py b/packages/core/openexecutive/monitoring/store.pyindex e649b260..f67808b3 100644--- a/packages/core/openexecutive/monitoring/store.py+++ b/packages/core/openexecutive/monitoring/store.py@@ -421,6 +421,41 @@ def mark_fired()+# Trust feedback: the principal's dismiss / approve on a watch-sourced alert+# teaches the watch. Multiplicative decay with a floor so one bad week never+# silences a watch for good; approvals climb back slowly.+_TRUST_DECAY = 0.8+_TRUST_FLOOR = 0.2+_TRUST_RECOVERY = 0.05+++def record_dismissal(slug: str, db_path: Path | None = None) -> bool:+ """A watch-sourced alert was dismissed: bump dismiss_count, decay trust."""+ resolved = _resolve_db_path(db_path)+ if not slug or not resolved.exists():+ return False+ with _get_conn(db_path) as conn:+ cursor = conn.execute(+ "UPDATE watchlist SET dismiss_count = dismiss_count + 1, "+ "trust_score = MAX(?, trust_score * ?) WHERE slug = ?",+ (_TRUST_FLOOR, _TRUST_DECAY, slug),+ )+ return cursor.rowcount > 0+++def record_confirmation(slug: str, db_path: Path | None = None) -> bool:+ """A watch-sourced alert was approved / acted on: recover trust a little."""+ resolved = _resolve_db_path(db_path)+ if not slug or not resolved.exists():+ return False+ with _get_conn(db_path) as conn:+ cursor = conn.execute(+ "UPDATE watchlist SET trust_score = MIN(1.0, trust_score + ?) WHERE slug = ?",+ (_TRUST_RECOVERY, slug),+ )+ return cursor.rowcount > 0++_ALLOWED_UPDATE_COLUMNS: frozenset[str] = frozenset({"enabled","mode",@@ -728,6 +763,8 @@ __all__ = ["DB_PATH","delete_watchlist_item","get_watchlist_item",+ "record_confirmation",+ "record_dismissal","get_watchlist_item_by_slug","initialize_db","insert_signal",diff --git a/packages/core/openexecutive/orchestrator/alert_tools.py b/packages/core/openexecutive/orchestrator/alert_tools.pyindex 9baa2b06..8f6e91ed 100644--- a/packages/core/openexecutive/orchestrator/alert_tools.py+++ b/packages/core/openexecutive/orchestrator/alert_tools.py@@ -75,6 +75,7 @@ async def handle_create_alert(tool_input: dict[str, Any]) -> str:event.channel = f"department:{dept}"if person_id_raw is not None:with contextlib.suppress(TypeError, ValueError):+ event.routed_to_person_id = int(person_id_raw)event.user = f"person:{int(person_id_raw)}"schedule_evaluation(event)logger.info("create_alert: scheduled subject=%r", tool_input["subject"])diff --git a/packages/core/openexecutive/orchestrator/schedule_tools.py b/packages/core/openexecutive/orchestrator/schedule_tools.pyindex 8b0da3e8..3a751869 100644--- a/packages/core/openexecutive/orchestrator/schedule_tools.py+++ b/packages/core/openexecutive/orchestrator/schedule_tools.py@@ -1544,6 +1544,11 @@ async def handle_ack_alert(tool_input: dict[str, Any]) -> str:# Lost the race with another writer / delete — surface it.return json.dumps({"error": f"alert {alert_id} could not be updated"})+ # Same feedback loop as the HTTP ack: a dismiss teaches the watch.+ from openexecutive.alerts.lifecycle import record_ack_feedback++ record_ack_feedback(existing, status)+session = current_session.get()session_id = getattr(session, "session_id", None) if session is not None else Nonefrom openexecutive.audit import log_event as audit_logdiff --git a/packages/core/openexecutive/scheduler/nudge_engine.py b/packages/core/openexecutive/scheduler/nudge_engine.pyindex 400ef856..060f331b 100644--- a/packages/core/openexecutive/scheduler/nudge_engine.py+++ b/packages/core/openexecutive/scheduler/nudge_engine.py@@ -484,6 +484,7 @@ async def run_nudge_scan("""One scan pass: collect → cap → dedup → route → insert. Returns count emitted."""from openexecutive.config import get_settingsfrom openexecutive.memory.episodic import (+ count_nudges_for_scope,insert_scheduled_action,recent_nudge_for_scope,)@@ -537,11 +538,22 @@ async def run_nudge_scan()emitted = 0+ max_per_scope = settings.nudge_max_per_scopefor cand in ranked:if recent_nudge_for_scope(cand.scope_key, now - cand.cooldown, db_path=db_path):continue+ # Per-scope cap: after N delivered chases the item stays visible on+ # /today (its alert / awaiting row) but the engine stops re-pinging.+ if max_per_scope > 0 and count_nudges_for_scope(+ cand.scope_key, db_path=db_path+ ) >= max_per_scope:+ logger.info(+ "nudge_engine: scope %s hit the per-scope cap (%d) — not re-chasing",+ cand.scope_key, max_per_scope,+ )+ continuerouted = _route_candidate(cand, now, max_defer_days=settings.nudge_max_defer_days)diff --git a/packages/core/openexecutive/scheduler/runner.py b/packages/core/openexecutive/scheduler/runner.pyindex 8ae35ef4..f53823ac 100644--- a/packages/core/openexecutive/scheduler/runner.py+++ b/packages/core/openexecutive/scheduler/runner.py@@ -10,7 +10,7 @@ from __future__ import annotationsimport asyncioimport logging-from datetime import UTC, datetime+from datetime import UTC, datetime, timedeltafrom typing import TYPE_CHECKINGif TYPE_CHECKING:@@ -50,6 +50,39 @@ def _company_profile_active() -> bool:return False+# Alert lifecycle sweep (alerts/lifecycle.py). A throttled call inside the+# tick loop rather than a scheduled_actions heartbeat: pure DB hygiene with+# no model call, so it needs no bootstrap / chain / kind branch, and it must+# not be held by the company-profile gate (an old backlog should expire even+# before onboarding completes).+_ALERT_SWEEP_INTERVAL = timedelta(minutes=15)+_last_alert_sweep_at: datetime | None = None+++def _maybe_sweep_alerts(now: datetime) -> int:+ """Run the expiry sweep if the interval has elapsed. Returns rows expired.++ Never raises — a sweep failure is logged and the tick continues.+ """+ global _last_alert_sweep_at+ if (+ _last_alert_sweep_at is not None+ and now - _last_alert_sweep_at < _ALERT_SWEEP_INTERVAL+ ):+ return 0+ _last_alert_sweep_at = now+ try:+ from openexecutive.alerts.lifecycle import expire_stale_alerts++ expired = expire_stale_alerts(now)+ if expired:+ logger.info("scheduler: expired %d stale alert(s)", expired)+ return expired+ except Exception:+ logger.exception("scheduler: alert expiry sweep failed")+ return 0++async def run_scheduler(gateway: MCPGateway | None = None,*,@@ -93,6 +126,20 @@ async def run_scheduler(except Exception:logger.exception("scheduler: rotation reconcile/seed failed")+ # Expire past-TTL alerts once at boot (a redeploy cleans an old backlog+ # immediately) and then every _ALERT_SWEEP_INTERVAL from the tick loop.+ _maybe_sweep_alerts(datetime.now(UTC))++ # Executive alert review heartbeat — idempotent bootstrap, like nudge_scan.+ try:+ from openexecutive.alerts.review import bootstrap_alert_review_scan+ from openexecutive.config import get_settings as _review_settings++ if _review_settings().alert_review_enabled:+ bootstrap_alert_review_scan()+ except Exception:+ logger.exception("scheduler: alert_review bootstrap failed")+logger.info("scheduler started (poll_interval=%ds)", poll_interval_seconds)@@ -101,6 +148,9 @@ async def run_scheduler(while True:try:now = datetime.now(UTC)+ # Alert expiry is pure DB hygiene and must not wait for+ # onboarding or a client rotation — it runs before both gates.+ _maybe_sweep_alerts(now)if not _company_profile_active():# No active company profile — don't claim or run anything.# Due rows stay 'pending' and fire once onboarding completes.@@ -397,6 +447,36 @@ async def _execute_action()return+ # ------------------------------------------------------------------+ # Executive alert review heartbeat (alerts/review.py): re-examine open+ # alerts with evidence and route / escalate / draft / merge / resolve+ # within authority. Same crash-resilient shape as nudge_scan.+ # ------------------------------------------------------------------+ if action.kind == "alert_review_scan":+ from openexecutive.alerts.review import (+ enqueue_next_alert_review_scan,+ run_alert_review,+ )+ try:+ summary = await run_alert_review(reason="heartbeat", now=now)+ logger.info("scheduler: alert_review_scan %s", summary.as_dict())+ except Exception:+ logger.exception("scheduler: alert_review_scan (action %d) crashed", action.id)+ try:+ mark_action_done(action.id)+ except Exception:+ logger.exception(+ "scheduler: alert_review_scan (action %d) — mark_done failed", action.id+ )+ try:+ enqueue_next_alert_review_scan(after=datetime.now(UTC))+ except Exception:+ logger.exception(+ "scheduler: failed to chain next alert_review_scan heartbeat — "+ "review will stall until next bootstrap"+ )+ return+# ------------------------------------------------------------------# Overnight client rotation (multi-client practice mode). The# rotation module owns the safety rails (claim pause via the marker,@@ -1362,6 +1442,16 @@ async def _run_principal_brief(action: ScheduledAction, now: datetime) -> None:wf_inputs = input_cls()run_id = str(uuid.uuid4())+ # Fresh relevance pass right before the morning brief so what it lists+ # reflects overnight evidence; a review failure never blocks the brief.+ if kind == "principal_brief_morning":+ try:+ from openexecutive.alerts.review import run_alert_review++ await run_alert_review(reason="pre_brief", now=now)+ except Exception:+ logger.exception("scheduler: pre-brief alert review failed")+try:create_run(run_id, workflow_name, f"{workflow.title} {now.strftime('%Y-%m-%d')}",@@ -1369,9 +1459,14 @@ async def _run_principal_brief(action: ScheduledAction, now: datetime) -> None:)store = ChromaDBStore(persist_directory=get_settings().vector_store_path)artifact = ""+ fingerprint: str | None = None+ suppressed = Falseasync for event in workflow.run(inputs=wf_inputs, store=store):if event.type == "artifact" and event.content:artifact = event.content+ elif event.type == "result" and event.data and event.data.get("brief_fingerprint"):+ fingerprint = str(event.data["brief_fingerprint"])+ suppressed = bool(event.data.get("suppressed"))elif event.type == "error" and event.message:raise RuntimeError(event.message)complete_run(run_id, artifact or "(no artifact)")@@ -1384,8 +1479,17 @@ async def _run_principal_brief(action: ScheduledAction, now: datetime) -> None:"scheduled_action",f"{kind} delivered ({detail})",actor="scheduler",- details={"phase": "delivered", "kind": kind, "channel_detail": detail},+ details={+ "phase": "delivered", "kind": kind, "channel_detail": detail,+ "suppressed": suppressed,+ },)+ # Only a delivered brief advances the "since last brief"+ # window and the unchanged-detection fingerprint.+ if fingerprint:+ from openexecutive.briefing import brief_state++ brief_state.record_delivered(kind, fingerprint, artifact)else:logger.warning("scheduler: %s NOT delivered — %s", kind, detail)audit_log(diff --git a/packages/core/openexecutive/workflows/end_of_day_digest.py b/packages/core/openexecutive/workflows/end_of_day_digest.pyindex 89a20dd1..415ce05a 100644--- a/packages/core/openexecutive/workflows/end_of_day_digest.py+++ b/packages/core/openexecutive/workflows/end_of_day_digest.py@@ -41,6 +41,16 @@ class EndOfDayDigestInput(BaseModel):default="",description="Human-readable period label (e.g. '2026-05-26'). Auto-filled when blank.",)+ force_full: bool = Field(+ default=False,+ description=(+ "Render the full digest even when nothing changed since the last "+ "delivered one (bypasses the one-line 'nothing new' suppression)."+ ),+ )+++BRIEF_KIND = "principal_brief_eod"_EOD_DIGEST_SYSTEM = (@@ -52,8 +62,10 @@ _EOD_DIGEST_SYSTEM = (" 1. **What I did today** — actions you took without prompting ""(DMs sent, follow-ups scheduled, workflows queued, alerts ""flagged). One bullet per item, terse.\n"- " 2. **Still pending** — proposals or workflows waiting on someone "- "(name the person and what's blocking).\n"+ " 2. **Still pending** — ONLY the NEW items listed under NEW SINCE LAST "+ "BRIEF (name the person and what's blocking). If the context has a "+ "CARRIED OVER line, add exactly one sentence ('N older items still "+ "open — see /today'); never re-list carried items.\n"" 3. **At risk tomorrow** — what might trip if no action happens ""overnight or first-thing.\n"" 4. **Sleep on this** — at most ONE open question worth the "@@ -68,6 +80,8 @@ def _render_eod_context(period_label: str,today_data: dict[str, Any],activity: list[dict[str, Any]],+ since: datetime | None = None,+ handled: list[dict[str, Any]] | None = None,) -> str:"""Pack /today + activity into the user-turn block.@@ -86,13 +100,46 @@ def _render_eod_context()parts.append("")- proposals = today_data.get("proposals", [])- if proposals:- parts.append("STILL AWAITING DECISION:")- for p in proposals[:10]:- parts.append(f"- {p.get('headline', '')[:160]}")+ if handled:+ parts.append("ALERTS I HANDLED TODAY (already done — report, don't ask):")+ for h in handled[:15]:+ parts.append(+ f"- [{str(h.get('at', ''))[:10]}] {h.get('kind', '')}: "+ f"{str(h.get('summary', ''))[:140]}"+ )parts.append("")+ proposals = today_data.get("proposals", [])+ if since is None:+ if proposals:+ parts.append("STILL AWAITING DECISION:")+ for p in proposals[:10]:+ parts.append(f"- {p.get('headline', '')[:160]}")+ parts.append("")+ else:+ from openexecutive.alerts.lifecycle import parse_aware+ from openexecutive.briefing.brief_state import split_proposals++ new_items, carried = split_proposals(proposals, since)+ if new_items:+ parts.append("STILL AWAITING DECISION — NEW SINCE LAST BRIEF:")+ for p in new_items[:10]:+ parts.append(f"- {p.get('headline', '')[:160]}")+ parts.append("")+ if carried:+ now = datetime.now(UTC)+ ages = [+ (now - dt).days+ for p in carried+ if (dt := parse_aware(p.get("created_at"))) is not None+ ]+ stale = sum(1 for p in carried if p.get("review_verdict") == "likely_stale")+ line = f"CARRIED OVER: {len(carried)} older item(s) still open (oldest {max(ages) if ages else 0}d"+ if stale:+ line += f", {stale} flagged likely stale"+ parts.append(line + ") — see /today")+ parts.append("")+depts = today_data.get("departments", [])at_risk = [d for d in depts if d.get("at_risk_count", 0) or d.get("off_track_count", 0)]if at_risk:@@ -165,30 +212,72 @@ class EndOfDayDigestWorkflow(Workflow):)from openexecutive.api.routes import today as today_route+ from openexecutive.briefing import brief_state++ # A recap since the last DELIVERED digest (24 h on a cold store,+ # clamped to 7 d) — same window rule as the morning brief.+ since = brief_state.since_for(BRIEF_KIND)try:today_response = today_route._build_today()today_data = today_response.model_dump()+ # Same exclusion as the morning brief: monitoring noise is not+ # "still pending" — it lives in the Monitoring lane on /today.+ today_data["proposals"] = [+ p for p in today_data["proposals"]+ if p.get("category", "action") == "action"+ ]except Exception:logger.exception("eod_digest: /today aggregation failed")today_data = {"departments": [], "people": [], "proposals": []}try:- activity_response = today_route._build_activity(limit=30)+ activity_response = today_route._build_activity(30, since=since)activity = [item.model_dump() for item in activity_response.items]except Exception:logger.exception("eod_digest: /today/activity aggregation failed")activity = []+ handled = brief_state.handled_since(since)+ fingerprint = brief_state.build_brief_fingerprint(+ today_data=today_data, activity=activity, handled=handled, since=since,+ )+ previous = brief_state.last_delivered(BRIEF_KIND)+ suppressed = (+ brief_state.suppress_unchanged_enabled()+ and not inputs.force_full+ and previous is not None+ and previous.input_hash == fingerprint+ )+yield WorkflowEvent(type="step_done",step_id="load_context",summary=(f"activity={len(activity)} "f"proposals={len(today_data['proposals'])} "- f"depts={len(today_data['departments'])}"+ f"depts={len(today_data['departments'])} handled={len(handled)}"),)+ yield WorkflowEvent(+ type="result",+ data={+ "brief_fingerprint": fingerprint,+ "suppressed": suppressed,+ "since": since.isoformat(),+ },+ )++ if suppressed:+ artifact_text = brief_state.suppressed_line(len(today_data["proposals"]))+ yield WorkflowEvent(+ type="step_done",+ step_id="synthesize",+ summary="unchanged since last digest — one-liner, no model call",+ )+ yield WorkflowEvent(type="artifact", content=artifact_text)+ yield WorkflowEvent(type="done")+ returnyield WorkflowEvent(type="step_start",@@ -200,7 +289,8 @@ class EndOfDayDigestWorkflow(Workflow):from openexecutive.providers import get_provideruser_content = _render_eod_context(- period_label=period, today_data=today_data, activity=activity+ period_label=period, today_data=today_data, activity=activity,+ since=since, handled=handled,)try:@@ -234,4 +324,4 @@ class EndOfDayDigestWorkflow(Workflow):return {"period_label": ""}-__all__ = ["EndOfDayDigestWorkflow", "EndOfDayDigestInput"]+__all__ = ["BRIEF_KIND", "EndOfDayDigestWorkflow", "EndOfDayDigestInput"]diff --git a/packages/core/openexecutive/workflows/executive_reflection.py b/packages/core/openexecutive/workflows/executive_reflection.pyindex 30f128d5..0575c9e3 100644--- a/packages/core/openexecutive/workflows/executive_reflection.py+++ b/packages/core/openexecutive/workflows/executive_reflection.py@@ -59,6 +59,9 @@ class ExecutiveReflectionInput(BaseModel):)+# Cap on yesterday's standup rendered into today's prompt.+_PREVIOUS_REFLECTION_CHARS = 1500+# Maximum iterations of the tool-use loop INSIDE the reflection workflow.# The reflection model can call a few tools, see the results, then# emit a final summary. 4 iterations is enough for "DM Sara + schedule@@ -139,6 +142,13 @@ def _build_reflection_system(configured: set[str], has_roster: bool = True) -> s"message rather than three. When you cite an EXTERNAL signal, ""include the source's provenance_url in the message so the ""principal can verify in one click.\n\n"+ "Memory: the block YESTERDAY'S STANDUP lists what you already did "+ "on the previous run. Do NOT re-act on or re-notify anyone about a "+ "signal listed there unless the input shows it changed since — "+ "repeating a DM or a proposal a day later is noise, not diligence. "+ "Open alerts carry the review verdict of your alert-review job "+ "(relevant / changed / likely_stale) and its recommended move; you "+ "never close alerts here (that job does, with evidence).\n\n""Per signal in the input, decide one of:\n"" (a) ACT NOW — call a tool to execute a follow-up, a DM, a ""broadcast, a workflow suggestion, or an alert.\n"@@ -167,10 +177,14 @@ def _render_reflection_context(activity: list[dict[str, Any]],recent_alerts: list[dict[str, Any]],external_signals: list[dict[str, Any]],+ previous_reflection: str | None = None,) -> str:"""Pack /today + activity + open alerts + external signals into asingle user-turn block for the LLM to reason over.+ ``previous_reflection`` is yesterday's standup artifact (capped) so the+ model can see what it already handled and not repeat it.+Research output is NOT a separate block — the executive_researchworkflow routes findings via DMs / alerts / watchlist additionsin real time, so they already show up in `activity`, `recent_alerts`,@@ -225,10 +239,25 @@ def _render_reflection_context(if recent_alerts:parts.append("RECENT OPEN ALERTS:")for a in recent_alerts[:10]:- parts.append(- f"- [{a.get('severity', '?')}] {a.get('headline', '')[:140]} "+ line = (+ f"- alert_id={a.get('alert_id')} [{a.get('severity', '?')}] "+ f"{a.get('headline', '')[:140]} "f"tags={','.join(a.get('topic_tags') or [])}")+ verdict = a.get("review_verdict")+ if verdict:+ line += f" review={verdict}"+ if a.get("review_note"):+ line += f" ({str(a['review_note'])[:100]})"+ move = a.get("recommended_move")+ if move and move != "none":+ line += f" next={move}"+ parts.append(line)+ parts.append("")++ if previous_reflection:+ parts.append("YESTERDAY'S STANDUP (already handled — do not repeat):")+ parts.append(previous_reflection.strip()[:_PREVIOUS_REFLECTION_CHARS])parts.append("")if external_signals:@@ -267,6 +296,25 @@ from openexecutive.workflows._synthesis import ( # noqa: E402)+def _previous_reflection_artifact() -> str | None:+ """Yesterday's standup: the artifact of the last completed reflection run."""+ try:+ from openexecutive.workflows import persistence++ runs = persistence.list_runs(+ workflow_name="executive_reflection", status="done", limit=1+ )+ if not runs:+ return None+ run = persistence.get_run(runs[0]["run_id"])+ artifact = (run or {}).get("artifact") or ""+ artifact = str(artifact).strip()+ return artifact if artifact and artifact != "(no artifact)" else None+ except Exception:+ logger.debug("reflection: previous artifact lookup failed", exc_info=True)+ return None++class ExecutiveReflectionWorkflow(Workflow):name = "executive_reflection"title = "Executive Reflection"@@ -326,7 +374,7 @@ class ExecutiveReflectionWorkflow(Workflow):step_title="Gather org signals",)- from openexecutive.alerts import store as alert_store+ from openexecutive.alerts.lifecycle import list_live_alertsfrom openexecutive.api.routes import today as today_routetry:@@ -345,12 +393,16 @@ class ExecutiveReflectionWorkflow(Workflow):activity = []try:- recent_alerts_objs = alert_store.list_alerts(status="unread", limit=10)+ recent_alerts_objs = list_live_alerts(limit=10)recent_alerts = [{+ "alert_id": a.id,"severity": a.severity,"headline": a.headline,"topic_tags": a.topic_tags,+ "review_verdict": a.review_verdict,+ "review_note": a.review_note,+ "recommended_move": a.recommended_move,}for a in recent_alerts_objs]@@ -430,6 +482,7 @@ class ExecutiveReflectionWorkflow(Workflow):activity=activity,recent_alerts=recent_alerts,external_signals=external_signals,+ previous_reflection=_previous_reflection_artifact(),)roster = _render_team_roster(people)if roster:diff --git a/packages/core/openexecutive/workflows/morning_brief.py b/packages/core/openexecutive/workflows/morning_brief.pyindex c94348b7..35c790d7 100644--- a/packages/core/openexecutive/workflows/morning_brief.py+++ b/packages/core/openexecutive/workflows/morning_brief.py@@ -48,6 +48,16 @@ class MorningBriefInput(BaseModel):default="",description="Human-readable period label (e.g. '2026-05-26'). Auto-filled when blank.",)+ force_full: bool = Field(+ default=False,+ description=(+ "Render the full brief even when nothing changed since the last "+ "delivered one (bypasses the one-line 'nothing new' suppression)."+ ),+ )+++BRIEF_KIND = "principal_brief_morning"# Narrative synthesis (system prompt + context render + LLM call) is shared@@ -102,6 +112,11 @@ class MorningBriefWorkflow(Workflow):)from openexecutive.api.routes import today as today_route+ from openexecutive.briefing import brief_state++ # The window is "since the last brief I actually delivered" (24 h on+ # a cold store), so "what changed" is a real delta, not the latest N.+ since = brief_state.since_for(BRIEF_KIND)try:today_response = today_route._build_today()@@ -118,21 +133,55 @@ class MorningBriefWorkflow(Workflow):today_data = {"departments": [], "people": [], "proposals": []}try:- activity_response = today_route._build_activity(limit=20)+ activity_response = today_route._build_activity(20, since=since)activity = [item.model_dump() for item in activity_response.items]except Exception:logger.exception("morning_brief: /today/activity aggregation failed")activity = []+ handled = brief_state.handled_since(since)+ fingerprint = brief_state.build_brief_fingerprint(+ today_data=today_data, activity=activity, handled=handled, since=since,+ )+ previous = brief_state.last_delivered(BRIEF_KIND)+ suppressed = (+ brief_state.suppress_unchanged_enabled()+ and not inputs.force_full+ and previous is not None+ and previous.input_hash == fingerprint+ )+yield WorkflowEvent(type="step_done",step_id="load_context",summary=(f"depts={len(today_data['departments'])} "f"proposals={len(today_data['proposals'])} "- f"activity={len(activity)}"+ f"activity={len(activity)} handled={len(handled)} "+ f"since={since.isoformat()[:16]}"),)+ # Structured payload for the scheduler: it records the fingerprint+ # only after a successful delivery, so "delivered" stays exact.+ yield WorkflowEvent(+ type="result",+ data={+ "brief_fingerprint": fingerprint,+ "suppressed": suppressed,+ "since": since.isoformat(),+ },+ )++ if suppressed:+ artifact_text = brief_state.suppressed_line(len(today_data["proposals"]))+ yield WorkflowEvent(+ type="step_done",+ step_id="synthesize",+ summary="unchanged since last brief — one-liner, no model call",+ )+ yield WorkflowEvent(type="artifact", content=artifact_text)+ yield WorkflowEvent(type="done")+ return# ------------------------------------------------------------------ ## Step 2: synthesize@@ -150,7 +199,7 @@ class MorningBriefWorkflow(Workflow):# not the /today header synthesis.artifact_text = await synthesize_briefing_narrative(today_data=today_data, activity=activity, period_label=period,- standalone=True,+ standalone=True, since=since, handled=handled,)except Exception as exc:logger.exception("morning_brief: synthesis failed")@@ -185,4 +234,4 @@ class MorningBriefWorkflow(Workflow):# / form) and from the scheduler. The scheduler invocation path lives in# `openexecutive.scheduler.runner._execute_action` (see the# `principal_brief_morning` branch).-__all__ = ["MorningBriefWorkflow", "MorningBriefInput"]+__all__ = ["BRIEF_KIND", "MorningBriefWorkflow", "MorningBriefInput"]diff --git a/packages/core/tests/unit/test_alert_sweep_runner.py b/packages/core/tests/unit/test_alert_sweep_runner.pynew file mode 100644index 00000000..a86b32be--- /dev/null+++ b/packages/core/tests/unit/test_alert_sweep_runner.py@@ -0,0 +1,40 @@+"""The scheduler's throttled alert expiry sweep (scheduler/runner.py)."""+from __future__ import annotations++from datetime import UTC, datetime, timedelta++import pytest++from openexecutive.alerts import lifecycle+from openexecutive.scheduler import runner++[email protected](autouse=True)+def _reset_throttle(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(runner, "_last_alert_sweep_at", None)+++def test_maybe_sweep_throttles_to_interval(monkeypatch: pytest.MonkeyPatch) -> None:+ calls: list[datetime] = []++ def fake_expire(now: datetime, db_path=None) -> int: # noqa: ARG001+ calls.append(now)+ return 2++ monkeypatch.setattr(lifecycle, "expire_stale_alerts", fake_expire)+ t0 = datetime.now(UTC)+ assert runner._maybe_sweep_alerts(t0) == 2+ assert runner._maybe_sweep_alerts(t0 + timedelta(minutes=5)) == 0+ assert runner._maybe_sweep_alerts(t0 + timedelta(minutes=14)) == 0+ assert runner._maybe_sweep_alerts(t0 + timedelta(minutes=15)) == 2+ assert calls == [t0, t0 + timedelta(minutes=15)]+++def test_maybe_sweep_swallows_errors(monkeypatch: pytest.MonkeyPatch) -> None:+ def boom(now: datetime, db_path=None) -> int: # noqa: ARG001+ raise RuntimeError("db locked")++ monkeypatch.setattr(lifecycle, "expire_stale_alerts", boom)+ assert runner._maybe_sweep_alerts(datetime.now(UTC)) == 0+ # The failed attempt still consumed the interval slot (no hot retry loop).+ assert runner._last_alert_sweep_at is not Nonediff --git a/packages/core/tests/unit/test_alerts_lifecycle.py b/packages/core/tests/unit/test_alerts_lifecycle.pynew file mode 100644index 00000000..43a27927--- /dev/null+++ b/packages/core/tests/unit/test_alerts_lifecycle.py@@ -0,0 +1,391 @@+"""Alert lifecycle: TTL, live view, expiry sweep, and the new store helpers."""+from __future__ import annotations++import sqlite3+from datetime import UTC, datetime, timedelta+from pathlib import Path++import pytest++from openexecutive.alerts import lifecycle+from openexecutive.alerts import store as alert_store+from openexecutive.alerts.store import (+ bulk_set_status,+ coalesce_alert,+ count_superseded_by,+ get_alert,+ initialize_db,+ insert_alert,+ mark_superseded,+ reopen_alert,+ set_review,+ update_alert_content,+ update_alert_routing,+)+++def db(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:+ db_path = tmp_path / "alerts.db"+ initialize_db(db_path)+ monkeypatch.setattr(alert_store, "DB_PATH", db_path)+ monkeypatch.setattr(lifecycle, "_ttl_settings", lambda: (3, 14))+ return db_path+++def _backdate(db: Path, alert_id: int, days: float) -> None:+ ts = (datetime.now(UTC) - timedelta(days=days)).isoformat()+ with sqlite3.connect(str(db)) as conn:+ conn.execute("UPDATE alerts SET created_at=? WHERE id=?", (ts, alert_id))+ conn.commit()+++def _insert(db: Path, **kw: object) -> int:+ defaults: dict = dict(+ source="triage", external_id=None, severity="medium",+ headline="h", body="b", db_path=db,+ )+ defaults.update(kw)+ if defaults["external_id"] is None:+ defaults["external_id"] = f"ext-{datetime.now(UTC).timestamp()}-{kw.get('headline', 'h')}"+ aid = insert_alert(**defaults)+ assert aid is not None+ return aid+++# --------------------------------------------------------------------------- #+# Migration+# --------------------------------------------------------------------------- #+++def test_migration_adds_lifecycle_columns_to_existing_db(tmp_path: Path) -> None:+ """A DB created by an older build gains the new columns with defaults."""+ legacy = tmp_path / "legacy.db"+ with sqlite3.connect(str(legacy)) as conn:+ conn.executescript(+ """+ CREATE TABLE alerts (+ id INTEGER PRIMARY KEY AUTOINCREMENT,+ external_id TEXT, source TEXT NOT NULL, severity TEXT NOT NULL,+ headline TEXT NOT NULL, body TEXT NOT NULL,+ suggested_action TEXT DEFAULT '', topic_tags TEXT DEFAULT '[]',+ channels_attempted TEXT DEFAULT '[]', channels_delivered TEXT DEFAULT '[]',+ dedup_key TEXT DEFAULT '', status TEXT NOT NULL DEFAULT 'unread',+ created_at TEXT NOT NULL, UNIQUE(source, external_id)+ );+ INSERT INTO alerts (external_id, source, severity, headline, body, created_at)+ VALUES ('x', 'email', 'high', 'old row', 'b', '2026-09-01T00:00:00+00:00');+ """+ )+ initialize_db(legacy)+ initialize_db(legacy) # idempotent+ row = get_alert(1, db_path=legacy)+ assert row is not None+ assert row.occurrence_count == 1+ assert row.review_verdict == ""+ assert row.last_seen_at is None+ assert row.snoozed_until is None+++# --------------------------------------------------------------------------- #+# TTL predicate+# --------------------------------------------------------------------------- #+++def test_ttl_monitoring_vs_action(db: Path) -> None:+ monitoring = _insert(db, source="stock", severity="low", topic_tags=["external:stock"])+ action = _insert(db, source="triage", severity="high")+ now = datetime.now(UTC)+ m = get_alert(monitoring, db_path=db)+ a = get_alert(action, db_path=db)+ assert m is not None and a is not None+ assert lifecycle.ttl_days_for(m, monitoring_days=3, action_days=14) == 3+ assert lifecycle.ttl_days_for(a, monitoring_days=3, action_days=14) == 14+ # Fresh rows are live under both TTLs.+ assert not lifecycle.is_expired(m, now, monitoring_days=3, action_days=14)+ assert not lifecycle.is_expired(a, now, monitoring_days=3, action_days=14)+ _backdate(db, monitoring, 4)+ _backdate(db, action, 4)+ m = get_alert(monitoring, db_path=db)+ a = get_alert(action, db_path=db)+ assert m is not None and a is not None+ assert lifecycle.is_expired(m, now, monitoring_days=3, action_days=14)+ assert not lifecycle.is_expired(a, now, monitoring_days=3, action_days=14)+++def test_zero_ttl_disables_expiry(db: Path) -> None:+ aid = _insert(db, source="triage", severity="high")+ _backdate(db, aid, 400)+ a = get_alert(aid, db_path=db)+ assert a is not None+ assert lifecycle.ttl_days_for(a, monitoring_days=3, action_days=0) is None+ assert not lifecycle.is_expired(a, monitoring_days=3, action_days=0)+++def test_exempt_sources_never_expire(db: Path) -> None:+ art = _insert(db, source="artifact", severity="medium", topic_tags=["artifact"])+ dec = _insert(db, source="decision_scheduling", severity="medium")+ _backdate(db, art, 90)+ _backdate(db, dec, 90)+ for aid in (art, dec):+ a = get_alert(aid, db_path=db)+ assert a is not None+ assert lifecycle.ttl_days_for(a, monitoring_days=3, action_days=14) is None+ assert not lifecycle.is_expired(a, monitoring_days=3, action_days=14)+++# --------------------------------------------------------------------------- #+# Live view + sweep+# --------------------------------------------------------------------------- #+++def test_list_live_alerts_skips_past_ttl_and_snoozed_before_any_sweep(db: Path) -> None:+ live = _insert(db, headline="live")+ stale = _insert(db, headline="stale")+ snoozed = _insert(db, headline="snoozed")+ _backdate(db, stale, 20)+ with sqlite3.connect(str(db)) as conn:+ conn.execute(+ "UPDATE alerts SET snoozed_until=? WHERE id=?",+ ((datetime.now(UTC) + timedelta(hours=3)).isoformat(), snoozed),+ )+ conn.commit()+ ids = {a.id for a in lifecycle.list_live_alerts(db_path=db)}+ assert ids == {live}+ # Still unread on disk — the view hides, the sweep persists.+ stale_row = get_alert(stale, db_path=db)+ assert stale_row is not None and stale_row.status == "unread"+++def test_list_live_alerts_not_starved_by_expired_rows(db: Path) -> None:+ """A run of expired rows newer than the live one must not push it out."""+ old_live = _insert(db, headline="old but live")+ _backdate(db, old_live, 1)+ for i in range(12):+ aid = _insert(db, headline=f"stale-{i}")+ _backdate(db, aid, 15 + i / 100)+ # Expired rows are older, so they sort after; the live one leads.+ rows = lifecycle.list_live_alerts(limit=5, db_path=db)+ assert [a.id for a in rows] == [old_live]+++def test_expire_stale_alerts_marks_expired_and_audits(+ db: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ events: list[tuple[str, dict]] = []++ def fake_audit(event_type: str, summary: str, **kw: object) -> None:+ events.append((event_type, dict(kw.get("details") or {})))++ import openexecutive.audit as audit_pkg++ monkeypatch.setattr(audit_pkg, "log_event", fake_audit)++ live = _insert(db, headline="live")+ stale_action = _insert(db, headline="stale action", severity="high")+ stale_monitoring = _insert(+ db, headline="stale mon", source="rss", severity="low", topic_tags=["external:rss"]+ )+ exempt = _insert(db, headline="artifact", source="artifact", topic_tags=["artifact"])+ _backdate(db, stale_action, 15)+ _backdate(db, stale_monitoring, 4)+ _backdate(db, exempt, 60)++ count = lifecycle.expire_stale_alerts(db_path=db)+ assert count == 2+ assert get_alert(stale_action, db_path=db).status == "expired" # type: ignore[union-attr]+ assert get_alert(stale_monitoring, db_path=db).status == "expired" # type: ignore[union-attr]+ assert get_alert(live, db_path=db).status == "unread" # type: ignore[union-attr]+ assert get_alert(exempt, db_path=db).status == "unread" # type: ignore[union-attr]+ assert events and events[0][0] == "alert_sweep"+ assert events[0][1]["count"] == 2+ assert set(events[0][1]["alert_ids"]) == {stale_action, stale_monitoring}++ # Second sweep: nothing left to do, no audit row.+ events.clear()+ assert lifecycle.expire_stale_alerts(db_path=db) == 0+ assert events == []+++def test_expire_stale_alerts_never_raises(db: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ def boom(*a: object, **k: object) -> list:+ raise RuntimeError("disk on fire")++ monkeypatch.setattr(alert_store, "list_alerts", boom)+ assert lifecycle.expire_stale_alerts(db_path=db) == 0+++# --------------------------------------------------------------------------- #+# Store helpers+# --------------------------------------------------------------------------- #+++def test_coalesce_alert_bumps_count_last_seen_and_severity(db: Path) -> None:+ aid = _insert(db, source="stock", dedup_key="watch:stock-aapl", severity="low", body="v1")+ hit = coalesce_alert(+ source="stock", dedup_key="watch:stock-aapl", severity="medium", body="v2", db_path=db+ )+ assert hit == (aid, True)+ row = get_alert(aid, db_path=db)+ assert row is not None+ assert row.occurrence_count == 2+ assert row.last_seen_at is not None+ assert row.body == "v2"+ assert row.severity == "medium"+ # A milder repeat never lowers severity, and reports no escalation.+ hit = coalesce_alert(+ source="stock", dedup_key="watch:stock-aapl", severity="low", body="v3", db_path=db+ )+ assert hit == (aid, False)+ row = get_alert(aid, db_path=db)+ assert row is not None and row.severity == "medium" and row.occurrence_count == 3+++def test_coalesce_alert_ignores_closed_rows_and_requires_key(db: Path) -> None:+ aid = _insert(db, source="email", dedup_key="churn-acme")+ alert_store.set_status(aid, "ack", db_path=db)+ assert coalesce_alert(+ source="email", dedup_key="churn-acme", severity="high", body="x", db_path=db+ ) is None+ assert coalesce_alert(+ source="email", dedup_key="", severity="high", body="x", db_path=db+ ) is None+ # Different source, same key → no match either.+ _insert(db, source="slack", dedup_key="k1")+ assert coalesce_alert(+ source="email", dedup_key="k1", severity="high", body="x", db_path=db+ ) is None+++def test_bulk_set_status_by_ids_and_by_age_with_category(db: Path) -> None:+ a1 = _insert(db, headline="a1")+ a2 = _insert(db, headline="a2")+ m1 = _insert(db, headline="m1", source="rss", severity="low", topic_tags=["external:rss"])+ _backdate(db, a2, 10)+ _backdate(db, m1, 10)++ assert bulk_set_status("dismissed", alert_ids=[a1], db_path=db) == [a1]+ assert get_alert(a1, db_path=db).status == "dismissed" # type: ignore[union-attr]+ # Already dismissed → not unread → not counted again.+ assert bulk_set_status("dismissed", alert_ids=[a1], db_path=db) == []++ cutoff = (datetime.now(UTC) - timedelta(days=7)).isoformat()+ assert bulk_set_status("dismissed", before=cutoff, category="monitoring", db_path=db) == [m1]+ assert get_alert(m1, db_path=db).status == "dismissed" # type: ignore[union-attr]+ assert get_alert(a2, db_path=db).status == "unread" # type: ignore[union-attr]+ assert bulk_set_status("ack", before=cutoff, category="action", db_path=db) == [a2]+ assert get_alert(a2, db_path=db).status == "ack" # type: ignore[union-attr]+ # No selector → no-op.+ assert bulk_set_status("ack", db_path=db) == []+ assert bulk_set_status("ack", alert_ids=[], db_path=db) == []+++def test_update_content_review_routing_and_reopen(db: Path) -> None:+ aid = _insert(db, headline="old", body="old body", severity="low")+ assert update_alert_content(aid, headline="new", severity="high", db_path=db)+ row = get_alert(aid, db_path=db)+ assert row is not None and row.headline == "new" and row.body == "old body"+ assert row.severity == "high"+ assert not update_alert_content(aid, db_path=db) # nothing to set++ assert set_review(+ aid, verdict="likely_stale", note="no activity in 9 days",+ recommended_move="close", why_now="", db_path=db,+ )+ row = get_alert(aid, db_path=db)+ assert row is not None+ assert row.review_verdict == "likely_stale"+ assert row.review_note == "no activity in 9 days"+ assert row.recommended_move == "close"+ assert row.last_reviewed_at is not None++ assert update_alert_routing(aid, 7, db_path=db)+ assert get_alert(aid, db_path=db).routed_to_person_id == 7 # type: ignore[union-attr]++ alert_store.set_status(aid, "expired", db_path=db)+ assert reopen_alert(aid, db_path=db)+ row = get_alert(aid, db_path=db)+ assert row is not None and row.status == "unread" and row.review_verdict == ""+ assert row.last_reviewed_at is None and row.why_now == "" and row.due_at is None+ assert not reopen_alert(aid, db_path=db) # already unread+ assert not reopen_alert(9999, db_path=db)+ # `ack` (approved + executed) is not an Undo target; exempt sources never reopen.+ alert_store.set_status(aid, "ack", db_path=db)+ assert not reopen_alert(aid, db_path=db)+ art = _insert(db, source="artifact", topic_tags=["artifact"])+ alert_store.set_status(art, "dismissed", db_path=db)+ assert not reopen_alert(art, db_path=db, exclude_sources=("artifact",))+ assert reopen_alert(art, db_path=db) # without the exclusion the store itself allows it+++def test_mark_superseded_folds_into_survivor(db: Path) -> None:+ survivor = _insert(db, headline="story")+ dup = _insert(db, headline="dup")+ assert mark_superseded(dup, survivor, db_path=db)+ d = get_alert(dup, db_path=db)+ s = get_alert(survivor, db_path=db)+ assert d is not None and d.status == "dismissed" and d.superseded_by_alert_id == survivor+ assert s is not None and s.occurrence_count == 2 # absorbs the dup's own count (1)+ assert count_superseded_by(db_path=db) == {survivor: 1}+ # Self-merge, missing survivor, or already-closed row → False.+ assert not mark_superseded(survivor, survivor, db_path=db)+ assert not mark_superseded(dup, 9999, db_path=db)+ assert not mark_superseded(dup, survivor, db_path=db)+++def test_is_expired_uses_last_seen_as_the_age_anchor(db: Path) -> None:+ """A situation that keeps re-firing stays live: coalescing bumps last_seen_at."""+ aid = _insert(db, source="stock", severity="low", topic_tags=["external:stock"], dedup_key="watch:x")+ _backdate(db, aid, 10) # created well past the 3-day monitoring TTL+ assert lifecycle.is_expired(get_alert(aid, db_path=db), monitoring_days=3, action_days=14) # type: ignore[arg-type]+ coalesce_alert(source="stock", dedup_key="watch:x", severity="low", body="again", db_path=db)+ assert not lifecycle.is_expired(get_alert(aid, db_path=db), monitoring_days=3, action_days=14) # type: ignore[arg-type]+ assert lifecycle.is_live(get_alert(aid, db_path=db)) # type: ignore[arg-type]+++def test_mute_pattern_allowed_rejects_broad_patterns(db: Path) -> None:+ from openexecutive.alerts.models import Alert++ alert = Alert(source="rss", severity="low", headline="h", body="b", created_at="2026-09-11T00:00:00+00:00",+ topic_tags=["external:rss", "external:acme-news", "press"])+ assert lifecycle.mute_pattern_allowed(alert, "external:acme-news")+ assert lifecycle.mute_pattern_allowed(alert, "press")+ assert lifecycle.mute_pattern_allowed(alert, "department:finance")+ assert not lifecycle.mute_pattern_allowed(alert, "e")+ assert not lifecycle.mute_pattern_allowed(alert, ":")+ assert not lifecycle.mute_pattern_allowed(alert, "finance") # not this alert's tag, not scoped+ assert not lifecycle.mute_pattern_allowed(alert, "external:")+++def test_reopen_makes_a_past_ttl_row_live_again(db: Path) -> None:+ aid = _insert(db, headline="old but wanted")+ _backdate(db, aid, 20)+ assert lifecycle.expire_stale_alerts(db_path=db) == 1+ assert reopen_alert(aid, db_path=db)+ assert lifecycle.is_live(get_alert(aid, db_path=db)) # type: ignore[arg-type]+ assert lifecycle.expire_stale_alerts(db_path=db) == 0 # not re-expired by the next sweep+ assert [a.id for a in lifecycle.list_live_alerts(db_path=db)] == [aid]+++def test_reopen_after_merge_hands_back_the_absorbed_count(db: Path) -> None:+ survivor = _insert(db, headline="story")+ dup = _insert(db, headline="dup")+ with sqlite3.connect(str(db)) as conn:+ conn.execute("UPDATE alerts SET occurrence_count = 4 WHERE id = ?", (dup,))+ conn.commit()+ assert mark_superseded(dup, survivor, db_path=db)+ assert get_alert(survivor, db_path=db).occurrence_count == 5 # type: ignore[union-attr]+ assert reopen_alert(dup, db_path=db)+ assert get_alert(survivor, db_path=db).occurrence_count == 1 # type: ignore[union-attr]+ assert get_alert(dup, db_path=db).superseded_by_alert_id is None # type: ignore[union-attr]+++def test_bulk_age_cutoff_uses_last_seen_anchor(db: Path) -> None:+ refiring = _insert(db, headline="refiring", source="stock", dedup_key="watch:y", severity="low",+ topic_tags=["external:stock"])+ idle = _insert(db, headline="idle")+ _backdate(db, refiring, 10)+ _backdate(db, idle, 10)+ coalesce_alert(source="stock", dedup_key="watch:y", severity="low", body="again", db_path=db)+ cutoff = (datetime.now(UTC) - timedelta(days=7)).isoformat()+ assert bulk_set_status("dismissed", before=cutoff, db_path=db) == [idle]diff --git a/packages/core/tests/unit/test_alerts_pipeline.py b/packages/core/tests/unit/test_alerts_pipeline.pyindex 258eb15a..8f1a24a6 100644--- a/packages/core/tests/unit/test_alerts_pipeline.py+++ b/packages/core/tests/unit/test_alerts_pipeline.py@@ -7,6 +7,7 @@ from pathlib import Pathimport pytest+from openexecutive.alerts import store as alert_storefrom openexecutive.alerts.models import (AlertChannel,AlertEvent,@@ -217,3 +218,165 @@ def test_in_quiet_hours_wraparound_window() -> None:assert _in_quiet_hours(prefs, now=datetime(2030, 1, 1, 3, 0, tzinfo=UTC))# 12:00 UTC — outside.assert not _in_quiet_hours(prefs, now=datetime(2030, 1, 1, 12, 0, tzinfo=UTC))+++# --------------------------------------------------------------------------- #+# Coalescing, routing, dedup hint (alert lifecycle)+# --------------------------------------------------------------------------- #+++def _stub_triage(monkeypatch, *, severity=AlertSeverity.MEDIUM, dedup_key="model-key",+ tags=None):+ from openexecutive.agents import triage as triage_module++ async def fake_triage(self, event, **kwargs): # noqa: ARG001+ return TriageDecision(+ alert=True,+ severity=severity,+ channels=[AlertChannel.PERSISTED],+ headline="Stub",+ body=f"body for {event.external_id}",+ topic_tags=list(tags or ["customer"]),+ dedup_key=dedup_key or f"key-{event.external_id}",+ )++ monkeypatch.setattr(triage_module.TriageAgent, "triage", fake_triage)+++def _count_dispatches(monkeypatch) -> list:+ from openexecutive.alerts import dispatcher++ calls: list = []++ async def fake_dispatch(alert, channels, **kw): # noqa: ARG001+ calls.append(alert.id)++ monkeypatch.setattr(dispatcher, "dispatch_all", fake_dispatch)+ return calls+++def test_pipeline_routes_person_only_from_the_explicit_field(monkeypatch, db: Path) -> None:+ from openexecutive.alerts import pipeline++ _stub_triage(monkeypatch, dedup_key=None)+ _count_dispatches(monkeypatch)++ async def run():+ _, a = await pipeline.evaluate_and_dispatch(+ AlertEvent(source="email", external_id="f", body="x", routed_to_person_id=4),+ db_path=db,+ )+ _, b = await pipeline.evaluate_and_dispatch(+ AlertEvent(source="email", external_id="u", body="x", user="person:9"),+ db_path=db,+ )+ _, c = await pipeline.evaluate_and_dispatch(+ AlertEvent(source="email", external_id="n", body="x", user="U123"),+ db_path=db,+ )+ return a, b, c++ a, b, c = asyncio.run(run())+ assert alert_store.get_alert(a, db_path=db).routed_to_person_id == 4 # type: ignore[union-attr]+ # `event.user` is a sender-controlled display name on some integrations —+ # a "person:9" there must never pick the routing target.+ assert alert_store.get_alert(b, db_path=db).routed_to_person_id is None # type: ignore[union-attr]+ assert alert_store.get_alert(c, db_path=db).routed_to_person_id is None # type: ignore[union-attr]+++def test_pipeline_replay_of_same_external_id_stays_a_noop(monkeypatch, db: Path) -> None:+ """A webhook retry (same source + external_id) must not coalesce into a+ second occurrence — it is the same event, not a repeat of the situation."""+ from openexecutive.alerts import pipeline++ _stub_triage(monkeypatch, dedup_key="same-key")+ calls = _count_dispatches(monkeypatch)++ async def run():+ _, a = await pipeline.evaluate_and_dispatch(+ AlertEvent(source="email", external_id="msg-1", body="x"), db_path=db,+ )+ _, b = await pipeline.evaluate_and_dispatch(+ AlertEvent(source="email", external_id="msg-1", body="x"), db_path=db,+ )+ return a, b++ a, b = asyncio.run(run())+ assert a is not None and b is None+ row = alert_store.get_alert(a, db_path=db)+ assert row is not None and row.occurrence_count == 1 and calls == [a]+++def test_pipeline_adds_department_tag_from_channel(monkeypatch, db: Path) -> None:+ from openexecutive.alerts import pipeline++ _stub_triage(monkeypatch, tags=["finance"])+ _count_dispatches(monkeypatch)++ async def run():+ _, aid = await pipeline.evaluate_and_dispatch(+ AlertEvent(source="email", external_id="d", body="x", channel="department:Finance"),+ db_path=db,+ )+ return aid++ aid = asyncio.run(run())+ row = alert_store.get_alert(aid, db_path=db)+ assert row is not None and row.topic_tags == ["finance", "department:finance"]+++def test_pipeline_coalesces_same_key_without_dispatch_and_redispatches_on_escalation(+ monkeypatch, db: Path+) -> None:+ from openexecutive.alerts import pipeline++ calls = _count_dispatches(monkeypatch)++ async def run():+ _stub_triage(monkeypatch, severity=AlertSeverity.LOW, dedup_key="k")+ _, first = await pipeline.evaluate_and_dispatch(+ AlertEvent(source="stock", external_id="day1", body="x"), db_path=db,+ )+ _, second = await pipeline.evaluate_and_dispatch(+ AlertEvent(source="stock", external_id="day2", body="x"), db_path=db,+ )+ _stub_triage(monkeypatch, severity=AlertSeverity.URGENT, dedup_key="k")+ _, third = await pipeline.evaluate_and_dispatch(+ AlertEvent(source="stock", external_id="day3", body="crash"), db_path=db,+ )+ return first, second, third++ first, second, third = asyncio.run(run())+ assert first is not None and second is None and third == first+ row = alert_store.get_alert(first, db_path=db)+ assert row is not None+ assert row.occurrence_count == 3+ assert row.severity == "urgent"+ assert row.body == "body for day3"+ # One dispatch for the insert, none for the quiet repeat, one for the escalation.+ assert calls == [first, first]+ assert len(alert_store.list_alerts(db_path=db)) == 1+++def test_pipeline_dedup_hint_overrides_model_key(monkeypatch, db: Path) -> None:+ from openexecutive.alerts import pipeline++ _count_dispatches(monkeypatch)++ async def run():+ _stub_triage(monkeypatch, dedup_key="model-a")+ _, a = await pipeline.evaluate_and_dispatch(+ AlertEvent(source="rss", external_id="1", body="x", dedup_hint="watch:acme-news"),+ db_path=db,+ )+ _stub_triage(monkeypatch, dedup_key="model-b")+ _, b = await pipeline.evaluate_and_dispatch(+ AlertEvent(source="rss", external_id="2", body="x", dedup_hint="watch:acme-news"),+ db_path=db,+ )+ return a, b++ a, b = asyncio.run(run())+ assert a is not None and b is None+ row = alert_store.get_alert(a, db_path=db)+ assert row is not None and row.dedup_key == "watch:acme-news" and row.occurrence_count == 2diff --git a/packages/core/tests/unit/test_alerts_routes.py b/packages/core/tests/unit/test_alerts_routes.pynew file mode 100644index 00000000..58ae5ccf--- /dev/null+++ b/packages/core/tests/unit/test_alerts_routes.py@@ -0,0 +1,152 @@+"""Alert queue-grooming routes: ack feedback + mute, bulk-ack, reopen, review."""+from __future__ import annotations++import sqlite3+from datetime import UTC, datetime, timedelta+from pathlib import Path++import pytest+from fastapi import FastAPI+from fastapi.testclient import TestClient++from openexecutive.alerts import lifecycle+from openexecutive.alerts import store as alert_store+from openexecutive.api.routes import alerts as alerts_route+from openexecutive.memory import episodic+from openexecutive.monitoring import store as monitoring_store+++def db(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:+ db_path = tmp_path / "alerts.db"+ monkeypatch.setattr(alert_store, "DB_PATH", db_path)+ monkeypatch.setattr(episodic, "DB_PATH", db_path)+ monkeypatch.setattr(lifecycle, "_ttl_settings", lambda: (3, 14))+ alert_store.initialize_db(db_path)+ episodic.initialize_db(db_path)+ monitoring_store.initialize_db(db_path)+ return db_path+++def client(db: Path) -> TestClient:+ app = FastAPI()+ app.include_router(alerts_route.router)+ return TestClient(app)+++def _insert(db: Path, headline: str, **kw: object) -> int:+ params: dict = dict(+ source="triage", external_id=f"ext-{headline}", severity="medium",+ headline=headline, body="b", db_path=db,+ )+ params.update(kw)+ aid = alert_store.insert_alert(**params)+ assert aid is not None+ return aid+++def _watch(db: Path, slug: str) -> None:+ monitoring_store.insert_watchlist_item(+ slug=slug, signal_type="rss", target="https://example.com/feed", db_path=db,+ )+++def test_single_ack_still_works_and_teaches_the_watch(client: TestClient, db: Path) -> None:+ _watch(db, "acme-news")+ aid = _insert(db, "acme raised", source="rss", topic_tags=["external:rss", "external:acme-news"])+ res = client.post(f"/alerts/{aid}/ack", json={"status": "dismissed"})+ assert res.status_code == 200 and res.json()["status"] == "dismissed"+ item = monitoring_store.get_watchlist_item_by_slug("acme-news", db_path=db)+ assert item is not None and item.dismiss_count == 1 and item.trust_score == pytest.approx(0.8)++ # Approving a later alert from the same watch recovers a little trust.+ aid2 = _insert(db, "acme again", source="rss", topic_tags=["external:rss", "external:acme-news"])+ client.post(f"/alerts/{aid2}/ack", json={"status": "ack"})+ item = monitoring_store.get_watchlist_item_by_slug("acme-news", db_path=db)+ assert item is not None and item.trust_score == pytest.approx(0.85)+ assert client.post("/alerts/9999/ack", json={"status": "ack"}).status_code == 404+ assert client.post(f"/alerts/{aid}/ack", json={"status": "expired"}).status_code == 422+ # Re-posting the same status is idempotent for the feedback loop.+ client.post(f"/alerts/{aid}/ack", json={"status": "dismissed"})+ client.post(f"/alerts/{aid}/ack", json={"status": "dismissed"})+ item = monitoring_store.get_watchlist_item_by_slug("acme-news", db_path=db)+ assert item is not None and item.dismiss_count == 1+++def test_ack_with_mute_topic_adds_a_mute(client: TestClient, db: Path) -> None:+ aid = _insert(db, "newsletter", topic_tags=["external:rss", "external:acme-news"])+ res = client.post(f"/alerts/{aid}/ack", json={"status": "dismissed", "mute_topic": True})+ assert res.status_code == 200+ assert [m.pattern for m in alert_store.list_mutes(db_path=db)] == ["external:acme-news"]+ aid2 = _insert(db, "finance thing", topic_tags=["finance", "department:finance"])+ client.post(f"/alerts/{aid2}/ack", json={"status": "dismissed", "mute_topic": "finance"})+ assert sorted(m.pattern for m in alert_store.list_mutes(db_path=db)) == ["external:acme-news", "finance"]+ # An ack (not a dismiss) never mutes, even if asked.+ aid3 = _insert(db, "keep", topic_tags=["customer"])+ client.post(f"/alerts/{aid3}/ack", json={"status": "ack", "mute_topic": True})+ assert len(alert_store.list_mutes(db_path=db)) == 2+ # A broad pattern (substring-matched against every future alert) is refused.+ aid4 = _insert(db, "broad", topic_tags=["customer"])+ client.post(f"/alerts/{aid4}/ack", json={"status": "dismissed", "mute_topic": "e"})+ assert len(alert_store.list_mutes(db_path=db)) == 2+++def test_bulk_ack_by_ids_and_by_age(client: TestClient, db: Path) -> None:+ a = _insert(db, "a")+ b = _insert(db, "b")+ old_mon = _insert(db, "old mon", source="rss", severity="low", topic_tags=["external:rss"])+ old_art = _insert(db, "old artifact", source="artifact", topic_tags=["artifact"])+ with sqlite3.connect(str(db)) as conn:+ for aid in (old_mon, old_art):+ conn.execute(+ "UPDATE alerts SET created_at=? WHERE id=?",+ ((datetime.now(UTC) - timedelta(days=10)).isoformat(), aid),+ )+ conn.commit()++ res = client.post("/alerts/bulk-ack", json={"status": "dismissed", "alert_ids": [a, b]})+ assert res.status_code == 200 and res.json() == {"count": 2}+ res = client.post(+ "/alerts/bulk-ack",+ json={"status": "dismissed", "older_than_days": 7, "category": "monitoring"},+ )+ assert res.json() == {"count": 1}+ assert alert_store.get_alert(old_mon, db_path=db).status == "dismissed" # type: ignore[union-attr]+ # Exempt sources are never bulk-closed by an age sweep.+ assert alert_store.get_alert(old_art, db_path=db).status == "unread" # type: ignore[union-attr]+ assert client.post("/alerts/bulk-ack", json={"status": "ack"}).status_code == 400+ assert client.post("/alerts/bulk-ack", json={"status": "read", "alert_ids": [a]}).status_code == 422+ # A 0-day sweep would close the whole company queue → rejected.+ assert client.post("/alerts/bulk-ack", json={"status": "dismissed", "older_than_days": 0}).status_code == 422+ assert client.post("/alerts/bulk-ack", json={"status": "ack", "alert_ids": []}).json() == {"count": 0}+ assert client.post("/alerts/bulk-ack", json={"status": "ack", "alert_ids": list(range(501))}).status_code == 422+++def test_bulk_ack_teaches_the_watch_like_a_single_dismiss(client: TestClient, db: Path) -> None:+ _watch(db, "acme-news")+ ids = [+ _insert(db, f"n{i}", source="rss", severity="low", topic_tags=["external:rss", "external:acme-news"])+ for i in range(2)+ ]+ assert client.post("/alerts/bulk-ack", json={"status": "dismissed", "alert_ids": ids}).json() == {"count": 2}+ item = monitoring_store.get_watchlist_item_by_slug("acme-news", db_path=db)+ assert item is not None and item.dismiss_count == 2 and item.trust_score == pytest.approx(0.64)+++def test_reopen_brings_a_closed_alert_back(client: TestClient, db: Path) -> None:+ aid = _insert(db, "closed")+ alert_store.set_status(aid, "expired", db_path=db)+ alert_store.set_review(aid, verdict="likely_stale", note="x", db_path=db)+ res = client.post(f"/alerts/{aid}/reopen")+ assert res.status_code == 200+ assert res.json()["status"] == "unread" and res.json()["review_verdict"] == ""+ assert client.post(f"/alerts/{aid}/reopen").status_code == 409+ assert client.post("/alerts/9999/reopen").status_code == 404+ # `ack` and exempt sources are not Undo targets.+ acked = _insert(db, "approved")+ alert_store.set_status(acked, "ack", db_path=db)+ assert client.post(f"/alerts/{acked}/reopen").status_code == 409+ art = _insert(db, "doc", source="artifact", topic_tags=["artifact"])+ alert_store.set_status(art, "dismissed", db_path=db)+ assert client.post(f"/alerts/{art}/reopen").status_code == 409diff --git a/packages/core/tests/unit/test_brief_state.py b/packages/core/tests/unit/test_brief_state.pynew file mode 100644index 00000000..ffc1f867--- /dev/null+++ b/packages/core/tests/unit/test_brief_state.py@@ -0,0 +1,134 @@+"""Delivered-brief state: window, new-vs-carried split, fingerprint, handled."""+from __future__ import annotations++from datetime import UTC, datetime, timedelta+from pathlib import Path++import pytest++from openexecutive.briefing import brief_state, narrative_cache++[email protected](autouse=True)+def _isolated_cache(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(narrative_cache, "DB_PATH", tmp_path / "cache.db")+++def _proposal(alert_id: int, *, hours_ago: float, **extra: object) -> dict:+ return {+ "alert_id": alert_id,+ "headline": f"item {alert_id}",+ "created_at": (datetime.now(UTC) - timedelta(hours=hours_ago)).isoformat(),+ **extra,+ }+++def test_since_for_defaults_to_24h_then_last_delivery() -> None:+ now = datetime.now(UTC)+ cold = brief_state.since_for("principal_brief_morning", now=now)+ assert abs((now - cold) - timedelta(hours=24)) < timedelta(seconds=5)++ brief_state.record_delivered("principal_brief_morning", "fp1", "text")+ warm = brief_state.since_for("principal_brief_morning", now=now + timedelta(hours=3))+ assert now - timedelta(seconds=5) <= warm <= now + timedelta(seconds=5)++ # A delivery stamped AFTER `now` (clock skew) never yields a future window.+ skewed = brief_state.since_for("principal_brief_morning", now=now - timedelta(hours=1))+ assert skewed <= now - timedelta(hours=1)++ # A delivery older than a week is clamped to 7 days back.+ narrative_cache.put(narrative_cache.BriefingNarrative(+ scope=brief_state.scope_for("principal_brief_eod"), input_hash="x",+ narrative_text="t", generated_at=(now - timedelta(days=30)).isoformat(),+ ))+ clamped = brief_state.since_for("principal_brief_eod", now=now)+ assert abs((now - clamped) - timedelta(days=7)) < timedelta(seconds=5)+++def test_record_and_last_delivered_roundtrip_per_kind() -> None:+ assert brief_state.last_delivered("principal_brief_morning") is None+ brief_state.record_delivered("principal_brief_morning", "fp-m", "morning text")+ brief_state.record_delivered("principal_brief_eod", "fp-e", "eod text")+ m = brief_state.last_delivered("principal_brief_morning")+ e = brief_state.last_delivered("principal_brief_eod")+ assert m is not None and m.input_hash == "fp-m" and m.narrative_text == "morning text"+ assert e is not None and e.input_hash == "fp-e"+ # The per-viewer header cache is untouched by the brief namespace.+ assert narrative_cache.get("principal") is None+++def test_split_proposals_by_window() -> None:+ since = datetime.now(UTC) - timedelta(hours=12)+ new, carried = brief_state.split_proposals(+ [_proposal(1, hours_ago=1), _proposal(2, hours_ago=30), {"alert_id": 3}], since+ )+ assert [p["alert_id"] for p in new] == [1, 3] # unknown created_at counts as new+ assert [p["alert_id"] for p in carried] == [2]+ all_new, none = brief_state.split_proposals([_proposal(1, hours_ago=100)], None)+ assert len(all_new) == 1 and none == []+++def test_fingerprint_is_order_independent_and_date_free() -> None:+ since = datetime.now(UTC) - timedelta(hours=12)+ a = _proposal(1, hours_ago=1)+ b = _proposal(2, hours_ago=2)+ old = _proposal(3, hours_ago=40, review_verdict="likely_stale")+ act1 = {"kind": "dm_sent", "summary": "DM'd Dana", "at": "2026-09-11T08:00:00+00:00"}+ act2 = {"kind": "decision_logged", "summary": "Chose vendor", "at": "2026-09-11T09:00:00+00:00"}+ handled = [{"kind": "routed", "summary": "Routed X to Dana", "at": "2026-09-11T07:00:00+00:00"}]+ depts = [{"slug": "sales", "at_risk_count": 1, "off_track_count": 0}]+ people = [{"id": 5, "awaiting_count": 2}, {"id": 6, "awaiting_count": 0}]++ fp1 = brief_state.build_brief_fingerprint(+ today_data={"proposals": [a, b, old], "departments": depts, "people": people},+ activity=[act1, act2], handled=handled, since=since,+ )+ fp2 = brief_state.build_brief_fingerprint(+ today_data={"proposals": [old, b, a], "departments": depts, "people": list(reversed(people))},+ activity=[act2, act1], handled=handled, since=since,+ )+ assert fp1 == fp2+ # Same activity a day later (different stamps) → same fingerprint: the+ # suppression must be able to fire on a day whose activity is unchanged.+ later = [{**act1, "at": "2026-09-12T08:00:00+00:00"}, {**act2, "at": "2026-09-12T09:00:00+00:00"}]+ fp_later = brief_state.build_brief_fingerprint(+ today_data={"proposals": [a, b, old], "departments": depts, "people": people},+ activity=later, handled=handled, since=since,+ )+ assert fp_later == fp1+ # A new proposal, a resolved carried item, or a new handled move changes it.+ fp3 = brief_state.build_brief_fingerprint(+ today_data={"proposals": [a, b, old, _proposal(9, hours_ago=0.5)], "departments": depts, "people": people},+ activity=[act1, act2], handled=handled, since=since,+ )+ fp4 = brief_state.build_brief_fingerprint(+ today_data={"proposals": [a, b], "departments": depts, "people": people},+ activity=[act1, act2], handled=handled, since=since,+ )+ fp5 = brief_state.build_brief_fingerprint(+ today_data={"proposals": [a, b, old], "departments": depts, "people": people},+ activity=[act1, act2], handled=[], since=since,+ )+ assert len({fp1, fp3, fp4, fp5}) == 4+++def test_suppressed_line_pluralises() -> None:+ assert brief_state.suppressed_line(1).endswith("1 item still waiting on you.")+ assert brief_state.suppressed_line(12).endswith("12 items still waiting on you.")+++def test_handled_since_reads_review_audit_events(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ from openexecutive.audit import logger as audit_logger++ al = audit_logger.AuditLogger(db_path=tmp_path / "audit.db")+ al.initialize_db()+ monkeypatch.setattr(audit_logger, "get_audit_logger", lambda: al)+ al.log("alert_review_routed", "Routed 'Acme renewal' to Dana", actor="executive")+ al.log("alert_review_closed", "Resolved 'Stripe incident' — vendor marked resolved", actor="executive")+ al.log("tool_invocation", "unrelated", actor="executive")++ handled = brief_state.handled_since(datetime.now(UTC) - timedelta(hours=1))+ kinds = sorted(h["kind"] for h in handled)+ assert kinds == ["closed", "routed"]+ assert all(h["summary"] and h["at"] for h in handled)+ assert brief_state.handled_since(datetime.now(UTC) + timedelta(hours=1)) == []diff --git a/packages/core/tests/unit/test_briefing_context_render.py b/packages/core/tests/unit/test_briefing_context_render.pynew file mode 100644index 00000000..61fbcf7c--- /dev/null+++ b/packages/core/tests/unit/test_briefing_context_render.py@@ -0,0 +1,82 @@+"""render_briefing_context / _render_eod_context: the since-bounded delta view."""+from __future__ import annotations++from datetime import UTC, datetime, timedelta++from openexecutive.briefing.narrative import render_briefing_context+from openexecutive.workflows.end_of_day_digest import _render_eod_context+++def _proposal(alert_id: int, *, hours_ago: float, **extra: object) -> dict:+ return {+ "alert_id": alert_id,+ "headline": f"item {alert_id}",+ "created_at": (datetime.now(UTC) - timedelta(hours=hours_ago)).isoformat(),+ "category": "action",+ **extra,+ }+++def _today() -> dict:+ return {+ "departments": [{"title": "Sales", "slug": "sales", "at_risk_count": 1, "off_track_count": 0, "awaiting_count": 0}],+ "proposals": [+ _proposal(1, hours_ago=2, why_now="SLA ends today", recommended_move="nudge"),+ _proposal(2, hours_ago=60, review_verdict="likely_stale"),+ _proposal(3, hours_ago=90),+ ],+ "people": [{"full_name": "Dana", "role": "CFO", "awaiting_count": 1, "soonest_sla_at": "x"}],+ "talent": [],+ }+++def test_render_context_without_since_is_the_legacy_single_list() -> None:+ text = render_briefing_context(period_label="2026-09-11", today_data=_today(), activity=[])+ assert "PROPOSALS AWAITING DECISION:" in text+ assert "- item 1" in text and "- item 2" in text and "- item 3" in text+ assert "NEW SINCE LAST BRIEF" not in text+ assert "CARRIED OVER" not in text+ assert "HANDLED OVERNIGHT" not in text+++def test_render_context_splits_new_vs_carried_and_lists_handled() -> None:+ since = datetime.now(UTC) - timedelta(hours=24)+ handled = [{"kind": "routed", "summary": "Routed 'Acme renewal' to Dana", "at": "2026-09-11T07:00:00+00:00"}]+ text = render_briefing_context(+ period_label="2026-09-11", today_data=_today(), activity=[], since=since, handled=handled,+ )+ assert "NEEDS YOU — NEW SINCE LAST BRIEF:" in text+ assert "- item 1 (why now: SLA ends today) [next move: nudge]" in text+ assert "- item 2" not in text and "- item 3" not in text+ assert "CARRIED OVER: 2 older item(s) still open (oldest 3d, 1 flagged likely stale) — see /today" in text+ assert "HANDLED OVERNIGHT BY THE EXECUTIVE" in text+ assert "routed: Routed 'Acme renewal' to Dana" in text+ assert "PROPOSALS AWAITING DECISION:" not in text+ # Sections that are unchanged by the window still render.+ assert "DEPARTMENTS WITH RISK:" in text+ assert "PEOPLE WAITING ON YOU:" in text+++def test_render_context_with_since_and_nothing_new_still_reports_carried() -> None:+ since = datetime.now(UTC) - timedelta(hours=1)+ today = {"departments": [], "proposals": [_proposal(7, hours_ago=50)], "people": []}+ text = render_briefing_context(period_label="p", today_data=today, activity=[], since=since)+ assert "NEW SINCE LAST BRIEF" not in text+ assert "CARRIED OVER: 1 older item(s) still open (oldest 2d) — see /today" in text+++def test_eod_context_splits_and_lists_handled() -> None:+ since = datetime.now(UTC) - timedelta(hours=24)+ handled = [{"kind": "closed", "summary": "Resolved 'Stripe incident'", "at": "2026-09-11T12:00:00+00:00"}]+ text = _render_eod_context(+ period_label="2026-09-11", today_data=_today(), activity=[+ {"kind": "dm_sent", "summary": "DM'd Dana", "at": "2026-09-11T10:00:00+00:00"}+ ], since=since, handled=handled,+ )+ assert "WHAT OE DID TODAY" in text+ assert "ALERTS I HANDLED TODAY" in text and "closed: Resolved 'Stripe incident'" in text+ assert "STILL AWAITING DECISION — NEW SINCE LAST BRIEF:" in text+ assert "- item 1" in text and "- item 3" not in text+ assert "CARRIED OVER: 2 older item(s)" in text+ legacy = _render_eod_context(period_label="p", today_data=_today(), activity=[])+ assert "STILL AWAITING DECISION:" in legacy and "CARRIED OVER" not in legacydiff --git a/packages/core/tests/unit/test_briefing_narrative.py b/packages/core/tests/unit/test_briefing_narrative.pyindex 83128c73..7ca9e7c9 100644--- a/packages/core/tests/unit/test_briefing_narrative.py+++ b/packages/core/tests/unit/test_briefing_narrative.py@@ -78,3 +78,11 @@ def test_standalone_dm_prompt_enumerates_actionables() -> None:assert "What changed" in STANDALONE_BRIEF_SYSTEM# ...and must NOT assume a card list renders below it.assert "cards BELOW" not in STANDALONE_BRIEF_SYSTEM+++def test_standalone_dm_prompt_carries_older_items_as_one_line() -> None:+ lowered = STANDALONE_BRIEF_SYSTEM.lower()+ assert "never re-list carried items" in lowered+ assert "Handled overnight" in STANDALONE_BRIEF_SYSTEM+ assert "Top call" in STANDALONE_BRIEF_SYSTEM+ assert "delta" in lowereddiff --git a/packages/core/tests/unit/test_briefing_ranking.py b/packages/core/tests/unit/test_briefing_ranking.pyindex abad6fee..cde06b51 100644--- a/packages/core/tests/unit/test_briefing_ranking.py+++ b/packages/core/tests/unit/test_briefing_ranking.py@@ -159,3 +159,43 @@ def test_surfaced_reason_aligns_with_categorize() -> None:)assert ranking.categorize(**args) == "action"assert ranking.surfaced_reason(**args) is not None+++# --------------------------------------------------------------------------- #+# Review / deadline / trust adjustments+# --------------------------------------------------------------------------- #+++def test_score_penalises_likely_stale_and_low_trust_boosts_due_soon() -> None:+ from datetime import UTC, datetime, timedelta++ from openexecutive.briefing.ranking import score, watch_slug_from_tags++ base = score(severity="medium", routed_to_person_id=None)+ assert score(severity="medium", routed_to_person_id=None, review_verdict="likely_stale") == base - 30+ now = datetime.now(UTC)+ soon = (now + timedelta(hours=3)).isoformat()+ later = (now + timedelta(days=5)).isoformat()+ assert score(severity="medium", routed_to_person_id=None, due_at=soon, now=now) == base + 20+ assert score(severity="medium", routed_to_person_id=None, due_at=later, now=now) == base+ assert score(severity="medium", routed_to_person_id=None, due_at="garbage", now=now) == base+ assert score(severity="medium", routed_to_person_id=None, trust_score=1.0) == base+ assert score(severity="medium", routed_to_person_id=None, trust_score=0.0) == base - 10+ assert score(severity="medium", routed_to_person_id=None, trust_score=0.5) == base - 5+ assert watch_slug_from_tags(["external:stock", "external:stock-aapl"]) == "stock-aapl"+ assert watch_slug_from_tags(["external:rss"]) is None+ assert watch_slug_from_tags(["customer"]) is None+++def test_score_and_categorize_applies_trust_by_slug() -> None:+ from openexecutive.briefing.ranking import score_and_categorize++ alert = {+ "source": "stock", "severity": "high", "routed_to_person_id": None,+ "topic_tags": ["external:stock", "external:stock-aapl"],+ }+ s_full, _, _ = score_and_categorize(alert, trust_by_slug={"stock-aapl": 1.0})+ s_low, _, _ = score_and_categorize(alert, trust_by_slug={"stock-aapl": 0.2})+ s_none, _, _ = score_and_categorize(alert)+ assert s_full == s_none+ assert s_low == s_full - 8diff --git a/packages/core/tests/unit/test_executive_reflection.py b/packages/core/tests/unit/test_executive_reflection.pyindex cfe6c83f..2471b909 100644--- a/packages/core/tests/unit/test_executive_reflection.py+++ b/packages/core/tests/unit/test_executive_reflection.py@@ -419,3 +419,26 @@ def test_action_chips_registry_drift_still_passes() -> None:assert not unclassified, (f"Shift 5 changes left tools unclassified: {sorted(unclassified)}")+++def test_previous_reflection_artifact_reads_last_done_run(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ from openexecutive.workflows import persistence as wf_persistence+ from openexecutive.workflows.executive_reflection import _previous_reflection_artifact++ db = tmp_path / "runs.db"+ monkeypatch.setattr(wf_persistence, "DB_PATH", db)+ wf_persistence.initialize_runs_db(db)+ assert _previous_reflection_artifact() is None++ wf_persistence.create_run("r1", "executive_reflection", "Reflection day 1", {})+ wf_persistence.complete_run("r1", "**Acted on:** DM'd Dana")+ wf_persistence.create_run("r2", "morning_brief", "Brief", {})+ wf_persistence.complete_run("r2", "BRIEF TEXT")+ wf_persistence.create_run("r3", "executive_reflection", "Reflection running", {})+ assert _previous_reflection_artifact() == "**Acted on:** DM'd Dana"++ wf_persistence.create_run("r4", "executive_reflection", "Reflection empty", {})+ wf_persistence.complete_run("r4", "(no artifact)")+ assert _previous_reflection_artifact() is Nonediff --git a/packages/core/tests/unit/test_executive_research_scheduler.py b/packages/core/tests/unit/test_executive_research_scheduler.pyindex 900bbb6a..63c8dcae 100644--- a/packages/core/tests/unit/test_executive_research_scheduler.py+++ b/packages/core/tests/unit/test_executive_research_scheduler.py@@ -262,13 +262,13 @@ async def test_scan_runs_when_stale_despite_unchanged_state(await research_scheduler.run_watchlist_research_scan(db_path=db, store=MagicMock())assert calls["n"] == 1- # A tick just after still skips (well within the default 24h floor).+ # A tick just after still skips (well within the default 168h floor).await research_scheduler.run_watchlist_research_scan(db_path=db, store=MagicMock())assert calls["n"] == 1# A tick past the floor runs again, even though profile / initiatives /# watchlist are unchanged.- future = datetime.now(UTC) + timedelta(hours=25)+ future = datetime.now(UTC) + timedelta(hours=169)await research_scheduler.run_watchlist_research_scan(db_path=db, store=MagicMock(), now=future,)diff --git a/packages/core/tests/unit/test_morning_brief_workflow.py b/packages/core/tests/unit/test_morning_brief_workflow.pyindex 596913fc..a9c51cf6 100644--- a/packages/core/tests/unit/test_morning_brief_workflow.py+++ b/packages/core/tests/unit/test_morning_brief_workflow.py@@ -12,6 +12,7 @@ import pytestfrom openexecutive.api.routes import today as today_routefrom openexecutive.api.routes.today import ActivityResponse, TodayResponse+from openexecutive.briefing import brief_state, narrative_cachefrom openexecutive.briefing import narrative as briefing_narrativefrom openexecutive.workflows.morning_brief import (MorningBriefInput,@@ -19,6 +20,14 @@ from openexecutive.workflows.morning_brief import ()[email protected](autouse=True)+def _isolated_brief_state(tmp_path, monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(narrative_cache, "DB_PATH", tmp_path / "cache.db")+ # The "handled overnight" block reads the audit log; keep it empty and+ # deterministic here regardless of what other modules audited.+ monkeypatch.setattr(brief_state, "handled_since", lambda since, limit=20: [])++@pytest.mark.asyncioasync def test_morning_brief_uses_standalone_prompt(monkeypatch: pytest.MonkeyPatch,@@ -36,7 +45,7 @@ async def test_morning_brief_uses_standalone_prompt(lambda: TodayResponse(departments=[], people=[], proposals=[]),)monkeypatch.setattr(- today_route, "_build_activity", lambda limit: ActivityResponse(items=[])+ today_route, "_build_activity", lambda limit, since=None: ActivityResponse(items=[]))wf = MorningBriefWorkflow()@@ -50,3 +59,76 @@ async def test_morning_brief_uses_standalone_prompt(# And the synthesized body becomes the artifact.artifacts = [e for e in events if getattr(e, "type", "") == "artifact"]assert artifacts and "MORNING BRIEF BODY" in artifacts[0].content+++def _stub_aggregators(monkeypatch: pytest.MonkeyPatch) -> None:+ from openexecutive.api.routes.today import ProposalItem++ monkeypatch.setattr(+ today_route, "_build_today",+ lambda: TodayResponse(departments=[], people=[], proposals=[+ ProposalItem(+ alert_id=1, headline="Renew Acme", body="b", routed_to_person_id=None,+ suggested_action="", created_at="2026-01-01T00:00:00+00:00", topic_tags=[],+ ),+ ]),+ )+ monkeypatch.setattr(+ today_route, "_build_activity", lambda limit, since=None: ActivityResponse(items=[])+ )+++async def test_morning_brief_passes_window_and_emits_fingerprint(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ captured: dict[str, object] = {}++ async def _synth(**kw: object) -> str:+ captured.update(kw)+ return "FULL BRIEF"++ monkeypatch.setattr(briefing_narrative, "synthesize_briefing_narrative", _synth)+ _stub_aggregators(monkeypatch)++ events = [e async for e in MorningBriefWorkflow().run(MorningBriefInput(), MagicMock())]+ result = next(e for e in events if e.type == "result")+ assert result.data["suppressed"] is False+ assert len(result.data["brief_fingerprint"]) == 64+ assert captured["since"] is not None+ assert captured["handled"] == []+ assert any(e.type == "artifact" and e.content == "FULL BRIEF" for e in events)+++async def test_morning_brief_suppressed_when_fingerprint_unchanged(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ calls = {"n": 0}++ async def _synth(**kw: object) -> str:+ calls["n"] += 1+ return "FULL BRIEF"++ monkeypatch.setattr(briefing_narrative, "synthesize_briefing_narrative", _synth)+ _stub_aggregators(monkeypatch)++ first = [e async for e in MorningBriefWorkflow().run(MorningBriefInput(), MagicMock())]+ fp = next(e for e in first if e.type == "result").data["brief_fingerprint"]+ assert calls["n"] == 1+ # The scheduler records a delivery; the next run sees an identical fingerprint.+ brief_state.record_delivered("principal_brief_morning", fp, "FULL BRIEF")++ second = [e async for e in MorningBriefWorkflow().run(MorningBriefInput(), MagicMock())]+ result = next(e for e in second if e.type == "result")+ artifact = next(e for e in second if e.type == "artifact")+ assert result.data["suppressed"] is True+ assert calls["n"] == 1 # no model call+ assert artifact.content == "Nothing new since yesterday's brief — 1 item still waiting on you."++ # force_full bypasses the suppression.+ third = [+ e async for e in MorningBriefWorkflow().run(MorningBriefInput(force_full=True), MagicMock())+ ]+ assert next(e for e in third if e.type == "result").data["suppressed"] is False+ assert calls["n"] == 2diff --git a/packages/core/tests/unit/test_nudge_engine.py b/packages/core/tests/unit/test_nudge_engine.pyindex 129eba49..aa095651 100644--- a/packages/core/tests/unit/test_nudge_engine.py+++ b/packages/core/tests/unit/test_nudge_engine.py@@ -95,6 +95,7 @@ def _settings(**overrides: object) -> Settings:nudge_max_defer_days=3,nudge_max_per_scan=10,nudge_max_per_person_per_scan=2,+ nudge_max_per_scope=3,)base.update(overrides)return base # type: ignore[return-value]@@ -739,3 +740,61 @@ class TestHeartbeat:# Should be ~5 minutes in the futuredelta = run_at - nowassert timedelta(minutes=4, seconds=30) <= delta <= timedelta(minutes=5, seconds=30)+++# ---------------------------------------------------------------------------+# Per-scope cap (alert lifecycle): stop re-chasing the same item forever+# ---------------------------------------------------------------------------++class TestPerScopeCap:+ def test_count_nudges_for_scope_counts_done_only(self) -> None:+ now = _now()+ ids = [+ episodic.insert_scheduled_action(+ run_at=now.isoformat(), channel="slack_dm", channel_ref="U_X",+ intent_text="nudge", kind="proactive_nudge",+ scope_key="nudge:stalled:run_cap", status="pending",+ )+ for _ in range(4)+ ]+ with sqlite3.connect(str(episodic.DB_PATH)) as conn:+ for aid, status in zip(ids, ("done", "done", "cancelled", "pending"), strict=True):+ conn.execute("UPDATE scheduled_actions SET status = ? WHERE id = ?", (status, aid))+ # A non-nudge row sharing the scope_key (calendar / onboarding+ # namespaces also use scope_key) must not count.+ conn.execute(+ "UPDATE scheduled_actions SET kind = 'ad_hoc' WHERE id = ?", (ids[0],)+ )+ conn.commit()+ assert episodic.count_nudges_for_scope("nudge:stalled:run_cap") == 1+ assert episodic.count_nudges_for_scope("nudge:stalled:other") == 0++ @pytest.mark.asyncio+ async def test_scan_skips_scope_at_cap(self, monkeypatch: pytest.MonkeyPatch) -> None:+ _patch_settings(monkeypatch, nudge_max_per_scope=2)+ pid = _make_person(slack_user_id="U_ALICE", preferred="slack")+ now = _now()+ _insert_workflow_run(+ run_id="run_capped",+ awaiting_person_id=pid,+ awaiting_until=now + timedelta(hours=12),+ updated_at=now - timedelta(days=2),+ )+ # Two nudges already delivered for this scope, both outside the cooldown.+ for days_ago in (5, 3):+ episodic.insert_scheduled_action(+ run_at=(now - timedelta(days=days_ago)).isoformat(), channel="slack_dm",+ channel_ref="U_ALICE", intent_text="nudge", kind="proactive_nudge",+ scope_key="nudge:stalled:run_capped", status="done",+ )+ with sqlite3.connect(str(episodic.DB_PATH)) as conn:+ conn.execute(+ "UPDATE scheduled_actions SET created_at = ? WHERE status = 'done'",+ ((now - timedelta(days=3)).isoformat(),),+ )+ conn.commit()+ assert await nudge_engine.run_nudge_scan(now=now) == 0++ # Cap disabled → the chase resumes.+ _patch_settings(monkeypatch, nudge_max_per_scope=0)+ assert await nudge_engine.run_nudge_scan(now=now) == 1diff --git a/packages/core/tests/unit/test_principal_briefs.py b/packages/core/tests/unit/test_principal_briefs.pyindex 593e0f5c..7a23dfb3 100644--- a/packages/core/tests/unit/test_principal_briefs.py+++ b/packages/core/tests/unit/test_principal_briefs.py@@ -184,3 +184,77 @@ def test_has_pending_brief_detects_existing(runner.seed_principal_briefs()assert runner._has_pending_brief("principal_brief_morning") is Trueassert runner._has_pending_brief("principal_brief_eod") is True+++# ---------------------------------------------------------------------------+# Delivered-brief state: the runner records the fingerprint only on delivery+# ---------------------------------------------------------------------------+++def _fake_brief_workflow(fingerprint: str, artifact: str = "BRIEF"):+ from openexecutive.workflows.base import WorkflowEvent+ from openexecutive.workflows.morning_brief import MorningBriefInput, MorningBriefWorkflow++ class _Fake(MorningBriefWorkflow):+ async def run(self, inputs, store): # type: ignore[override]+ yield WorkflowEvent(type="result", data={"brief_fingerprint": fingerprint, "suppressed": False})+ yield WorkflowEvent(type="artifact", content=artifact)+ yield WorkflowEvent(type="done")++ def input_model(self): # type: ignore[override]+ return MorningBriefInput++ return _Fake()+++def _run_brief(tmp_path: Path, monkeypatch: pytest.MonkeyPatch, *, deliver_ok: bool) -> None:+ import asyncio++ from openexecutive.briefing import narrative_cache+ from openexecutive.workflows import persistence as wf_persistence++ db = tmp_path / "brief.db"+ _setup_isolated_db(db, monkeypatch)+ monkeypatch.setattr(narrative_cache, "DB_PATH", tmp_path / "cache.db")+ monkeypatch.setattr(wf_persistence, "DB_PATH", db)+ monkeypatch.setitem(WORKFLOW_REGISTRY, "morning_brief", _fake_brief_workflow("fp-123"))++ async def _deliver(text: str) -> tuple[bool, str]:+ return deliver_ok, "discord_dm → 1"++ monkeypatch.setattr(runner, "_deliver_to_principal", _deliver)+ monkeypatch.setattr(runner, "_enqueue_next_principal_brief", lambda kind, after: None)++ class _Store:+ def __init__(self, **kw): ...++ import openexecutive.knowledge.store as kstore++ monkeypatch.setattr(kstore, "ChromaDBStore", _Store)++ action_id = episodic.insert_scheduled_action(+ run_at=datetime.now(UTC).isoformat(), channel="__internal__", channel_ref="principal",+ intent_text="brief", kind="principal_brief_morning",+ )+ action = episodic.get_scheduled_action(action_id)+ assert action is not None+ asyncio.run(runner._run_principal_brief(action, datetime.now(UTC)))+++def test_run_principal_brief_records_fingerprint_after_delivery(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ from openexecutive.briefing import brief_state++ _run_brief(tmp_path, monkeypatch, deliver_ok=True)+ last = brief_state.last_delivered("principal_brief_morning")+ assert last is not None and last.input_hash == "fp-123" and last.narrative_text == "BRIEF"+++def test_run_principal_brief_does_not_record_on_delivery_failure(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ from openexecutive.briefing import brief_state++ _run_brief(tmp_path, monkeypatch, deliver_ok=False)+ assert brief_state.last_delivered("principal_brief_morning") is Nonediff --git a/packages/core/tests/unit/test_reflection_external_signals.py b/packages/core/tests/unit/test_reflection_external_signals.pyindex 00dd7bd7..78fa7d63 100644--- a/packages/core/tests/unit/test_reflection_external_signals.py+++ b/packages/core/tests/unit/test_reflection_external_signals.py@@ -101,3 +101,62 @@ def test_render_handles_pending_outcome_label() -> None:assert "pending" in rendered+++# --------------------------------------------------------------------------- #+# Yesterday's standup + review verdicts (alert lifecycle)+# --------------------------------------------------------------------------- #+++def test_render_includes_previous_reflection_block_and_caps_it() -> None:+ rendered = _render_reflection_context(+ period_label="2026-09-11",+ today_data=_empty_today(),+ activity=[],+ recent_alerts=[],+ external_signals=[],+ previous_reflection="**Acted on:** DM'd Dana about the renewal\n" + ("x" * 5000),+ )+ assert "YESTERDAY'S STANDUP (already handled — do not repeat):" in rendered+ assert "DM'd Dana about the renewal" in rendered+ assert len(rendered) < 2500+++def test_render_skips_previous_block_when_none() -> None:+ rendered = _render_reflection_context(+ period_label="2026-09-11",+ today_data=_empty_today(),+ activity=[],+ recent_alerts=[],+ external_signals=[],+ )+ assert "YESTERDAY'S STANDUP" not in rendered+++def test_render_open_alerts_carry_alert_id_and_review_verdict() -> None:+ rendered = _render_reflection_context(+ period_label="2026-09-11",+ today_data=_empty_today(),+ activity=[],+ recent_alerts=[+ {+ "alert_id": 42, "severity": "high", "headline": "Acme renewal at risk",+ "topic_tags": ["customer"], "review_verdict": "relevant",+ "review_note": "Dana has not replied in 3 days", "recommended_move": "nudge",+ },+ {"alert_id": 43, "severity": "low", "headline": "plain", "topic_tags": []},+ ],+ external_signals=[],+ )+ assert "alert_id=42 [high] Acme renewal at risk tags=customer review=relevant (Dana has not replied in 3 days) next=nudge" in rendered+ assert "alert_id=43 [low] plain tags=" in rendered+ assert "review=" not in rendered.split("alert_id=43")[1]+++def test_reflection_prompt_has_memory_rule_and_never_instructs_ack_alert() -> None:+ from openexecutive.workflows.executive_reflection import _build_reflection_system++ prompt = _build_reflection_system({"discord"}, True)+ assert "YESTERDAY'S STANDUP" in prompt+ assert "Do NOT re-act" in prompt+ assert "ack_alert" not in promptdiff --git a/packages/core/tests/unit/test_today_route.py b/packages/core/tests/unit/test_today_route.pyindex 81d409cd..1316ffe1 100644--- a/packages/core/tests/unit/test_today_route.py+++ b/packages/core/tests/unit/test_today_route.py@@ -15,8 +15,7 @@ from openexecutive.briefing import narrative as briefing_narrativefrom openexecutive.briefing import narrative_cachefrom openexecutive.departments import registry as dept_registryfrom openexecutive.departments import store as dept_store-from openexecutive.memory import decision_ledger-from openexecutive.memory import episodic+from openexecutive.memory import decision_ledger, episodicfrom openexecutive.people import insights_cachefrom openexecutive.people import registry as people_registryfrom openexecutive.people import store as people_store@@ -965,14 +964,16 @@ def test_proposals_recency_tiebreak_within_band(source="triage", external_id="newer", severity="high",headline="newer action", body="y", db_path=db,)+ # Both inside the action TTL (alerts/lifecycle.py) — a backdate past the+ # TTL would drop the row from the live queue rather than sort it.with sqlite3.connect(str(db)) as conn:conn.execute("UPDATE alerts SET created_at=? WHERE external_id=?",- ("2026-01-01T00:00:00+00:00", "older"),+ ((datetime.now(UTC) - timedelta(hours=2)).isoformat(), "older"),)conn.execute("UPDATE alerts SET created_at=? WHERE external_id=?",- ("2026-05-01T00:00:00+00:00", "newer"),+ ((datetime.now(UTC) - timedelta(hours=1)).isoformat(), "newer"),)conn.commit()@@ -1408,3 +1409,99 @@ def test_today_talent_empty_when_no_searches(client: TestClient) -> None:resp = client.get("/today")assert resp.status_code == 200assert resp.json()["talent"] == []+++# --------------------------------------------------------------------------- #+# Alert lifecycle on the read side (alerts/lifecycle.py)+# --------------------------------------------------------------------------- #+++def test_proposals_exclude_expired_resolved_and_past_ttl_rows(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ """Only live unread rows surface: swept (`expired`), Executive-closed+ (`resolved`) and unswept-but-past-TTL rows are all absent."""+ import sqlite3++ db = tmp_path / "lifecycle.db"+ _setup_isolated_db(db, monkeypatch)+ from openexecutive.alerts import lifecycle++ monkeypatch.setattr(lifecycle, "_ttl_settings", lambda: (3, 14))++ alert_store.insert_alert(+ source="triage", external_id="live", severity="high",+ headline="live item", body="x", db_path=db,+ )+ swept = alert_store.insert_alert(+ source="triage", external_id="swept", severity="high",+ headline="swept item", body="x", db_path=db,+ )+ resolved = alert_store.insert_alert(+ source="triage", external_id="resolved", severity="high",+ headline="resolved item", body="x", db_path=db,+ )+ alert_store.insert_alert(+ source="triage", external_id="old", severity="high",+ headline="past ttl item", body="x", db_path=db,+ )+ assert swept is not None and resolved is not None+ alert_store.set_status(swept, "expired", db_path=db)+ alert_store.set_status(resolved, "resolved", db_path=db)+ with sqlite3.connect(str(db)) as conn:+ conn.execute(+ "UPDATE alerts SET created_at=? WHERE external_id='old'",+ ((datetime.now(UTC) - timedelta(days=20)).isoformat(),),+ )+ conn.commit()++ headlines = [p["headline"] for p in _make_client().get("/today").json()["proposals"]]+ assert headlines == ["live item"]+++def test_proposals_carry_lifecycle_fields_and_demote_likely_stale(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ db = tmp_path / "fields.db"+ _setup_isolated_db(db, monkeypatch)++ stale = alert_store.insert_alert(+ source="triage", external_id="s", severity="high",+ headline="stale one", body="x", db_path=db,+ )+ fresh = alert_store.insert_alert(+ source="triage", external_id="f", severity="high",+ headline="fresh one", body="x", db_path=db,+ )+ folded = alert_store.insert_alert(+ source="triage", external_id="dup", severity="high",+ headline="dup", body="x", db_path=db,+ )+ assert stale is not None and fresh is not None and folded is not None+ alert_store.set_review(+ stale, verdict="likely_stale", note="no activity in 9 days",+ recommended_move="close", db_path=db,+ )+ alert_store.set_review(+ fresh, verdict="relevant", note="Dana replied overnight",+ recommended_move="nudge", why_now="SLA ends today",+ due_at=(datetime.now(UTC) + timedelta(hours=6)).isoformat(), db_path=db,+ )+ alert_store.mark_superseded(folded, fresh, db_path=db)++ proposals = _make_client().get("/today").json()["proposals"]+ by_headline = {p["headline"]: p for p in proposals}+ assert set(by_headline) == {"stale one", "fresh one"}+ assert proposals[0]["headline"] == "fresh one" # due-soon bonus + stale penalty+ f = by_headline["fresh one"]+ assert f["review_verdict"] == "relevant"+ assert f["review_note"] == "Dana replied overnight"+ assert f["recommended_move"] == "nudge"+ assert f["why_now"] == "SLA ends today"+ assert f["due_at"] is not None+ assert f["superseded_count"] == 1+ assert f["occurrence_count"] == 2+ assert f["last_reviewed_at"] is not None+ s = by_headline["stale one"]+ assert s["review_verdict"] == "likely_stale"+ assert s["score"] < f["score"]diff --git a/packages/ui/src/components/Briefing.tsx b/packages/ui/src/components/Briefing.tsxindex 10e1e60b..0c101266 100644--- a/packages/ui/src/components/Briefing.tsx+++ b/packages/ui/src/components/Briefing.tsx@@ -8,10 +8,14 @@ import remarkGfm from "remark-gfm";import {ackAlert,approveDecision,+ bulkAckAlerts,getToday,rejectDecision,+ reopenAlert,+ reviewAlerts,type CandidateStage,type DepartmentBriefItem,+ type HandledItem,type InFlightItem,type OnboardingBriefItem,type PersonBriefItem,@@ -49,6 +53,50 @@ const NARRATIVE_HEAD_BULLETS = 2;// with a Show more/less toggle, so the "Needs you" queue stays scannable.const LONG_BODY_CHARS = 180;+// "Needs you" shows this many cards after "Start here" before a Show-more+// toggle takes over — a queue, not a wall.+const NEEDS_YOU_VISIBLE = 8;+// Bulk-dismiss cutoffs (days) offered under each lane.+const NEEDS_YOU_DISMISS_OLDER_THAN_DAYS = 7;+const MONITORING_DISMISS_OLDER_THAN_DAYS = 3;++// Compact age label ("3h", "9d") for a card chip; "" for an unparseable stamp.+function ageLabel(iso: string | null | undefined, now: Date = new Date()): string {+ if (!iso) return "";+ const t = Date.parse(iso);+ if (Number.isNaN(t)) return "";+ const mins = Math.max(0, Math.round((now.getTime() - t) / 60000));+ if (mins < 60) return `${mins}m`;+ const hours = Math.round(mins / 60);+ if (hours < 48) return `${hours}h`;+ return `${Math.round(hours / 24)}d`;+}++// Whole days between now and an ISO stamp: 0 = due within the day, negative =+// past (floor, so an 11-hour-old deadline is -1 → "overdue", never "due today").+// null if unparseable.+function daysUntil(iso: string | null | undefined, now: Date = new Date()): number | null {+ if (!iso) return null;+ const t = Date.parse(iso);+ if (Number.isNaN(t)) return null;+ return Math.floor((t - now.getTime()) / 86400000);+}++// Ids of proposals older than `days` — what the bulk "Dismiss older than"+// footer sends: explicit ids from the caller's own lane (visible cards and+// those behind "Show more" alike), never a server-side age sweep, which would+// also hit teammates' routed items.+function olderThan(proposals: ProposalItem[], days: number, now: Date = new Date()): number[] {+ const cutoff = now.getTime() - days * 86400000;+ return proposals+ .filter((p) => {+ // Same age anchor as the server's TTL: a re-firing situation is not old.+ const t = Date.parse(p.last_seen_at ?? p.created_at);+ return !Number.isNaN(t) && t < cutoff;+ })+ .map((p) => p.alert_id);+}+interface BriefingProps {// Called when the user clicks a briefing item to continue the thread// in chat. The parent (usually the root page) is expected to switch@@ -387,6 +435,7 @@ const STAT_TONES: Record<StatTone, string> = {// ids and the `id={…}` attributes on the sections stay in sync.const SECTION_IDS = {needsYou: "sec-needs-you",+ handled: "sec-handled",inFlight: "sec-in-flight",monitoring: "sec-monitoring",departments: "sec-departments",@@ -415,6 +464,7 @@ function scrollToFirstVisible(ids: string[]): void {// dropped; an empty result renders an "All clear" pill at the call site.function briefingStats(args: {needsYou: number;+ handledOvernight: number;peopleOverdue: number;peopleNeedReply: number;deptAtRisk: number;@@ -426,6 +476,10 @@ function briefingStats(args: {const peopleTargets = [SECTION_IDS.people];if (args.needsYou > 0)pills.push({ label: `${args.needsYou} need${args.needsYou === 1 ? "s" : ""} you`, tone: "indigo", targetIds: [SECTION_IDS.needsYou] });+ // What the Executive already did on its own — shown right after the ask,+ // so the first read is "N need you, it handled M" (trust + relief).+ if (args.handledOvernight > 0)+ pills.push({ label: `Executive handled ${args.handledOvernight} overnight`, tone: "sky", targetIds: [SECTION_IDS.handled] });if (args.peopleOverdue > 0)pills.push({ label: `${args.peopleOverdue} overdue`, tone: "rose", targetIds: peopleTargets });if (args.peopleNeedReply > 0)@@ -447,6 +501,118 @@ function briefingStats(args: {return pills;}+// Lifecycle presentation for one proposal card — the review-driven pieces the+// card composes: the one-line "what changed since you last looked", the chip+// row (age, seen ×N, why-now / due, likely-stale, folded-in, draft-ready), the+// muted "Reviewed <ago>" footer, and the single recommended move as a control.+// A pure builder (no hooks) so ProposalCard stays a layout function.+function buildProposalLifecycle({+ proposal,+ assignee,+ onContinue,+ busy,+}: {+ proposal: ProposalItem;+ assignee: PersonBriefItem | null | undefined;+ onContinue?: (p: string) => void;+ busy: boolean;+}): {+ reviewLine: React.ReactNode;+ lifecycleRow: React.ReactNode;+ reviewedFooter: React.ReactNode;+ moveButton: React.ReactNode;+} {+// Lifecycle signals from the Executive's review (alerts/review.py) and the+// coalescing pipeline: the one-line "what changed since you last looked",+// then chips — age, seen ×N, why-now / deadline, likely-stale, folded-in,+// updated — and a muted "Reviewed <ago>" footer.+const verdict = proposal.review_verdict ?? "";+const isLikelyStale = verdict === "likely_stale";+const age = ageLabel(proposal.created_at);+const dueIn = daysUntil(proposal.due_at);+const reviewLine = proposal.review_note ? (+ <p className={`mb-1.5 text-xs leading-snug ${isLikelyStale ? "text-amber-300" : "text-fg-muted"}`}>+ <span className="text-[10px] uppercase tracking-wide mr-1">+ {isLikelyStale ? "Likely stale" : verdict === "changed" ? "Updated" : "Since you last looked"}+ </span>+ {proposal.review_note}+ </p>+) : null;+const lifecycleChips: { label: string; cls: string; title?: string }[] = [];+if (age) lifecycleChips.push({ label: age, cls: "text-fg-subtle border-line", title: `Raised ${new Date(proposal.created_at).toLocaleString()}` });+if ((proposal.occurrence_count ?? 1) > 1)+ lifecycleChips.push({+ label: `seen ×${proposal.occurrence_count}`,+ cls: "text-fg-muted border-line",+ title: proposal.last_seen_at ? `Last seen ${ageLabel(proposal.last_seen_at)} ago` : undefined,+ });+if (proposal.why_now || dueIn != null) {+ const due = dueIn == null ? "" : dueIn < 0 ? "overdue" : dueIn === 0 ? "due today" : `due in ${dueIn}d`;+ lifecycleChips.push({+ label: [proposal.why_now, due].filter(Boolean).join(" · "),+ cls: "bg-amber-500/15 text-amber-300 border-amber-500/30",+ });+}+if (isLikelyStale && !proposal.review_note)+ lifecycleChips.push({ label: "Likely stale", cls: "bg-amber-500/15 text-amber-300 border-amber-500/30" });+if ((proposal.superseded_count ?? 0) > 0)+ lifecycleChips.push({ label: `${proposal.superseded_count} folded in`, cls: "text-fg-muted border-line" });+if (verdict === "changed" && !proposal.review_note)+ lifecycleChips.push({ label: "Updated by the Executive", cls: "text-sky-300 border-sky-500/30" });+if (verdict === "drafted")+ lifecycleChips.push({ label: "Draft ready in your queue", cls: "bg-amber-500/15 text-amber-300 border-amber-500/30" });+const lifecycleRow = lifecycleChips.length > 0 ? (+ <div className="mb-1.5 flex flex-wrap gap-1">+ {lifecycleChips.map((c) => (+ <span key={c.label} title={c.title} className={`inline-block px-1.5 py-0.5 rounded border text-[10px] ${c.cls}`}>+ {c.label}+ </span>+ ))}+ </div>+) : null;+const reviewedFooter = proposal.last_reviewed_at ? (+ <p className="mt-1 text-[10px] text-fg-subtle">+ Reviewed {ageLabel(proposal.last_reviewed_at)} ago+ {verdict && verdict !== "likely_stale" ? ` · ${verdict}` : ""}+ </p>+) : null;+// The single recommended move, as the primary control on the card. Route /+// escalate / draft already happened server-side (the card shows their+// trace); nudge and a suggested workflow are the two the user completes.+const moveButton = (() => {+ const move = proposal.recommended_move ?? "";+ if (move === "nudge" && onContinue) {+ const who = assignee?.full_name ?? "the owner";+ return (+ <button+ type="button"+ onClick={() => onContinue(+ `Nudge ${who} about this item — it has gone quiet: ${proposal.headline}\n\n` ++ `Send a short, friendly check-in via message_person and tell me what you sent.`,+ )}+ disabled={busy}+ className="text-xs font-medium text-indigo-300 hover:text-indigo-200 px-2 py-1 rounded border border-indigo-500/30 transition-colors disabled:opacity-50"+ >+ ↪ Nudge {assignee?.full_name?.split(" ")[0] ?? "owner"}+ </button>+ );+ }+ if (move === "suggest_workflow" && proposal.suggested_workflow) {+ return (+ <Link+ href={`/jobs/${proposal.suggested_workflow}`}+ onClick={(e) => e.stopPropagation()}+ className="text-xs font-medium text-indigo-300 hover:text-indigo-200 px-2 py-1 rounded border border-indigo-500/30 transition-colors"+ >+ ▶ Run {proposal.suggested_workflow.replace(/_/g, " ")}+ </Link>+ );+ }+ return null;+})();+ return { reviewLine, lifecycleRow, reviewedFooter, moveButton };+}+function ProposalCard({proposal,people,@@ -621,8 +787,14 @@ function ProposalCard({// document layout + amber badge), not a user-meaningful topic — hide it// from the tag pills so it doesn't double up with the "Artifact" badge.const visibleTags = proposal.topic_tags.filter((t) => t !== "artifact");+ const { reviewLine, lifecycleRow, reviewedFooter, moveButton } = buildProposalLifecycle({+ proposal, assignee, onContinue, busy,+ });+ const isLikelyStale = (proposal.review_verdict ?? "") === "likely_stale";const meta = (<>+ {reviewLine}+ {lifecycleRow}{suggestedActionBlock}{surfacedNote}{visibleTags.length > 0 && (@@ -646,6 +818,7 @@ function ProposalCard({})}</div>)}+ {reviewedFooter}</>);// Card splits into a content area and an action row living as siblings@@ -806,6 +979,7 @@ function ProposalCard({explicit so the affordance is discoverable. Hidden on thestandalone /today route (no onContinue). */}<div className="flex items-center gap-2">+ {moveButton}{onContinue && (<buttontype="button"@@ -840,7 +1014,11 @@ function ProposalCard({type="button"onClick={() => onDismiss(proposal)}disabled={busy}- className="text-xs text-fg-muted hover:text-rose-300 px-2 py-1 rounded transition-colors disabled:opacity-50 disabled:cursor-not-allowed"+ className={`text-xs px-2 py-1 rounded transition-colors disabled:opacity-50 disabled:cursor-not-allowed ${+ isLikelyStale+ ? "font-medium text-amber-300 hover:text-amber-200 border border-amber-500/30"+ : "text-fg-muted hover:text-rose-300"+ }`}>✕ Dismiss</button>@@ -1259,13 +1437,16 @@ function MonitoringPanel({proposals,onContinue,onDismiss,+ onBulkDismiss,id,}: {proposals: ProposalItem[];onContinue?: (p: string) => void;onDismiss?: (p: ProposalItem) => void;+ onBulkDismiss?: (ids: number[]) => void;id?: string;}) {+ const staleIds = olderThan(proposals, MONITORING_DISMISS_OLDER_THAN_DAYS);if (proposals.length === 0) return null;return (<section id={id} className="rounded-xl border border-line bg-surface-elevated p-4">@@ -1282,6 +1463,87 @@ function MonitoringPanel({<MonitoringRow key={p.alert_id} proposal={p} onContinue={onContinue} onDismiss={onDismiss} />))}</div>+ {onBulkDismiss && staleIds.length > 0 && (+ <button+ type="button"+ onClick={() => onBulkDismiss(staleIds)}+ className="mt-2 text-[11px] text-fg-muted hover:text-rose-300 transition-colors"+ >+ ✕ Dismiss {staleIds.length} older than {MONITORING_DISMISS_OLDER_THAN_DAYS} days+ </button>+ )}+ </section>+ );+}++// Handled overnight — what the Executive's alert review did on its own since+// the last morning brief (routed, nudged, escalated, drafted, merged, closed,+// updated). Every autonomous close is reversible here (Undo → reopen), which+// is what makes the autonomy un-scary: visible, evidence-cited, one click back.+const HANDLED_KIND_LABEL: Record<string, string> = {+ closed: "Closed",+ routed: "Routed",+ nudged: "Nudged",+ escalated: "Escalated",+ drafted: "Drafted",+ merged: "Merged",+ suggested_workflow: "Suggested",+ changed: "Updated",+};++// Stable key for one handled row (an alert can appear twice in one pass —+// e.g. updated then closed — so the alert id alone is not unique).+function handledKey(h: HandledItem): string {+ return `${h.kind}-${h.at}-${h.alert_id ?? ""}`;+}++function HandledOvernightPanel({+ items,+ onReopen,+ undone,+}: {+ items: HandledItem[];+ onReopen?: (rowKey: string, alertId: number) => void;+ undone: Set<string>;+}) {+ if (items.length === 0) return null;+ return (+ <section id={SECTION_IDS.handled} className="rounded-xl border border-line bg-surface-elevated p-4">+ <div className="flex items-center gap-1.5 mb-1">+ <SectionHeading title="Handled overnight" count={items.length} icon="check" />+ <InfoTip align="left">+ Moves the Executive made on its own while reviewing open alerts —+ each one audited with its evidence. Undo brings an item back to+ your queue.+ </InfoTip>+ </div>+ <div className="max-h-[24rem] overflow-y-auto pr-1 divide-y divide-line">+ {items.map((h) => {+ const rowKey = handledKey(h);+ const canUndo = onReopen && h.alert_id != null && (h.kind === "closed" || h.kind === "merged");+ const isUndone = undone.has(rowKey);+ return (+ <div key={rowKey} className="py-2 flex items-start justify-between gap-2">+ <div className="min-w-0">+ <span className="mr-1.5 inline-block px-1.5 py-0.5 rounded border text-[10px] text-sky-300 border-sky-500/30">+ {HANDLED_KIND_LABEL[h.kind] ?? h.kind}+ </span>+ <span className={`text-xs ${isUndone ? "line-through text-fg-subtle" : "text-fg-muted"}`}>{h.summary}</span>+ <span className="ml-1.5 text-[10px] text-fg-subtle">{ageLabel(h.at)} ago</span>+ </div>+ {canUndo && !isUndone && (+ <button+ type="button"+ onClick={() => onReopen(rowKey, h.alert_id as number)}+ className="flex-shrink-0 text-[11px] text-fg-muted hover:text-indigo-300 transition-colors"+ >+ ↶ Undo+ </button>+ )}+ </div>+ );+ })}+ </div></section>);}@@ -1298,6 +1560,13 @@ export default function Briefing({ onContinue, showHeader = false, firstName }:// the click feels instant; the canonical state will be picked up by// the next /today fetch.const [actedAlertIds, setActedAlertIds] = useState<Set<number>>(new Set());+ // "Needs you" shows NEEDS_YOU_VISIBLE cards after "Start here"; the rest+ // sit behind one toggle so a long queue reads as a queue, not a wall.+ const [showAllNeedsYou, setShowAllNeedsYou] = useState(false);+ // "Re-check relevance" runs the Executive's review on demand.+ const [recheckBusy, setRecheckBusy] = useState(false);+ // Handled-rail rows undone this session (keyed per row, see handledKey).+ const [undoneRows, setUndoneRows] = useState<Set<string>>(new Set());// Re-pull /today after a server-side mutation (e.g. a decision approve/reject)// so derived data — the narrative header, per-person and department counts —@@ -1374,6 +1643,59 @@ export default function Briefing({ onContinue, showHeader = false, firstName }:}}, [actedAlertIds, refreshToday]);+ // Bulk dismiss: the footer under a lane sends explicit ids (the cards the+ // caller can see), never a server-side age sweep. Same optimistic-removal+ // + rollback pattern as the single-card handlers.+ const handleBulkDismiss = useCallback(async (ids: number[]) => {+ if (ids.length === 0) return;+ const prev = actedAlertIds;+ const next = new Set(prev);+ ids.forEach((id) => next.add(id));+ setActedAlertIds(next);+ try {+ await bulkAckAlerts({ status: "dismissed", alert_ids: ids });+ refreshToday();+ } catch (e) {+ setActedAlertIds(prev);+ // eslint-disable-next-line no-console+ console.error("Bulk dismiss failed", e);+ }+ }, [actedAlertIds, refreshToday]);++ // Re-check relevance: ask the Executive to review every open alert now+ // (route / escalate / draft / merge / resolve within authority), then+ // re-pull /today so the verdicts, chips and "handled" rail refresh.+ const handleRecheck = useCallback(async () => {+ setRecheckBusy(true);+ try {+ await reviewAlerts();+ refreshToday();+ } catch (e) {+ // eslint-disable-next-line no-console+ console.error("Alert review failed", e);+ } finally {+ setRecheckBusy(false);+ }+ }, [refreshToday]);++ // Undo an autonomous close from the "Handled overnight" rail. The rail is+ // rebuilt from the audit log on every fetch (the "closed" row persists after+ // a reopen), so a 409 "already open" after a reload counts as done.+ const handleReopen = useCallback(async (rowKey: string, alertId: number) => {+ try {+ await reopenAlert(alertId);+ setUndoneRows((prev) => new Set(prev).add(rowKey));+ refreshToday();+ } catch (e) {+ if (e instanceof Error && /409|already/i.test(e.message)) {+ setUndoneRows((prev) => new Set(prev).add(rowKey));+ return;+ }+ // eslint-disable-next-line no-console+ console.error("Reopen failed", e);+ }+ }, [refreshToday]);+// Approve-with-edits: user has tweaked the draft text and wants OE to// send exactly what they wrote (no LLM rephrasing). Same optimistic-// removal + ack pattern as plain approve; the chat seed instructs the@@ -1477,6 +1799,8 @@ export default function Briefing({ onContinue, showHeader = false, firstName }:// so mineProposals[0] is the sharpest.const startHereProposal = mineProposals[0] ?? null;const restProposals = mineProposals.slice(1);+ const staleNeedsYouIds = olderThan(mineProposals, NEEDS_YOU_DISMISS_OLDER_THAN_DAYS);+ const handledOvernight = today?.handled_overnight ?? [];// Status-strip inputs, all from data already computed above.const inFlightCount = today?.in_flight?.length ?? 0;@@ -1498,6 +1822,7 @@ export default function Briefing({ onContinue, showHeader = false, firstName }:const statPills: StatPill[] = today? briefingStats({needsYou: mineProposals.length,+ handledOvernight: handledOvernight.length,peopleOverdue,peopleNeedReply,deptAtRisk: deptAtRiskCount,@@ -1702,7 +2027,7 @@ export default function Briefing({ onContinue, showHeader = false, firstName }:emphasized/></div>- {restProposals.map((p) => (+ {(showAllNeedsYou ? restProposals : restProposals.slice(0, NEEDS_YOU_VISIBLE)).map((p) => (<ProposalCardkey={p.alert_id}proposal={p}@@ -1713,10 +2038,44 @@ export default function Briefing({ onContinue, showHeader = false, firstName }:onApproveWithEdits={handleApproveWithEdits}/>))}+ {restProposals.length > NEEDS_YOU_VISIBLE && (+ <button+ type="button"+ onClick={() => setShowAllNeedsYou((v) => !v)}+ className="w-full py-2 text-[11px] text-fg-muted hover:text-fg transition-colors"+ >+ {showAllNeedsYou+ ? "Show fewer"+ : `Show ${restProposals.length - NEEDS_YOU_VISIBLE} more`}+ </button>+ )}</div>) : !isQuiet ? (<p className="text-sm text-fg-muted py-3">Nothing waiting on you.</p>) : null}+ {/* Relief valves: clear the old tail in one click, or ask+ the Executive to re-judge everything right now. */}+ {(staleNeedsYouIds.length > 0 || mineProposals.length > 0) && (+ <div className="mt-2 flex flex-wrap items-center gap-3">+ {staleNeedsYouIds.length > 0 && (+ <button+ type="button"+ onClick={() => handleBulkDismiss(staleNeedsYouIds)}+ className="text-[11px] text-fg-muted hover:text-rose-300 transition-colors"+ >+ ✕ Dismiss {staleNeedsYouIds.length} older than {NEEDS_YOU_DISMISS_OLDER_THAN_DAYS} days+ </button>+ )}+ <button+ type="button"+ onClick={handleRecheck}+ disabled={recheckBusy}+ className="text-[11px] text-fg-muted hover:text-indigo-300 transition-colors disabled:opacity-50"+ >+ {recheckBusy ? "⟳ Re-checking…" : "⟳ Re-check relevance"}+ </button>+ </div>+ )}</details></section>@@ -1858,10 +2217,16 @@ export default function Briefing({ onContinue, showHeader = false, firstName }:clients={today.practice_clients ?? []}id={SECTION_IDS.practice}/>+ <HandledOvernightPanel+ items={handledOvernight}+ onReopen={handleReopen}+ undone={undoneRows}+ /><MonitoringPanelproposals={monitoringProposals}onContinue={onContinue}onDismiss={handleDismiss}+ onBulkDismiss={handleBulkDismiss}id={SECTION_IDS.monitoring}/></div>diff --git a/packages/ui/src/lib/api.ts b/packages/ui/src/lib/api.tsindex 63aed833..5fdc423f 100644--- a/packages/ui/src/lib/api.ts+++ b/packages/ui/src/lib/api.ts@@ -2501,6 +2501,35 @@ export interface ProposalItem {// /decisions endpoints (which book/cancel server-side) instead of the// ack-and-handoff-to-chat flow. Null/absent for ordinary alert proposals.decision_instance_id?: number | null;+ // Alert lifecycle (alerts/lifecycle.py + alerts/review.py). All optional so+ // older API builds and test mocks keep compiling.+ // Coalescing: how many times the same situation re-fired, and when last.+ occurrence_count?: number;+ last_seen_at?: string | null;+ // The Executive's latest review: verdict ('' | relevant | changed |+ // likely_stale | drafted | routed | merged | resolved | stale — the last+ // two only on closed rows), the one-line "what changed+ // since you last looked", the move the card should lead with, a short+ // "why now", and a deadline when one exists.+ last_reviewed_at?: string | null;+ review_verdict?: string;+ review_note?: string;+ recommended_move?: string;+ why_now?: string;+ due_at?: string | null;+ // Rows the review folded into this one (merge).+ superseded_count?: number;+ // Registry workflow the review suggested as the next step ('' = none).+ suggested_workflow?: string;+}++// One autonomous alert-review move since the last delivered morning brief+// (routed / nudged / escalated / drafted / merged / closed / changed).+export interface HandledItem {+ kind: string;+ summary: string;+ at: string;+ alert_id?: number | null;}export interface InFlightItem {@@ -2581,6 +2610,9 @@ export interface Today {// vs "across the team". Null when no caller could be resolved.// Optional to keep existing test mocks and older API builds compiling.caller_person_id?: number | null;+ // What the Executive's alert review did on its own since the last morning+ // brief — the "handled overnight" rail with Undo. Optional/default-empty.+ handled_overnight?: HandledItem[];}export async function getToday(): Promise<Today> {@@ -2595,15 +2627,62 @@ export async function getToday(): Promise<Today> {export async function ackAlert(alertId: number,status: "read" | "ack" | "dismissed",+ opts: { muteTopic?: string | boolean } = {},): Promise<void> {+ const body: Record<string, unknown> = { status };+ if (opts.muteTopic) body.mute_topic = opts.muteTopic;const res = await fetch(`${API_BASE}/alerts/${alertId}/ack`, {method: "POST",headers: { "content-type": "application/json" },- body: JSON.stringify({ status }),+ body: JSON.stringify(body),});if (!res.ok) throw new Error(`Failed to ack alert ${alertId}: ${res.statusText}`);}+// Groom many alerts at once. The briefing sends explicit ids (it knows which+// cards the caller owns); `older_than_days` / `category` are for ops use.+export async function bulkAckAlerts(body: {+ status: "ack" | "dismissed";+ alert_ids?: number[];+ older_than_days?: number;+ category?: "action" | "monitoring";+}): Promise<{ count: number }> {+ const res = await fetch(`${API_BASE}/alerts/bulk-ack`, {+ method: "POST",+ headers: { "content-type": "application/json" },+ body: JSON.stringify(body),+ });+ if (!res.ok) throw new Error(`Failed to bulk-ack alerts: ${res.statusText}`);+ return res.json();+}++// Undo for an autonomous close / expiry / dismiss: back to the live queue.+export async function reopenAlert(alertId: number): Promise<void> {+ const res = await fetch(`${API_BASE}/alerts/${alertId}/reopen`, { method: "POST" });+ // 409 = already open (not an Undo target any more); callers treat it as done.+ if (!res.ok) throw new Error(`Failed to reopen alert ${alertId}: ${res.status} ${res.statusText}`);+}++export interface AlertReviewSummary {+ reviewed: number;+ closed: number;+ changed: number;+ routed: number;+ nudged: number;+ escalated: number;+ drafted: number;+ merged: number;+ suggested: number;+ annotated: number;+}++// Run the Executive's relevance review on demand ("Re-check relevance").+export async function reviewAlerts(): Promise<AlertReviewSummary> {+ const res = await fetch(`${API_BASE}/alerts/review`, { method: "POST" });+ if (!res.ok) throw new Error(`Failed to run alert review: ${res.statusText}`);+ return res.json();+}+// Recent self-initiated Executive activity for the briefing rail.// `kind` is a coarse classifier the UI uses to pick an icon/verb:// "dm_sent" | "email_sent" | "nudge_sent" | "cadence_sent" |