AI-powered virtual executive team — a single coherent executive persona backed by 8 specialist agents (FastAPI + Next.js).
Move handled-rail logic to lib/handled.ts and test it
Claude156f3fc2556e
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 1943beaf..eb9601e3 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -118,9 +118,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0"person 12", and the nudge bookkeeping marker is stripped for display.The rail is now one line by default — a count-only first-person heading("Since your last brief: N off your plate, N in others' hands, N waiting- on you", plus drafts / suggestions / watch changes / reopened-by-you- when present) — with the rows behind a "details" disclosure, and nothing- at all on a night with nothing handled. Expanded, rows read first-person+ on you", plus drafts / suggestions / watch changes / other moves / back+ on your plate when present) — with the rows behind a "details"+ disclosure, and nothing at all on a night with nothing handled. The+ grouping and summary logic lives in `packages/ui/src/lib/handled.ts`+ and is covered by `npm test`. Expanded, rows read first-person("Resolved *X* — evidence", "Dismissed *X* as stale — …", "Handed *X* toDana Kim", "Chased Dana Kim on *X*"), escalations first, one row peralert, every row linking its evidence to a pre-filtered `/audit` (thediff --git a/packages/core/openexecutive/architecture/architecture-facts.yaml b/packages/core/openexecutive/architecture/architecture-facts.yamlindex 6c9112b3..457ac76b 100644--- a/packages/core/openexecutive/architecture/architecture-facts.yaml+++ b/packages/core/openexecutive/architecture/architecture-facts.yaml@@ -1281,8 +1281,9 @@ today:close renders "Reopened" rather than a second Undo). The UI's handledrail is first-person and count-based ("Since your last brief: N off yourplate, N in others' hands, N waiting on you", plus drafts ready /- workflows suggested / watch changes / reopened by you when present)- shown as ONE line by default, rows behind a "details" disclosure (escalations first, one row+ workflows suggested / watch changes / other moves / back on your plate+ when present) shown as ONE sentence by default (logic in+ `packages/ui/src/lib/handled.ts`, tested by `npm test`), rows behind a "details" disclosure (escalations first, one rowper alert, each linking its evidence to `/audit?event_type=…&q=…` and astill-open row to `#alert-<id>`; Undo → `POST /alerts/{id}/reopen`),nothing rendered when empty. The "Executive handled N overnight" statusdiff --git a/packages/core/openexecutive/architecture/prebuilt/today.json b/packages/core/openexecutive/architecture/prebuilt/today.jsonindex 0cca72a4..e81f01ff 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 *completed* since the last delivered morning brief: the alert review's (routed, nudged, escalated, drafted, merged, closed) plus the research watch policy's (`watching` — a watch added on its own because it was grounded in company data; `stopped_watching` — a research watch auto-disabled as noisy or dead; no alert id, re-enable from `/watchlist`). A `changed` verdict (the review rewrote an open alert's headline / body / severity) is deliberately **not** here: the alert is still open in \"Needs you\" and its card carries the note, so the brief reports it under \"what changed\" (a REWRITTEN block) rather than as done. Each row is structured, not just a sentence: `kind`, the audit `summary` (nudge bookkeeping marker stripped), `at`, `alert_id`, `event_type` (for a pre-filtered `/audit` deep link), `headline` (the alert's headline at move time; a watch's slug), `target` (person name for routed / nudged, survivor headline for merged, new severity for escalated, draft title, workflow name), `detail` (the cited evidence or the watch policy's reason), `outcome` (`resolved` | `dismissed` for a close, `proposed` for a route that went through the authority gate), `evidence_ref` (S1 / R2 / A3), `superseded_by_alert_id`, and `status` — the alert's lifecycle state **now** (`open` = live in the queue per `lifecycle.is_live` | `resolved` | `dismissed` | `expired` | `merged` | `acked` | `inactive` for snoozed / past-TTL rows), looked up per row so a close the principal already undid renders as reopened instead of offering a second Undo, and a \"still open\" jump link only appears when there is a card to land on. The morning brief also carries a one-line count of research watch suggestions waiting on `/watchlist`.\n- **`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) is deliberately one line by default: a first-person heading built from counts only — \"Since your last brief: N off your plate (closes and merges still standing), N in others' hands (routed / nudged), N waiting on you (escalated)\", plus \"N drafts ready\", \"N workflows suggested\", \"N watch changes\" and \"N reopened by you\" (a close the principal undid) when present — with the rows behind a \"details\" disclosure, and nothing rendered at all when the grouped rows are empty. Expanded, it shows one first-person row per alert (\"Resolved *X* — evidence\", \"Dismissed *X* as stale — evidence\", \"Handed *X* to Dana Kim\" / \"Proposed *X* to Dana Kim (awaiting their approval)\", \"Chased Dana Kim on *X*\", \"Raised *X* to high\", \"Drafted *T* from *X*\", \"Folded *X* into *Y*\", \"Started watching *slug*\"), escalations first; rows sharing an alert collapse to the newest move with the others as an \"also …\" trailer — a close always keeps the visible slot (it carries Undo), otherwise an escalation beats routed / nudged / drafted; a merge whose survivor is listed becomes \"N duplicates folded in\" on the survivor. Every row links its `evidence_ref` (or \"evidence\") to `/audit?event_type=…&q=…` (the audit page pre-fills those filters from the query string), a still-open row jumps to its card (`#alert-<id>`), drafted rows link `/artifacts`, watch rows `/watchlist`. Undo is offered only while the close still stands (`status` not `open`); a reverted close shows \"Reopened\". Dismissing a watch-sourced alert lowers that watch's `trust_score` (which discounts ranking and is shown to the review as evidence); the ack body may carry `mute_topic`.\n\n## Multi-client practice section\n\nIn multi-client practice mode (2+ client slots — see the Client Companies section), the response gains an additive `practice_clients` list: rollup cards for the **parked** clients (overdue follow-ups, awaiting replies, unread alerts, onboarding due soon, renewal countdowns), each stamped with the save point its data reflects. Single-company installs always receive an empty list and the UI renders nothing.",+ "markdown": "`openexecutive.api.routes.today` serves the morning brief — a one-screen, read-only view of what is happening across the org. It is the default landing surface (the Next.js root renders `<Briefing>`).\n\n`GET /today` returns `TodayResponse` assembled by `_build_today()`, which is synchronous and caller-agnostic:\n\n- **`departments`** — per-department goal health, rolling up each department's goal counts (`total`, `at_risk`, `off_track`) plus its awaiting-workflow count, and `attention_goals`: the actual off-track/at-risk goals (worst first, capped at 3) with `key_result`, `current`, `target`, and `status`, so the briefing's Department card shows *which* goal is off and how far without a click. Empty for healthy/inactive departments.\n- **`people`** — an attention-ranked roster. Each person carries `awaiting_action` count, soonest SLA, a `status` (`on_leave` / `needs_reply` / `awaiting` / `clear`), reachability, `overdue`, a server `priority` sort key, and a cached one-line `insight`. Sorted by `(-priority, full_name)`.\n- **`proposals`** — the *live* unread alerts (workflow approvals, triage-classified inbound, Executive signals, flagged artifacts, and gated calendar bookings): unread, inside their category TTL, not snoozed — see *Alert lifecycle* below. Each carries `score`, `category` (`action` vs `monitoring`), `surfaced_reason` from `openexecutive.briefing.ranking`, the lifecycle fields (`occurrence_count`, `last_seen_at`, `last_reviewed_at`, `review_verdict`, `review_note`, `recommended_move`, `why_now`, `due_at`, `superseded_count`, `suggested_workflow`), and `decision_instance_id` (set only when the proposal is backed by a decision-ledger row — a calendar booking awaiting approval). The UI splits them into 'mine' vs 'across the team' using `caller_person_id`. For decision-backed proposals the card's Approve/Reject call the `/decisions` endpoints (which book or cancel the event server-side and clear the alert) instead of the ack-and-hand-off-to-chat flow — so meeting bookings are reviewed in the briefing itself rather than on a separate page.\n- **`narrative`** — a per-viewer Executive-voice header synthesized by `synthesize_briefing_narrative`; the principal gets the whole-company scope, teammates a role-scoped one. In the web UI each bullet of this narrative is a click target: clicking one hands off to chat (the same `onContinue` path as the proposal cards) seeded to discuss that item. The Executive recognizes it because every chat turn now carries a `<briefing>` digest of open alerts (see Memory).\n- **`in_flight`** / **`awaiting`** — upcoming Executive commitments and people we are waiting on.\n- **`handled_overnight`** — the autonomous moves the Executive *completed* since the last delivered morning brief: the alert review's (routed, nudged, escalated, drafted, merged, closed) plus the research watch policy's (`watching` — a watch added on its own because it was grounded in company data; `stopped_watching` — a research watch auto-disabled as noisy or dead; no alert id, re-enable from `/watchlist`). A `changed` verdict (the review rewrote an open alert's headline / body / severity) is deliberately **not** here: the alert is still open in \"Needs you\" and its card carries the note, so the brief reports it under \"what changed\" (a REWRITTEN block) rather than as done. Each row is structured, not just a sentence: `kind`, the audit `summary` (nudge bookkeeping marker stripped), `at`, `alert_id`, `event_type` (for a pre-filtered `/audit` deep link), `headline` (the alert's headline at move time; a watch's slug), `target` (person name for routed / nudged, survivor headline for merged, new severity for escalated, draft title, workflow name), `detail` (the cited evidence or the watch policy's reason), `outcome` (`resolved` | `dismissed` for a close, `proposed` for a route that went through the authority gate), `evidence_ref` (S1 / R2 / A3), `superseded_by_alert_id`, and `status` — the alert's lifecycle state **now** (`open` = live in the queue per `lifecycle.is_live` | `resolved` | `dismissed` | `expired` | `merged` | `acked` | `inactive` for snoozed / past-TTL rows), looked up per row so a close the principal already undid renders as reopened instead of offering a second Undo, and a \"still open\" jump link only appears when there is a card to land on. The morning brief also carries a one-line count of research watch suggestions waiting on `/watchlist`.\n- **`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) is deliberately one sentence by default: a first-person heading built from counts only — \"Since your last brief: N off your plate (closes still standing, and merges whose survivor is not itself listed; a merge into a listed survivor counts on that survivor's row), N in others' hands (routed / nudged), N waiting on you (escalated)\", plus \"N drafts ready\", \"N workflows suggested\", \"N watch changes\", \"N other moves\" (a kind the UI does not know) and \"N back on your plate\" (a close that is open again) when present — with the rows behind a \"details\" disclosure, and nothing rendered at all when the grouped rows are empty. The pure logic (grouping, headline, links) lives in `packages/ui/src/lib/handled.ts` and is covered by `npm test`. Expanded, it shows one first-person row per alert (\"Resolved *X* — evidence\", \"Dismissed *X* as stale — evidence\", \"Handed *X* to Dana Kim\" / \"Proposed *X* to Dana Kim (awaiting their approval)\", \"Chased Dana Kim on *X*\", \"Raised *X* to high\", \"Drafted *T* from *X*\", \"Folded *X* into *Y*\", \"Started watching *slug*\"), escalations first; rows sharing an alert collapse to the newest move with the others as an \"also …\" trailer — a close always keeps the visible slot (it carries Undo), otherwise an escalation beats routed / nudged / drafted; a merge whose survivor is listed becomes \"N duplicates folded in\" on the survivor. Every row links its `evidence_ref` (or \"evidence\") to `/audit?event_type=…&q=…` (the audit page pre-fills those filters from the query string), a still-open row jumps to its card (`#alert-<id>`), drafted rows link `/artifacts`, watch rows `/watchlist`. Undo is offered only while the close still stands (`status` not `open`); a reverted close shows \"Reopened\". Dismissing a watch-sourced alert lowers that watch's `trust_score` (which discounts ranking and is shown to the review as evidence); the ack body may carry `mute_topic`.\n\n## Multi-client practice section\n\nIn multi-client practice mode (2+ client slots — see the Client Companies section), the response gains an additive `practice_clients` list: rollup cards for the **parked** clients (overdue follow-ups, awaiting replies, unread alerts, onboarding due soon, renewal countdowns), each stamped with the save point its data reflects. Single-company installs always receive an empty list and the UI renders nothing.","mermaid": "flowchart TD\n REQ[\"GET /today\"]\n BUILD[\"_build_today()\"]\n DEPTS[\"departments<br/>(per-dept goal health)\"]\n ROSTER[\"people<br/>(attention-ranked roster)\"]\n PROPS[\"proposals<br/>(unread alerts, routed)\"]\n INFLIGHT[\"in_flight<br/>(pending follow-ups / nudges)\"]\n AWAIT[\"awaiting<br/>(replies we await)\"]\n 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-13T00:00:00+00:00"}diff --git a/packages/ui/scripts/handled.test.mjs b/packages/ui/scripts/handled.test.mjsnew file mode 100644index 00000000..be6dfef0--- /dev/null+++ b/packages/ui/scripts/handled.test.mjs@@ -0,0 +1,125 @@+import assert from "node:assert/strict";+import test from "node:test";+import {+ HANDLED_REOPENABLE,+ groupHandled,+ handledAlsoLine,+ handledHeadline,+ handledKey,+ handledProofHref,+ joinClauses,+} from "../src/lib/handled.ts";++// Rows arrive newest-first from /today (brief_state.handled_since sorts by+// `at` descending); `at` values below are chosen to match that order.+const row = (kind, alertId, extra = {}) => ({+ kind,+ summary: `${kind} ${alertId}`,+ at: extra.at ?? "2026-09-13T06:00:00+00:00",+ alert_id: alertId,+ status: extra.status ?? "open",+ ...extra,+});+const never = () => false;++test("a newer close keeps the visible slot over an older escalation, with Undo intact", () => {+ const rows = groupHandled([+ row("closed", 7, { at: "2026-09-13T07:00:00+00:00", status: "resolved" }),+ row("escalated", 7, { at: "2026-09-13T01:00:00+00:00" }),+ ]);+ assert.equal(rows.length, 1);+ assert.equal(rows[0].item.kind, "closed");+ assert.deepEqual(rows[0].also.map((a) => a.kind), ["escalated"]);+ assert.equal(handledAlsoLine(rows[0]), "also raised");+});++test("an escalation beats a newer route or nudge on the same alert", () => {+ const rows = groupHandled([+ row("nudged", 3, { at: "2026-09-13T07:00:00+00:00" }),+ row("escalated", 3, { at: "2026-09-13T03:00:00+00:00" }),+ row("routed", 3, { at: "2026-09-13T01:00:00+00:00" }),+ ]);+ assert.equal(rows[0].item.kind, "escalated");+ assert.deepEqual(rows[0].also.map((a) => a.kind), ["nudged", "routed"]);+});++test("a merge into a listed survivor folds into that survivor's row", () => {+ const rows = groupHandled([+ row("closed", 9, { status: "resolved" }),+ row("merged", 10, { superseded_by_alert_id: 9, status: "merged" }),+ row("merged", 11, { superseded_by_alert_id: 9, status: "merged" }),+ ]);+ assert.equal(rows.length, 1);+ assert.equal(rows[0].foldedIn, 2);+ assert.equal(handledAlsoLine(rows[0]), "2 duplicates folded in");+});++test("a merge whose survivor is not listed stays as its own row", () => {+ const rows = groupHandled([row("merged", 10, { superseded_by_alert_id: 99, status: "merged" })]);+ assert.equal(rows.length, 1);+ assert.equal(rows[0].item.kind, "merged");+});++test("a self-referencing merge produces no rows (the panel renders nothing)", () => {+ assert.deepEqual(groupHandled([row("merged", 7, { superseded_by_alert_id: 7 })]), []);+});++test("rows sort escalations first, then closes, then routed/nudged, then transparency", () => {+ const rows = groupHandled([+ row("watching", null, { alert_id: null, headline: "stock-acme" }),+ row("routed", 1),+ row("closed", 2, { status: "resolved" }),+ row("escalated", 3),+ ]);+ assert.deepEqual(rows.map((r) => r.item.kind), ["escalated", "closed", "routed", "watching"]);+});++test("headline buckets every kind and pluralises", () => {+ const rows = groupHandled([+ row("closed", 1, { status: "resolved" }),+ row("merged", 2, { superseded_by_alert_id: 50, status: "merged" }),+ row("routed", 3),+ row("nudged", 4),+ row("escalated", 5),+ row("drafted", 6),+ row("suggested_workflow", 7),+ row("watching", null, { alert_id: null, at: "2026-09-13T05:00:00+00:00" }),+ row("stopped_watching", null, { alert_id: null, at: "2026-09-13T04:00:00+00:00" }),+ row("snoozed", 8),+ ]);+ assert.equal(+ handledHeadline(rows, never),+ "Since your last brief: 2 off your plate, 2 in others' hands, 1 waiting on you, " ++ "1 draft ready, 1 workflow suggested, 2 watch changes, and 1 other move.",+ );+});++test("a reverted close is back on the plate, never a fresh move", () => {+ const rows = groupHandled([row("closed", 1, { status: "open" })]);+ const reverted = (h) => h.status === "open";+ assert.equal(handledHeadline(rows, reverted), "Since your last brief: 1 back on your plate.");+});++test("joinClauses reads naturally at one, two and many parts", () => {+ assert.equal(joinClauses(["a"]), "a");+ assert.equal(joinClauses(["a", "b"]), "a and b");+ assert.equal(joinClauses(["a", "b", "c", "d"]), "a, b, c, and d");+});++test("proof link encodes both filters and is absent without an event type", () => {+ assert.equal(+ handledProofHref(row("closed", 1, { event_type: "alert_review_closed", headline: "Q3 pricing & copy" })),+ "/audit?event_type=alert_review_closed&q=Q3%20pricing%20%26%20copy",+ );+ assert.equal(handledProofHref(row("closed", 1)), null);+});++test("row keys distinguish two moves on one alert", () => {+ const a = row("routed", 1, { at: "2026-09-13T01:00:00+00:00" });+ const b = row("closed", 1, { at: "2026-09-13T07:00:00+00:00" });+ assert.notEqual(handledKey(a), handledKey(b));+});++test("reopenable statuses match what the server accepts, plus unknown", () => {+ assert.deepEqual([...HANDLED_REOPENABLE].sort(), ["", "dismissed", "expired", "merged", "resolved"]);+});diff --git a/packages/ui/src/components/Briefing.tsx b/packages/ui/src/components/Briefing.tsxindex 8a2dfb66..cd40554e 100644--- a/packages/ui/src/components/Briefing.tsx+++ b/packages/ui/src/components/Briefing.tsx@@ -25,6 +25,16 @@ import {type Today,} from "@/lib/api";import { clientCountsSummary, renewalBadge } from "@/lib/practice";+import {+ HANDLED_REOPENABLE,+ groupHandled,+ handledAlsoLine,+ handledHeadline,+ handledKey,+ handledProofHref,+ isCloseKind,+ type HandledRow,+} from "@/lib/handled";import InfoTip from "./InfoTip";import { phaseLabel } from "./onboarding/meta";import { SectionHeading } from "./memories/shared";@@ -1476,134 +1486,8 @@ function MonitoringPanel({);}-// 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.-//-// Deliberately quiet: the default render is ONE sentence of counts. The-// rows — and Undo for every autonomous close, which is what makes the-// autonomy un-scary (visible, evidence-cited, one click back) — sit behind-// a "details" disclosure. A night with nothing handled renders nothing.-//-// 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.--// One table per kind: reading order (what needs the principal first, then-// what they can undo, then what went to others, then transparency) and the-// short past-tense verb for the "also …" trailer.-const HANDLED_KINDS: Record<string, { order: number; verb: string }> = {- 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" },- watching: { order: 3, verb: "started watching" },- stopped_watching: { order: 3, verb: "stopped watching" },-};-const handledOrder = (kind: string) => HANDLED_KINDS[kind]?.order ?? 4;-const handledVerb = (kind: string) => HANDLED_KINDS[kind]?.verb ?? kind;--// Stable key for one handled row (an alert can appear twice in one pass —-// 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, with two overrides: a close (terminal,-// and the row that carries Undo) is never hidden behind an older move, and-// otherwise an escalation beats routed / nudged / drafted — 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" && !isCloseKind(row.item) && 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. Every kind lands in some bucket, because-// this sentence is the whole default render: a close the principal already-// undid reads as "reopened by you", never as a fresh move.-function handledHeadline(rows: HandledRow[], reverted: (h: HandledItem) => boolean): string {- const counts = { offPlate: 0, reopened: 0, others: 0, waiting: 0, drafted: 0, suggested: 0, watches: 0, other: 0 };- for (const r of rows) {- const k = r.item.kind;- if (isCloseKind(r.item)) counts[reverted(r.item) ? "reopened" : "offPlate"] += 1;- else if (k === "routed" || k === "nudged") counts.others += 1;- else if (k === "escalated") counts.waiting += 1;- else if (k === "drafted") counts.drafted += 1;- else if (k === "suggested_workflow") counts.suggested += 1;- else if (k === "watching" || k === "stopped_watching") counts.watches += 1;- else counts.other += 1;- }- const plural = (n: number, one: string, many: string) => `${n} ${n === 1 ? one : many}`;- const parts: string[] = [];- if (counts.offPlate > 0) parts.push(`${counts.offPlate} off your plate`);- if (counts.others > 0) parts.push(`${counts.others} in others' hands`);- if (counts.waiting > 0) parts.push(`${counts.waiting} waiting on you`);- if (counts.drafted > 0) parts.push(plural(counts.drafted, "draft ready", "drafts ready"));- if (counts.suggested > 0) parts.push(plural(counts.suggested, "workflow suggested", "workflows suggested"));- if (counts.watches > 0) parts.push(plural(counts.watches, "watch change", "watch changes"));- if (counts.other > 0) parts.push(plural(counts.other, "other move", "other moves"));- if (counts.reopened > 0) parts.push(`${counts.reopened} reopened by you`);- return `Since your last brief: ${joinClauses(parts)}.`;-}+// Handled rail — pure logic lives in @/lib/handled (tested by `npm test`);+// only rendering stays here.// 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).@@ -1641,9 +1525,6 @@ function handledSentence(h: HandledItem): React.ReactNode {}}-// Statuses `POST /alerts/{id}/reopen` accepts, plus "" for an unknown lookup.-const HANDLED_REOPENABLE = new Set(["", "resolved", "dismissed", "expired", "merged"]);-// Jump to the alert's card; when it is folded behind "Show more" (no element// yet), land on the queue section instead of clicking dead.function scrollToAlertCard(alertId: number) {@@ -1651,22 +1532,6 @@ function scrollToAlertCard(alertId: number) {target?.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(", ")}`);- return parts.join(" · ");-}-function HandledTrailerLink({ href, label }: { href: string; label: string }) {return (<>@@ -1783,13 +1648,13 @@ function HandledOvernightPanel({{open ? "hide" : "details"} <span aria-hidden="true">{open ? "▾" : "▸"}</span></button></div>- {open && (- <div id={HANDLED_DETAILS_ID} className="mt-1.5 divide-y divide-line border-t border-line">- {rows.map((row) => (+ {/* Always in the DOM so aria-controls resolves while collapsed. */}+ <div id={HANDLED_DETAILS_ID} hidden={!open} className="mt-1.5 divide-y divide-line border-t border-line">+ {open &&+ rows.map((row) => (<HandledRowView key={handledKey(row.item)} row={row} reverted={reverted(row.item)} onReopen={onReopen} />))}- </div>- )}+ </div></section>);}diff --git a/packages/ui/src/lib/handled.ts b/packages/ui/src/lib/handled.tsnew file mode 100644index 00000000..cfa70826--- /dev/null+++ b/packages/ui/src/lib/handled.ts@@ -0,0 +1,155 @@+// Pure logic behind the briefing's handled rail (HandledOvernightPanel in+// components/Briefing.tsx): grouping audit rows per alert, the one-line+// summary, and the trailer links. No React here so `npm test` can exercise+// it directly (scripts/handled.test.mjs).+import type { HandledItem } from "./api";++// 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.+//+// Deliberately quiet: the default render is ONE sentence of counts. The+// rows — and Undo for every autonomous close, which is what makes the+// autonomy un-scary (visible, evidence-cited, one click back) — sit behind+// a "details" disclosure. A night with nothing handled renders nothing.+//+// 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.++// One table per kind: reading order (what needs the principal first, then+// what they can undo, then what went to others, then transparency) and the+// short past-tense verb for the "also …" trailer.+export const HANDLED_KINDS: Record<string, { order: number; verb: string }> = {+ 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" },+ watching: { order: 3, verb: "started watching" },+ stopped_watching: { order: 3, verb: "stopped watching" },+};+export const handledOrder = (kind: string) => HANDLED_KINDS[kind]?.order ?? 4;+export const handledVerb = (kind: string) => HANDLED_KINDS[kind]?.verb ?? kind;++// Stable key for one handled row (an alert can appear twice in one pass —+// e.g. routed then closed — so the alert id alone is not unique).+export function handledKey(h: HandledItem): string {+ return `${h.kind}-${h.at}-${h.alert_id ?? ""}`;+}++export 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.+export 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, with two overrides: a close (terminal,+// and the row that carries Undo) is never hidden behind an older move, and+// otherwise an escalation beats routed / nudged / drafted — the boast must+// never bury the row that needs the CEO.+export 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" && !isCloseKind(row.item) && 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;+}++export 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. Every kind lands in some bucket, because+// this sentence is the whole default render: a close the principal already+// undid reads as "back on your plate" (the status alone does not say who+// reopened it), never as a fresh move.+export function handledHeadline(rows: HandledRow[], reverted: (h: HandledItem) => boolean): string {+ const counts = { offPlate: 0, reopened: 0, others: 0, waiting: 0, drafted: 0, suggested: 0, watches: 0, other: 0 };+ for (const r of rows) {+ const k = r.item.kind;+ if (isCloseKind(r.item)) counts[reverted(r.item) ? "reopened" : "offPlate"] += 1;+ else if (k === "routed" || k === "nudged") counts.others += 1;+ else if (k === "escalated") counts.waiting += 1;+ else if (k === "drafted") counts.drafted += 1;+ else if (k === "suggested_workflow") counts.suggested += 1;+ else if (k === "watching" || k === "stopped_watching") counts.watches += 1;+ else counts.other += 1;+ }+ const plural = (n: number, one: string, many: string) => `${n} ${n === 1 ? one : many}`;+ const parts: string[] = [];+ if (counts.offPlate > 0) parts.push(`${counts.offPlate} off your plate`);+ if (counts.others > 0) parts.push(`${counts.others} in others' hands`);+ if (counts.waiting > 0) parts.push(`${counts.waiting} waiting on you`);+ if (counts.drafted > 0) parts.push(plural(counts.drafted, "draft ready", "drafts ready"));+ if (counts.suggested > 0) parts.push(plural(counts.suggested, "workflow suggested", "workflows suggested"));+ if (counts.watches > 0) parts.push(plural(counts.watches, "watch change", "watch changes"));+ if (counts.other > 0) parts.push(plural(counts.other, "other move", "other moves"));+ if (counts.reopened > 0) parts.push(`${counts.reopened} back on your plate`);+ return `Since your last brief: ${joinClauses(parts)}.`;+}++// Statuses `POST /alerts/{id}/reopen` accepts, plus "" for an unknown lookup.+export const HANDLED_REOPENABLE = new Set(["", "resolved", "dismissed", "expired", "merged"]);+++// The audit page pre-filters on these two query params, so the row's+// "evidence" link lands on the rows that back it.+export 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.+export 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(", ")}`);+ return parts.join(" · ");+}