Skip to content

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

Make "Handled overnight" report completed moves, first person, with proof

Claudec08d0a225ee0
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 205299ab..d3a989f4 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -104,6 +104,28 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
ranking and is shown to the review as evidence.
### Changed
+- **"Handled overnight" now says what the Executive actually did, and says
+ it with some pride.** The briefing rail no longer lists the review's
+ `changed` verdict (an "Updated '<old headline>' — …" row): that rewrite
+ leaves the alert open in "Needs you", where the card already shows the
+ note, so the row double-reported it and called it done. Rewritten items
+ now render in the morning brief and end-of-day digest as a REWRITTEN block
+ under "what changed" (`brief_state.rewritten_since`), and a rewrite alone
+ still un-suppresses the brief. Each remaining `/today.handled_overnight`
+ row is structured (headline, target, detail, outcome, evidence_ref,
+ event_type, and the alert's `status` now) instead of one truncated
+ sentence; routed / nudged audit summaries name the person rather than
+ "person 12", and the nudge bookkeeping marker is stripped for display.
+ The rail reads first-person: a count-only heading ("Since your last
+ brief: N off your plate, N in others' hands, N waiting on you"),
+ escalations first, one row per alert ("Resolved *X* — evidence",
+ "Dismissed *X* as stale — …", "Handed *X* to Dana Kim", "Chased Dana Kim
+ on *X*"), five rows before "Show more", every row linking its evidence to
+ a pre-filtered `/audit` (the audit page now reads `event_type` / `q` from
+ the query string) and a still-open row jumping to its card. Undo is only
+ offered while the close still stands; a close already undone shows
+ "Reopened" after a reload. A quiet night renders one honest line instead
+ of nothing.
- **Specialists are told what departments watch.** The research context
every specialist receives now carries a `DEPARTMENT WATCH INTERESTS`
block (each department's watched entities), and the grounding rule
diff --git a/packages/core/openexecutive/alerts/review.py b/packages/core/openexecutive/alerts/review.py
index 1294c0f2..6c394b0c 100644
--- a/packages/core/openexecutive/alerts/review.py
+++ b/packages/core/openexecutive/alerts/review.py
@@ -578,6 +578,16 @@ class _MoveContext:
and self.summary.moves_used < self.settings.max_moves_per_scan
)
+ def person_label(self, person_id: int) -> str:
+ """Roster name for an audit summary; ``person <id>`` when unknown."""
+ for p in self.evidence.get("roster") or []:
+ try:
+ if int(p["id"]) == person_id and p.get("name"):
+ return str(p["name"])
+ except (KeyError, TypeError, ValueError):
+ continue
+ return f"person {person_id}"
+
def _close_or_annotate(ctx: _MoveContext) -> str:
"""resolved / stale: close only on high confidence with named evidence,
@@ -665,7 +675,8 @@ def _apply_merge(ctx: _MoveContext) -> bool:
recommended_move="merge", reviewed_at=ctx.now.isoformat(), db_path=ctx.db_path,
)
_audit(EVENT_MERGED, f"Merged '{alert.headline[:80]}' into '{survivor.headline[:80]}'",
- {**ctx.base_details, "superseded_by_alert_id": survivor.id})
+ {**ctx.base_details, "superseded_by_alert_id": survivor.id,
+ "superseded_by_headline": survivor.headline[:160]})
ctx.summary.merged += 1
return True
@@ -722,8 +733,10 @@ async def _apply_route(ctx: _MoveContext) -> None:
ctx.summary.routed += 1
ctx.move_taken = "route"
ctx.label = "routed"
- _audit(EVENT_ROUTED, f"Routed '{alert.headline[:80]}' to person {target} ({detail})",
- {**ctx.base_details, "target_person_id": target, "detail": detail, "proposed": proposed})
+ who = ctx.person_label(target)
+ _audit(EVENT_ROUTED, f"Routed '{alert.headline[:80]}' to {who} ({detail})",
+ {**ctx.base_details, "target_person_id": target, "target_person_name": who,
+ "detail": detail, "proposed": proposed})
else:
_audit(EVENT_REVIEWED, f"Route attempt failed for '{alert.headline[:80]}': {detail}",
{**ctx.base_details, "target_person_id": target, "error": detail})
@@ -746,8 +759,10 @@ async def _apply_nudge(ctx: _MoveContext) -> None:
if ok:
ctx.summary.nudged += 1
ctx.move_taken = "nudge"
- _audit(EVENT_NUDGED, f"[alert {ctx.alert_id}] Nudged person {target} about '{alert.headline[:80]}'",
- {**ctx.base_details, "target_person_id": target, "detail": detail})
+ who = ctx.person_label(target)
+ _audit(EVENT_NUDGED, f"[alert {ctx.alert_id}] Nudged {who} about '{alert.headline[:80]}'",
+ {**ctx.base_details, "target_person_id": target, "target_person_name": who,
+ "detail": detail})
async def _apply_escalate(ctx: _MoveContext) -> None:
diff --git a/packages/core/openexecutive/api/routes/today.py b/packages/core/openexecutive/api/routes/today.py
index 9fb6aa03..ddf55451 100644
--- a/packages/core/openexecutive/api/routes/today.py
+++ b/packages/core/openexecutive/api/routes/today.py
@@ -156,23 +156,96 @@ class ProposalItem(BaseModel):
suggested_workflow: str = ""
+def _as_int(raw: Any) -> int | None:
+ try:
+ return int(raw) if raw is not None else None
+ except (TypeError, ValueError):
+ return None
+
+
+def _alert_status_now(alert_id: int | None) -> str:
+ """Current lifecycle state of the alert a handled row touched."""
+ if alert_id is None:
+ return ""
+ try:
+ from openexecutive.alerts.store import get_alert
+
+ alert = get_alert(alert_id)
+ except Exception:
+ logger.debug("today: alert status lookup failed for %s", alert_id, exc_info=True)
+ return ""
+ if alert is None:
+ return ""
+ if alert.superseded_by_alert_id is not None:
+ return "merged"
+ if alert.status in {"resolved", "dismissed", "expired"}:
+ return alert.status
+ return "open"
+
+
+# Which audit-details keys fill a handled row's `target` and `detail`, per
+# kind. `headline` defaults to the alert headline; watch rows use the slug.
+_HANDLED_TARGET_KEY: dict[str, str] = {
+ "routed": "target_person_name",
+ "nudged": "target_person_name",
+ "escalated": "new_severity",
+ "drafted": "draft_title",
+ "merged": "superseded_by_headline",
+ "suggested_workflow": "workflow_name",
+}
+_HANDLED_DETAIL_KEYS: dict[str, tuple[str, ...]] = {
+ "closed": ("evidence",),
+ "escalated": ("evidence",),
+ "watching": ("rationale", "reason"),
+ "stopped_watching": ("rationale", "reason"),
+}
+_WATCH_KINDS = frozenset({"watching", "stopped_watching"})
+
+
+def _handled_outcome(kind: str, details: dict[str, Any]) -> str:
+ """resolved | dismissed for a close, proposed for a gated route, else ''."""
+ if kind == "closed":
+ return str(details.get("new_status") or "")
+ if kind == "routed" and details.get("proposed"):
+ return "proposed"
+ return ""
+
+
+def _handled_item(h: dict[str, Any]) -> HandledItem:
+ """One structured rail row from a `brief_state.handled_since` entry."""
+ kind = str(h["kind"])
+ raw_details = h.get("details")
+ details: dict[str, Any] = raw_details if isinstance(raw_details, dict) else {}
+ alert_id = _as_int(h.get("alert_id"))
+ headline = details.get("slug") if kind in _WATCH_KINDS else details.get("headline")
+ target_key = _HANDLED_TARGET_KEY.get(kind)
+ target = details.get(target_key) if target_key else None
+ detail = next(
+ (str(details[k]) for k in _HANDLED_DETAIL_KEYS.get(kind, ()) if details.get(k)), ""
+ )
+ return HandledItem(
+ kind=kind,
+ summary=str(h["summary"]),
+ at=str(h["at"]),
+ alert_id=alert_id,
+ event_type=str(h.get("event_type") or ""),
+ headline=str(headline) if headline else None,
+ target=str(target) if target else None,
+ detail=detail,
+ outcome=_handled_outcome(kind, details),
+ evidence_ref=str(details.get("evidence_ref") or ""),
+ superseded_by_alert_id=_as_int(details.get("superseded_by_alert_id")),
+ status=_alert_status_now(alert_id),
+ )
+
+
def _handled_overnight(now: datetime) -> list[HandledItem]:
- """What the alert review did since the last delivered morning brief."""
+ """What the alert review completed 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
+ return [_handled_item(h) for h in brief_state.handled_since(since, limit=20)]
except Exception:
logger.debug("today: handled_overnight unavailable", exc_info=True)
return []
@@ -267,6 +340,34 @@ class HandledItem(BaseModel):
# The alert the move touched, when known — lets the UI offer Undo
# (POST /alerts/{id}/reopen) right next to the "handled" row.
alert_id: int | None = None
+ # Structured view of the same audit row so the rail can render "who /
+ # what / why" instead of one truncated sentence. All additive; `summary`
+ # stays the fallback line.
+ # Raw audit event type, for a pre-filtered /audit deep link.
+ event_type: str = ""
+ # The alert's headline when the move was made (a watch's slug for the
+ # watching / stopped_watching kinds).
+ headline: str | None = None
+ # Who or what the move went to: a person's name (routed / nudged), the
+ # survivor headline (merged), the new severity (escalated), the draft
+ # title (drafted) or the workflow name (suggested_workflow).
+ target: str | None = None
+ # The "why": the cited evidence (closed / escalated) or the watch
+ # policy's reason (watching / stopped_watching).
+ detail: str = ""
+ # Finer than `kind`: "resolved" | "dismissed" for a close (a dismissal is
+ # a judgment call and must read differently), "proposed" for a route
+ # that went through the authority gate instead of a DM, else "".
+ outcome: str = ""
+ # Server-minted evidence ref a close cited (S1 / R2 / A3), else "".
+ evidence_ref: str = ""
+ # The survivor a merge folded this alert into, for collapsing the pair.
+ superseded_by_alert_id: int | None = None
+ # The alert's status NOW ("open" | "resolved" | "dismissed" | "expired" |
+ # "merged"), "" when there is no alert. The rail is rebuilt from the audit
+ # log on every fetch, so this is what tells the UI a close was already
+ # undone (offer "Reopened", not another Undo).
+ status: str = ""
class TodayResponse(BaseModel):
diff --git a/packages/core/openexecutive/architecture/architecture-facts.yaml b/packages/core/openexecutive/architecture/architecture-facts.yaml
index 68e897d2..cf38884d 100644
--- a/packages/core/openexecutive/architecture/architecture-facts.yaml
+++ b/packages/core/openexecutive/architecture/architecture-facts.yaml
@@ -472,8 +472,13 @@ routing:
`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`.
+ `_changed` — `briefing.brief_state.handled_since` reads all but
+ `_changed` for the brief's "Handled overnight" block and
+ `/today.handled_overnight` (a rewrite leaves the alert open, so it is
+ reported under "what changed" via `brief_state.rewritten_since`, never as
+ done). Routed / nudged summaries name the roster person
+ (`_MoveContext.person_label`, `target_person_name` in details); merged
+ details carry `superseded_by_headline`.
artifact_tools: |
`draft_artifact(title, document, why_interesting, source_urls?,
severity?)` (openexecutive.orchestrator.artifact_tools) lets the
@@ -1268,10 +1273,18 @@ today:
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`
+ COMPLETED autonomous moves since the last delivered morning brief
+ (`brief_state.handled_since`, `changed` excluded) as structured rows:
+ kind, summary, at, alert_id, event_type, headline, target, detail,
+ outcome (resolved | dismissed | proposed), evidence_ref,
+ superseded_by_alert_id and `status` (the alert's state NOW, so an undone
+ close renders "Reopened" rather than a second Undo). The UI's handled
+ rail is first-person and count-based ("Since your last brief: N off your
+ plate, N in others' hands, N waiting on you"), escalations first, one
+ row per alert, five before "Show more", each row linking its evidence to
+ `/audit?event_type=…&q=…` and a still-open row to `#alert-<id>`; Undo →
+ `POST /alerts/{id}/reopen`. The "Executive handled N overnight" status
+ pill is unchanged. 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
@@ -2265,8 +2278,8 @@ 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. 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`."
+ - "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 REWRITTEN block lists carried items the review rewrote in the window (`brief_state.rewritten_since`: verdict `changed`, still open — reported under 'what changed', never as done); a HANDLED OVERNIGHT block lists the alert review's completed moves (`brief_state.handled_since`, `changed` excluded). 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 (completed moves only; rewritten-but-open items render as a REWRITTEN block under still pending), 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."
diff --git a/packages/core/openexecutive/architecture/prebuilt/today.json b/packages/core/openexecutive/architecture/prebuilt/today.json
index 2d4715a4..04ffe7a1 100644
--- a/packages/core/openexecutive/architecture/prebuilt/today.json
+++ b/packages/core/openexecutive/architecture/prebuilt/today.json
@@ -1,7 +1,7 @@
{
"section_id": "today",
"title": "Today / Morning Brief",
- "markdown": "`openexecutive.api.routes.today` serves the morning brief — a one-screen, read-only view of what is happening across the org. It is the default landing surface (the Next.js root renders `<Briefing>`).\n\n`GET /today` returns `TodayResponse` assembled by `_build_today()`, which is synchronous and caller-agnostic:\n\n- **`departments`** — per-department goal health, rolling up each department's goal counts (`total`, `at_risk`, `off_track`) plus its awaiting-workflow count, and `attention_goals`: the actual off-track/at-risk goals (worst first, capped at 3) with `key_result`, `current`, `target`, and `status`, so the briefing's Department card shows *which* goal is off and how far without a click. Empty for healthy/inactive departments.\n- **`people`** — an attention-ranked roster. Each person carries `awaiting_action` count, soonest SLA, a `status` (`on_leave` / `needs_reply` / `awaiting` / `clear`), reachability, `overdue`, a server `priority` sort key, and a cached one-line `insight`. Sorted by `(-priority, full_name)`.\n- **`proposals`** — the *live* unread alerts (workflow approvals, triage-classified inbound, Executive signals, flagged artifacts, and gated calendar bookings): unread, inside their category TTL, not snoozed — see *Alert lifecycle* below. Each carries `score`, `category` (`action` vs `monitoring`), `surfaced_reason` from `openexecutive.briefing.ranking`, the lifecycle fields (`occurrence_count`, `last_seen_at`, `last_reviewed_at`, `review_verdict`, `review_note`, `recommended_move`, `why_now`, `due_at`, `superseded_count`, `suggested_workflow`), and `decision_instance_id` (set only when the proposal is backed by a decision-ledger row — a calendar booking awaiting approval). The UI splits them into 'mine' vs 'across the team' using `caller_person_id`. For decision-backed proposals the card's Approve/Reject call the `/decisions` endpoints (which book or cancel the event server-side and clear the alert) instead of the ack-and-hand-off-to-chat flow — so meeting bookings are reviewed in the briefing itself rather than on a separate page.\n- **`narrative`** — a per-viewer Executive-voice header synthesized by `synthesize_briefing_narrative`; the principal gets the whole-company scope, teammates a role-scoped one. In the web UI each bullet of this narrative is a click target: clicking one hands off to chat (the same `onContinue` path as the proposal cards) seeded to discuss that item. The Executive recognizes it because every chat turn now carries a `<briefing>` digest of open alerts (see Memory).\n- **`in_flight`** / **`awaiting`** — upcoming Executive commitments and people we are waiting on.\n- **`handled_overnight`** — the autonomous moves the Executive made since the last delivered morning brief: the alert review's (routed, nudged, escalated, drafted, merged, closed, updated), each with the alert id so the UI can offer Undo, plus the research watch policy's (`watching` — a watch added on its own because it was grounded in company data; `stopped_watching` — a research watch auto-disabled as noisy or dead; no alert id, re-enable from `/watchlist`). The morning brief also carries a one-line count of research watch suggestions waiting on `/watchlist`.\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.",
+ "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 *completed* since the last delivered morning brief: the alert review's (routed, nudged, escalated, drafted, merged, closed) plus the research watch policy's (`watching` — a watch added on its own because it was grounded in company data; `stopped_watching` — a research watch auto-disabled as noisy or dead; no alert id, re-enable from `/watchlist`). A `changed` verdict (the review rewrote an open alert's headline / body / severity) is deliberately **not** here: the alert is still open in \"Needs you\" and its card carries the note, so the brief reports it under \"what changed\" (a REWRITTEN block) rather than as done. Each row is structured, not just a sentence: `kind`, the audit `summary` (nudge bookkeeping marker stripped), `at`, `alert_id`, `event_type` (for a pre-filtered `/audit` deep link), `headline` (the alert's headline at move time; a watch's slug), `target` (person name for routed / nudged, survivor headline for merged, new severity for escalated, draft title, workflow name), `detail` (the cited evidence or the watch policy's reason), `outcome` (`resolved` | `dismissed` for a close, `proposed` for a route that went through the authority gate), `evidence_ref` (S1 / R2 / A3), `superseded_by_alert_id`, and `status` — the alert's lifecycle state **now** (`open` | `resolved` | `dismissed` | `expired` | `merged`), looked up per row so a close the principal already undid renders as reopened instead of offering a second Undo. The morning brief also carries a one-line count of research watch suggestions waiting on `/watchlist`.\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 rail (anchor of the \"Executive handled N overnight\" pill) reads as the Executive reporting in, not an audit export: a first-person heading built from counts only — \"Since your last brief: N off your plate (resolved + dismissed closes still standing), N in others' hands (routed / nudged), N waiting on you (escalated)\" — then one first-person row per alert (\"Resolved *X* — evidence\", \"Dismissed *X* as stale — evidence\", \"Handed *X* to Dana Kim\" / \"Proposed *X* to Dana Kim (awaiting their approval)\", \"Chased Dana Kim on *X*\", \"Raised *X* to high\", \"Drafted *T* from *X*\", \"Folded *X* into *Y*\", \"Started watching *slug*\"). Escalations always sort first and never collapse; rows sharing an alert collapse to the newest move with the others as an \"also …\" trailer; a merge whose survivor is listed becomes \"N duplicates folded in\" on the survivor; five rows show before \"Show N more\", with workflow suggestions and stopped watches behind it by default. Every row links its `evidence_ref` (or \"evidence\") to `/audit?event_type=…&q=…` (the audit page pre-fills those filters from the query string), a still-open row jumps to its card (`#alert-<id>`), drafted rows link `/artifacts`, watch rows `/watchlist`. Undo is offered only while the close still stands (`status` not `open`); a reverted close shows \"Reopened\". A footer counts closes still standing (\"N fewer cards in your queue since your last brief · every close cites its evidence\"), and an empty rail with reviewed open alerts renders one line (\"Quiet night. I re-read N open alerts — none needed a move.\"). 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-09-12T10:49:14.352822+00:00"
+ "generated_at": "2026-09-13T00:00:00+00:00"
}
diff --git a/packages/core/openexecutive/architecture/prebuilt/workflows.json b/packages/core/openexecutive/architecture/prebuilt/workflows.json
index 698b1c81..1cb6ca51 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` — 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.",
+ "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, a *rewritten* block lists carried items the review rewrote inside the window (`brief_state.rewritten_since`: verdict `changed`, still open — the brief reports them under \"what changed\", never as done), and a *handled overnight* block lists what the Executive's alert review **completed** on its own (`brief_state.handled_since`; the `changed` verdict is excluded because the alert is still open). 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-09-11T19:18:55+00:00"
+ "generated_at": "2026-09-13T00:00:00+00:00"
}
diff --git a/packages/core/openexecutive/briefing/brief_state.py b/packages/core/openexecutive/briefing/brief_state.py
index 2a2d7e62..ae7189ac 100644
--- a/packages/core/openexecutive/briefing/brief_state.py
+++ b/packages/core/openexecutive/briefing/brief_state.py
@@ -24,6 +24,7 @@ from __future__ import annotations
import hashlib
import json
import logging
+import re
from datetime import UTC, datetime, timedelta
from typing import Any
@@ -52,15 +53,30 @@ REVIEW_EVENT_TYPES: tuple[str, ...] = (
"alert_review_changed",
)
+# Review events that are bookkeeping on a still-open alert, not a completed
+# move. A `changed` verdict rewrites the card's text in place — the alert
+# stays in "Needs you" and the card itself shows the note — so listing it
+# under "handled" double-reports it and mislabels it as done. It renders in
+# the brief's REWRITTEN block instead (see rewritten_since).
+_NOT_HANDLED_EVENT_TYPES: frozenset[str] = frozenset({"alert_review_changed"})
+
# Every audit event type the handled block reads, mapped to the short kind
# the brief and the /today rail render. The research watch policy's
# autonomous moves ride alongside the alert review's.
HANDLED_EVENT_KINDS: dict[str, str] = {
- **{t: t.removeprefix("alert_review_") for t in REVIEW_EVENT_TYPES},
+ **{
+ t: t.removeprefix("alert_review_")
+ for t in REVIEW_EVENT_TYPES
+ if t not in _NOT_HANDLED_EVENT_TYPES
+ },
"watchlist_research_added": "watching",
"watchlist_auto_disabled": "stopped_watching",
}
+# The nudge audit summary opens with "[alert N] " so `alerts.review` can count
+# delivered nudges per alert with a text query; it is bookkeeping, not prose.
+_ALERT_MARKER_RE = re.compile(r"^\[alert \d+\]\s*")
+
def scope_for(kind: str) -> str:
return f"{SCOPE_PREFIX}{kind}"
@@ -121,11 +137,48 @@ def split_proposals(
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``.
+def rewritten_since(
+ proposals: list[dict[str, Any]], since: datetime | None
+) -> list[dict[str, Any]]:
+ """Open proposals the review rewrote (verdict ``changed``) at/after ``since``.
+
+ These are the alerts that dropped out of the handled block: still open,
+ text or severity refreshed by the Executive. The brief reports them under
+ "what changed", never as done. Empty when ``since`` is None.
+ """
+ if since is None:
+ return []
+ out: list[dict[str, Any]] = []
+ for p in proposals:
+ if p.get("review_verdict") != "changed":
+ continue
+ reviewed = parse_aware(p.get("last_reviewed_at"))
+ if reviewed is not None and reviewed >= since:
+ out.append(p)
+ return out
+
+
+def rewritten_lines(
+ proposals: list[dict[str, Any]], since: datetime | None, limit: int = 10
+) -> list[str]:
+ """Bullet lines for the briefs' REWRITTEN block (one per rewritten open
+ proposal): ``- <headline> — <review note>``. Shared by the morning brief
+ and the end-of-day digest so the two never drift."""
+ return [
+ f"- {str(p.get('headline', ''))[:160]} — {str(p.get('review_note', ''))[:120]}"
+ for p in rewritten_since(proposals, since)[:limit]
+ ]
- Each item: ``{"kind": event_type sans prefix, "summary": str, "at": iso,
- "alert_id": int | None}``, newest first. Empty when the audit store is unavailable.
+
+def handled_since(since: datetime, limit: int = 20) -> list[dict[str, Any]]:
+ """Completed autonomous moves recorded in the audit log since ``since``.
+
+ Each item: ``{"kind": event_type sans prefix, "event_type": str,
+ "summary": str, "at": iso, "alert_id": int | None, "details": dict}``,
+ newest first. ``summary`` has the nudge bookkeeping marker stripped;
+ ``details`` is the audit row's structured payload (headline, target
+ person, evidence ref, new status …) for callers that render more than
+ one line. Empty when the audit store is unavailable.
"""
try:
from openexecutive.audit.logger import get_audit_logger
@@ -137,9 +190,11 @@ def handled_since(since: datetime, limit: int = 20) -> list[dict[str, Any]]:
details = ev.details if isinstance(ev.details, dict) else {}
out.append({
"kind": kind,
- "summary": ev.summary,
+ "event_type": event_type,
+ "summary": _ALERT_MARKER_RE.sub("", ev.summary or ""),
"at": ev.ts,
"alert_id": details.get("alert_id"),
+ "details": details,
})
out.sort(key=lambda e: e["at"], reverse=True)
return out[:limit]
@@ -168,6 +223,12 @@ def build_brief_fingerprint(
(str(a.get("kind", "")), str(a.get("summary", ""))[:80]) for a in activity
),
"handled": sorted((h["kind"], h["summary"][:80]) for h in handled),
+ # A rewrite alone must still un-suppress the brief now that it no
+ # longer rides in `handled` (keyed on the note, never the stamp).
+ "rewritten": sorted(
+ (int(p.get("alert_id", 0)), str(p.get("review_note", ""))[:80])
+ for p in rewritten_since(today_data.get("proposals", []), since)
+ ),
"depts": sorted(
(d.get("slug", ""), d.get("at_risk_count", 0), d.get("off_track_count", 0))
for d in today_data.get("departments", [])
@@ -218,6 +279,8 @@ __all__ = [
"last_delivered",
"pending_watch_suggestions",
"record_delivered",
+ "rewritten_lines",
+ "rewritten_since",
"scope_for",
"since_for",
"split_proposals",
diff --git a/packages/core/openexecutive/briefing/narrative.py b/packages/core/openexecutive/briefing/narrative.py
index 38b87fb5..ca5b2d6d 100644
--- a/packages/core/openexecutive/briefing/narrative.py
+++ b/packages/core/openexecutive/briefing/narrative.py
@@ -45,9 +45,11 @@ STANDALONE_BRIEF_SYSTEM = (
" 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"
+ " 3. **Handled overnight** — what you already completed on your own from "
+ "the HANDLED block (routed, nudged, escalated, drafted, merged, closed "
+ "with evidence). One bullet each, past tense, naming the person or item. "
+ "Items under REWRITTEN are still open — they belong in 'What changed', "
+ "never here.\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 "
@@ -171,7 +173,7 @@ def render_briefing_context(
parts.append(f"- {p.get('headline', '')[:160]}")
parts.append("")
else:
- from openexecutive.briefing.brief_state import split_proposals
+ from openexecutive.briefing.brief_state import rewritten_lines, split_proposals
new_items, carried = split_proposals(proposals, since)
if new_items:
@@ -193,6 +195,14 @@ def render_briefing_context(
line += f", {stale} flagged likely stale"
parts.append(line + ") — see /today")
parts.append("")
+ rewritten = rewritten_lines(carried, since)
+ if rewritten:
+ parts.append(
+ "REWRITTEN BY THE EXECUTIVE SINCE LAST BRIEF (still open — mention under "
+ "\"What changed\", never as done):"
+ )
+ parts.extend(rewritten)
+ parts.append("")
if handled:
parts.append("HANDLED OVERNIGHT BY THE EXECUTIVE (already done — report, don't ask):")
for h in handled[:15]:
diff --git a/packages/core/openexecutive/workflows/end_of_day_digest.py b/packages/core/openexecutive/workflows/end_of_day_digest.py
index 415ce05a..f4d53a26 100644
--- a/packages/core/openexecutive/workflows/end_of_day_digest.py
+++ b/packages/core/openexecutive/workflows/end_of_day_digest.py
@@ -118,7 +118,7 @@ def _render_eod_context(
parts.append("")
else:
from openexecutive.alerts.lifecycle import parse_aware
- from openexecutive.briefing.brief_state import split_proposals
+ from openexecutive.briefing.brief_state import rewritten_lines, split_proposals
new_items, carried = split_proposals(proposals, since)
if new_items:
@@ -139,6 +139,14 @@ def _render_eod_context(
line += f", {stale} flagged likely stale"
parts.append(line + ") — see /today")
parts.append("")
+ rewritten = rewritten_lines(carried, since)
+ if rewritten:
+ parts.append(
+ "REWRITTEN BY THE EXECUTIVE TODAY (still open — mention under "
+ "\"Still pending\", never as done):"
+ )
+ parts.extend(rewritten)
+ 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)]
diff --git a/packages/core/tests/unit/test_alert_review.py b/packages/core/tests/unit/test_alert_review.py
index d5b92ef2..96d3563e 100644
--- a/packages/core/tests/unit/test_alert_review.py
+++ b/packages/core/tests/unit/test_alert_review.py
@@ -312,7 +312,10 @@ def test_route_in_auto_execute_department_assigns_and_dms(db: Path, audit_events
assert row.recommended_move == "route" and row.review_verdict == "routed"
assert dms == [(dana, "Dana — can you own the Acme renewal pricing by Friday?")]
assert summary.routed == 1 and summary.moves_used == 1
- assert any(e[0] == review.EVENT_ROUTED and e[2]["target_person_id"] == dana for e in audit_events)
+ routed = next(e for e in audit_events if e[0] == review.EVENT_ROUTED)
+ # The rail and the brief read this summary: a name, never a bare person id.
+ assert routed[1] == "Routed 'Renewal pricing question' to Dana (sent)"
+ assert routed[2]["target_person_id"] == dana and routed[2]["target_person_name"] == "Dana"
def test_route_in_propose_only_department_proposes_instead_of_dm(db: Path, audit_events, dms, monkeypatch) -> None:
@@ -375,7 +378,8 @@ def test_nudge_respects_cap_and_records_marker(db: Path, audit_events, dms, monk
_apply(db, aid, _verdict(aid, recommended_move="nudge", message="Gentle ping"), summary=summary)
assert dms == [(dana, "Gentle ping")] and summary.nudged == 1
nudged = next(e for e in audit_events if e[0] == review.EVENT_NUDGED)
- assert nudged[1].startswith(f"[alert {aid}]")
+ assert nudged[1] == f"[alert {aid}] Nudged Dana about 'Waiting on Dana'"
+ assert nudged[2]["target_person_name"] == "Dana"
# At the cap: no DM, audited as capped.
monkeypatch.setattr(review, "_nudges_so_far", lambda alert_id: 3)
_apply(db, aid, _verdict(aid, recommended_move="nudge", message="again"), summary=summary)
@@ -456,6 +460,9 @@ def test_merge_supersedes_only_into_a_shown_live_survivor(db: Path, audit_events
s = alert_store.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 == 4 and summary.merged == 1 # absorbs the dup's count
+ merged = next(e for e in audit_events if e[0] == review.EVENT_MERGED)
+ assert merged[2]["superseded_by_alert_id"] == survivor
+ assert merged[2]["superseded_by_headline"] == "Story" # lets the rail collapse the pair
# Not shown to the model (no shared tag / source) → refused, even if live.
unrelated = _insert(db, "unrelated", hours_ago=1, source="email", topic_tags=["hiring"])
diff --git a/packages/core/tests/unit/test_brief_state.py b/packages/core/tests/unit/test_brief_state.py
index c51080f9..08502b01 100644
--- a/packages/core/tests/unit/test_brief_state.py
+++ b/packages/core/tests/unit/test_brief_state.py
@@ -158,3 +158,61 @@ def test_pending_watch_suggestions_counts_dry_run_research_rows(tmp_path: Path,
mode="dry_run", origin="research_proposed", db_path=db)
ms.insert_watchlist_item(slug="rss-b", signal_type="rss", target="https://b.com/f", db_path=db)
assert brief_state.pending_watch_suggestions() == 1
+
+
+def test_handled_since_excludes_rewrites_and_strips_nudge_marker(
+ 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)
+ # A rewrite leaves the alert open: it is not "handled" and must not be listed.
+ al.log("alert_review_changed", "Updated 'Old headline' — now 7 merchants", actor="executive",
+ details={"alert_id": 4, "headline": "Old headline"})
+ al.log("alert_review_nudged", "[alert 7] Nudged Dana Kim about 'Acme renewal'", actor="executive",
+ details={"alert_id": 7, "headline": "Acme renewal", "target_person_name": "Dana Kim"})
+
+ handled = brief_state.handled_since(datetime.now(UTC) - timedelta(hours=1))
+ assert [h["kind"] for h in handled] == ["nudged"]
+ row = handled[0]
+ assert row["summary"] == "Nudged Dana Kim about 'Acme renewal'"
+ assert row["event_type"] == "alert_review_nudged"
+ assert row["alert_id"] == 7
+ assert row["details"]["target_person_name"] == "Dana Kim"
+ assert "alert_review_changed" not in brief_state.HANDLED_EVENT_KINDS
+
+
+def test_rewritten_since_picks_changed_verdicts_reviewed_in_window() -> None:
+ since = datetime.now(UTC) - timedelta(hours=12)
+ inside = (datetime.now(UTC) - timedelta(hours=2)).isoformat()
+ before = (datetime.now(UTC) - timedelta(hours=30)).isoformat()
+ proposals = [
+ {"alert_id": 1, "review_verdict": "changed", "last_reviewed_at": inside},
+ {"alert_id": 2, "review_verdict": "changed", "last_reviewed_at": before},
+ {"alert_id": 3, "review_verdict": "relevant", "last_reviewed_at": inside},
+ {"alert_id": 4, "review_verdict": "changed"},
+ ]
+ assert [p["alert_id"] for p in brief_state.rewritten_since(proposals, since)] == [1]
+ assert brief_state.rewritten_since(proposals, None) == []
+
+
+def test_fingerprint_moves_when_a_carried_item_is_rewritten() -> None:
+ since = datetime.now(UTC) - timedelta(hours=12)
+ old = _proposal(5, hours_ago=40)
+ base = dict(activity=[], handled=[], since=since)
+ fp_plain = brief_state.build_brief_fingerprint(
+ today_data={"proposals": [old], "departments": [], "people": []}, **base,
+ )
+ rewritten = {**old, "review_verdict": "changed", "review_note": "now 7 merchants",
+ "last_reviewed_at": (datetime.now(UTC) - timedelta(hours=1)).isoformat()}
+ fp_rewritten = brief_state.build_brief_fingerprint(
+ today_data={"proposals": [rewritten], "departments": [], "people": []}, **base,
+ )
+ assert fp_plain != fp_rewritten
+ # Re-running with the same note (a later timestamp) is still the same brief.
+ again = {**rewritten, "last_reviewed_at": datetime.now(UTC).isoformat()}
+ assert brief_state.build_brief_fingerprint(
+ today_data={"proposals": [again], "departments": [], "people": []}, **base,
+ ) == fp_rewritten
diff --git a/packages/core/tests/unit/test_briefing_context_render.py b/packages/core/tests/unit/test_briefing_context_render.py
index a238cb50..53ace04f 100644
--- a/packages/core/tests/unit/test_briefing_context_render.py
+++ b/packages/core/tests/unit/test_briefing_context_render.py
@@ -90,3 +90,38 @@ def test_render_context_mentions_pending_watch_suggestions_once() -> None:
assert "WATCH SUGGESTIONS WAITING: 2 sources" in text and "/watchlist" in text
quiet = render_briefing_context(period_label="p", today_data=_today(), activity=[], since=since)
assert "WATCH SUGGESTIONS" not in quiet
+
+
+def test_render_context_lists_rewritten_open_items_separately_from_handled() -> None:
+ since = datetime.now(UTC) - timedelta(hours=24)
+ today = _today()
+ reviewed = (datetime.now(UTC) - timedelta(hours=3)).isoformat()
+ # A carried item the review rewrote inside the window: still open, so it
+ # must surface as "what changed", never under HANDLED.
+ today["proposals"].append(_proposal(
+ 4, hours_ago=70, review_verdict="changed",
+ review_note="payouts now delayed for 7 merchants", last_reviewed_at=reviewed,
+ ))
+ handled = [{"kind": "closed", "summary": "Resolved 'Stripe incident' — vendor marked resolved",
+ "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 "REWRITTEN BY THE EXECUTIVE SINCE LAST BRIEF" in text
+ assert "- item 4 — payouts now delayed for 7 merchants" in text
+ handled_block = text.split("HANDLED OVERNIGHT BY THE EXECUTIVE", 1)[1]
+ assert "item 4" not in handled_block
+ # Rewritten items are still carried-over for the count.
+ assert "CARRIED OVER: 3 older item(s)" in text
+
+
+def test_eod_context_lists_rewritten_open_items() -> None:
+ since = datetime.now(UTC) - timedelta(hours=24)
+ today = _today()
+ today["proposals"].append(_proposal(
+ 4, hours_ago=70, review_verdict="changed", review_note="two offers now expiring Friday",
+ last_reviewed_at=(datetime.now(UTC) - timedelta(hours=3)).isoformat(),
+ ))
+ text = _render_eod_context(period_label="p", today_data=today, activity=[], since=since)
+ assert "REWRITTEN BY THE EXECUTIVE TODAY" in text
+ assert "- item 4 — two offers now expiring Friday" in text
diff --git a/packages/core/tests/unit/test_today_route.py b/packages/core/tests/unit/test_today_route.py
index 1316ffe1..5215d44c 100644
--- a/packages/core/tests/unit/test_today_route.py
+++ b/packages/core/tests/unit/test_today_route.py
@@ -1505,3 +1505,83 @@ def test_proposals_carry_lifecycle_fields_and_demote_likely_stale(
s = by_headline["stale one"]
assert s["review_verdict"] == "likely_stale"
assert s["score"] < f["score"]
+
+
+def test_handled_overnight_rows_are_structured_and_track_current_status(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """The rail is rebuilt from audit rows: each carries the who / what / why the
+ audit row recorded, plus the alert's status NOW so an undone close renders
+ as reopened instead of offering a second Undo."""
+ from openexecutive.audit import logger as audit_logger
+ from openexecutive.briefing import brief_state
+
+ db = tmp_path / "today.db"
+ _setup_isolated_db(db, monkeypatch)
+ al = audit_logger.AuditLogger(db_path=tmp_path / "audit.db")
+ al.initialize_db()
+ monkeypatch.setattr(audit_logger, "get_audit_logger", lambda: al)
+ monkeypatch.setattr(brief_state, "since_for", lambda kind, now=None: datetime.now(UTC) - timedelta(hours=1))
+
+ def _alert(headline: str) -> int:
+ aid = alert_store.insert_alert(
+ source="triage", external_id=f"ext-{headline}", severity="medium",
+ headline=headline, body=headline,
+ )
+ assert aid is not None
+ return aid
+
+ closed_id = _alert("Stripe payouts delayed")
+ undone_id = _alert("Old webinar follow-up")
+ routed_id = _alert("Q3 pricing page copy stale")
+ survivor_id = _alert("Payout delay")
+ dup_id = _alert("Payout delay (duplicate)")
+ alert_store.set_status(closed_id, "resolved")
+ alert_store.set_status(undone_id, "dismissed")
+ alert_store.mark_superseded(dup_id, survivor_id)
+
+ al.log("alert_review_closed", "Resolved 'Stripe payouts delayed' — vendor confirmed", actor="executive",
+ details={"alert_id": closed_id, "headline": "Stripe payouts delayed", "new_status": "resolved",
+ "evidence": "vendor status page confirmed the fix", "evidence_ref": "R2"})
+ al.log("alert_review_closed", "Dismissed as stale 'Old webinar follow-up' — no activity", actor="executive",
+ details={"alert_id": undone_id, "headline": "Old webinar follow-up", "new_status": "dismissed",
+ "evidence": "no activity in 30 days", "evidence_ref": "A1"})
+ al.log("alert_review_routed", "Routed 'Q3 pricing page copy stale' to Dana Kim (proposal 9)",
+ actor="executive",
+ details={"alert_id": routed_id, "headline": "Q3 pricing page copy stale",
+ "target_person_id": 3, "target_person_name": "Dana Kim", "proposed": True})
+ al.log("alert_review_merged", "Merged 'Payout delay (duplicate)' into 'Payout delay'", actor="executive",
+ details={"alert_id": dup_id, "headline": "Payout delay (duplicate)",
+ "superseded_by_alert_id": survivor_id, "superseded_by_headline": "Payout delay"})
+ al.log("watchlist_research_added", "Started watching stock-acme — competitor ticker", actor="executive",
+ details={"slug": "stock-acme", "rationale": "competitor ticker named on Sales"})
+ al.log("alert_review_changed", "Updated 'Something' — rewritten", actor="executive",
+ details={"alert_id": routed_id, "headline": "Something"})
+ # The principal undid the dismissal after the review ran.
+ assert alert_store.reopen_alert(undone_id)
+
+ res = _make_client().get("/today")
+ assert res.status_code == 200
+ rows = {r["headline"]: r for r in res.json()["handled_overnight"]}
+ assert "Something" not in rows # rewrites are not "handled"
+
+ closed = rows["Stripe payouts delayed"]
+ assert closed["kind"] == "closed" and closed["outcome"] == "resolved"
+ assert closed["detail"] == "vendor status page confirmed the fix"
+ assert closed["evidence_ref"] == "R2" and closed["event_type"] == "alert_review_closed"
+ assert closed["status"] == "resolved" and closed["alert_id"] == closed_id
+
+ undone = rows["Old webinar follow-up"]
+ assert undone["outcome"] == "dismissed" and undone["status"] == "open"
+
+ routed = rows["Q3 pricing page copy stale"]
+ assert routed["target"] == "Dana Kim" and routed["outcome"] == "proposed"
+ assert routed["status"] == "open"
+
+ merged = rows["Payout delay (duplicate)"]
+ assert merged["target"] == "Payout delay" and merged["superseded_by_alert_id"] == survivor_id
+ assert merged["status"] == "merged"
+
+ watching = rows["stock-acme"]
+ assert watching["kind"] == "watching" and watching["alert_id"] is None
+ assert watching["detail"] == "competitor ticker named on Sales" and watching["status"] == ""
diff --git a/packages/ui/src/app/audit/page.tsx b/packages/ui/src/app/audit/page.tsx
index 224a7b09..f8a9d1e3 100644
--- a/packages/ui/src/app/audit/page.tsx
+++ b/packages/ui/src/app/audit/page.tsx
@@ -1,7 +1,8 @@
"use client";
import Link from "next/link";
-import { Fragment, useCallback, useEffect, useMemo, useRef, useState } from "react";
+import { useSearchParams } from "next/navigation";
+import { Fragment, Suspense, useCallback, useEffect, useMemo, useRef, useState } from "react";
import {
getAuditLog,
@@ -157,16 +158,27 @@ function formatTimeOnly(ts: string): string {
}
}
+// Deep links (e.g. the briefing's "Handled" rail linking a move to its
+// evidence) pre-fill the type and text filters from the query string.
export default function AuditPage() {
+ return (
+ <Suspense fallback={null}>
+ <AuditPageInner />
+ </Suspense>
+ );
+}
+
+function AuditPageInner() {
+ const searchParams = useSearchParams();
const [items, setItems] = useState<AuditEvent[]>([]);
const [total, setTotal] = useState(0);
const [eventTypes, setEventTypes] = useState<string[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
- const [eventType, setEventType] = useState<string>("");
+ const [eventType, setEventType] = useState<string>(searchParams.get("event_type") ?? "");
const [sessionId, setSessionId] = useState<string>("");
- const [q, setQ] = useState<string>("");
+ const [q, setQ] = useState<string>(searchParams.get("q") ?? "");
const [since, setSince] = useState<string>("");
const [until, setUntil] = useState<string>("");
const [offset, setOffset] = useState<number>(0);
diff --git a/packages/ui/src/components/Briefing.tsx b/packages/ui/src/components/Briefing.tsx
index 0c101266..df958eb8 100644
--- a/packages/ui/src/components/Briefing.tsx
+++ b/packages/ui/src/components/Briefing.tsx
@@ -958,7 +958,7 @@ function ProposalCard({
<div>{content}</div>
);
return (
- <div className={`group py-3 hover:bg-surface-overlay/30 transition-colors${rowAccent}`}>
+ <div id={`alert-${proposal.alert_id}`} className={`group py-3 hover:bg-surface-overlay/30 transition-colors${rowAccent}`}>
{contentArea}
{/* Body expander — a sibling of the content area (never nested inside the
Discuss click target, which HTML disallows) so a clamped long body can
@@ -1476,74 +1476,320 @@ function MonitoringPanel({
);
}
-// 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",
+// Handled since your last brief — what the Executive's alert review COMPLETED
+// on its own since the last delivered morning brief (routed, nudged,
+// escalated, drafted, merged, closed) plus the research watch policy's
+// autonomous adds/drops. Rewrites of open alerts are deliberately absent:
+// the alert is still in "Needs you" and its card carries the note, so
+// listing it here would double-report it and call it done. Every autonomous
+// close is reversible here (Undo → reopen), which is what makes the autonomy
+// un-scary: visible, evidence-cited, one click back.
+//
+// Voice: first person, past tense, specific, nothing the audit row cannot
+// back. The heading counts three buckets and never interpolates names, so
+// it reads the same whether the roster lookup found "Dana Kim" or not.
+const HANDLED_VISIBLE = 5;
+
+// One table per kind: reading order (what needs the principal first, then
+// what they can undo, then what went to others, then transparency), the short
+// past-tense verb for the "also …" trailer, and whether the row is
+// transparency rather than accomplishment (folded behind "Show more").
+const HANDLED_KINDS: Record<string, { order: number; verb: string; quiet?: true }> = {
+ escalated: { order: 0, verb: "raised" },
+ closed: { order: 1, verb: "closed" },
+ merged: { order: 1, verb: "folded" },
+ routed: { order: 2, verb: "routed" },
+ nudged: { order: 2, verb: "chased" },
+ drafted: { order: 2, verb: "drafted" },
+ suggested_workflow: { order: 3, verb: "suggested a workflow", quiet: true },
+ watching: { order: 3, verb: "started watching" },
+ stopped_watching: { order: 3, verb: "stopped watching", quiet: true },
};
+const handledOrder = (kind: string) => HANDLED_KINDS[kind]?.order ?? 4;
+const handledVerb = (kind: string) => HANDLED_KINDS[kind]?.verb ?? kind;
+const isQuietKind = (kind: string) => HANDLED_KINDS[kind]?.quiet === true;
// 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).
+// e.g. routed then closed — so the alert id alone is not unique).
function handledKey(h: HandledItem): string {
return `${h.kind}-${h.at}-${h.alert_id ?? ""}`;
}
+function isCloseKind(h: HandledItem): boolean {
+ return h.kind === "closed" || h.kind === "merged";
+}
+
+// One visible row plus the other moves on the same alert folded under it.
+interface HandledRow {
+ item: HandledItem;
+ also: HandledItem[];
+ foldedIn: number;
+}
+
+// Collapse the newest-first list to one row per alert. A merge whose survivor
+// is also listed becomes a "duplicate folded in" count on the survivor. The
+// newest move wins the visible slot, except an escalation, which always
+// stays visible — the boast must never bury the row that needs the CEO.
+function groupHandled(items: HandledItem[]): HandledRow[] {
+ const listed = new Set(items.map((h) => h.alert_id).filter((id): id is number => id != null));
+ const foldedInto = new Map<number, number>();
+ const rest: HandledItem[] = [];
+ for (const h of items) {
+ const into = h.superseded_by_alert_id;
+ if (h.kind === "merged" && into != null && listed.has(into)) {
+ foldedInto.set(into, (foldedInto.get(into) ?? 0) + 1);
+ } else {
+ rest.push(h);
+ }
+ }
+ const byKey = new Map<string, HandledRow>();
+ const rows: HandledRow[] = [];
+ for (const h of rest) {
+ const key = h.alert_id != null ? `alert-${h.alert_id}` : handledKey(h);
+ const row = byKey.get(key);
+ if (!row) {
+ const fresh: HandledRow = {
+ item: h,
+ also: [],
+ foldedIn: h.alert_id != null ? foldedInto.get(h.alert_id) ?? 0 : 0,
+ };
+ byKey.set(key, fresh);
+ rows.push(fresh);
+ } else if (h.kind === "escalated" && row.item.kind !== "escalated") {
+ row.also.push(row.item);
+ row.item = h;
+ } else {
+ row.also.push(h);
+ }
+ }
+ // Stable sort keeps newest-first inside each bucket.
+ rows.sort((a, b) => handledOrder(a.item.kind) - handledOrder(b.item.kind));
+ return rows;
+}
+
+function joinClauses(parts: string[]): string {
+ if (parts.length <= 1) return parts.join("");
+ if (parts.length === 2) return `${parts[0]} and ${parts[1]}`;
+ return `${parts.slice(0, -1).join(", ")}, and ${parts[parts.length - 1]}`;
+}
+
+// "Since your last brief: 3 off your plate, 2 in others' hands, and 1 waiting
+// on you." Counts only — a name lookup that fell back to "person 12" can
+// never leak into the headline. A reverted close is back on the plate, so it
+// is not counted.
+function handledHeadline(rows: HandledRow[], reverted: (h: HandledItem) => boolean): string {
+ let offPlate = 0;
+ let others = 0;
+ let waiting = 0;
+ for (const r of rows) {
+ const k = r.item.kind;
+ if (k === "closed" && !reverted(r.item)) offPlate += 1;
+ else if (k === "routed" || k === "nudged") others += 1;
+ else if (k === "escalated") waiting += 1;
+ }
+ const parts: string[] = [];
+ if (offPlate > 0) parts.push(`${offPlate} off your plate`);
+ if (others > 0) parts.push(`${others} in others' hands`);
+ if (waiting > 0) parts.push(`${waiting} waiting on you`);
+ if (parts.length === 0) {
+ const n = rows.length;
+ return `Since your last brief: ${n} move${n === 1 ? "" : "s"} on my own.`;
+ }
+ return `Since your last brief: ${joinClauses(parts)}.`;
+}
+
+// First-person sentence for one row. Falls back to the audit summary when the
+// row predates the structured fields (no headline / target to compose from).
+function handledSentence(h: HandledItem): React.ReactNode {
+ const headline = h.headline ?? "";
+ const target = h.target ?? "";
+ const H = <span className="text-fg">{headline}</span>;
+ const T = <span className="text-fg">{target}</span>;
+ const why = h.detail ? <span className="text-fg-subtle"> — {h.detail}</span> : null;
+ if (!headline) return h.summary;
+ switch (h.kind) {
+ case "closed":
+ return h.outcome === "dismissed" ? <>Dismissed {H} as stale{why}</> : <>Resolved {H}{why}</>;
+ case "routed":
+ if (!target) return h.summary;
+ return h.outcome === "proposed"
+ ? <>Proposed {H} to {T} <span className="text-fg-subtle">(awaiting their approval)</span></>
+ : <>Handed {H} to {T}</>;
+ case "nudged":
+ return target ? <>Chased {T} on {H}</> : h.summary;
+ case "escalated":
+ return target ? <>Raised {H} to {T}{why}</> : <>Raised {H}{why}</>;
+ case "drafted":
+ return target ? <>Drafted {T} from {H}</> : h.summary;
+ case "merged":
+ return target ? <>Folded {H} into {T}</> : h.summary;
+ case "suggested_workflow":
+ return target ? <>Suggested running {T} on {H}</> : h.summary;
+ case "watching":
+ return <>Started watching {H}{why}</>;
+ case "stopped_watching":
+ return <>Stopped watching {H}{why}</>;
+ default:
+ return h.summary;
+ }
+}
+
+function scrollToAlertCard(alertId: number) {
+ document.getElementById(`alert-${alertId}`)?.scrollIntoView({ behavior: "smooth", block: "center" });
+}
+
+// The audit page pre-filters on these two query params, so the row's
+// "evidence" link lands on the rows that back it.
+function handledProofHref(h: HandledItem): string | null {
+ if (!h.event_type) return null;
+ const q = (h.headline ?? "").slice(0, 40);
+ return `/audit?event_type=${encodeURIComponent(h.event_type)}&q=${encodeURIComponent(q)}`;
+}
+
+// Muted trailer under a collapsed row: duplicates folded in, other moves.
+function handledAlsoLine(row: HandledRow): string {
+ const parts: string[] = [];
+ if (row.foldedIn > 0) parts.push(`${row.foldedIn} duplicate${row.foldedIn === 1 ? "" : "s"} folded in`);
+ if (row.also.length > 0) parts.push(`also ${row.also.map((a) => handledVerb(a.kind)).join(", ")} earlier`);
+ return parts.join(" · ");
+}
+
+function HandledTrailerLink({ href, label }: { href: string; label: string }) {
+ return (
+ <>
+ <span aria-hidden="true">·</span>
+ <Link href={href} className="hover:text-indigo-300 transition-colors">{label}</Link>
+ </>
+ );
+}
+
+function HandledRowView({
+ row,
+ reverted,
+ onReopen,
+}: {
+ row: HandledRow;
+ reverted: boolean;
+ onReopen?: (rowKey: string, alertId: number) => void;
+}) {
+ const h = row.item;
+ const canUndo = Boolean(onReopen) && h.alert_id != null && isCloseKind(h) && !reverted;
+ const stillOpen = h.alert_id != null && h.status === "open" && !isCloseKind(h);
+ const proofHref = handledProofHref(h);
+ const alsoLine = handledAlsoLine(row);
+ return (
+ <div className="py-2 flex items-start justify-between gap-3">
+ <div className="min-w-0">
+ <p className={`text-xs leading-snug ${reverted ? "line-through text-fg-subtle" : "text-fg-muted"}`}>
+ {handledSentence(h)}
+ </p>
+ <p className="mt-0.5 text-[10px] text-fg-subtle flex flex-wrap items-center gap-x-1.5">
+ {alsoLine && <span>{alsoLine}</span>}
+ {alsoLine && <span aria-hidden="true">·</span>}
+ <span>{ageLabel(h.at)} ago</span>
+ {proofHref && <HandledTrailerLink href={proofHref} label={h.evidence_ref || "evidence"} />}
+ {h.kind === "drafted" && <HandledTrailerLink href="/artifacts" label="read the draft" />}
+ {(h.kind === "watching" || h.kind === "stopped_watching") && (
+ <HandledTrailerLink href="/watchlist" label="watchlist" />
+ )}
+ {reverted && (
+ <>
+ <span aria-hidden="true">·</span>
+ <span className="text-sky-300">Reopened</span>
+ </>
+ )}
+ </p>
+ </div>
+ {canUndo && (
+ <button
+ type="button"
+ onClick={() => onReopen?.(handledKey(h), h.alert_id as number)}
+ className="flex-shrink-0 text-[11px] text-fg-muted hover:text-indigo-300 transition-colors"
+ >
+ ↶ Undo
+ </button>
+ )}
+ {stillOpen && (
+ <button
+ type="button"
+ onClick={() => scrollToAlertCard(h.alert_id as number)}
+ className="flex-shrink-0 text-[11px] text-fg-muted hover:text-indigo-300 transition-colors"
+ title="Jump to it in your queue"
+ >
+ still open ↓
+ </button>
+ )}
+ </div>
+ );
+}
+
function HandledOvernightPanel({
items,
+ reviewedOpenCount,
onReopen,
undone,
}: {
items: HandledItem[];
+ // Open alerts the review re-read in the last day — the honest basis for
+ // the quiet-night line.
+ reviewedOpenCount: number;
onReopen?: (rowKey: string, alertId: number) => void;
undone: Set<string>;
}) {
- if (items.length === 0) return null;
+ const [showAll, setShowAll] = useState(false);
+ // The rail is rebuilt from the audit log on every fetch, so a close the
+ // principal already undid still has its row: `status === "open"` (server
+ // truth after a reload) or the in-session set marks it reverted.
+ const reverted = (h: HandledItem) => isCloseKind(h) && (h.status === "open" || undone.has(handledKey(h)));
+
+ if (items.length === 0) {
+ if (reviewedOpenCount === 0) return null;
+ return (
+ <section id={SECTION_IDS.handled} className="rounded-xl border border-line bg-surface-elevated px-4 py-3">
+ <p className="text-xs text-fg-muted">
+ Quiet night. I re-read {reviewedOpenCount} open alert{reviewedOpenCount === 1 ? "" : "s"} — none needed a move.
+ </p>
+ </section>
+ );
+ }
+
+ const rows = groupHandled(items);
+ const loud = rows.filter((r) => !isQuietKind(r.item.kind));
+ const quiet = rows.filter((r) => isQuietKind(r.item.kind));
+ const visible = showAll ? [...loud, ...quiet] : loud.slice(0, HANDLED_VISIBLE);
+ const hiddenCount = rows.length - visible.length;
+ const closesStanding = rows.filter((r) => r.item.kind === "closed" && !reverted(r.item)).length;
+
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" />
+ <div className="flex items-start gap-1.5 mb-2">
+ <p className="text-sm font-medium text-fg">{handledHeadline(rows, reverted)}</p>
<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.
+ Moves I completed on my own since your last delivered brief — routed,
+ chased, escalated, drafted, folded, or closed with cited evidence.
+ Rewrites of open alerts show on the card itself, not here. Undo puts a
+ closed item back in 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 className="divide-y divide-line">
+ {visible.map((row) => (
+ <HandledRowView key={handledKey(row.item)} row={row} reverted={reverted(row.item)} onReopen={onReopen} />
+ ))}
</div>
+ {(hiddenCount > 0 || showAll) && (
+ <button
+ type="button"
+ onClick={() => setShowAll((v) => !v)}
+ className="w-full pt-2 text-[11px] text-fg-muted hover:text-fg transition-colors"
+ >
+ {showAll ? "Show fewer" : `Show ${hiddenCount} more`}
+ </button>
+ )}
+ {closesStanding > 0 && (
+ <p className="mt-2 pt-2 border-t border-line text-[11px] text-fg-subtle">
+ {closesStanding} fewer card{closesStanding === 1 ? "" : "s"} in your queue since your last brief · every close cites its evidence.
+ </p>
+ )}
</section>
);
}
@@ -1678,7 +1924,7 @@ export default function Briefing({ onContinue, showHeader = false, firstName }:
}
}, [refreshToday]);
- // Undo an autonomous close from the "Handled overnight" rail. The rail is
+ // Undo an autonomous close from the handled rail (HandledOvernightPanel). 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) => {
@@ -1801,6 +2047,13 @@ export default function Briefing({ onContinue, showHeader = false, firstName }:
const restProposals = mineProposals.slice(1);
const staleNeedsYouIds = olderThan(mineProposals, NEEDS_YOU_DISMISS_OLDER_THAN_DAYS);
const handledOvernight = today?.handled_overnight ?? [];
+ // Open alerts the review actually re-read in the last day — the honest
+ // basis for the quiet-night line (a verdict stamped three days ago is not
+ // "I read it last night").
+ const reviewedOpenCount = (today?.proposals ?? []).filter((p) => {
+ const t = Date.parse(p.last_reviewed_at ?? "");
+ return !Number.isNaN(t) && Date.now() - t < 24 * 60 * 60 * 1000;
+ }).length;
// Status-strip inputs, all from data already computed above.
const inFlightCount = today?.in_flight?.length ?? 0;
@@ -2219,6 +2472,7 @@ export default function Briefing({ onContinue, showHeader = false, firstName }:
/>
<HandledOvernightPanel
items={handledOvernight}
+ reviewedOpenCount={reviewedOpenCount}
onReopen={handleReopen}
undone={undoneRows}
/>
diff --git a/packages/ui/src/lib/api.ts b/packages/ui/src/lib/api.ts
index d280919f..4b7460ac 100644
--- a/packages/ui/src/lib/api.ts
+++ b/packages/ui/src/lib/api.ts
@@ -2549,6 +2549,18 @@ export interface HandledItem {
summary: string;
at: string;
alert_id?: number | null;
+ // Structured view of the audit row (all additive; `summary` is the fallback).
+ event_type?: string;
+ headline?: string | null;
+ target?: string | null;
+ detail?: string;
+ // "resolved" | "dismissed" for a close, "proposed" for a gated route, else "".
+ outcome?: string;
+ evidence_ref?: string;
+ superseded_by_alert_id?: number | null;
+ // The alert's status NOW: "open" | "resolved" | "dismissed" | "expired" |
+ // "merged" | "" — "open" on a closed row means the close was already undone.
+ status?: string;
}
export interface InFlightItem {