Skip to content

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

fix(alerts): label alerts team members raise and limit what they can dismiss (#509)

Rufus47084a3dc10e
diff --git a/packages/core/openexecutive/alerts/models.py b/packages/core/openexecutive/alerts/models.py
index c302dc0b..44e6f566 100644
--- a/packages/core/openexecutive/alerts/models.py
+++ b/packages/core/openexecutive/alerts/models.py
@@ -110,6 +110,18 @@ class AlertEvent(BaseModel):
# routes it to the principal, keeps it out of every broadcast and live
# push, and never coalesces it into a card someone else can see.
private: bool = False
+ # Set only by the create_alert tool on a team member's chat turn: who
+ # raised it, for its "Raised by <name>" label. Such an alert keeps a
+ # source and id the server picked (``TEAM_RAISED_SOURCE``), whatever the
+ # turn asked, and never goes out as a company-wide broadcast — a person
+ # or department only (alerts/pipeline.py).
+ raised_by: str = ""
+
+
+# The source of every alert a team member raises from chat (see
+# ``AlertEvent.raised_by``): never "email" or a watch, so it can't pose as
+# one, coalesce into one, or claim the id a real one will arrive with.
+TEAM_RAISED_SOURCE = "team_member"
class TriageDecision(BaseModel):
diff --git a/packages/core/openexecutive/alerts/pipeline.py b/packages/core/openexecutive/alerts/pipeline.py
index a1d5525d..9d90a3fb 100644
--- a/packages/core/openexecutive/alerts/pipeline.py
+++ b/packages/core/openexecutive/alerts/pipeline.py
@@ -136,6 +136,16 @@ def _ground_decision(
)
+def _label_team_raised(decision: TriageDecision, name: str) -> TriageDecision:
+ """``decision`` with its body led by who raised it, so a card a team
+ member raised from chat never reads as news from anywhere else."""
+ label = f"Raised by {name}."
+ body = decision.body.strip()
+ if body.startswith(label):
+ return decision
+ return decision.model_copy(update={"body": f"{label} {body}".strip()})
+
+
async def evaluate_and_dispatch(
event: AlertEvent,
db_path: Path | None = None,
@@ -213,14 +223,25 @@ async def evaluate_and_dispatch(
# dispatch: keep only what the event itself (or the profile, or the
# initiatives triage was shown) supports.
decision = _ground_decision(decision, event, initiatives)
+ if event.raised_by:
+ decision = _label_team_raised(decision, event.raised_by)
effective_channels = preferences.resolve_channels(
decision.channels, decision.severity, prefs
)
+ if event.raised_by:
+ # People and departments only: a company-wide post stays with the
+ # owner, whatever triage made of what the team member wrote.
+ effective_channels = [
+ c for c in effective_channels if c != AlertChannel.COMPANY_BROADCAST
+ ]
# A producer that knows the stable identity of the situation (a watch
# slug) wins over the model's free-text key.
dedup_key = event.dedup_hint or decision.dedup_key
+ if event.raised_by:
+ # One team member's alert never folds into another's card.
+ dedup_key = f"raised_by:{(event.from_ or event.raised_by).lower()}:{dedup_key}"
topic_tags = _with_department_tag(
decision.topic_tags, event.department or event.channel,
)
diff --git a/packages/core/openexecutive/api/routes/alerts.py b/packages/core/openexecutive/api/routes/alerts.py
index a316ff13..739b58ac 100644
--- a/packages/core/openexecutive/api/routes/alerts.py
+++ b/packages/core/openexecutive/api/routes/alerts.py
@@ -50,6 +50,28 @@ def _caller_is_principal(request: Request) -> bool:
return caller_is_principal(request)
+def _caller_clears_anything(request: Request) -> bool:
+ """The principal (or anyone on an install with no principal yet, so a
+ first run is never locked out) may clear any card."""
+ from openexecutive.api.routes.chat import _caller_is_principal_or_unclaimed
+
+ return _caller_is_principal_or_unclaimed(request)
+
+
+def _caller_may_clear(alert: Alert, request: Request) -> bool:
+ """Whether the caller may approve or dismiss ``alert``: the principal
+ anything, a team member only what is routed to them."""
+ if _caller_clears_anything(request):
+ return True
+ from openexecutive.api.routes.chat import _resolve_caller_person_id
+
+ caller = _resolve_caller_person_id(request)
+ return caller is not None and alert.routed_to_person_id == caller
+
+
+_NOT_YOURS = "Only items assigned to you can be cleared. Ask the owner to clear this one."
+
+
class AckBody(BaseModel):
status: str = Field(..., pattern="^(read|ack|dismissed)$")
# Optional on a dismiss: a topic pattern to mute (see alerts/preferences
@@ -68,6 +90,8 @@ def ack_alert(alert_id: int, body: AckBody, request: Request) -> Alert:
status_code=409,
detail="Answer this one from its card: add them, say who they are, or ignore them.",
)
+ if body.status != "read" and not _caller_may_clear(existing, request):
+ raise HTTPException(status_code=403, detail=_NOT_YOURS)
if not store.set_status(alert_id, body.status):
raise HTTPException(status_code=404, detail="Alert not found")
# Feedback loop: a dismiss on a watch-sourced alert lowers that watch's
@@ -75,7 +99,8 @@ def ack_alert(alert_id: int, body: AckBody, request: Request) -> Alert:
# on a real transition — re-posting the same status teaches nothing.
if existing.status != body.status:
lifecycle.record_ack_feedback(existing, body.status)
- if body.status == "dismissed":
+ # A mute silences the topic for everyone: the principal's call.
+ if body.status == "dismissed" and _caller_clears_anything(request):
lifecycle.apply_mute_request(existing, body.mute_topic)
updated = store.get_alert(alert_id)
if updated is None:
@@ -405,9 +430,24 @@ def bulk_ack_alerts(body: BulkAckBody, request: Request) -> BulkAckResponse:
for a in (store.get_alert(i) for i in (body.alert_ids or [])[:500])
if a is not None
}
+ alert_ids = body.alert_ids
+ if not _caller_clears_anything(request):
+ # A team member clears only their own items, by id: never an age or
+ # category sweep of the company's queue.
+ if body.older_than_days is not None:
+ raise HTTPException(status_code=403, detail=_NOT_YOURS)
+ from openexecutive.api.routes.chat import _resolve_caller_person_id
+
+ caller = _resolve_caller_person_id(request)
+ alert_ids = [
+ i for i, a in targets.items()
+ if i is not None and caller is not None and a.routed_to_person_id == caller
+ ]
+ if not alert_ids:
+ return BulkAckResponse(count=0)
updated_ids = store.bulk_set_status(
body.status,
- alert_ids=body.alert_ids,
+ alert_ids=alert_ids,
before=before,
category=body.category,
exclude_sources=tuple(lifecycle.TTL_EXEMPT_SOURCES),
diff --git a/packages/core/openexecutive/architecture/architecture-facts.yaml b/packages/core/openexecutive/architecture/architecture-facts.yaml
index 703ce3fe..3dfaa874 100644
--- a/packages/core/openexecutive/architecture/architecture-facts.yaml
+++ b/packages/core/openexecutive/architecture/architecture-facts.yaml
@@ -887,6 +887,22 @@ routing:
the HTTP ack applies: a `dismissed` on a watch-sourced alert lowers
that watch's `trust_score` (`monitoring.store.record_dismissal`); an
`ack` recovers it a little.
+ TEAM MEMBERS: on a team member's turn (`department_gate.speaker`, via
+ `alert_tools.team_member_speaker`) `ack_alert` refuses any alert not
+ routed to them (`routed_to_person_id`); the principal clears anything.
+ `create_alert` there ignores the given `source`, `external_id` and
+ `from_address`: source `team_member` (`alerts.models.TEAM_RAISED_SOURCE`),
+ a fresh uuid id, from = their email, `AlertEvent.raised_by` = their name.
+ Otherwise a teammate could raise "urgent from ceo@..." or pre-claim a
+ real (source, external_id) so the real alert is dropped as a duplicate.
+ The pipeline leads the body with "Raised by <name>." and drops
+ `company_broadcast` after `resolve_channels` (person / department only),
+ and prefixes the dedup key with who raised it so teammates' cards never
+ coalesce. A teammate's saved workflow raises as its creator
+ (`alert_tools.raised_for_workflow_owner`, bound in `action_step._dispatch`).
+ HTTP matches: `/alerts/{id}/ack` (ack/dismissed) and `/alerts/bulk-ack`
+ let a team member clear only alerts routed to them (403 otherwise, no age
+ sweep), and only the principal's dismiss applies `mute_topic`.
alert_lifecycle: |
`openexecutive.alerts.lifecycle` gives every alert a lifetime and one
shared read view. TTL per category — `ALERT_TTL_DAYS_ACTION` (14) for
diff --git a/packages/core/openexecutive/architecture/prebuilt/lifecycle.json b/packages/core/openexecutive/architecture/prebuilt/lifecycle.json
index 67c446fe..18493674 100644
--- a/packages/core/openexecutive/architecture/prebuilt/lifecycle.json
+++ b/packages/core/openexecutive/architecture/prebuilt/lifecycle.json
@@ -1,7 +1,7 @@
{
"section_id": "lifecycle",
"title": "Request Lifecycle",
- "markdown": "A single chat message makes a full round-trip through the API, the orchestrator's tool-use loop, a parallel specialist fan-out, and synthesis — all streamed back as server-sent events.\n\n### Steps\n\n1. **Arrival** — the client mints a `client_turn_id` and posts to `POST /chat` (`openexecutive.api.routes.chat`). The turn carries a `<current_speaker>` hint resolved from the caller's `person_id` (followed by that person's `<working_style>` rules when they have any — see the attunement section — and a `<lessons>` block when a lesson the conversation review learned from a miss matches the message, `memory/lessons.py`; see the memory section), plus a `<briefing>` digest of current open alerts (built in parallel with RAG/episodic/peer-memory fetches) so the Executive can discuss any item shown on the `/today` briefing page. A turn arriving from a chat adapter instead of the web app also carries a `<channel>` block naming the surface and stating which approvals can be completed there; on Slack the `<briefing>` digest is gated to the principal's DMs. All three ride in the **user turn**, never a cached system block, as does a `<drive_memory>` block naming the Drive files this conversation already found or opened and the Drive searches that matched nothing (see the memory section). The server registers a stop switch under that id *before* the context fetch, so a Stop pressed during those first seconds halts the turn before any model call is made.\n2. **Tool-use loop** — the `Executive` calls Claude. For a cross-domain question the assistant turn emits multiple `consult_specialist` tool-use blocks at once. The call carries the conversation so far (`Session.get_recent_history`: 20 to 30 turns, its start moving in steps of 10) with a 1h cache marker on the previous reply, so each message reads the earlier conversation from the prompt cache and writes only what is new (see Caching); on the OpenRouter path the translator keeps that marker on the reply's text. The history is re-read from the stored transcript at the start of every web turn, so a chat continued in a chat app and then reopened on the web or phone includes the turns the app added.\n The person can keep typing while it works. A message sent then (`POST /chat/add`) joins the running turn: the loop adds it after the next round's tool results, so the answer follows it, and it is saved as its own message before the reply. One that arrives while the final answer is being written becomes the next turn instead. A conversation runs one turn at a time.\n3. **Parallel fan-out** — `openexecutive.orchestrator.router.route_parallel` dispatches those calls concurrently, bounded by `MAX_PARALLEL_SPECIALISTS`; calls past the cap get a skip tool_result. A specialist that raises (a timeout, an overloaded model) or returns no text no longer fails the batch: its tool_result says it is unavailable and tells the Executive not to invent its view, the others' results stand, and the turn goes on. It does not count as consulted, so it takes no committee seat and no department memory records the turn, and its documents are left out of the answer's sources. On the web chat the reply need not mention the gap, because the app shows it under the answer; on every other channel the tool_result asks the Executive to say in one sentence that part of the analysis is missing. A knowledge retrieval that fails likewise leaves that specialist without context rather than failing the turn.\n4. **Per-specialist RAG** — each specialist runs its own domain-filtered ChromaDB query, then reasons over the retrieved chunks and returns analysis as a tool_result. Its user turn also carries a `<company_stage>` tag from the session's company profile, so stage-sensitive advice (venture benchmarks vs. cash-first for a bootstrapped company) does not depend on the Executive remembering to mention it. Once the batch is done, the documents each answering specialist's retrieval returned are named, in call order, into the turn's `TurnSources` (`orchestrator/answer_sources.py`), which the web chat route owns and which also holds its own search's documents. Synced Google Drive files are recorded as `drive` sources with their Drive link, and the web chat lists them under **Google Drive**.\n5. **Synthesis** — the Executive feeds the tool_results back to Claude and streams one coherent reply. Every tool round — not just a specialist one — emits an `activity` event naming what is running, immediately followed by a `thinking` keepalive. The label names the *activity*, never the internal agent: \"Putting time on the calendar…\", \"Looking up people…\", or, for a connected (MCP) tool, plain words for what it does (\"Searching Drive…\"), from the same table (`orchestrator/tool_labels.py`) that names the finished chip (\"Searched Drive\"). The raw `server__tool` name never reaches the user. Under the reply, repeats of the same action collapse into one chip with a count, and tapping it lists what each run looked at. A round that really does fan out collapses to the generic \"Consulting specialists…\" — the one voice holds even in the progress line. The keepalive carries no tool information of its own; it used to drive a hardcoded \"Consulting specialists…\" string, so an MCP or calendar round misreported itself as a fan-out.\n **Do what it says.** Before the turn ends, its last reply is checked against the tool calls the turn made (`orchestrator/claim_check.py`). A reply with no word that can claim a change (\"done\", \"removed\", \"I'll remind you\"…) ends the turn as before. Otherwise one small forced-tool call on `ROUTING_MODEL` reads the person's message, the reply and each call with the start of its result, and reports a claim of a change no call made (or put up for approval). The claim must appear word for word in the reply, or it is ignored. The loop then gets one more round with a note in the user turn (never a cached block): make the change with the right tool, or say plainly it isn't done. Once a turn; a failed check lets the reply through. On the web chat the extra round streams after the first reply, separated by a blank line; chat apps send the whole reply at once. `CLAIM_CHECK_ENABLED` turns it off.\n **A chat several people are in.** When its owner shared a web chat (`session_shares`), every turn in it is labelled: the history is re-read with each person's message starting `[Name]: `, the current message too, and a note naming everyone in the chat rides in the user turn (`channel_context_block`, never a cached block). The Executive answers whoever wrote the latest message. Such a session is no private conversation (`Session.shared_chat`): Act as me is off there (`delegation.settings.private_conversation`), open loops are not listed as on a private surface, no one's mail is read there, the principal's included (`teammate_mail._reader_id`), what the Executive remembers about the speaker (peer memory) is not fetched, the alert digest leaves out the principal's private cards and roster requests (`briefing.context.render_and_trust`), and the principal-only tools are withheld whoever speaks (`content_trust.principal_only_withheld`), because the others write into what the principal's turn reads. A message that starts like a label (`[Alex]: …`) loses it before its sender's own goes in front. Peer memory still records each person's own words. Turns stay one at a time under the conversation's lock; the route publishes each one to the chat's live stream (`api.chat_live`) as it runs, so everyone else in the chat watches it happen. A chat of one publishes nothing.\n6. **Optional committee review** — when enabled, `Executive.stream_chat_with_committee()` runs a silent draft, parallel reviewer critiques, then a streamed revision pass.\n7. **Side effects** — after the reply, every rostered speaker's turn (not only the principal's) schedules a fire-and-forget **open-loop pass** (Attunement) beside the episodic extraction: a keyword prefilter, then one forced-tool call that may open or close loops, every item quote-gated against the speaker's own words. A verified speaker's turn is also kept for the **conversation review** (`memory.chat_review`, see Memory), which reads it once the chat has been quiet 30 minutes and fixes what the replies left undone, from the speaker's own quoted words. The user message is persisted with `sender_person_id` — the resolved speaker, never the principal fallback a Discord / Telegram session uses for ownership — and the session records the speaker for the turn (`Session.caller_person_id`), which `close_open_loop` reads. A DM sent while proactive work is tagged (`attunement.outcomes.tag_proactive` — scheduler dispatch, reflection, research, alert review) also opens an outcome-ledger row at `_record_outbound_context`; a user's own turn is never tagged. A tagged DM is also subject to the recipient's own notification settings: in their quiet hours, or when they chose *In my briefs*, the send handler stores it (`outbound_guard.check_hold`, `people.held_messages`) and returns `{\"status\": \"held\"}` instead of sending (see Org). Any side-effecting tool call surfaces an `action_taken` chip, which unlike the ephemeral `activity` label is persisted with the assistant message; once the reply is over — also when it was stopped or timed out — the web chat route sends one `sources` event: the documents and web pages the turn looked at (its own search, each specialist that answered, web search results, and the pages the reply cites, which are always kept) and the areas (\"finance\", never a specialist) it had to go without. The web chat shows it under the reply, and it is persisted with the assistant message as `chat_messages.sources`; other channels don't collect it. The stream closes with a `done` event — preceded by a `stopped` event when the user halted the turn, in which case the partial reply is still persisted and flagged so it reads as cut short rather than complete, and is mirrored into the live in-memory session so the next turn's prompt matches what was saved. The stream still ends with `done` event. While nothing else is going out — a slow tool call, a long specialist round — the route sends an SSE comment (`: keepalive`) every `CHAT_STREAM_KEEPALIVE_S` (15 s by default, 0 for none) so a browser or proxy does not drop the connection as idle; the step it waits on keeps running across it, and the whole-turn deadline is unchanged. Every call through the MCP gateway (Gmail, Calendar, Drive, Outlook, OneDrive, tool search) has its own ceiling, `MCP_TOOL_TIMEOUT_S` (120 s): past it the model gets an error saying the tool did not answer and may still have run, so it checks before calling again, and no outbound linkage is recorded for a send that timed out. One side-effecting tool is gated server-side rather than by its description: `ack_alert` will only accept an `alert_id` from the live alert board the server itself derived this turn — the whole live set, not only the rows the `<briefing>` digest printed, since `/today` renders more cards than the digest lists and every one of them is Discuss-able — and it fails closed, so an id it cannot even parse is refused rather than waved through to the handler's own parse. That check runs on **every** session. It used to run only on turns that arrived from a chat channel, keyed on `origin_channel`, which the browser never sets — so the web, the surface the principal actually uses, was unchecked and the model could ack any id, including one quoted out of an alert body by the briefing page's Discuss handoff. What that buys is bounded and worth stating plainly: an id that is invented, closed, snoozed or expired is refused, including one quoted out of an attacker-written alert body; the model being argued into acking the wrong *live* card is not prevented. The one way to widen that set is `find_alerts`, for an item the principal names that has left the live board (already opened, snoozed, older than the board): a keyword search over alerts of every status whose own results — never an id the model supplies — join the trusted set. It runs only in a turn where `render_and_trust` showed the principal their own board (`Session.principal_board_shown`: the verified principal, and on a channel only in their DM), never merely because the session has a set — every `Session` starts with an empty one, and that empty set is how a Google Chat turn, someone else's DM or an unattended pass refuses every ack — and not on the principal's turn in a shared Slack or Discord thread either, where others read the reply and write into what the model reads. It trusts only rows still open (`unread`, `read`), never a roster-request card, and at most 25 ids per turn across calls, and refuses a query with no word of three or more letters. It also moves the admitted limit outward: a model argued into the wrong search can now reach up to 25 open alerts that are off the board, not only live ones. The board is recorded on the turn's `Session`, and the route binds that session for the **whole** SSE body (`schedule_tools.set_session`, alongside `set_turn`) rather than letting `stream_chat` bind it from inside its own generator. `_sse_body` drives the executive with `asyncio.wait_for(stream.__anext__())`, which runs each step in a fresh Task holding a *copy* of the context, so a binding made inside the generator is discarded with the step that made it: step one sees the session and every later step sees `None`. The tool-call loop runs on those later steps, so the whole guard read an empty set and refused every ack on the web — on live, open cards — until the binding moved out to the route. Anything reading `current_session` mid-turn has the same requirement, and two of them needed more than the binding to behave. `schedule_followup`'s seen-`channel_ref` anti-spam gate refuses a send to an address the session has not seen; with no session it skipped itself, so a web turn could schedule to **any** address, and with an empty one it refused even the principal's own. The route now seeds the caller's own addresses onto the session, so on web the gate means what it means on every other surface. Reply linkage (`_record_outbound_context`, read back by `inbound_hydration` to quote the originating conversation into the turn handling a recipient's reply) is the other: it was never reachable on web, and rather than switch that on for the principal's broadest surface as a side effect it is held back, keyed on an explicit `Session.from_web_chat` flag. Not on an empty `origin_channel` — alert review, the CLI and the unattended workflows all leave it empty while legitimately recording linkage, as does the email poller under its own `email` tag. `scheduled_actions` rows also take their `session_id` from the session. A session that was shown no board has an empty trusted set and can ack nothing, so the unattended passes (the nightly reflection, the research synthesis) are refused by default — they also still withhold the tool outright, which is belt-and-braces rather than the only thing stopping them. After the stream closes, the turn is also handed to the episodic memory extractor (`memory.episodic.schedule_extraction`, fire-and-forget) — on every turn where the principal said anything at all, and only the principal: a turn naming an `origin_channel` must resolve to a person marked `is_principal`, because the quote validator downstream cannot tell whose words it is checking. Both this path and the committee path call the same `should_extract` predicate, and it applies no length floor: the gate used to sum in the assistant's reply, which let a verbose answer drag a trivial turn in and discarded the short, decisive instructions that are the whole point of extracting. A user-side floor would fare no better — \"Do B.\" and \"Done\" are one character apart. See **Memory** for what that cost on a live tenant. None of this runs for a **replay** of a graded turn (`Session.replay`, `memory/replay.py`): the loop answers its acting tools with \"done\" and records them on the session, offers no script, job or server load, and skips every post-turn pass, so the nightly replay of the misses changes nothing and reaches nobody.\n8. **Tool failures** — a handler that raises instead of returning its JSON error is isolated: both tool gathers run with `return_exceptions=True`, the model gets an error `tool_result` naming only the exception's TYPE — a message can carry a filesystem path, a validation error echoing the input, or a third-party HTTP body, and anything in model context can be quoted back to the user, so the full repr stays in the log and the audit row — and the failure is audited with `ok=false`. Only `CancelledError` is re-raised, so turn-timeout and client-disconnect handling still work. Before this one crashing tool aborted the whole turn, which reached the user as an unexplained apology with no audit row (#136).\n\nWeb search, when invoked on the Anthropic path, executes inside the Anthropic API itself (`web_search_20250305`) and returns within the same generation; for any model routed via OpenRouter the same tool becomes OpenRouter's `openrouter:web_search` server tool, which also runs inside the generation with the same search cap and domain lists.\n\nThe install's workspace mode (solo or team, see Org) is read fresh at the start of each turn by `memory.workspace_settings.pin_turn_workspace_mode(session)` and pinned on the session for that turn only (`Session.turn_workspace_mode`): the persona, the org block, the tool list and every tool handler in the turn then agree, and a switch made mid-turn applies from the next turn. A session can instead carry an explicit override, `Session.workspace_mode` (`None` by default), which wins over both — so a caller that runs many conversations concurrently on one Executive, such as evals, can pick the mode per session rather than flipping the install-wide setting. Everything reads it through `effective_workspace_mode(session)` (override, then the turn's pin, then the setting). The principal's role is pinned the same way (`pin_turn_principal_role(session, mode)` → `Session.turn_principal_role`: in solo the `Session.principal_role` override, else the workspace settings read fresh; in team an empty role). The org block renders it, each specialist batch gets it as a `<principal_role>` user-turn tag, and a workflow the turn starts reads the same pin through `effective_principal_role` (override, then the pin, then the setting), so a role edited mid-turn applies from the next turn; a team turn sends none.\n\nAct as me is pinned beside them: `delegation.settings.pin_turn_delegation(session, speaker_text)` records on `Session.turn_delegation` whether the speaker has it on, whether `ghostwrite_email` is offered this turn (the principal, or a team member once the owner lets them, on a verified surface, in a conversation private to them, attended), and the speaker's own words. The pin is also held in a context variable for the turn's task, so two turns running at once on one session each read their own. The tool list, the tool handler and the turn's audit privacy all read that one pin, so a switch flipped mid-turn applies from the next turn. Once the tool touches the speaker's mailbox, the conversation is the speaker's alone (`session_store.mark_mail_private`, the principal included when it isn't theirs), the rest of the turn's audit rows are private (a team member's theirs alone) and the turn teaches no memory: no extraction, open-loop, working-style or Honcho pass runs on it. Later turns of that conversation stay private the same way; the pin also records whether the reading turn is still in the history the model is shown (`mail_in_view`, from `sessions.mail_read_at` against `session.history_window_start`), and links, scripts, workflows and posts to everyone stay withheld only while it is.",
+ "markdown": "A single chat message makes a full round-trip through the API, the orchestrator's tool-use loop, a parallel specialist fan-out, and synthesis — all streamed back as server-sent events.\n\n### Steps\n\n1. **Arrival** — the client mints a `client_turn_id` and posts to `POST /chat` (`openexecutive.api.routes.chat`). The turn carries a `<current_speaker>` hint resolved from the caller's `person_id` (followed by that person's `<working_style>` rules when they have any — see the attunement section — and a `<lessons>` block when a lesson the conversation review learned from a miss matches the message, `memory/lessons.py`; see the memory section), plus a `<briefing>` digest of current open alerts (built in parallel with RAG/episodic/peer-memory fetches) so the Executive can discuss any item shown on the `/today` briefing page. A turn arriving from a chat adapter instead of the web app also carries a `<channel>` block naming the surface and stating which approvals can be completed there; on Slack the `<briefing>` digest is gated to the principal's DMs. All three ride in the **user turn**, never a cached system block, as does a `<drive_memory>` block naming the Drive files this conversation already found or opened and the Drive searches that matched nothing (see the memory section). The server registers a stop switch under that id *before* the context fetch, so a Stop pressed during those first seconds halts the turn before any model call is made.\n2. **Tool-use loop** — the `Executive` calls Claude. For a cross-domain question the assistant turn emits multiple `consult_specialist` tool-use blocks at once. The call carries the conversation so far (`Session.get_recent_history`: 20 to 30 turns, its start moving in steps of 10) with a 1h cache marker on the previous reply, so each message reads the earlier conversation from the prompt cache and writes only what is new (see Caching); on the OpenRouter path the translator keeps that marker on the reply's text. The history is re-read from the stored transcript at the start of every web turn, so a chat continued in a chat app and then reopened on the web or phone includes the turns the app added.\n The person can keep typing while it works. A message sent then (`POST /chat/add`) joins the running turn: the loop adds it after the next round's tool results, so the answer follows it, and it is saved as its own message before the reply. One that arrives while the final answer is being written becomes the next turn instead. A conversation runs one turn at a time.\n3. **Parallel fan-out** — `openexecutive.orchestrator.router.route_parallel` dispatches those calls concurrently, bounded by `MAX_PARALLEL_SPECIALISTS`; calls past the cap get a skip tool_result. A specialist that raises (a timeout, an overloaded model) or returns no text no longer fails the batch: its tool_result says it is unavailable and tells the Executive not to invent its view, the others' results stand, and the turn goes on. It does not count as consulted, so it takes no committee seat and no department memory records the turn, and its documents are left out of the answer's sources. On the web chat the reply need not mention the gap, because the app shows it under the answer; on every other channel the tool_result asks the Executive to say in one sentence that part of the analysis is missing. A knowledge retrieval that fails likewise leaves that specialist without context rather than failing the turn.\n4. **Per-specialist RAG** — each specialist runs its own domain-filtered ChromaDB query, then reasons over the retrieved chunks and returns analysis as a tool_result. Its user turn also carries a `<company_stage>` tag from the session's company profile, so stage-sensitive advice (venture benchmarks vs. cash-first for a bootstrapped company) does not depend on the Executive remembering to mention it. Once the batch is done, the documents each answering specialist's retrieval returned are named, in call order, into the turn's `TurnSources` (`orchestrator/answer_sources.py`), which the web chat route owns and which also holds its own search's documents. Synced Google Drive files are recorded as `drive` sources with their Drive link, and the web chat lists them under **Google Drive**.\n5. **Synthesis** — the Executive feeds the tool_results back to Claude and streams one coherent reply. Every tool round — not just a specialist one — emits an `activity` event naming what is running, immediately followed by a `thinking` keepalive. The label names the *activity*, never the internal agent: \"Putting time on the calendar…\", \"Looking up people…\", or, for a connected (MCP) tool, plain words for what it does (\"Searching Drive…\"), from the same table (`orchestrator/tool_labels.py`) that names the finished chip (\"Searched Drive\"). The raw `server__tool` name never reaches the user. Under the reply, repeats of the same action collapse into one chip with a count, and tapping it lists what each run looked at. A round that really does fan out collapses to the generic \"Consulting specialists…\" — the one voice holds even in the progress line. The keepalive carries no tool information of its own; it used to drive a hardcoded \"Consulting specialists…\" string, so an MCP or calendar round misreported itself as a fan-out.\n **Do what it says.** Before the turn ends, its last reply is checked against the tool calls the turn made (`orchestrator/claim_check.py`). A reply with no word that can claim a change (\"done\", \"removed\", \"I'll remind you\"…) ends the turn as before. Otherwise one small forced-tool call on `ROUTING_MODEL` reads the person's message, the reply and each call with the start of its result, and reports a claim of a change no call made (or put up for approval). The claim must appear word for word in the reply, or it is ignored. The loop then gets one more round with a note in the user turn (never a cached block): make the change with the right tool, or say plainly it isn't done. Once a turn; a failed check lets the reply through. On the web chat the extra round streams after the first reply, separated by a blank line; chat apps send the whole reply at once. `CLAIM_CHECK_ENABLED` turns it off.\n **A chat several people are in.** When its owner shared a web chat (`session_shares`), every turn in it is labelled: the history is re-read with each person's message starting `[Name]: `, the current message too, and a note naming everyone in the chat rides in the user turn (`channel_context_block`, never a cached block). The Executive answers whoever wrote the latest message. Such a session is no private conversation (`Session.shared_chat`): Act as me is off there (`delegation.settings.private_conversation`), open loops are not listed as on a private surface, no one's mail is read there, the principal's included (`teammate_mail._reader_id`), what the Executive remembers about the speaker (peer memory) is not fetched, the alert digest leaves out the principal's private cards and roster requests (`briefing.context.render_and_trust`), and the principal-only tools are withheld whoever speaks (`content_trust.principal_only_withheld`), because the others write into what the principal's turn reads. A message that starts like a label (`[Alex]: …`) loses it before its sender's own goes in front. Peer memory still records each person's own words. Turns stay one at a time under the conversation's lock; the route publishes each one to the chat's live stream (`api.chat_live`) as it runs, so everyone else in the chat watches it happen. A chat of one publishes nothing.\n6. **Optional committee review** — when enabled, `Executive.stream_chat_with_committee()` runs a silent draft, parallel reviewer critiques, then a streamed revision pass.\n7. **Side effects** — after the reply, every rostered speaker's turn (not only the principal's) schedules a fire-and-forget **open-loop pass** (Attunement) beside the episodic extraction: a keyword prefilter, then one forced-tool call that may open or close loops, every item quote-gated against the speaker's own words. A verified speaker's turn is also kept for the **conversation review** (`memory.chat_review`, see Memory), which reads it once the chat has been quiet 30 minutes and fixes what the replies left undone, from the speaker's own quoted words. The user message is persisted with `sender_person_id` — the resolved speaker, never the principal fallback a Discord / Telegram session uses for ownership — and the session records the speaker for the turn (`Session.caller_person_id`), which `close_open_loop` reads. A DM sent while proactive work is tagged (`attunement.outcomes.tag_proactive` — scheduler dispatch, reflection, research, alert review) also opens an outcome-ledger row at `_record_outbound_context`; a user's own turn is never tagged. A tagged DM is also subject to the recipient's own notification settings: in their quiet hours, or when they chose *In my briefs*, the send handler stores it (`outbound_guard.check_hold`, `people.held_messages`) and returns `{\"status\": \"held\"}` instead of sending (see Org). Any side-effecting tool call surfaces an `action_taken` chip, which unlike the ephemeral `activity` label is persisted with the assistant message; once the reply is over — also when it was stopped or timed out — the web chat route sends one `sources` event: the documents and web pages the turn looked at (its own search, each specialist that answered, web search results, and the pages the reply cites, which are always kept) and the areas (\"finance\", never a specialist) it had to go without. The web chat shows it under the reply, and it is persisted with the assistant message as `chat_messages.sources`; other channels don't collect it. The stream closes with a `done` event — preceded by a `stopped` event when the user halted the turn, in which case the partial reply is still persisted and flagged so it reads as cut short rather than complete, and is mirrored into the live in-memory session so the next turn's prompt matches what was saved. The stream still ends with `done` event. While nothing else is going out — a slow tool call, a long specialist round — the route sends an SSE comment (`: keepalive`) every `CHAT_STREAM_KEEPALIVE_S` (15 s by default, 0 for none) so a browser or proxy does not drop the connection as idle; the step it waits on keeps running across it, and the whole-turn deadline is unchanged. Every call through the MCP gateway (Gmail, Calendar, Drive, Outlook, OneDrive, tool search) has its own ceiling, `MCP_TOOL_TIMEOUT_S` (120 s): past it the model gets an error saying the tool did not answer and may still have run, so it checks before calling again, and no outbound linkage is recorded for a send that timed out. One side-effecting tool is gated server-side rather than by its description: `ack_alert` will only accept an `alert_id` from the live alert board the server itself derived this turn — the whole live set, not only the rows the `<briefing>` digest printed, since `/today` renders more cards than the digest lists and every one of them is Discuss-able — and it fails closed, so an id it cannot even parse is refused rather than waved through to the handler's own parse. That check runs on **every** session. It used to run only on turns that arrived from a chat channel, keyed on `origin_channel`, which the browser never sets — so the web, the surface the principal actually uses, was unchecked and the model could ack any id, including one quoted out of an alert body by the briefing page's Discuss handoff. What that buys is bounded and worth stating plainly: an id that is invented, closed, snoozed or expired is refused, including one quoted out of an attacker-written alert body; the model being argued into acking the wrong *live* card is not prevented. The one way to widen that set is `find_alerts`, for an item the principal names that has left the live board (already opened, snoozed, older than the board): a keyword search over alerts of every status whose own results — never an id the model supplies — join the trusted set. It runs only in a turn where `render_and_trust` showed the principal their own board (`Session.principal_board_shown`: the verified principal, and on a channel only in their DM), never merely because the session has a set — every `Session` starts with an empty one, and that empty set is how a Google Chat turn, someone else's DM or an unattended pass refuses every ack — and not on the principal's turn in a shared Slack or Discord thread either, where others read the reply and write into what the model reads. It trusts only rows still open (`unread`, `read`), never a roster-request card, and at most 25 ids per turn across calls, and refuses a query with no word of three or more letters. It also moves the admitted limit outward: a model argued into the wrong search can now reach up to 25 open alerts that are off the board, not only live ones. The board is recorded on the turn's `Session`, and the route binds that session for the **whole** SSE body (`schedule_tools.set_session`, alongside `set_turn`) rather than letting `stream_chat` bind it from inside its own generator. `_sse_body` drives the executive with `asyncio.wait_for(stream.__anext__())`, which runs each step in a fresh Task holding a *copy* of the context, so a binding made inside the generator is discarded with the step that made it: step one sees the session and every later step sees `None`. The tool-call loop runs on those later steps, so the whole guard read an empty set and refused every ack on the web — on live, open cards — until the binding moved out to the route. Anything reading `current_session` mid-turn has the same requirement, and two of them needed more than the binding to behave. `schedule_followup`'s seen-`channel_ref` anti-spam gate refuses a send to an address the session has not seen; with no session it skipped itself, so a web turn could schedule to **any** address, and with an empty one it refused even the principal's own. The route now seeds the caller's own addresses onto the session, so on web the gate means what it means on every other surface. Reply linkage (`_record_outbound_context`, read back by `inbound_hydration` to quote the originating conversation into the turn handling a recipient's reply) is the other: it was never reachable on web, and rather than switch that on for the principal's broadest surface as a side effect it is held back, keyed on an explicit `Session.from_web_chat` flag. Not on an empty `origin_channel` — alert review, the CLI and the unattended workflows all leave it empty while legitimately recording linkage, as does the email poller under its own `email` tag. `scheduled_actions` rows also take their `session_id` from the session. A session that was shown no board has an empty trusted set and can ack nothing, so the unattended passes (the nightly reflection, the research synthesis) are refused by default — they also still withhold the tool outright, which is belt-and-braces rather than the only thing stopping them. After the stream closes, the turn is also handed to the episodic memory extractor (`memory.episodic.schedule_extraction`, fire-and-forget) — on every turn where the principal said anything at all, and only the principal: a turn naming an `origin_channel` must resolve to a person marked `is_principal`, because the quote validator downstream cannot tell whose words it is checking. Both this path and the committee path call the same `should_extract` predicate, and it applies no length floor: the gate used to sum in the assistant's reply, which let a verbose answer drag a trivial turn in and discarded the short, decisive instructions that are the whole point of extracting. A user-side floor would fare no better — \"Do B.\" and \"Done\" are one character apart. See **Memory** for what that cost on a live tenant. None of this runs for a **replay** of a graded turn (`Session.replay`, `memory/replay.py`): the loop answers its acting tools with \"done\" and records them on the session, offers no script, job or server load, and skips every post-turn pass, so the nightly replay of the misses changes nothing and reaches nobody. On a team member's turn (`department_gate.speaker`) it also refuses an alert that is not routed to them (`routed_to_person_id`), so they clear only their own items; the principal clears anything on the board. `create_alert` on such a turn ignores the `source`, `external_id` and `from_address` it was given: the alert gets the source `team_member`, a fresh id and `raised_by` (their name), so it can't pose as mail or a watch, coalesce into one, or pre-claim the id a real alert will arrive with.\n8. **Tool failures** — a handler that raises instead of returning its JSON error is isolated: both tool gathers run with `return_exceptions=True`, the model gets an error `tool_result` naming only the exception's TYPE — a message can carry a filesystem path, a validation error echoing the input, or a third-party HTTP body, and anything in model context can be quoted back to the user, so the full repr stays in the log and the audit row — and the failure is audited with `ok=false`. Only `CancelledError` is re-raised, so turn-timeout and client-disconnect handling still work. Before this one crashing tool aborted the whole turn, which reached the user as an unexplained apology with no audit row (#136).\n\nWeb search, when invoked on the Anthropic path, executes inside the Anthropic API itself (`web_search_20250305`) and returns within the same generation; for any model routed via OpenRouter the same tool becomes OpenRouter's `openrouter:web_search` server tool, which also runs inside the generation with the same search cap and domain lists.\n\nThe install's workspace mode (solo or team, see Org) is read fresh at the start of each turn by `memory.workspace_settings.pin_turn_workspace_mode(session)` and pinned on the session for that turn only (`Session.turn_workspace_mode`): the persona, the org block, the tool list and every tool handler in the turn then agree, and a switch made mid-turn applies from the next turn. A session can instead carry an explicit override, `Session.workspace_mode` (`None` by default), which wins over both — so a caller that runs many conversations concurrently on one Executive, such as evals, can pick the mode per session rather than flipping the install-wide setting. Everything reads it through `effective_workspace_mode(session)` (override, then the turn's pin, then the setting). The principal's role is pinned the same way (`pin_turn_principal_role(session, mode)` → `Session.turn_principal_role`: in solo the `Session.principal_role` override, else the workspace settings read fresh; in team an empty role). The org block renders it, each specialist batch gets it as a `<principal_role>` user-turn tag, and a workflow the turn starts reads the same pin through `effective_principal_role` (override, then the pin, then the setting), so a role edited mid-turn applies from the next turn; a team turn sends none.\n\nAct as me is pinned beside them: `delegation.settings.pin_turn_delegation(session, speaker_text)` records on `Session.turn_delegation` whether the speaker has it on, whether `ghostwrite_email` is offered this turn (the principal, or a team member once the owner lets them, on a verified surface, in a conversation private to them, attended), and the speaker's own words. The pin is also held in a context variable for the turn's task, so two turns running at once on one session each read their own. The tool list, the tool handler and the turn's audit privacy all read that one pin, so a switch flipped mid-turn applies from the next turn. Once the tool touches the speaker's mailbox, the conversation is the speaker's alone (`session_store.mark_mail_private`, the principal included when it isn't theirs), the rest of the turn's audit rows are private (a team member's theirs alone) and the turn teaches no memory: no extraction, open-loop, working-style or Honcho pass runs on it. Later turns of that conversation stay private the same way; the pin also records whether the reading turn is still in the history the model is shown (`mail_in_view`, from `sessions.mail_read_at` against `session.history_window_start`), and links, scripts, workflows and posts to everyone stay withheld only while it is.",
"mermaid": "sequenceDiagram\n participant C as Client\n participant API as FastAPI /chat\n participant E as Executive\n participant CL as Claude\n participant S as Specialists\n participant KB as ChromaDB\n C->>API: POST /chat message\n API->>E: start turn\n E->>CL: messages (tool-use loop)\n CL-->>E: consult_specialist calls\n E->>S: route_parallel fan-out\n S->>KB: domain-filtered RAG\n KB-->>S: chunks\n S-->>E: analysis tool_results\n E->>CL: synthesize\n CL-->>E: streamed reply\n E-->>API: SSE chunks then done\n API-->>C: streamed response",
- "generated_at": "2026-10-16T21:00:00Z"
+ "generated_at": "2026-10-16T14:11:25Z"
}
diff --git a/packages/core/openexecutive/architecture/prebuilt/today.json b/packages/core/openexecutive/architecture/prebuilt/today.json
index a4ae774d..4b2851bc 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>`). Every signed-in page shares one sidebar (`AppSidebar`). Its Recent list is capped at the 7 newest web chats. The full history, including Slack, Telegram and Discord conversations (recognised by their session-id prefix), lives on `/chats`. A chat opens from any page through `/?session=<id>`.\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- **Private cards.** An alert tagged `private:principal` (`alerts.models.PRIVATE_ALERT_TAG` — raised on a turn about mail from one of the principal's contacts or mail they forwarded, or a meeting proposal with a contact) is in `proposals` only when the caller is the principal. The chat's alert digest (`briefing.context.render_and_trust`) shows it, and the roster requests, only on the principal's own verified turn, never in a web chat they shared with others, where everyone reads the reply. `_build_today` leaves it out by default, so the end-of-day digest, the reflection and Discord's `/today` never see it, and the morning brief reads it only on a run for the principal (the scheduler's, or the principal's own verified chat turn in a conversation only they can read — see Workflows). The narrative is written from one only in the principal's own `principal` scope, which nobody else is served; the shared `company` scope an unresolved caller gets, and a teammate's scope, never are. The activity rail skips it, and the chat digest includes it only on the principal's own verified turn.\n- **Roster-request cards.** When someone not on the People list writes in (see Org and Integrations), `people.roster_requests.surface_card` raises an alert of source `roster_request` (medium, tagged `roster_request:<id>` and `private:principal`, routed to the principal), so it follows every private-card rule above. `GET /today` attaches `roster_request` to that proposal (`_roster_request_card`: channel, address or account id, the sender's sanitised and unverified name, profile email, company-domain flag, suggested kind and person, message count, whether they were acknowledged, first seen, and the held messages' first lines) while the request is still pending. The Briefing renders it as its own card (`RosterRequestCard`: add as a new person with a name and an explicit team/contact choice — pre-filled as team on a company domain — or \"someone already on the list\", with a replace-account option for a chat id, or Ignore), which calls `/people/requests/{id}` directly and never hands off to chat, so what a stranger wrote never seeds a turn. The card is kept out of everything that could close it without answering it or put the stranger's words in front of a model: the narrative (`_action_proposals` drops it), the chat's open-alert digest (`<briefing>` — the principal's verified turn gets a separate `<roster_requests>` block instead; see Agents), `ack_alert`, a single ack (`POST /alerts/{id}/ack` is a 409), the \"Dismiss N older than 7 days\" count and the server's bulk ack, reopen, the TTL sweep and the alert review (`roster_request` is in `lifecycle.TTL_EXEMPT_SOURCES`). It ends when the request does: answered (`ack`, or `dismissed` on a decline) or expired after `ROSTER_REQUEST_TTL_DAYS`.\n- **`people`** — an attention-ranked roster of the **team** (the principal's contacts are never listed, and get no insight note). 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)`. Stale insight notes are regenerated in the background only when the roster has more than one person: the UI shows the People sidebar only for more than one, so a one-person install (solo, or a team before anyone else is added) does not pay a daily model and peer-memory call for a note nobody sees. Cached notes are still served.\n- **`proposals`** — the *live* unread alerts (workflow approvals, triage-classified inbound, Executive signals, flagged artifacts, and gated calendar bookings; an artifact is listed only to its owner (`alerts.models.visible_alert`; every other build of the board — the briefs, the reflection, the review, the chat digest on anyone else's turn, the activity rail — leaves drafted artifacts out) and carries `artifact_format` / `artifact_url` and a `body` already rendered to Markdown for its format, so the card badges it as a web page, Word doc, spreadsheet or link and offers *Open artifact*): 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). `failed_run_id` is set only on a `workflow_failed` card (a scheduled run that ended in error, see Scheduler): its main button is **Run again** (`POST /workflows/runs/{id}/rerun`, which also closes the card) and its ⋯ opens the run; it has no Approve. The response also carries `held_back` for the principal alone: the lines grounding left out of the morning brief or end-of-day digest in the last day, which Home lists under **Left out of your brief** (the brief's note names it; Hide is remembered in that browser). The UI splits them into 'mine' vs 'across the team' using `caller_person_id`. Approve is carried out on the server for every card. 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), so meeting bookings are reviewed in the briefing itself rather than on a separate page. Every other proposal is approved at `POST /alerts/{id}/approve` (`alerts.approvals`): it records who approved the card and when (an `alert_approvals` row plus `alert_approved`, then `alert_approval_done` / `alert_approval_failed`, audit rows), claims the card in one transaction so a double click or a second approver gets a 409 and the work runs once, then does the work. A card the scheduler filed for a department-gated action is bound to it server-side (`alert_held_actions`, written only as the card is filed, never read from the card's tags or text, which a model reading inbound mail can write), and approving it queues that exact action again with no department, the approval being the consent the gate waited for. Any other proposal runs one Executive turn as the approver in a new chat on the server (`chat.start_background_turn`, the machinery behind `POST /chat/background`), with the edited text verbatim for Edit & approve; it keeps going if the page closes. Only the card's routed person or the principal may approve a routed card, and only the principal an unrouted one (403 otherwise); the card's text reaches the turn as quoted data, not instructions. A row at the top of Needs you follows the approval (`GET /alerts/approvals/{id}`): working on it with a link to the chat, then done, or didn't work with Try again; a card whose last approval failed can be approved again, and one still running at a restart is marked failed on boot. The page no longer acks the card and seeds a chat turn with the proposal, which left no record of the approval and did nothing if the tab closed first.\n- **`narrative`** — a per-viewer Executive-voice header (\"What's going on\") synthesized by `synthesize_briefing_narrative`, cached per scope in `briefing_narrative`: the resolved principal gets the whole-company `principal` scope (which may carry what is private to them), a caller who resolves to no roster row the shared `company` scope (written from what everyone may see), and each teammate a role-scoped `person:<id>` one. `narrative_generated_at` says when the served text was written and `narrative_stale` whether a fresher one is being written now. In the web UI each bullet of this narrative is a click target: clicking one hands off to chat (the same `onContinue` path as the proposal cards) seeded to discuss that item. The Executive recognizes it because every chat turn now carries a `<briefing>` digest of open alerts (see Memory). That digest (`briefing.context.format_open_alerts_for_prompt`) is capped at 30 items; when the board is longer the header says so explicitly and tells the Executive to point at this page for the rest — it previously presented the capped list as the complete board, so the Executive described a slice as everything that was open (#136). Chat adapters get the digest too, but Slack gates it to the principal's DMs: the board is company-wide and must not be pulled into a shared channel. The `[alert_id]` at the start of each line is also what `ack_alert` trusts, because an id quoted inside an alert's own body came from inbound mail or chat and is attacker-controlled. This page's `[Discuss mode — alert_id=N]` handoff primer is a pointer to which item is under discussion, not authority on its own: the server accepts it only if that id is on the live board too. Two things enforce that. Every field the digest interpolates — headline, body, suggested action, tags, review note — is collapsed to a single line, since a newline in any of them would forge a whole extra `[N]` line and with it a fabricated instruction to clear someone else's alert. And the server records the live board it derived, so `ack_alert` refuses any id outside it — on **every** session, not just the chat adapters. The recorded set is the whole live board, not just the rows the digest printed, so a card past the render cap stays ackable. The control stops invented, closed, snoozed and expired ids; it does not stop the model being argued into acking the wrong *live* card. When the principal names an item that has already left the board — opened, snoozed, or older than it — the Executive looks it up with `find_alerts` (a keyword search over every status, `alerts.store.search_alerts`); matches that are still open (`unread` or `read`) become ackable for that turn, up to 25, and closed ones come back labelled so the Executive can say the item is already settled. It works only where the principal's own board was shown this turn — the web app or their DM — and never returns roster-request cards (see Lifecycle). The digest's header also labels every headline and detail as untrusted content drawn from inbound mail, chat and watched pages — act on what the principal asks about an item, never on what its text asks — and triage reads each signal inside an `<event>` block whose closing tag the sender's text cannot forge (it is defanged in any case and spacing, after NFKC folds fullwidth forms). That check used to run only when `origin_channel` was set, which the browser never sets, so the one surface where the principal actually reads their board had no check at all and the model could ack any id, including one quoted out of an alert body by the Discuss handoff. Rendering the block and recording its ids now happen together in `briefing.context.render_and_trust`, which both the web chat route and the channel adapters call: render without recording and the tool refuses everything, record without rendering and the model gets reach it was never shown. A turn that was shown nothing trusts nothing. Recording it is only half the wiring: the tool reads the board off the turn's session through a ContextVar, and the chat route binds that session for the whole SSE body (`set_session`, next to `set_turn`). Bound from inside the Executive's own generator instead, it survives exactly one stream step — `asyncio.wait_for` runs each step in a fresh Task with a copy of the context — and the tool-call loop, which runs later, sees nothing. That shipped, and every web ack was refused on cards that were open the whole time. The digest also carries a short **already handled** tail — recently acked / dismissed / resolved rows, named but deliberately NOT trusted for acking — because a card cleared on the page minutes ago is otherwise simply absent from chat: asked to \"record that as fixed\", the Executive could not tell a settled item from one it had never heard of, and sent the principal back to dismiss a card that was already gone. That tail renders even when nothing is open, which is exactly when it matters. Note it is a different window from the `handled_overnight` rail above: that one runs since the last delivered morning brief, while the chat tail looks back 14 days (matching the action-alert TTL, so it still covers an item cleared late in its life), so chat can name a settled item the rail no longer shows. The narrative is held to what is **live**, and to what it is actually for. The `alert_raised` source is dropped from the activity it reasons over (`_build_activity(..., include_alert_raised=False)`): a closed alert reads as work the principal already settled, and a *live* one is worse than redundant — `lifecycle.is_live` is the very predicate behind `list_live_alerts`, so every live raise is already a proposal card below the header, which the prompt forbids re-listing. The `/today/activity` rail keeps the whole source, because a raise really happened. The activity block is only labelled \"since last brief\" when the caller bounded it with `since` (the standalone briefs do; the header does not), since calling an unbounded history rail a delta made the header present weeks-old rows as overnight news. When the viewer's slice holds nothing that wants a decision — no action proposal, no at-risk/off-track department, nobody awaiting — the regen skips the model call entirely and writes the fixed quiet line (`Quiet right now — nothing pressing.`, or `… nothing needs you.` for a teammate). **The cache key is a hash of the rendered context itself** (`today._narrative_context` builds it once and both the hot path and the background task key off that one string, which is also handed to the model verbatim). That makes the key a function of the model's input: everything the prompt renders is covered, and nothing it omits can trigger a regeneration. Keying on hand-picked fields broke one half or the other each time — headlines alone left the rendered activity block uncovered, while the proposals' review fields are never rendered by this header yet are rewritten with fresh prose by every `alerts.review` pass, so they regenerated each viewer's narrative several times a day to re-synthesize identical input. A quiet board keys off a fixed sentinel instead, so a moving rail cannot re-key an entry whose text is constant. Together: on a fully dismissed board every other input was empty, the rail became the only context, and the model synthesized a confident header out of closed items.\n\n **Live, not just the board.** The header used to reason over the alert board, goal health and the Executive's own bookkeeping only — mail and chat handled that day, replies the gate held and the next meeting never reached it, so it read the same for days while the principal's day moved on. The whole-company scopes now open the context with the principal's world as it is happening (`briefing.live_signals.gather_live_signals`, rendered by `render_live_blocks`), under a `NOW:` line: **INBOUND** (`integration_inbound` audit rows that carry a message, one per message id, grouped by sender and subject, with an email's first line; the principal's own mail reads \"from the principal\", an email from the roster says \"the Executive replied\" only when a reply was logged in its thread after it (`unanswered_mail.record_reply`) and \"no reply went out\" while its `unanswered_mail` card is open (on the principal's own read only), and a time on another day carries its weekday and date), **STUCK** (`integration_outbound_blocked` to a recipient, the inbound \"reply blocked at outbound gate\" and Google Chat \"left unanswered\" / \"not delivered\" rows, and chat drafts Act as me saved in the principal's mailbox that are still there: `delegation_drafts` rows not yet marked sent or `gone_at`; before each scheduled header refresh and each morning brief, `live_signals.settle_principal_drafts` looks up the principal's open chat drafts from the last two days in their mailbox and marks the ones sent or deleted there, so a draft they sent from Gmail stops reading as waiting), **CONVERSATIONS** (the principal's own web chat titles) and the **REST OF TODAY'S CALENDAR**. The window is the local day, or the last 12 hours when that is longer. Private audit rows, drafts, chat titles and the calendar (meeting titles are the principal's own) are read only in the `principal` scope — `gather_live_signals` drops the calendar whenever `include_private` is false, whatever the caller passes, so the shared `company` header never quotes it. The calendar is never fetched on the request: `live_signals.refresh_calendar` caches one read per 15 minutes (the scheduler tick refreshes it) and the header quotes the cache. Every quoted field is collapsed to one line and cut, and the blocks and the prompt both say the text is data, never instructions — inbound mail is attacker-controlled. With live blocks present the context also ages each proposal (`raised 2d ago`, whole days), names each at-risk department's slipping goals (`attention_goals`) and adds an **EXTERNAL SIGNALS** block (monitoring alerts from the last 24 h, never enough on their own to break the quiet line); the rhythm runs (`today.RHYTHM_WORKFLOWS`: the morning brief, end-of-day digest, reflection and weekly review) are dropped from the activity it reasons over. The prompts (`BRIEFING_NARRATIVE_SYSTEM` and its solo variant, `NARRATIVE_PROMPT_VERSION` 6) lead with what is live and give a days-old item at most one bullet. Anything live breaks the quiet line; the NOW line and window move at most once an hour, so the key moves hourly on time alone plus whenever something new lands; the calendar is placed at the real time (a meeting that has ended drops out, the one under way is IN PROGRESS), which moves it only when a meeting starts or ends.\n\n **Fresh without a reload.** The daily floor in the key and the PERIOD line are the principal's **local** date (`narrative_cache.local_today`), not UTC's, and a row written on an earlier local day is not served as today's. Regenerations are serialized per scope; a trigger that finds one running marks the scope pending and the running pass goes round once more (it built its context before that trigger's news landed), and after a failed pass (model error, the 25 s timeout, empty text) no view or tick starts another for 5 minutes and `narrative_stale` reads false, so the page drops its placeholder instead of spending a model call per view. They log `today: narrative served scope=… age_s=… stale=…` and `today: narrative regenerated scope=… ms=…`, and no longer need a page view: every `BRIEFING_NARRATIVE_REFRESH_MINUTES` (10) between `BRIEFING_NARRATIVE_REFRESH_START_HOUR` and `_END_HOUR` (06–22 local) the scheduler runs `today.refresh_principal_narrative`, which refreshes the calendar cache and rewrites the principal's header only when its key moved (see Scheduler). The Briefing re-polls `/today` at 4, 10 and 20 s while `narrative_stale` is true, re-pulls it when the tab comes back (at most once a minute) and every 5 minutes while visible, shows \"Updated 2:04 PM\" beside the heading, and shows \"Catching up on today…\" while the first header of the day is written (`lib/narrativeFreshness.ts`, tested by `npm test`).\n\n In **solo mode** (one person using Open Executive for themselves) the header speaks to the principal, whatever their role: a solo prompt over a context that lists goals at risk by *area* and has no \"people waiting on you\" block, and the quiet check ignores who is awaiting. The cache key carries the mode for solo only, so solo and team never share a cached narrative while every team key stays exactly what it was — no team cache is invalidated. The response shape does not change. For the principal's own view the solo context also carries a **DUE THIS WEEK** block — the principal's open loops that are overdue or due within 7 days (`today._with_due_soon` → `open_loops.principal_due_soon`, labelled OVERDUE / due today / due <weekday>) — which counts as needing attention in the quiet check and moves the cache key when an item is added, closed or falls due; a teammate's scoped view and team mode never get it. The header never gets the morning brief's *top three today* block — that is the DM brief's (see Workflows); the page shows the same top three in a card of its own (see *Solo focus cards* below). It does get the rest of today's calendar through the live blocks above, from the cached read.\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. Audit rows private to the principal (say, one naming their contact) are in this list only on the principal's own `/today`: `brief_state.handled_since` leaves them out unless asked, and the written briefs never ask, since a brief can be read by others. The Pulse heatmap's per-day counts (`GET /today/activity/daily`) likewise leave out a private decision or private alert, as the activity rail does. The morning brief also carries a one-line count of research watch suggestions waiting on `/watchlist`.\n\n**From your chats.** `briefing.brief_requests` holds what the principal asked of their brief in conversation: `leave_out` lines from `leave_out_of_brief` (\"take the Halcyon renewal out of my brief\", kept 14 days) and `raise` lines the conversation review could not fix itself (`raise_in_brief`, kept 2 days), at most 20 live. A line is at most 12 words (leave out) or 30 (raise), with no link, handle, markup, identifier or talk of instructions, and only lines written under the principal's own id render. `render_briefing_context(brief_requests=True)` adds the raise lines before the quiet-day check, so they are raised even on a quiet day, and the leave-out list as the very last block; both sit inside the rendered string the /today header hashes. A teammate's brief or header passes `False`: they are the principal's own words.\n\n**Standing facts.** `render_briefing_context` appends the standing facts (`memory.facts`: corrections kept from chat, a teammate's marked `(per <name>)`) as its last block, after the quiet-day check, so a fact never makes a quiet day look busy. The morning brief also carries **TEAMMATE CORRECTIONS SINCE LAST BRIEF** (`facts.render_teammate_changes(since)`: each teammate fact recorded in the window that is in use now, plus — only when the brief is the principal's own private one (`_private_ok`), which then keeps the run out of the shared history — those waiting for their approval, since other teammates may run the brief and never see a proposal that is not theirs) before the quiet check — it is news, the principal's only FYI of it — and in the brief's fingerprint (`build_brief_fingerprint(teammate_changes=)`), so a correction alone un-suppresses an otherwise unchanged brief. Every other caller passes none, so its context is unchanged. The /today header hashes that rendered string as its cache key, so a new or retired fact marks the header stale and it is rewritten with the correction. The morning brief (standalone) and the teammate-scoped header get the same block. On the scheduler's delivery to the owner alone, with their Always in the loop switch on, `render_briefing_context(owner_notes=)` also carries FROM YOUR NOTES — DUE SOON (their own notes of what they promised or asked, overdue to a week ahead; `memory.history_brief`), which counts against a quiet day, enters the fingerprint and marks the run private; both standalone prompts turn it into a **From your notes** section. The /today header never gets it. **The first week.** For seven days from the principal's People row (`briefing.first_week`), `render_briefing_context(getting_started=)` carries a GETTING STARTED block right after the live blocks: the install's goal rows (department, key result, target, period) or, while there are none (setup saves no goal rows, so this is a fresh install's usual case), this year's priorities and north star from the saved profile (`strategic_priorities`, up to five, keys `priority:<text>`), departments with no `head_person_id`, and, on the scheduler's delivery to the principal alone with Act as me and Draft replies to my inbox both on and the mailbox connected (the inbox watcher's consent), up to five people who wrote to their own mailbox in the last 48 hours as sender and subject only (`inbox_message_ids` + headers of `get_message`, bulk and automated mail skipped; the same \"where, never what\" rule as `delegation.mail_reads`) and, with Act as me and Read my calendar on, up to eight of today's events on their own calendar as time and title (declined ones left out). It counts against a quiet day, enters the fingerprint (`getting_started=` keys, no dates; a meeting's key is its event id) and, with the inbox or calendar part, marks the run private. Both standalone prompts open with a **Getting started** section and take the Top call from it (`GETTING_STARTED_RULE`); the whole-company /today header gets the block without the inbox (`getting_started_shared`, synchronous, no mailbox read) and the header prompts take the bottom line and move from it (`GETTING_STARTED_HEADER_RULE`), so a new install's header is not short-circuited to the quiet line. `GET /today` sets `first_week`; while it is true the Briefing hides the \"Quiet day\" banner, renders the header narrative open in the page under **Getting started · your first week** (in place of the \"Read today's brief\" side panel), and, when the summary counts are all zero, shows the narrative's **Move today:** line in place of \"All clear\" (`firstWeekMove`). The last setup screen (`OnboardDone`) offers one first question built from the saved priorities (`firstQuestion`) and hands it to Home through session storage (`oe.onboard.firstQuestion`, never the URL), which asks it once. A teammate's scoped header never gets it. The alert review's `render_batch` puts the same block ahead of the alerts (read once per pass), so a note, rewrite or routed DM never repeats a figure the principal already corrected.\n\n**When a brief isn't sent.** Above the Briefing, the owner sees a one-line notice when their latest morning brief, end-of-day digest or (in solo mode) weekly review wasn't sent — \"Your morning brief wasn't sent: nothing is set up to send it to you\" — with the day, what fixes it, a link to read the brief on the Artifacts page (left out when the brief couldn't be written at all) and one to Setup status. It comes from `GET /today/brief-delivery` (the scheduler records each run's outcome), shows nothing while briefs go out or while the scheduler is off, and clears once the cause is fixed. When the Executive's mail connection wasn't running (the MCP gateway failed to start and is retrying), the notice says that instead of blaming the owner's setup; a send that failed on every channel names what each channel answered, from the recorded `detail`, with addresses left out. Teammates never see it.\n\n**Replies waiting.** With Act as me's **Draft replies to my inbox** on, the top of the Briefing's left column lists the replies the Executive drafted in the owner's own Gmail for mail that needs them (`RepliesWaiting`, from `GET /delegation/replies` — see Act as Me). They belong to the owner alone: the route answers only the person who can have Act as me, the decisions behind the cards (`delegation_reply`) are principal-only and carry `private: true`, so `/today/activity` and the heatmap leave them out, and none is ever an alert, so nothing of them reaches `GET /today`, the header or the briefs. Each card shows who wrote and who they are to the owner, whether their address was verified, the subject, what they wrote (as plain text), the draft, **Decide before sending** (its open questions) and its warnings, with **Send**, **Edit in Gmail** (the thread in their Gmail) and **Dismiss** (which deletes the draft unless they edited it). **Send** asks first, naming who the reply goes to, then sends the draft exactly as it is in Gmail (`POST /decisions/{id}/approve`); when its recipients changed in Gmail or a newer message arrived, the backend's 409 `confirm` becomes a second question naming them. The card hides itself when nothing is waiting.\n\n**Solo focus cards.** `GET /today/top-three` and `GET /today/weekly-review` feed two solo-only cards, so a principal who only uses the web app — no chat app, no Google Workspace — sees today's top three and the weekly review instead of finding them only in the Workflows run history. Both answer only in solo mode (`effective_workspace_mode`) and only to the principal, by the stricter rule for starting a principal-only run (`workflows._caller_is_the_principal`: the caller's own email on a principal entry that is not archived, or no `x-caller-email` at all — never \"nobody is principal yet\"); a teammate, any other signed-in caller and team mode get null. `top-three` hands `open_loops.principal_due_soon()` to `briefing.top_three.build_top_three` — the morning brief's own inputs and code, so the items, their order and their free slots are the brief's — and returns `{items: [{key, kind, text, why, slot}]}`: `slot` is the free block (\"10:00–11:00\", the user's zone), \"\" when none is left, or null when no calendar was read (none connected, a failure or the 4 s timeout, a weekend); `items` is empty when there is nothing to pick. It is a route of its own, never part of `GET /today`, so the Briefing never waits on the calendar. `weekly-review` returns the latest `weekly_review` run with status `done` (`persistence.list_runs(..., status=\"done\", limit=1)`, newest `updated_at` first; failed and running runs never count) as `{run_id, completed_at, period, top_three, excerpt}`: `weekly_review.summarize_review` reads the artifact's title line and its last *Next week's top 3* section back as plain text, and `excerpt` stands in when that list is empty (the section's own note, else the review's first lines). Null when no review has completed or the run store cannot be read.\n\nThe route resolves the caller from `x-caller-email`, serves the viewer's cached narrative and, when its key moved, rewrites it in a `BackgroundTask` so the request never blocks on an LLM call (the page re-polls while `narrative_stale` is true). `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; solo mode has its own, with goals at risk by area and no waiting-on section). `GET /morning-brief` is a deprecated alias.\n\n**Solo mode in the UI.** The response is the same in both modes; the briefing reads the workspace mode from the app-wide `WorkspaceProvider` (which reads team while loading or on error, so a team install never flashes solo) and, in solo, drops the team surfaces: the Departments card, the People card, the \"Across the team\" lane (every action proposal is the one user's, so all of them land in \"Needs you\"), the people-awaiting, people-overdue and departments-at-risk status pills, and the quiet-day \"Set up a check-in\" link. A \"N goals at risk\" pill (at-risk plus off-track goals, from `departments`) links to `/goals` instead, so the strip never reads \"All clear\" over a goal that is slipping. In the Departments card's place, **Your projects** lists the initiatives with status `active` (`GET /memories/initiatives`): **Done** marks one `completed` through `PATCH /memories/initiatives/{id}` (only `completed` takes an initiative out of the Executive's active context), and **Drop** deletes it through `DELETE /memories/initiatives/{id}` after a confirm. Under **Needs you**, a **Due soon** card lists the principal's open loops that are overdue or due within 7 days — their dated commitments and what others asked of them — read from `GET /people/{id}/open-loops` for the principal (the oldest principal in `people`, the backend's rule), labelled by `lib/dueSoon.ts` (tested by `npm test`: \"Overdue since Sep 23\" / \"Due today\" / \"Due Mon, Sep 28\", with a count of anything due later); **Done** closes one through `POST /open-loops/{id}/close`, which also stops the nudge engine chasing it. Above it, **Top three today** numbers the morning brief's three (`GET /today/top-three`) with each one's reason and, when a calendar was read, its free slot (or \"No free time left today\"); at the top of the right-hand column, **This week's review** (`GET /today/weekly-review`) shows the period, when it ran, next week's top three (or the excerpt) and a *Read the review* link to its run page (`/jobs/runs/{id}`). Each card fetches on its own once the Briefing has loaded, so a slow calendar never holds the page up, and renders nothing when the API returns null or an empty list. A commitment in the top three reads as the owner's own (\"Send the proposal\") through `lib/dueSoon.ts`'s `loopText`, as in Due soon; the cards' wording lives in `lib/rhythmCards.ts` (tested by `npm test`). The Pulse page hides its \"Department check-ins\" and \"Awaiting people\" blocks in solo, and its header shows active projects in place of the department check-in count. Team rendering is unchanged.\n\n**Your month (`GET /today/value`).** The owner's own tally of what the Executive did for them, `briefing.value_summary.summarize(period, offset)`: the calendar `month` or `week` (Monday first) in the user's zone, `offset` periods back (0–24), each line beside the period before. Every number is a `COUNT(*)` of rows that prove it happened, never a model's: messages sent for the owner (the DM handlers' own `kind=outbound` sent rows to anyone but the owner, plus Gmail / Outlook send-tool calls that didn't come back with an error, so mail sent from a chat turn counts), replies drafted and sent from the owner's inbox (their Act as me rows), meetings booked (calendar create calls), briefs delivered (the scheduler's `delivered` row), reports (finished team workflow runs, minus the daily rhythm runs and any run a teammate started for themselves, which stays theirs alone; the latest ten listed with links), follow-ups and nudges sent, tasks tracked and closed as done, proposals decided, alerts flagged and requests answered (`chat_turn` out rows). No \"hours saved\" and no cost line: nothing recorded supports the first, and cost next to what the owner got reads as a bill; it has `GET /audit/usage`. The owner's alone (403 for anyone else): it counts rows private to the owner, never a row private to another member. Pulse shows it as a **Your month** card on the overview (\"October 2026: 42 messages sent, 6 reports, 3 meetings booked.\") and a focused screen, `/memories?tab=value`, with a month / week switch and previous / next. On the first weekday of each month, in daytime (09:00–18:00 local), a scheduler tick hook sends the owner last month's lines and a link (`value_summary.maybe_send_monthly`, claimed once per month under `briefing_narrative` scope `value_summary:YYYY-MM`), in solo and team mode alike; nothing is sent for an empty month. Off with `VALUE_SUMMARY_MONTHLY_ENABLED=false`.\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. Four things now keep it live and true:\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. **Snooze** (a card's ⋯: later today, tomorrow 9:00, Monday 9:00, in the viewer's clock; `POST /alerts/{id}/snooze`) hides a card until `snoozed_until`, with an Undo; the TTL anchor is the latest of `created_at`, `last_seen_at` and `snoozed_until`, so a snoozed card comes back rather than expiring unseen.\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- **Collection tags** (`alerts.pipeline`). A triaged alert never carries a `collection:<name>` tag: the pipeline strips them before inserting. Only an installed extension's own code files a document into its collection (`orchestrator.extensions`), so injected text can't make a card that the extension would treat as its own.\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 (team members only — an alert routed to a contact never puts them in the slice, so they are never routed to, nudged or chased; a private card is never reviewed at all, nor used as evidence for another), 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). A review DM is proactive outreach, so the recipient's notification settings apply: one held for their quiet hours or brief counts as a route made but not as a nudge toward the cap (and no second nudge is held while one waits), and one about an alert whose severity is (or becomes) `urgent` is marked urgent (`notifications.urgent_send`) and gets through when they let urgent things through.\n- **Grounded text** (`openexecutive.briefing.grounding`). Nobody reads an alert's text before it is dispatched, so what the model wrote onto it must be supported by what it read. After triage (`alerts.pipeline._ground_decision`, before coalescing or inserting), a headline naming a person or figure the event does not hold — sources are the event's subject, sender, title and body, the initiatives triage was shown and the company profile — is replaced by the event's own subject, such body sentences are dropped (all of them → the event body cut to 280 chars); both fallbacks are raw event text, so they are made inert first — links masked, Markdown and Slack `<…>` syntax and @-mentions stripped — because a broadcast posts them as written, and such a suggested action is dropped. A review `changed` rewrite is checked against the alert's own text and the evidence it was reviewed with (signals, related alerts, activity, the roster slice), plus the standing facts the batch was shown, so a rewrite that corrects a card to one of the principal's corrections is grounded; an ungrounded rewrite keeps the old text, still applies a severity change, and audits `text_ungrounded`. A name counts as grounded only when one source line holds all of it; a figure only when a source number matches it within the precision it is written with. Each finding writes a `grounding` audit row; `GROUNDING_CHECKS=report` records without changing anything.\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`. Acknowledging or resolving an alert — including the review closing it itself — marks the review's DMs about it `acted` in the Attunement outcome ledger, for the person it is routed to and the principal only; dismissing it, finding it stale or letting it expire voids them (counted neither way). Review DMs are tagged `alert_review` with `alert:<id>`.\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>`). Every signed-in page shares one sidebar (`AppSidebar`). Its Recent list is capped at the 7 newest web chats. The full history, including Slack, Telegram and Discord conversations (recognised by their session-id prefix), lives on `/chats`. A chat opens from any page through `/?session=<id>`.\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- **Private cards.** An alert tagged `private:principal` (`alerts.models.PRIVATE_ALERT_TAG` — raised on a turn about mail from one of the principal's contacts or mail they forwarded, or a meeting proposal with a contact) is in `proposals` only when the caller is the principal. The chat's alert digest (`briefing.context.render_and_trust`) shows it, and the roster requests, only on the principal's own verified turn, never in a web chat they shared with others, where everyone reads the reply. `_build_today` leaves it out by default, so the end-of-day digest, the reflection and Discord's `/today` never see it, and the morning brief reads it only on a run for the principal (the scheduler's, or the principal's own verified chat turn in a conversation only they can read — see Workflows). The narrative is written from one only in the principal's own `principal` scope, which nobody else is served; the shared `company` scope an unresolved caller gets, and a teammate's scope, never are. The activity rail skips it, and the chat digest includes it only on the principal's own verified turn.\n- **Raised by a team member.** An alert a team member raised from chat (`AlertEvent.raised_by`, source `team_member`) has its body led by \"Raised by <name>.\" and never goes out on `company_broadcast`: the pipeline drops that channel after `resolve_channels`, so it reaches a person or a department room only. One team member's alert never coalesces into another's (the dedup key is prefixed with who raised it). A team member's saved workflow raises alerts as its creator (`action_step` binds `dynamic_store.get_owner` around `oe__create_alert`). Alerts from email, watches and other sources are unchanged.\n- **Who clears a card.** `POST /alerts/{id}/ack` with `ack` or `dismissed` answers 403 to a team member unless the alert is routed to them (`read` is open to anyone who can see it); only the principal's dismiss applies `mute_topic`, since a mute silences the topic for everyone. `POST /alerts/bulk-ack` from a team member clears only the listed ids routed to them and refuses an `older_than_days` sweep. The principal, or anyone before a principal is set up, clears anything. `ack_alert` in chat follows the same rule.\n- **Roster-request cards.** When someone not on the People list writes in (see Org and Integrations), `people.roster_requests.surface_card` raises an alert of source `roster_request` (medium, tagged `roster_request:<id>` and `private:principal`, routed to the principal), so it follows every private-card rule above. `GET /today` attaches `roster_request` to that proposal (`_roster_request_card`: channel, address or account id, the sender's sanitised and unverified name, profile email, company-domain flag, suggested kind and person, message count, whether they were acknowledged, first seen, and the held messages' first lines) while the request is still pending. The Briefing renders it as its own card (`RosterRequestCard`: add as a new person with a name and an explicit team/contact choice — pre-filled as team on a company domain — or \"someone already on the list\", with a replace-account option for a chat id, or Ignore), which calls `/people/requests/{id}` directly and never hands off to chat, so what a stranger wrote never seeds a turn. The card is kept out of everything that could close it without answering it or put the stranger's words in front of a model: the narrative (`_action_proposals` drops it), the chat's open-alert digest (`<briefing>` — the principal's verified turn gets a separate `<roster_requests>` block instead; see Agents), `ack_alert`, a single ack (`POST /alerts/{id}/ack` is a 409), the \"Dismiss N older than 7 days\" count and the server's bulk ack, reopen, the TTL sweep and the alert review (`roster_request` is in `lifecycle.TTL_EXEMPT_SOURCES`). It ends when the request does: answered (`ack`, or `dismissed` on a decline) or expired after `ROSTER_REQUEST_TTL_DAYS`.\n- **`people`** — an attention-ranked roster of the **team** (the principal's contacts are never listed, and get no insight note). 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)`. Stale insight notes are regenerated in the background only when the roster has more than one person: the UI shows the People sidebar only for more than one, so a one-person install (solo, or a team before anyone else is added) does not pay a daily model and peer-memory call for a note nobody sees. Cached notes are still served.\n- **`proposals`** — the *live* unread alerts (workflow approvals, triage-classified inbound, Executive signals, flagged artifacts, and gated calendar bookings; an artifact is listed only to its owner (`alerts.models.visible_alert`; every other build of the board — the briefs, the reflection, the review, the chat digest on anyone else's turn, the activity rail — leaves drafted artifacts out) and carries `artifact_format` / `artifact_url` and a `body` already rendered to Markdown for its format, so the card badges it as a web page, Word doc, spreadsheet or link and offers *Open artifact*): 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). `failed_run_id` is set only on a `workflow_failed` card (a scheduled run that ended in error, see Scheduler): its main button is **Run again** (`POST /workflows/runs/{id}/rerun`, which also closes the card) and its ⋯ opens the run; it has no Approve. The response also carries `held_back` for the principal alone: the lines grounding left out of the morning brief or end-of-day digest in the last day, which Home lists under **Left out of your brief** (the brief's note names it; Hide is remembered in that browser). The UI splits them into 'mine' vs 'across the team' using `caller_person_id`. Approve is carried out on the server for every card. 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), so meeting bookings are reviewed in the briefing itself rather than on a separate page. Every other proposal is approved at `POST /alerts/{id}/approve` (`alerts.approvals`): it records who approved the card and when (an `alert_approvals` row plus `alert_approved`, then `alert_approval_done` / `alert_approval_failed`, audit rows), claims the card in one transaction so a double click or a second approver gets a 409 and the work runs once, then does the work. A card the scheduler filed for a department-gated action is bound to it server-side (`alert_held_actions`, written only as the card is filed, never read from the card's tags or text, which a model reading inbound mail can write), and approving it queues that exact action again with no department, the approval being the consent the gate waited for. Any other proposal runs one Executive turn as the approver in a new chat on the server (`chat.start_background_turn`, the machinery behind `POST /chat/background`), with the edited text verbatim for Edit & approve; it keeps going if the page closes. Only the card's routed person or the principal may approve a routed card, and only the principal an unrouted one (403 otherwise); the card's text reaches the turn as quoted data, not instructions. A row at the top of Needs you follows the approval (`GET /alerts/approvals/{id}`): working on it with a link to the chat, then done, or didn't work with Try again; a card whose last approval failed can be approved again, and one still running at a restart is marked failed on boot. The page no longer acks the card and seeds a chat turn with the proposal, which left no record of the approval and did nothing if the tab closed first.\n- **`narrative`** — a per-viewer Executive-voice header (\"What's going on\") synthesized by `synthesize_briefing_narrative`, cached per scope in `briefing_narrative`: the resolved principal gets the whole-company `principal` scope (which may carry what is private to them), a caller who resolves to no roster row the shared `company` scope (written from what everyone may see), and each teammate a role-scoped `person:<id>` one. `narrative_generated_at` says when the served text was written and `narrative_stale` whether a fresher one is being written now. In the web UI each bullet of this narrative is a click target: clicking one hands off to chat (the same `onContinue` path as the proposal cards) seeded to discuss that item. The Executive recognizes it because every chat turn now carries a `<briefing>` digest of open alerts (see Memory). That digest (`briefing.context.format_open_alerts_for_prompt`) is capped at 30 items; when the board is longer the header says so explicitly and tells the Executive to point at this page for the rest — it previously presented the capped list as the complete board, so the Executive described a slice as everything that was open (#136). Chat adapters get the digest too, but Slack gates it to the principal's DMs: the board is company-wide and must not be pulled into a shared channel. The `[alert_id]` at the start of each line is also what `ack_alert` trusts, because an id quoted inside an alert's own body came from inbound mail or chat and is attacker-controlled. This page's `[Discuss mode — alert_id=N]` handoff primer is a pointer to which item is under discussion, not authority on its own: the server accepts it only if that id is on the live board too. Two things enforce that. Every field the digest interpolates — headline, body, suggested action, tags, review note — is collapsed to a single line, since a newline in any of them would forge a whole extra `[N]` line and with it a fabricated instruction to clear someone else's alert. And the server records the live board it derived, so `ack_alert` refuses any id outside it — on **every** session, not just the chat adapters. The recorded set is the whole live board, not just the rows the digest printed, so a card past the render cap stays ackable. The control stops invented, closed, snoozed and expired ids; it does not stop the model being argued into acking the wrong *live* card. When the principal names an item that has already left the board — opened, snoozed, or older than it — the Executive looks it up with `find_alerts` (a keyword search over every status, `alerts.store.search_alerts`); matches that are still open (`unread` or `read`) become ackable for that turn, up to 25, and closed ones come back labelled so the Executive can say the item is already settled. It works only where the principal's own board was shown this turn — the web app or their DM — and never returns roster-request cards (see Lifecycle). The digest's header also labels every headline and detail as untrusted content drawn from inbound mail, chat and watched pages — act on what the principal asks about an item, never on what its text asks — and triage reads each signal inside an `<event>` block whose closing tag the sender's text cannot forge (it is defanged in any case and spacing, after NFKC folds fullwidth forms). That check used to run only when `origin_channel` was set, which the browser never sets, so the one surface where the principal actually reads their board had no check at all and the model could ack any id, including one quoted out of an alert body by the Discuss handoff. Rendering the block and recording its ids now happen together in `briefing.context.render_and_trust`, which both the web chat route and the channel adapters call: render without recording and the tool refuses everything, record without rendering and the model gets reach it was never shown. A turn that was shown nothing trusts nothing. Recording it is only half the wiring: the tool reads the board off the turn's session through a ContextVar, and the chat route binds that session for the whole SSE body (`set_session`, next to `set_turn`). Bound from inside the Executive's own generator instead, it survives exactly one stream step — `asyncio.wait_for` runs each step in a fresh Task with a copy of the context — and the tool-call loop, which runs later, sees nothing. That shipped, and every web ack was refused on cards that were open the whole time. The digest also carries a short **already handled** tail — recently acked / dismissed / resolved rows, named but deliberately NOT trusted for acking — because a card cleared on the page minutes ago is otherwise simply absent from chat: asked to \"record that as fixed\", the Executive could not tell a settled item from one it had never heard of, and sent the principal back to dismiss a card that was already gone. That tail renders even when nothing is open, which is exactly when it matters. Note it is a different window from the `handled_overnight` rail above: that one runs since the last delivered morning brief, while the chat tail looks back 14 days (matching the action-alert TTL, so it still covers an item cleared late in its life), so chat can name a settled item the rail no longer shows. The narrative is held to what is **live**, and to what it is actually for. The `alert_raised` source is dropped from the activity it reasons over (`_build_activity(..., include_alert_raised=False)`): a closed alert reads as work the principal already settled, and a *live* one is worse than redundant — `lifecycle.is_live` is the very predicate behind `list_live_alerts`, so every live raise is already a proposal card below the header, which the prompt forbids re-listing. The `/today/activity` rail keeps the whole source, because a raise really happened. The activity block is only labelled \"since last brief\" when the caller bounded it with `since` (the standalone briefs do; the header does not), since calling an unbounded history rail a delta made the header present weeks-old rows as overnight news. When the viewer's slice holds nothing that wants a decision — no action proposal, no at-risk/off-track department, nobody awaiting — the regen skips the model call entirely and writes the fixed quiet line (`Quiet right now — nothing pressing.`, or `… nothing needs you.` for a teammate). **The cache key is a hash of the rendered context itself** (`today._narrative_context` builds it once and both the hot path and the background task key off that one string, which is also handed to the model verbatim). That makes the key a function of the model's input: everything the prompt renders is covered, and nothing it omits can trigger a regeneration. Keying on hand-picked fields broke one half or the other each time — headlines alone left the rendered activity block uncovered, while the proposals' review fields are never rendered by this header yet are rewritten with fresh prose by every `alerts.review` pass, so they regenerated each viewer's narrative several times a day to re-synthesize identical input. A quiet board keys off a fixed sentinel instead, so a moving rail cannot re-key an entry whose text is constant. Together: on a fully dismissed board every other input was empty, the rail became the only context, and the model synthesized a confident header out of closed items.\n\n **Live, not just the board.** The header used to reason over the alert board, goal health and the Executive's own bookkeeping only — mail and chat handled that day, replies the gate held and the next meeting never reached it, so it read the same for days while the principal's day moved on. The whole-company scopes now open the context with the principal's world as it is happening (`briefing.live_signals.gather_live_signals`, rendered by `render_live_blocks`), under a `NOW:` line: **INBOUND** (`integration_inbound` audit rows that carry a message, one per message id, grouped by sender and subject, with an email's first line; the principal's own mail reads \"from the principal\", an email from the roster says \"the Executive replied\" only when a reply was logged in its thread after it (`unanswered_mail.record_reply`) and \"no reply went out\" while its `unanswered_mail` card is open (on the principal's own read only), and a time on another day carries its weekday and date), **STUCK** (`integration_outbound_blocked` to a recipient, the inbound \"reply blocked at outbound gate\" and Google Chat \"left unanswered\" / \"not delivered\" rows, and chat drafts Act as me saved in the principal's mailbox that are still there: `delegation_drafts` rows not yet marked sent or `gone_at`; before each scheduled header refresh and each morning brief, `live_signals.settle_principal_drafts` looks up the principal's open chat drafts from the last two days in their mailbox and marks the ones sent or deleted there, so a draft they sent from Gmail stops reading as waiting), **CONVERSATIONS** (the principal's own web chat titles) and the **REST OF TODAY'S CALENDAR**. The window is the local day, or the last 12 hours when that is longer. Private audit rows, drafts, chat titles and the calendar (meeting titles are the principal's own) are read only in the `principal` scope — `gather_live_signals` drops the calendar whenever `include_private` is false, whatever the caller passes, so the shared `company` header never quotes it. The calendar is never fetched on the request: `live_signals.refresh_calendar` caches one read per 15 minutes (the scheduler tick refreshes it) and the header quotes the cache. Every quoted field is collapsed to one line and cut, and the blocks and the prompt both say the text is data, never instructions — inbound mail is attacker-controlled. With live blocks present the context also ages each proposal (`raised 2d ago`, whole days), names each at-risk department's slipping goals (`attention_goals`) and adds an **EXTERNAL SIGNALS** block (monitoring alerts from the last 24 h, never enough on their own to break the quiet line); the rhythm runs (`today.RHYTHM_WORKFLOWS`: the morning brief, end-of-day digest, reflection and weekly review) are dropped from the activity it reasons over. The prompts (`BRIEFING_NARRATIVE_SYSTEM` and its solo variant, `NARRATIVE_PROMPT_VERSION` 6) lead with what is live and give a days-old item at most one bullet. Anything live breaks the quiet line; the NOW line and window move at most once an hour, so the key moves hourly on time alone plus whenever something new lands; the calendar is placed at the real time (a meeting that has ended drops out, the one under way is IN PROGRESS), which moves it only when a meeting starts or ends.\n\n **Fresh without a reload.** The daily floor in the key and the PERIOD line are the principal's **local** date (`narrative_cache.local_today`), not UTC's, and a row written on an earlier local day is not served as today's. Regenerations are serialized per scope; a trigger that finds one running marks the scope pending and the running pass goes round once more (it built its context before that trigger's news landed), and after a failed pass (model error, the 25 s timeout, empty text) no view or tick starts another for 5 minutes and `narrative_stale` reads false, so the page drops its placeholder instead of spending a model call per view. They log `today: narrative served scope=… age_s=… stale=…` and `today: narrative regenerated scope=… ms=…`, and no longer need a page view: every `BRIEFING_NARRATIVE_REFRESH_MINUTES` (10) between `BRIEFING_NARRATIVE_REFRESH_START_HOUR` and `_END_HOUR` (06–22 local) the scheduler runs `today.refresh_principal_narrative`, which refreshes the calendar cache and rewrites the principal's header only when its key moved (see Scheduler). The Briefing re-polls `/today` at 4, 10 and 20 s while `narrative_stale` is true, re-pulls it when the tab comes back (at most once a minute) and every 5 minutes while visible, shows \"Updated 2:04 PM\" beside the heading, and shows \"Catching up on today…\" while the first header of the day is written (`lib/narrativeFreshness.ts`, tested by `npm test`).\n\n In **solo mode** (one person using Open Executive for themselves) the header speaks to the principal, whatever their role: a solo prompt over a context that lists goals at risk by *area* and has no \"people waiting on you\" block, and the quiet check ignores who is awaiting. The cache key carries the mode for solo only, so solo and team never share a cached narrative while every team key stays exactly what it was — no team cache is invalidated. The response shape does not change. For the principal's own view the solo context also carries a **DUE THIS WEEK** block — the principal's open loops that are overdue or due within 7 days (`today._with_due_soon` → `open_loops.principal_due_soon`, labelled OVERDUE / due today / due <weekday>) — which counts as needing attention in the quiet check and moves the cache key when an item is added, closed or falls due; a teammate's scoped view and team mode never get it. The header never gets the morning brief's *top three today* block — that is the DM brief's (see Workflows); the page shows the same top three in a card of its own (see *Solo focus cards* below). It does get the rest of today's calendar through the live blocks above, from the cached read.\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. Audit rows private to the principal (say, one naming their contact) are in this list only on the principal's own `/today`: `brief_state.handled_since` leaves them out unless asked, and the written briefs never ask, since a brief can be read by others. The Pulse heatmap's per-day counts (`GET /today/activity/daily`) likewise leave out a private decision or private alert, as the activity rail does. The morning brief also carries a one-line count of research watch suggestions waiting on `/watchlist`.\n\n**From your chats.** `briefing.brief_requests` holds what the principal asked of their brief in conversation: `leave_out` lines from `leave_out_of_brief` (\"take the Halcyon renewal out of my brief\", kept 14 days) and `raise` lines the conversation review could not fix itself (`raise_in_brief`, kept 2 days), at most 20 live. A line is at most 12 words (leave out) or 30 (raise), with no link, handle, markup, identifier or talk of instructions, and only lines written under the principal's own id render. `render_briefing_context(brief_requests=True)` adds the raise lines before the quiet-day check, so they are raised even on a quiet day, and the leave-out list as the very last block; both sit inside the rendered string the /today header hashes. A teammate's brief or header passes `False`: they are the principal's own words.\n\n**Standing facts.** `render_briefing_context` appends the standing facts (`memory.facts`: corrections kept from chat, a teammate's marked `(per <name>)`) as its last block, after the quiet-day check, so a fact never makes a quiet day look busy. The morning brief also carries **TEAMMATE CORRECTIONS SINCE LAST BRIEF** (`facts.render_teammate_changes(since)`: each teammate fact recorded in the window that is in use now, plus — only when the brief is the principal's own private one (`_private_ok`), which then keeps the run out of the shared history — those waiting for their approval, since other teammates may run the brief and never see a proposal that is not theirs) before the quiet check — it is news, the principal's only FYI of it — and in the brief's fingerprint (`build_brief_fingerprint(teammate_changes=)`), so a correction alone un-suppresses an otherwise unchanged brief. Every other caller passes none, so its context is unchanged. The /today header hashes that rendered string as its cache key, so a new or retired fact marks the header stale and it is rewritten with the correction. The morning brief (standalone) and the teammate-scoped header get the same block. On the scheduler's delivery to the owner alone, with their Always in the loop switch on, `render_briefing_context(owner_notes=)` also carries FROM YOUR NOTES — DUE SOON (their own notes of what they promised or asked, overdue to a week ahead; `memory.history_brief`), which counts against a quiet day, enters the fingerprint and marks the run private; both standalone prompts turn it into a **From your notes** section. The /today header never gets it. **The first week.** For seven days from the principal's People row (`briefing.first_week`), `render_briefing_context(getting_started=)` carries a GETTING STARTED block right after the live blocks: the install's goal rows (department, key result, target, period) or, while there are none (setup saves no goal rows, so this is a fresh install's usual case), this year's priorities and north star from the saved profile (`strategic_priorities`, up to five, keys `priority:<text>`), departments with no `head_person_id`, and, on the scheduler's delivery to the principal alone with Act as me and Draft replies to my inbox both on and the mailbox connected (the inbox watcher's consent), up to five people who wrote to their own mailbox in the last 48 hours as sender and subject only (`inbox_message_ids` + headers of `get_message`, bulk and automated mail skipped; the same \"where, never what\" rule as `delegation.mail_reads`) and, with Act as me and Read my calendar on, up to eight of today's events on their own calendar as time and title (declined ones left out). It counts against a quiet day, enters the fingerprint (`getting_started=` keys, no dates; a meeting's key is its event id) and, with the inbox or calendar part, marks the run private. Both standalone prompts open with a **Getting started** section and take the Top call from it (`GETTING_STARTED_RULE`); the whole-company /today header gets the block without the inbox (`getting_started_shared`, synchronous, no mailbox read) and the header prompts take the bottom line and move from it (`GETTING_STARTED_HEADER_RULE`), so a new install's header is not short-circuited to the quiet line. `GET /today` sets `first_week`; while it is true the Briefing hides the \"Quiet day\" banner, renders the header narrative open in the page under **Getting started · your first week** (in place of the \"Read today's brief\" side panel), and, when the summary counts are all zero, shows the narrative's **Move today:** line in place of \"All clear\" (`firstWeekMove`). The last setup screen (`OnboardDone`) offers one first question built from the saved priorities (`firstQuestion`) and hands it to Home through session storage (`oe.onboard.firstQuestion`, never the URL), which asks it once. A teammate's scoped header never gets it. The alert review's `render_batch` puts the same block ahead of the alerts (read once per pass), so a note, rewrite or routed DM never repeats a figure the principal already corrected.\n\n**When a brief isn't sent.** Above the Briefing, the owner sees a one-line notice when their latest morning brief, end-of-day digest or (in solo mode) weekly review wasn't sent — \"Your morning brief wasn't sent: nothing is set up to send it to you\" — with the day, what fixes it, a link to read the brief on the Artifacts page (left out when the brief couldn't be written at all) and one to Setup status. It comes from `GET /today/brief-delivery` (the scheduler records each run's outcome), shows nothing while briefs go out or while the scheduler is off, and clears once the cause is fixed. When the Executive's mail connection wasn't running (the MCP gateway failed to start and is retrying), the notice says that instead of blaming the owner's setup; a send that failed on every channel names what each channel answered, from the recorded `detail`, with addresses left out. Teammates never see it.\n\n**Replies waiting.** With Act as me's **Draft replies to my inbox** on, the top of the Briefing's left column lists the replies the Executive drafted in the owner's own Gmail for mail that needs them (`RepliesWaiting`, from `GET /delegation/replies` — see Act as Me). They belong to the owner alone: the route answers only the person who can have Act as me, the decisions behind the cards (`delegation_reply`) are principal-only and carry `private: true`, so `/today/activity` and the heatmap leave them out, and none is ever an alert, so nothing of them reaches `GET /today`, the header or the briefs. Each card shows who wrote and who they are to the owner, whether their address was verified, the subject, what they wrote (as plain text), the draft, **Decide before sending** (its open questions) and its warnings, with **Send**, **Edit in Gmail** (the thread in their Gmail) and **Dismiss** (which deletes the draft unless they edited it). **Send** asks first, naming who the reply goes to, then sends the draft exactly as it is in Gmail (`POST /decisions/{id}/approve`); when its recipients changed in Gmail or a newer message arrived, the backend's 409 `confirm` becomes a second question naming them. The card hides itself when nothing is waiting.\n\n**Solo focus cards.** `GET /today/top-three` and `GET /today/weekly-review` feed two solo-only cards, so a principal who only uses the web app — no chat app, no Google Workspace — sees today's top three and the weekly review instead of finding them only in the Workflows run history. Both answer only in solo mode (`effective_workspace_mode`) and only to the principal, by the stricter rule for starting a principal-only run (`workflows._caller_is_the_principal`: the caller's own email on a principal entry that is not archived, or no `x-caller-email` at all — never \"nobody is principal yet\"); a teammate, any other signed-in caller and team mode get null. `top-three` hands `open_loops.principal_due_soon()` to `briefing.top_three.build_top_three` — the morning brief's own inputs and code, so the items, their order and their free slots are the brief's — and returns `{items: [{key, kind, text, why, slot}]}`: `slot` is the free block (\"10:00–11:00\", the user's zone), \"\" when none is left, or null when no calendar was read (none connected, a failure or the 4 s timeout, a weekend); `items` is empty when there is nothing to pick. It is a route of its own, never part of `GET /today`, so the Briefing never waits on the calendar. `weekly-review` returns the latest `weekly_review` run with status `done` (`persistence.list_runs(..., status=\"done\", limit=1)`, newest `updated_at` first; failed and running runs never count) as `{run_id, completed_at, period, top_three, excerpt}`: `weekly_review.summarize_review` reads the artifact's title line and its last *Next week's top 3* section back as plain text, and `excerpt` stands in when that list is empty (the section's own note, else the review's first lines). Null when no review has completed or the run store cannot be read.\n\nThe route resolves the caller from `x-caller-email`, serves the viewer's cached narrative and, when its key moved, rewrites it in a `BackgroundTask` so the request never blocks on an LLM call (the page re-polls while `narrative_stale` is true). `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; solo mode has its own, with goals at risk by area and no waiting-on section). `GET /morning-brief` is a deprecated alias.\n\n**Solo mode in the UI.** The response is the same in both modes; the briefing reads the workspace mode from the app-wide `WorkspaceProvider` (which reads team while loading or on error, so a team install never flashes solo) and, in solo, drops the team surfaces: the Departments card, the People card, the \"Across the team\" lane (every action proposal is the one user's, so all of them land in \"Needs you\"), the people-awaiting, people-overdue and departments-at-risk status pills, and the quiet-day \"Set up a check-in\" link. A \"N goals at risk\" pill (at-risk plus off-track goals, from `departments`) links to `/goals` instead, so the strip never reads \"All clear\" over a goal that is slipping. In the Departments card's place, **Your projects** lists the initiatives with status `active` (`GET /memories/initiatives`): **Done** marks one `completed` through `PATCH /memories/initiatives/{id}` (only `completed` takes an initiative out of the Executive's active context), and **Drop** deletes it through `DELETE /memories/initiatives/{id}` after a confirm. Under **Needs you**, a **Due soon** card lists the principal's open loops that are overdue or due within 7 days — their dated commitments and what others asked of them — read from `GET /people/{id}/open-loops` for the principal (the oldest principal in `people`, the backend's rule), labelled by `lib/dueSoon.ts` (tested by `npm test`: \"Overdue since Sep 23\" / \"Due today\" / \"Due Mon, Sep 28\", with a count of anything due later); **Done** closes one through `POST /open-loops/{id}/close`, which also stops the nudge engine chasing it. Above it, **Top three today** numbers the morning brief's three (`GET /today/top-three`) with each one's reason and, when a calendar was read, its free slot (or \"No free time left today\"); at the top of the right-hand column, **This week's review** (`GET /today/weekly-review`) shows the period, when it ran, next week's top three (or the excerpt) and a *Read the review* link to its run page (`/jobs/runs/{id}`). Each card fetches on its own once the Briefing has loaded, so a slow calendar never holds the page up, and renders nothing when the API returns null or an empty list. A commitment in the top three reads as the owner's own (\"Send the proposal\") through `lib/dueSoon.ts`'s `loopText`, as in Due soon; the cards' wording lives in `lib/rhythmCards.ts` (tested by `npm test`). The Pulse page hides its \"Department check-ins\" and \"Awaiting people\" blocks in solo, and its header shows active projects in place of the department check-in count. Team rendering is unchanged.\n\n**Your month (`GET /today/value`).** The owner's own tally of what the Executive did for them, `briefing.value_summary.summarize(period, offset)`: the calendar `month` or `week` (Monday first) in the user's zone, `offset` periods back (0–24), each line beside the period before. Every number is a `COUNT(*)` of rows that prove it happened, never a model's: messages sent for the owner (the DM handlers' own `kind=outbound` sent rows to anyone but the owner, plus Gmail / Outlook send-tool calls that didn't come back with an error, so mail sent from a chat turn counts), replies drafted and sent from the owner's inbox (their Act as me rows), meetings booked (calendar create calls), briefs delivered (the scheduler's `delivered` row), reports (finished team workflow runs, minus the daily rhythm runs and any run a teammate started for themselves, which stays theirs alone; the latest ten listed with links), follow-ups and nudges sent, tasks tracked and closed as done, proposals decided, alerts flagged and requests answered (`chat_turn` out rows). No \"hours saved\" and no cost line: nothing recorded supports the first, and cost next to what the owner got reads as a bill; it has `GET /audit/usage`. The owner's alone (403 for anyone else): it counts rows private to the owner, never a row private to another member. Pulse shows it as a **Your month** card on the overview (\"October 2026: 42 messages sent, 6 reports, 3 meetings booked.\") and a focused screen, `/memories?tab=value`, with a month / week switch and previous / next. On the first weekday of each month, in daytime (09:00–18:00 local), a scheduler tick hook sends the owner last month's lines and a link (`value_summary.maybe_send_monthly`, claimed once per month under `briefing_narrative` scope `value_summary:YYYY-MM`), in solo and team mode alike; nothing is sent for an empty month. Off with `VALUE_SUMMARY_MONTHLY_ENABLED=false`.\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. Four things now keep it live and true:\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. **Snooze** (a card's ⋯: later today, tomorrow 9:00, Monday 9:00, in the viewer's clock; `POST /alerts/{id}/snooze`) hides a card until `snoozed_until`, with an Undo; the TTL anchor is the latest of `created_at`, `last_seen_at` and `snoozed_until`, so a snoozed card comes back rather than expiring unseen.\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- **Collection tags** (`alerts.pipeline`). A triaged alert never carries a `collection:<name>` tag: the pipeline strips them before inserting. Only an installed extension's own code files a document into its collection (`orchestrator.extensions`), so injected text can't make a card that the extension would treat as its own.\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 (team members only — an alert routed to a contact never puts them in the slice, so they are never routed to, nudged or chased; a private card is never reviewed at all, nor used as evidence for another), 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). A review DM is proactive outreach, so the recipient's notification settings apply: one held for their quiet hours or brief counts as a route made but not as a nudge toward the cap (and no second nudge is held while one waits), and one about an alert whose severity is (or becomes) `urgent` is marked urgent (`notifications.urgent_send`) and gets through when they let urgent things through.\n- **Grounded text** (`openexecutive.briefing.grounding`). Nobody reads an alert's text before it is dispatched, so what the model wrote onto it must be supported by what it read. After triage (`alerts.pipeline._ground_decision`, before coalescing or inserting), a headline naming a person or figure the event does not hold — sources are the event's subject, sender, title and body, the initiatives triage was shown and the company profile — is replaced by the event's own subject, such body sentences are dropped (all of them → the event body cut to 280 chars); both fallbacks are raw event text, so they are made inert first — links masked, Markdown and Slack `<…>` syntax and @-mentions stripped — because a broadcast posts them as written, and such a suggested action is dropped. A review `changed` rewrite is checked against the alert's own text and the evidence it was reviewed with (signals, related alerts, activity, the roster slice), plus the standing facts the batch was shown, so a rewrite that corrects a card to one of the principal's corrections is grounded; an ungrounded rewrite keeps the old text, still applies a severity change, and audits `text_ungrounded`. A name counts as grounded only when one source line holds all of it; a figure only when a source number matches it within the precision it is written with. Each finding writes a `grounding` audit row; `GROUNDING_CHECKS=report` records without changing anything.\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`. Acknowledging or resolving an alert — including the review closing it itself — marks the review's DMs about it `acted` in the Attunement outcome ledger, for the person it is routed to and the principal only; dismissing it, finding it stale or letting it expire voids them (counted neither way). Review DMs are tagged `alert_review` with `alert:<id>`.\n\n## Multi-client practice section\n\nIn multi-client practice mode (2+ client slots — see the Client Companies section), the response gains an additive `practice_clients` list: rollup cards for the **parked** clients (overdue follow-ups, awaiting replies, unread alerts, onboarding due soon, renewal countdowns), each stamped with the save point its data reflects. Single-company installs always receive an empty list and the UI renders nothing.",
"mermaid": "flowchart TD\n REQ[\"GET /today\"]\n BUILD[\"_build_today()\"]\n DEPTS[\"departments<br/>(per-dept goal health)\"]\n ROSTER[\"people<br/>(attention-ranked roster)\"]\n PROPS[\"proposals<br/>(unread alerts, routed)\"]\n INFLIGHT[\"in_flight<br/>(pending follow-ups / nudges)\"]\n AWAIT[\"awaiting<br/>(replies we await)\"]\n NARR[\"viewer-scoped narrative (BackgroundTask)\"]\n MB[\"morning_brief workflow\"]\n TOP3[\"GET /today/top-three<br/>(solo, principal only)\"]\n PICK[\"build_top_three()<br/>(calendar read, 4 s cap)\"]\n WREV[\"GET /today/weekly-review<br/>(solo, principal only)\"]\n RUNS[\"workflow_runs<br/>(latest done weekly_review)\"]\n LIVE[\"live_signals<br/>(inbound / held replies / chats,<br/>cached calendar)\"]\n TICK[\"scheduler tick<br/>(every 10 min, 06–22 local)\"]\n CACHE[\"briefing_narrative<br/>(principal / company / person:id)\"]\n REQ --> BUILD\n BUILD --> DEPTS\n BUILD --> ROSTER\n BUILD --> PROPS\n BUILD --> INFLIGHT\n BUILD --> AWAIT\n REQ -->|\"resolve caller, attach\"| NARR\n LIVE --> NARR\n TICK -->|\"refresh_principal_narrative\"| NARR\n NARR --> CACHE\n MB -->|\"since last brief\"| LIVE\n MB -->|\"calls directly for standalone DM\"| BUILD\n MB -->|\"same pick for the DM\"| PICK\n TOP3 --> PICK\n WREV --> RUNS\n class REQ entry\n class BUILD compute\n class DEPTS storage\n class ROSTER storage\n class PROPS storage\n class INFLIGHT storage\n class AWAIT storage\n class NARR compute\n class MB compute\n class TOP3 entry\n class PICK compute\n class WREV entry\n class RUNS storage\n class LIVE compute\n class TICK entry\n class CACHE storage",
- "generated_at": "2026-10-15T16:30:00+00:00"
+ "generated_at": "2026-10-16T14:02:22Z"
}
diff --git a/packages/core/openexecutive/architecture/prebuilt/workflows.json b/packages/core/openexecutive/architecture/prebuilt/workflows.json
index e800ff53..0b8278a9 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 25 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`, `exec_search_brief` — people and org artifacts (the last is an advisory hiring brief / scorecard from the CHRO, with input from the hired function's specialist — `sales` for a sales role — kept when the recruiting pipeline was removed).\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` (`department_check_in.persist_goal_verdicts`, shared with `weekly_review`).\n- `weekly_review` — the principal's weekly look back and ahead (see *Weekly review* below).\n\n**Standing facts in unattended output.** `end_of_day_digest`, the weekly review's top-three call and the morning reflection append the standing facts (`memory.facts.with_standing_facts`; a teammate's marked `(per <name>)`) to their user turn, and the morning brief gets them through `render_briefing_context`. A workflow step that consults a specialist gets them through `route_to_specialist`. A correction made in chat therefore holds in every recurring brief and run. The morning brief also reads `facts.render_teammate_changes(since)` off the event loop and passes it to both `render_briefing_context` (a TEAMMATE CORRECTIONS SINCE LAST BRIEF block) and `build_brief_fingerprint`, so the principal hears of each correction a teammate made in the window, and that alone un-suppresses an otherwise unchanged brief. Proposals waiting for approval are listed only in a brief the principal reads privately (`include_proposed=_private_ok()`), and then mark the run private to them. The principal's own Always in the loop notes (`memory.history_brief`, only with their switch on) come in by a stricter rule, only on the scheduler's delivery (`PRINCIPAL_DELIVERY`), never a run from chat, whose tool result reaches the turn's shared audit row and peer memory: the morning brief's FROM YOUR NOTES — DUE SOON block and the end-of-day digest's FROM YOUR NOTES — TODAY block (what they committed to since the last digest, then what is due tomorrow). Either marks the run `private_to_principal` and moves its fingerprint; the digest, which had no private reads before, now emits that flag too. In the install's first week (`briefing.first_week`, seven days from the principal's People row) the morning brief also passes a GETTING STARTED block to `render_briefing_context(getting_started=)` and its keys to `build_brief_fingerprint`: onboarding goals, departments with no leader and, on the scheduler's delivery with Act as me and Draft replies to my inbox on, who wrote to the owner's own mailbox (sender and subject only) and, with Read my calendar on, today's meetings on their own calendar (time and title), either of which marks the run `private_to_principal`. The brief opens with **Getting started** and is never the quiet line while the block has anything in it (see Today).\n\n### Change-aware principal briefs\n\n`morning_brief` and `end_of_day_digest` are the two recurring briefs the scheduler sends 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). The morning brief also reads the principal's **live world** since that window opened (`briefing.live_signals.gather_live_signals`): mail and chat the Executive handled (INBOUND, grouped by sender and subject, each email from the roster marked replied or not, earlier days dated), under a NOW line and THE PRINCIPAL line that names its reader so the brief writes \"you\" (the end-of-day digest gets the same line, and the team reflection a YOUR PRINCIPAL line under its roster; the reflection flags only what today's input still shows), what got stuck (STUCK: a reply the outbound gate held, a non-roster sender who got no reply, a Google Chat message left unanswered, chat drafts still in the principal's Gmail, after `live_signals.settle_principal_drafts` has marked the ones they since sent or deleted there), the principal's own chats, and — in both modes now, unless the solo top three already listed it — today's calendar, read fresh (`live_signals.refresh_calendar(max_age=0)`). The 07:30 reflection's **Flagged for the brief** bullets are carried across (`brief_state.reflection_flags_since`, the latest reflection run finished inside the window) instead of surviving only as an activity line with the run's title, and the rhythm runs themselves (`today.RHYTHM_WORKFLOWS`) are dropped from the brief's activity: their dated titles were noise and moved the fingerprint every day. At-risk departments name their slipping goals and each proposal carries its age. The period is the principal's local date. Section order: top call → **today** (the calendar's shape and anything stuck) → what changed (inbound first, naming who wrote) → handled overnight → needs you (new only) → waiting on → at risk (the slipping goal, or the department left out — never \"no detail yet\"). Quoted mail, chat, invite and reflection text is marked as data, never instructions. **Privacy:** the brief reads what is private to the principal — their contacts' alerts and mail, their drafts, their chats and their calendar — only on a run for them: the scheduler's (`morning_brief.PRINCIPAL_DELIVERY`) or the principal's own verified chat turn in a conversation only they can read (`delegation.settings.private_conversation`: the web chat, a Slack or Discord DM, a private Telegram chat — never a shared channel, where the reply is posted for everyone). A run anyone else starts (a teammate from chat in team mode, `POST /workflows/…/runs`) reads what everyone may see, as before. A run that did read a private row says so on its `result` event (`private_to_principal`: its live read differs from the shared one in any key or count), and the scheduler, `run_workflow` and `POST /workflows/{name}/runs` all then keep `persistence.PRIVATE_RUN_ARTIFACT` in the run history instead of the text. Text another pass wrote (the reflection's flags) renders as quoted ` > ` lines and every goal and headline field is one-lined, so none can start a line that reads as a block header. The fingerprint carries the live signals' time-free keys (who wrote about what, what is stuck, the calendar's shape) and the reflection flags when there are any, so \"nothing new\" means the principal's world was quiet too; the context summary is logged at INFO (`morning_brief: context since=… inbound=… stuck=… suppressed=…`). In **solo mode** (one person using Open Executive for themselves) both briefs speak to the principal, whatever their role: the morning brief runs top call → top three today → what changed (inbound and stuck first) → handled overnight → needs you → due this week (the principal's open loops overdue or due within 7 days, from `open_loops.principal_due_soon`) → goals at risk (named by area), the end-of-day digest what I did → open decisions → goals at risk tomorrow → sleep on this, over a context with goals at risk by area and no people-waiting or department block; the fingerprint carries the mode and ignores who is awaiting, and carries the due items as `(loop_id, state)` pairs when there are any. **Top three today** is picked in code, not by the model (`briefing.top_three`: overdue then due-today commitments, off-track then at-risk goals, commitments due later this week, then active projects, stalest first). The solo Briefing's *Top three today* card shows the same pick from the same code (`GET /today/top-three`, see Today). When the MCP gateway runs the Google Workspace server, one `google_workspace__get_events` call (4 s timeout) lists today's events on the principal's calendar — their address as the calendar id, read with the Executive's account (`primary` when the Executive is signed in as them) — and on a business day (`calendar_tools.is_business_day`, the rule the booking tools apply; at the weekend the day's events are still listed but no slot is suggested) each item gets its own free block inside `CALENDAR_BUSINESS_HOURS_START`–`_END`, rendered with a TODAY'S CALENDAR block — only a date-only event is all day, a zero-length one blocks nothing, and one whose times can't be read is left out; no gateway, no principal address, an error, a timeout or a reply it cannot read all mean no calendar and no slots, never a failed brief; the log records only the reply's length or the error's type, never calendar text. The fingerprint carries the three items' keys (no dates, no slot times) and only a coarse hash of the day (busy blocks rounded to 15 minutes, no titles, no dates), so an unchanged day still suppresses. A day whose calendar read fails after one that worked (or the reverse) changes the fingerprint once, so that brief is written in full. 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**Brief delivery.** `scheduler.runner._deliver_to_principal` maps the principal's `preferred_channel` (`slack` / `discord` / `telegram` / `email`) to its delivery channel and tries it first, then the other chat channels the principal has an id for, in the order Slack → Discord → Telegram. Email goes through the active MCP gateway (`google_workspace__send_gmail_message` as the Executive's own address, to the principal, subject `<title> — <date>`) and is used only for an explicit `email` preference, or for `any` when no chat channel resolves — an owner linked by email at setup has `any`, so one who also has Slack does not start getting two emails a day. When nothing can deliver (a web-only principal, or email with no gateway), the brief is still generated and stored as a run with its artifact, as before — a web-only principal reads it on the Artifacts page — it is just not delivered (audited), so the window does not advance, and the next occurrence is chained. The same delivery path carries the client-rotation digest and the weekly review.\n\n**Grounding.** Nothing an unattended pass writes is read by anyone before it goes, so `openexecutive.briefing.grounding` checks it deterministically — no model judges the model. A name (a run of two or more capitalised words once section headers, weekdays, imperative openers and org nouns are trimmed, or one capitalised word in a person slot like \"ask Marcus\" or \"Marcus wrote\") is grounded only when a single line of the pass's inputs holds all of it, or it belongs to a roster person some input mentions — being on the roster alone is not enough. A figure (money, a percentage, a k/M/B number, any bare number of 11 or more; never a date, time, year, duration, id, list marker, `Q3` or small count) is grounded when an input number matches it within the precision it is written with (`$1.2M` matches `$1,234,567`; `47 units` does not match 48). The inputs are the rendered context split into lines labelled by section (a header also carries its bullet count), the company profile and the department titles. `morning_brief` renders its context itself and hands it to the synthesizer as `rendered_context`, so the check reads exactly what the model read; after the quiet fallback, `ground_brief` runs on both briefs. When something is ungrounded it makes one repair call to the fast model (same system prompt, the list of items, \"remove or correct using only the context\"), re-checks, then drops each line still ungrounded and any header left empty, and appends \"_I left out N lines that named people or figures I couldn't match to your data. They're under Left out of your brief on Home._\" (everything ungrounded → one held-back line). Every held line goes in the `grounding` audit row's untruncated `full` payload (up to 30, 400 chars each; `details` keeps a five-line preview), and `grounding.recent_held_back` reads the last day's back for `GET /today`'s `held_back`, which Home lists under **Left out of your brief** for the principal alone — after the narrative inputs are taken, so the held lines never reach a prompt. Then each grounded figure gets a server-chosen ` [n]` — the matching input line with the most words in common with the figure's clause — and a `**Sources**` list closes the brief (`- [n] <section> — <snippet>`, at most 9, snippets quote inbound mail, so links are masked (\"(link removed)\"), Markdown, angle brackets and @-mentions stripped, and they are cut to 90 chars; never `[n]:` at a line start, which Markdown reads as a link definition). Text with nothing to change comes back byte-identical, the fingerprint hashes the inputs so suppression is unaffected, and the grounded text is what is delivered, stored and recorded as delivered. Both brief prompts and the digest prompts say the rule up front. `executive_reflection` wraps its handlers in a `GroundingScope`: `create_alert`, `message_person`, `send_department_message`, `send_company_broadcast` and `schedule_followup` refuse text with an ungrounded name or figure, returning a JSON error that names the items so the model can look the person up or leave the figure out (every tool result joins the inputs, so a `lookup_person` answer grounds the DM after it; the recipient's own name always counts). Its **Flagged for the brief** bullets are filtered the same way before the tool log is appended — the next brief quotes them, where they would ground themselves — and `brief_state.reflection_flags_since` now stops at the tool log's `---`. The reflection's `grounding` rows are private when a private-to-principal alert reached its context, and the digest's always are (its HANDLED block can quote one). Everything fails open. `GROUNDING_CHECKS=enforce` (default) acts, `report` only writes the `grounding` audit rows, `off` skips it; `GROUNDING_CITATIONS=false` drops the markers. Not yet grounded: the /today header (its cards sit beside it), `weekly_review`, the research synthesis, dates and meetings, and a real person named in the wrong role.\n\n### Weekly review (solo)\n\n`weekly_review` (background, inputs all defaulted) closes out the principal's week in six steps. **Goals**: every area with goals is graded by its own specialist, concurrently, with the department check-in's verdict contract (`_parse_verdicts`) and write-back (`persist_goal_verdicts` → `record_goal_review`, one `goal_status_review` audit row per area with actor `weekly_review`); an area with no goals is skipped, one without a specialist is listed ungraded, and one whose specialist fails is shown as last recorded. **Commitments**: `open_loops.principal_due_soon` — overdue or due within 7 days. **Projects**: active initiatives with no update for 7+ days. **Decisions**: the week's (`episodic.decisions_since`). **Revisit**: up to three decisions older than 30 days with an empty outcome (`episodic.decisions_awaiting_outcome`, newest first), listed as `[decision N]` under *How did these turn out?* — the principal's answer is recorded with `record_decision_outcome` (see Agents). **Assemble**: every section always renders (a one-line note when empty), ending with *Next week's top 3* from one fast-model call that follows the `weekly-review` playbook (a constant system prompt; the playbook rides in the user turn), trimmed to at most three list items — or, when that call fails or returns nothing, the same ranked pick the morning brief uses. In solo mode the scheduler fires it weekly (`principal_weekly_review`, see Scheduler) and delivers it through `_deliver_to_principal` like the briefs, recording the delivery outcome. The solo Briefing also shows the latest completed run to the principal (`GET /today/weekly-review`, see Today): `weekly_review.summarize_review` reads the artifact's title line (`TITLE_PREFIX`) and its last `TOP_THREE_HEADING` section back as plain text, so a principal no channel reaches still sees next week's top three. Wording is role-neutral; run by hand in team mode it says *department* instead of *area*.\n\n**Principal-only workflows.** A workflow can name the workspace modes in which only the principal may start it (`Workflow.principal_only_modes`): `weekly_review` in both modes (built from the principal's decision log, commitments and goals, and it re-grades the goals) and `morning_brief` in solo (built from the principal's commitments and calendar). Team `morning_brief` and every other workflow can be started by anyone as before. This decides who may start or trigger a run, not who may read one: stored runs, the scheduled briefs and weekly reviews included, are read under the existing `/workflows/runs` rules — which is why a morning brief that drew on the principal's private rows is stored as `PRIVATE_RUN_ARTIFACT`, not as its text.\n\n- **From chat**, `run_workflow` checks at dispatch, before any run row is created, that the turn is the principal on a verified surface — `create_goal`'s rule — and otherwise refuses with a plain error that does not spell out the rule.\n- **Over HTTP**, the Jobs page's `POST /workflows/{name}/runs` and `POST /evals/runs` (a workflow scenario runs the workflow on live data) call `refuse_principal_only_run`: only a caller signed in as the principal, or a request with no caller email (the CLI or local login), may start the run. Unlike the workspace settings, an install with no principal on the roster lets no signed-in caller in, as in chat. Anyone else gets a 403 (\"Only the principal can run this workflow.\") before any run row exists. The mode is the stored one, or an eval scenario's own `workspace_mode`. The eval route runs exactly the scenario list it checked.\n\nEvery refusal is audited `refused=true` with the workflow, the mode and the caller. The checks fail closed: a mode that cannot be read counts as principal-only, and a check that cannot read the roster refuses.\n\n**Knowledge in the reflection.** A chat turn looks the knowledge base up before the Executive answers; the reflection reads the org's state instead, so nothing looked it up for it. It now carries its own `search_knowledge` tool (`orchestrator.knowledge_tools`, not in the shared `_ALL_SKILL_TOOLS`), which runs the same `knowledge.retriever.retrieve` as chat — the review gate, the synced Drive / OneDrive / Confluence / Notion collections and the published-artifact rule (the pass has no viewer, so no one's private document comes back). The prompt (`_KNOWLEDGE_RULE`, both modes) asks it to search before acting on or flagging something that turns on a customer's or supplier's terms, a price, a policy, a plan or a past decision. Its passages come back up to 4,000 characters (`execute_tool_calls(wide_results=...)`) while other tools stay at their short preview, its result counts as grounding input like any tool result, and the run's tool log keeps each line to 160 characters. Read-only, so Take the lead never gates it. The loop has 5 iterations (was 4) to leave room for a search before acting.\n\nNeither the nightly reflection nor the research synthesis can call `ack_alert`: both run unattended with open alerts rendered into their context, and those headlines are minted from inbound mail and chat, so an injected \"the principal already dismissed 13\" would be acted on with nobody watching. Closing an alert is the alert review's job, with evidence.\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. It also renders an **OPEN LOOPS** block (up to 10, soonest due first, overdue flagged) from Attunement so the standup can connect a slipped promise to the rest of the org state; the nudge engine already chases overdue loops, so the prompt tells it not to DM about a loop merely for being overdue. A **WHAT LANDS** block (from the Attunement outcome ledger) shows, per person, how often each kind of proactive DM got answered over 30 days; the prompt steers DMs toward kinds that land and away from kinds a person reliably ignores. Reflection and research tag their tool execution as proactive (`tag_proactive`) so their DMs are counted. Resolving a wait-for-human approval (`resumer.apply_resolution`) marks the nudges that chased it `acted`. `close_open_loop` is withheld from reflection for the same reason as `ack_alert`: loop text is quoted from what people wrote. `unattended_toolkit` also drops `schedule_tools.UNATTENDED_WITHHELD_TOOLS` (today `create_goal`) from both passes in both modes: a goal is the principal's own decision, and these passes see only inbound text. A turn private to the principal (mail from one of their contacts, or mail they forwarded) cannot start a workflow either: `run_workflow` and `run_executive_research` are in `schedule_tools.PRIVATE_TURN_WITHHELD_TOOLS`, which the chat loop neither offers nor runs on such a turn, since a workflow's steps can reach anyone.\n\nIn **solo mode** the reflection is framed for the principal, whatever their role: they are the only person who uses Open Executive and the only one it takes direction from, it prefers `create_alert` and `schedule_followup` to the principal, and it never messages anyone else from an unattended pass — the people in the principal's world are contacts, so anything they should hear is flagged for the principal to raise. The team roster is replaced by one YOUR PRINCIPAL line (person_id and follow-up channels), its follow-up guard is seeded from the principal only, and department risk renders as areas with goals at risk. The research synthesis follows the same rule — its routing menu and roster name only the principal. In both, `send_department_message`, `send_company_broadcast` and `set_department_head` are withheld, and so are `create_calendar_event`, `create_instant_meeting` and `run_workflow` — a booking reaches its attendees and a workflow can do anything its steps do, so the principal books and starts workflows from chat — and `message_person` refuses anyone but the principal. These passes run unattended with inbound text in their context, so the rules are enforced in code, not only in the prompt.\n\nIn either mode, both passes now dispatch only the tools they offer: the handler map is built from the offered list, so a name the model emits without being offered it is skipped as an unknown tool. They used to look names up in the full handler registry, so tools they deliberately withhold — the raw DM tools (`send_slack_dm` has no roster check), `ack_alert`, `close_open_loop`, and in research the watchlist writes and `run_workflow` — still ran when the model emitted them. Both read the mode before binding their own session (so a caller's override, such as an eval's, counts) and pin it on that session, so their tool handlers use the same mode. They carry the principal's role across the same way (`effective_principal_role` of the caller's session, pinned as `turn_principal_role`), so a specialist or workflow started from either pass sees the role of the turn that started it. Team runs are unchanged.\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: the runner calls `save_checkpoint`, the `workflow_runs` row moves to `status='awaiting_human'`, and the serialized `WaitForHumanEvent` is stored in `state_json`. (Department authority is a *separate* mechanism — `propose_only` departments file a briefing alert via `departments.authority.propose_via_alert` and mark the scheduled action done; they do not route through this gate.)\n\n**Delivery.** Both checkpoint sites — the SSE route and the `run_workflow` chat tool — call `workflows.gate_delivery.deliver_gate_question` immediately *before* checkpointing, so `state_json` carries the routing fields a reply is matched against. Two modes. When the approver is the person already in the conversation (the chat session's `origin_channel` is set — to anything but `email`, whose answer is no chat reply and would never be sent — and its `caller_person_id` is the gate's `person_id`), nothing is sent — the question rides in the Executive's own reply — and the gate records `origin_session_id` plus the session's channel. The resolver compares base ids (`memory.conversation_ids.base_session_id`), so a question asked in one conversation of a Telegram chat or a DM is still answered by a reply after a quiet gap or /new has started the next. Otherwise the question is delivered through `schedule_tools.handle_message_person`, which picks the person's preferred channel, falls through on a failed send, and falls back to a briefing alert; the gate then records the channel, address and provider message id that send returned, plus the id of the DM session it landed in — that send is always 1:1, so the answer belongs in that conversation and nowhere else. Without it the gate matched on person and channel alone, so an unrelated @mention in a public channel resolved it and had the acknowledgement, run title included, posted where everyone could read it. The question is sent with `notifications.approval_send`, so the person's quiet hours and *In my briefs* never hold it, whatever their urgent setting: only a reply to it resolves the gate. Delivery is not guaranteed: the outbound guard can suppress it (duplicate, rate cap, quiet hours) and an unreachable person gets the alert fallback. Both cases leave the routing fields empty and report `delivery` as `suppressed` / `alerted` rather than claiming someone was asked, and the chat tool's presentation hint changes accordingly.\n\n**Matching a reply.** Each inbound adapter passes the message to `inbound_resolver.resolve_inbound_message` with its `session_id`. Matching is three-tier: an explicit `in_reply_to` against a stored `outbound_message_id`; otherwise a single open run on that channel; otherwise one utility-fast disambiguation call gated at 0.85 confidence. An unmatched explicit reference rules out only the candidates that carry a stored outbound id — the ones it could have matched — and the rest continue; rejecting outright meant an adapter that passes a thread id on every message (Slack's `thread_ts`) short-circuited the later tiers forever, and a global test let one delivered gate's id block an unrelated self-approval gate. Channel names are normalized (`slack_dm` ≡ `slack`), the delivered address is compared when both sides know it, a row whose `state_json` will not parse is refused (a corrupt row otherwise presents as a legacy one), and an empty stored channel is treated as a wildcard only for rows checkpointed before gate delivery existed. Two guards keep an open gate from swallowing unrelated traffic: a gate carrying an `origin_session_id` matches replies only from the conversations the adapter names (a Slack or Discord thread offers its parent channel session too, mirroring the history double-write, since a gate raised on a mention recorded that session while the answer arrives under the thread's — on Slack only when that person rooted the thread, or the alias would reach into a colleague's), and the parser can return `unrelated`, which declines to resolve and lets the message reach the normal chat path. The parser is handed the gate's own question, so a bare \"yes\" is judged against something. Its fallback is flagged by a key the model cannot emit rather than by a magic note string it could, and a fallback declines to resolve on *every* reply shape — recording the empty string a `free_text` fallback fabricates would close a sign-off on a parser outage. Every shape can answer `unrelated`, not just `approve_reject`: without it an open `free_text` gate turned the person's next message into its answer verbatim, and a `numeric` one swallowed any message containing a number. The parser has one caller outside workflows: its `roster_identity` shape — `{decision: approve|link|decline|unrelated, name, kind: team|contact|null}`, with `name` only as the person wrote it (never inferred) and a fallback of `unrelated` — reads the principal's emailed answer to a roster request (who a new sender is; see Org). It is not a gate reply shape, and a fallback or `unrelated` leaves the request waiting. `resumer.apply_resolution` then 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 outcome surfaces on the Today dashboard.\n\n**Resuming past the gate.** A paused run continues on its own. Re-entering it was long assumed to mean serializing a Python generator frame; it does not. The only state alive across a dynamic workflow's steps is its inputs (already persisted), a company-profile block that is recomputed, the completed steps' output strings, and the loop cursor — so the engine hands the checkpoint a small JSON `WorkflowResumeState` (workflow name, the gate's id and index, the next index, the outputs so far), stored in `workflow_runs.resume_state_json`, and `DynamicWorkflow.resume` replays its step loop from the recorded index. `run()` and `resume()` share that one loop, which is why a second gate needs no special handling — it is simply another pause raised from the same place. The payload rides on a `WaitForHumanEvent` field declared `exclude=True`, so it can never leak into `state_json`, whose exact key set the resolver branches on. A gate with no payload is *pause-only*: the decision is recorded and the run stops, which is what every caller got before resume existed.\n\n`resumer._process_resumable` claims a resolved run with one guarded UPDATE — `resolved` → `running`, stamping `resumed_at` and minting a claim token — and drives it to a terminal row. It runs two ways: immediately, via a task `apply_resolution` kicks off so a Slack approval starts moving in seconds, and every 60s from the poll loop as the durable backstop. Both share the claim, so a run executes exactly once even with two resumers against one database. The kicked task binds no chat session (`set_session(None)`), exactly like the poll loop: it is created inside the inbound handler that recorded the answer and would otherwise inherit that person's live turn — so a run resumed because the principal replied on Slack does not act with the principal's identity (it cannot, for example, reach the principal's contacts). It drops the handler's audit scope too (`audit.context.unscoped_audit_rows`): inherited, the principal's scope would make private every row of the run that names a contact, and whoever started the run would see those rows vanish after the approval. The poll runs the executor *after* the timeout loop, which is what finally makes `on_timeout='auto_proceed'` do what its name says: the timeout resolves the run and the same tick executes it. While the Executive is paused (`scheduler.pause`) the resumer does nothing — no startup sweep, no timeouts, no resumes — and `apply_resolution` still records the decision but skips the immediate kick; the first unpaused iteration catches up on all of it, so a timeout that lapsed during the pause applies its `on_timeout` policy then.\n\n**The claim is fenced, because it is not a lease.** The stale sweep decides a worker is dead from a wall-clock guess, so a slow but *alive* worker will eventually be declared dead and replaced. Every write the executor makes carries its claim token and is refused once superseded — otherwise the replaced worker's late completion lands on top of its replacement's result, or its checkpoint at a later gate resurrects an already-finished run and asks the approver a second time. The retry budget resets at each new gate (a gate is new work, not a retry), and a run that exhausts it is *ended* rather than dropped: an exhausted run sits in `running` with a payload, in neither queue, and would otherwise show as in-progress forever.\n\n**The gate fails closed.** Continuing is an allowlist — `approve` and the synthetic `auto_proceed` — not \"anything that is not a stop word\". `decision` is whatever a fast model extracted from free-form chat and it drifts; under a denylist, \"rejected\", \"Reject\", \"decline\" and \"no\" would all continue, so the approver declines and the deliverable is produced anyway. Reply shapes that ask a question rather than seek permission always continue, since the answer *is* the value. A stop ends the run at `error` with the human's note. Either way the decision becomes the gate step's own output, so it reads as a section *in* the artifact — capped and blockquoted, because that text reaches the synthesis specialist as prompt context.\n\n**A definition edited during the pause is refused.** Resume re-validates the payload's version, the recorded gate, *and* a fingerprint of the whole step list, and derives the index to continue at rather than reading it from the payload. Pinning only the gate would not be enough: definitions are overwritten by name and any rostered user can save one, so someone could keep the gate identical and replace every step after it — and the approver's sign-off would be recorded against work they never saw, which defeats the one thing an approval gate is for. No built-in workflow yields the gate; only user-created dynamic workflows do.\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 — literally the same code, since both call `workflows.gate.checkpoint_gate`, which delivers the question and writes the checkpoint in one place. It never hangs waiting on a human, and it reports both whether the question reached them and whether the run will continue by itself once answered. The runners that *cannot* pause — the schedulers, evals, client rotation, onboarding, the research tools — call `gate.ensure_workflow_event`, which raises on a gate rather than letting one be swallowed; the scheduler's dynamic-workflow branch used to ignore it and record a successful run containing nothing. `executive_research` is excluded (it has the dedicated `run_executive_research` tool). Running a workflow from chat delivers nothing on its own — it renders the artifact into the conversation, and the recurring principal briefs (`morning_brief`, `end_of_day_digest`) reach anyone only via the scheduler's own `_deliver_to_principal`. The tool description used to claim those two DM the principal when run and to confirm before firing them, which had the model soliciting a confirmation on a false premise; it now names `executive_reflection` as the one workflow that really does execute tool calls of its own (DMs to heads, broadcasts, alerts). 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, the conversational wizard at `/jobs/new`, or the step-by-step advanced editor — without shipping code. The Workflows page (`/jobs`) opens on a *Start here* panel that leads to all three: the user describes the job in a sentence and *Start* opens the wizard with that text sent as its first message (handed over in `sessionStorage`, so a link cannot make the wizard send text the user never typed; where storage is blocked it falls back to `/jobs/new?describe=`, which only fills the composer and sends nothing), or picks *Step by step* (advanced editor) or *Talk it through in chat* (`/?new=1&draft=`). Below it come the user's own workflows, then four ready-made starter picks with the full built-in list folded behind *Browse all* (`?browse=1`). The picks and the example chips follow the workspace mode: a team gets the investor update, board prep, MBR and competitive teardown (and a board pre-read chip); a solo owner-operator gets the MBR, pricing review, churn deep dive and quarterly plan, with chips for a Friday cash and pipeline check, customers who stopped buying and a competitor digest (`lib/workflowStarters.ts`; a unit test pins every pick to a startable `WORKFLOW_REGISTRY` entry). 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 four kinds: **specialist** (consult a specialist with a goal prompt, optionally grounded by RAG), **action** (get something done with tools — see below), **approval_gate** (a `wait_for_human` pause), and a terminal **synthesis** step that assembles the artifact. At least one specialist or action step is required. `validate_definition` enforces the structural rules: exactly one terminal synthesis step, valid specialists, `{placeholder}` tokens that reference declared input fields, rostered approval/cadence people (team members — never one of the principal's contacts, whom an unattended run may not message), 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 step-by-step advanced editor drives the `/workflows/custom` CRUD endpoints directly.\n\n**The New workflow wizard** (`/jobs/new`) is the default way to create one from the UI. It works like conversational onboarding: the user describes the job, the `workflow_designer` Council agent (`openexecutive/workflows/designer.py`) asks one clarifying question per turn — deliverable, per-run inputs, sign-off, schedule, recipient — with up to four clickable suggested answers, then emits a complete definition plus a plain-language summary and the assumptions it made. Every turn offers the model exactly three fixed, name-sorted tools (`ask_clarifying_question`, `emit_workflow_draft` — reusing the chat tool's `DEFINITION_SCHEMA` — and `search_available_tools`, which is answered inside the same turn from the tool catalog, up to four searches per turn, with the tool_use/tool_result pairs never stored in the plain-text transcript; every tool a search returns is remembered on the session and replayed into later turns, so a forced draft or a repair turn — which cannot search — still has the exact names); `tool_choice` flips to the emit tool once, when the six-question budget is spent or the user clicks *Draft it now*. The emitted definition goes through `validate_definition`, the tool-availability check, and a check against saved custom names, with one repair turn that feeds the errors back. The system prompt is a cached constant; the live context — specialists, the roster with person ids, the user's timezone (the one set through `PUT /workspace`, else `USER_TIMEZONE`; cadences stay UTC), and taken names — is rendered once per session into the first user turn, and while refining, the exact current draft is prepended to the latest user turn so the model edits it rather than re-deriving it. Roster names and roles are flattened to one line and capped at 80 characters before they enter that context, and the system prompt tells the model to treat the whole block as data, never instructions. Sessions live in memory (`/workflows/designer/*`, 2 h TTL, 50-session cap), run one model turn at a time (a second concurrent `/message` or `/draft` gets 409, and a failed turn is rolled back by identity), and never write: the review card saves through the same `POST /workflows/custom`, which re-validates, and *Edit details* opens the draft in the advanced editor (`/jobs/new?designer=<id>`) before saving.\n\n**Editing is a conversation too.** *Edit* on a saved workflow (`/jobs/new?edit=<name>`) opens the same designer through `POST /workflows/designer/edit`: the stored definition is the starting draft, so the user's first message (\"have Mark sign off and run it Fridays\") is applied to it like any refinement, and a note in the context block (a user turn, never the cached system block) tells the model it is changing a saved workflow. The draft always keeps the workflow's name — `_check_draft` puts it back and skips the taken-name check — and the route keeps its on/off state, so an edit can neither fork a copy nor switch on a tool workflow waiting for approval. The stored draft is handed to the model marked as data, not instructions. The review card lists *What changes* in plain words against the saved version (`lib/workflowChanges.ts`): every field is compared, with named sentences for the sign-off person and what it asks for — a sign-off moved off approve/reject is called out because the run then continues whatever the answer — the schedule, steps added/removed/reordered, inputs, tools and the tool-call budget, and a catch-all line for any other field. It names only the newly added tools that may change things. *Save changes* calls `POST /workflows/custom/{name}/save-edit`, which saves the session's own draft after re-validating it, only when it is the draft the card showed (the card sends what it displayed; a message that landed since is a 409), and only if the stored workflow has not changed since the conversation opened (409 otherwise), so an edit started before someone switched the workflow off cannot switch it back on. The step-by-step form stays as the advanced editor (`/jobs/new?edit=<name>&mode=advanced`).\n\n**Action steps (workflows that act).** An `action` step (`ActionStepSpec`: `goal`, `tools`, `max_tool_calls` 1–50, default 20) is run by the `workflow_actor` Council agent (`openexecutive/workflows/action_step.py`) as a bounded tool-use loop. Its `tools` list is an allowlist of exact tool names — MCP gateway tools (`server__tool`, e.g. `google_workspace__append_table_rows`) and a small set of built-ins (`oe__read_file`, `oe__message_person`, `oe__create_alert`, plus any installed extension's tools registered with `workflow=True`, as `oe__<name>`, run inside `extensions.workflow_step(name)`; a built-in wins a name clash, and an extension tool counts as reading only when it says so) — and **clicking Create is the user's approval** of that list: the review card shows every tool, flags the ones that may change things (anything whose name doesn't say it reads, and any tool with a URL/URI/endpoint/webhook parameter anywhere in its schema, or whose schema couldn't be read, since a URL can carry data out), and names them in a \"this workflow can use these without asking again\" notice. Because that card is the approval, a workflow with action steps saved from chat (`draft_workflow`/`save_workflow`, whose confirmation is a token the model holds itself) is stored **switched off** (`is_active=false`) and `save_workflow` returns `status: saved_pending_review` with a `/jobs/{name}` link. An inactive workflow can't run or schedule (`get_workflow` and the scheduler skip it); `/jobs/{name}` shows it on the same review card, where **Turn on workflow** (`POST /workflows/custom/{name}/activate`, which re-validates the tools) is the approval — the click sends the definition the card showed, and the server refuses (409) if the stored one has changed since, so chat overwriting it while the card is open can't get new tools switched on. Chat may revise a switched-off workflow but refuses to replace a switched-on one that has action steps (an inbound email steering the Executive could otherwise switch off an approved job and stage new tools under its name); those edits happen in the advanced editor. The Workflows catalog (`/jobs`) lists switched-off workflows in a compact *Waiting for your approval* strip, and saving edits in the advanced editor keeps one off. `tool_catalog.py` resolves names to schemas through the gateway's `search_tools` (extensible-mcp's Markdown output is parsed; resolving is also the per-session discovery its `call_tool` requires) and validates availability at save time (`POST`/`PUT /workflows/custom`, chat `draft_workflow`/`save_workflow`, designer drafts) — an unknown, misspelled or deny-listed tool is a 422. The gateway meta-tools (`search_tools`, `call_tool`, `load_mcp_server`) can never be step tools. `run()` resolves every action step's tools before any step runs, so a vanished tool stops the run before an earlier step acts; `resume()` checks only the steps still to run, after the gate and decision are validated. The last turn of an action step always switches tools off so the agent can report. At run time only the allowlisted tools are offered (sorted; constant cached system block, per-run goal/inputs/earlier results in the user turn), every `tool_use` is re-checked against the allowlist, MCP calls go through `MCPGateway.call_tool` so the config deny-list and the Gmail/Calendar/Drive recipient gates still apply, the call budget is enforced (then a final tools-off turn asks for the report; running out of turns fails the step and lists what was already done), tool errors (the gateway's `Error:` / `Error calling tool` / `Tool error:` prefixes, or a truthy `error` field) return to the model as `is_error` results, each call emits a `progress` event and an audit row (`workflow_tool_call`: tool and outcome; for tools that may change things also a short digest of target arguments — ids, recipients, URLs, paths — so a redirected write is visible; content arguments are never logged), and the step's output is the agent's report plus an \"Actions taken\" list. Tool output is framed as data, never instructions.\n\n**Scripts in action steps.** Besides the step's own tools, the agent is offered one more, `run_script` (`openexecutive/workflows/step_script.py`), for work that repeats over many items — every file in a folder, every row, every email — or chains calls with simple logic. It writes a short Python script once instead of spending a model turn per call; each of the step's tools is a function in the script (`drive__move_file(file_id=…)`, or `call_tool(name, arguments)` by exact name), and only the script's final value and printed output come back. The script runs in **Monty** (`pydantic-monty`), a sandboxed Python interpreter for model-written code, in a worker process spawned per script: no files, network, environment, subprocesses or third-party imports — the step's tools are the only things it can reach. **A script is a faster way to make the same calls, never a way around them:** every call it makes goes through the same per-call path as a direct `tool_use` (`action_step._StepCalls`) — the allowlist, a call budget (a script's calls have their own: 10× the step's `max_tool_calls`, capped at `WORKFLOW_SCRIPT_MAX_CALLS`, default 500, because they cost no model turn each — so a step can work through a folder of hundreds of files while its direct calls stay capped at 1–50), the first-write target check (a held write comes back to the script as `{\"status\": \"held\", …}`) and one `workflow_tool_call` audit row per call — and the script itself is audited as `run_script`, with how many calls it made and how long it took. The step's \"Actions taken\" list collapses repeats into one line with a count. A step whose direct calls are spent keeps its tools on while the script budget has room, so it can still script the rest (a direct call is refused as over budget). When a tool returns a list of five or more items and the round didn't use `run_script`, the step adds the same `FANOUT_HINT` as chat (once a step), pointing the per-item work at one script. The worker is stepped from the step's own task (each call pauses it and is answered there), so cancelling the run stops the script and its in-flight call together, and each call's progress shows as it happens. At most `SCRIPT_MAX_WORKERS` (default 2) scripts run at once across the server, chat and workflows together; another waits for a slot within its own wall clock, else returns \"the server was busy\". A worker exists only while its script runs (about 8 MB idle). Execution time (excluding time waiting on tools), memory and recursion depth are capped inside the worker, the script has a wall-clock limit, and its text is size-capped; printed output past its cap is dropped. A failing script returns its error to the agent as an `is_error` result, with the calls it already made listed first (ahead of any long result, so a cut never drops them) so a fixed re-run doesn't repeat writes; a call cut off by the time limit is listed as `may_have_run`, and gets a `cancelled (may have run)` audit row. A workflow definition still holds no code; a script lives on only if the agent saves it as a tool (below). Because a step can loop at run time, the workflow designer keeps work that repeats over items (each email, file, row or listed follow-up) in ONE action step whose goal spells out the items, rather than a step per item; `run_script` is never a step tool, and a definition that lists it is rejected (`validate_definition`) so the designer's repair turn removes it. `WORKFLOW_STEP_SCRIPTS=false` turns the tool off, and a step then only calls its tools one by one.\n\n**Python jobs (`run_python_job`, `openexecutive/workflows/python_job.py`).** Monty can't run libraries, so library work on files (split or merge PDFs with pypdf, spreadsheets with openpyxl and pandas, charts with matplotlib, images with Pillow, and documents made from scratch or from files: Word with python-docx, PowerPoint with python-pptx, laid-out PDFs with fpdf2) runs as a Python job: Pyodide (Python in WebAssembly) executed by **Deno** in a process of its own per job. Pyodide alone is not a sandbox — its Python can call into the JavaScript runtime, which under plain Node reaches the server's environment, files and network — so Deno is what isolates it: it is started with read access to the sandbox folder and the worker script only, with no network, environment, writes or processes, and an empty process environment. Files go in on stdin and results come back on stdout. A job gets only what the call names: Knowledge-library files, the files attached to the chat message being answered (`attachment_files`, the uploads as sent, bound for that turn only by `POST /chat/upload` in `workflows/turn_files.py`, so the model never retypes an attachment's text), text the caller passes, and `inputs` (a dict the code reads); result files are kept 7 days under the company folder and served to the principal at `GET /python-jobs/{job}/{file}`, which the Executive links in its reply. A deployment can instead send jobs to a separate runner (`PYTHON_JOB_RUNNER_URL`, with `PYTHON_JOB_RUNNER_KEY` as a bearer token): `run_job` POSTs the same job (code, inputs, files, caps, time and memory limits) and reads back the same result object, at most as large as a local job's output, keeping only its known fields, so kept results, links and metering are unchanged; the local sandbox is then not needed, and the runner is trusted to isolate jobs. A runner can turn a job away with `{\"run_locally\": true}` (and an optional `reason`) in a non-200 reply, for example when the deployment's allowance for it is used up: the job then runs in the local sandbox if this machine has one, and otherwise fails with the runner's reason. Any other non-200 reply stays a job error, so a busy or broken runner never moves every job onto the machine. A runner with more libraries lists them in `PYTHON_JOB_EXTRA_LIBRARIES`, which the job tool's description then names, so the Executive doesn't refuse a job that needs one. The tool sits in the `workflows` tool group, labelled for jobs with or without attached files. The library set is fixed at build time: the API image installs Pyodide and Deno from npm and the compiled libraries from Pyodide's CDN, each checked against the sha256 in Pyodide's lock file, and a build smoke runs a job. Pyodide can't infer the compiled packages the pure-Python libraries import (lxml, Pillow, fonttools), so the worker loads them when a job imports docx, pptx or fpdf. Pyodide, Deno and the pure-Python libraries are pinned by hash too (an npm lock installed with `npm ci`, pip `--require-hashes`). One job runs at a time per process (200–450 MB each), with a `PYTHON_JOB_TIMEOUT_S` limit and a memory cap (`PYTHON_JOB_MEMORY_MB`, default 1536, as the process's data limit, plus V8 heap and WebAssembly memory caps); the worker returns at most 20 result files and 25 MB, and the API stops the job as soon as its reply passes that. The job runs at a lower CPU priority and is first in line if the machine runs out of memory, so a heavy job slows or loses itself rather than the API; Deno's own caches go in a temporary folder removed with the job; and kept results are capped at 200 MB in all, oldest first. The tool is chat-only, offered only on the principal's own turns (`PRINCIPAL_ONLY_TOOLS`), withheld on private turns, unattended passes and under the Act as me lockdown, and not offered at all without the sandbox (`PYTHON_JOBS_ENABLED`, `PYTHON_SANDBOX_DIR`).\n\nA job that worked can be kept the same way as a script (below): `save_as` and `description` keep its code as a Custom tool of kind `python`, and `run_python_job(tool=<name>, inputs={...})` with its files runs it again, recording the run, so a job done before costs no code-writing tokens. Python tools run only on the principal's own chat turns: they are never listed for workflow steps and never turn on for workflows (`PUT /saved-tools/{name}` answers 409), and `run_script` refuses one (and `run_python_job` a script tool). Every job writes one `python_job` audit row (`ok`, `duration_ms`, `cpu_ms` and `peak_mb` read from the process's /proc entry just before it is stopped, files and bytes in and out, attachments, the Custom tool it ran or kept), which `GET /audit/usage` sums into `python_jobs` with the model usage of the turns that ran one.\n\n**Saved tools.** A script that works can be kept to run again by name (`openexecutive/workflows/saved_tools.py`); each tool has a `kind`, `script` (`run_script`) or `python` (`run_python_job`, above). `run_script` takes `save_as` and `description` with a new script: if the script succeeds it is saved, with the set of tools it actually called, and a failed script is never saved. Later, `run_script(tool=<name>, inputs={...})` runs the saved script instead of new code, with `inputs` available to it as a dict. Only the principal's own turns save: a chat turn where the principal is speaking on a verified, interactive surface (the same test as `load_mcp_server`), never an inbound email, a teammate, an unattended run or a workflow step — a step is offered `tool=` but not `save_as`. A saved tool runs with the authority of whoever runs it, so its author must be trusted at least as much as anyone who may run it. For the same reason only a workflow step (its tools owner-approved) or the principal's own turn may run one: anyone else's chat turn is refused `tool=` and not offered `list_saved_tools`, so a stranger can neither list the principal's automations nor run one with inputs they choose. Descriptions are kept to one line of printable text (they are shown to models), and every save writes a `saved_tool_changed` audit row (`actor: executive`) beside the owner's own changes. Saving needs no approval beyond that, because a saved tool can do no more than the context running it: its calls go through the same per-call path as any script (in a step: the allowlist, budget, target check and audit), and a step runs one only when the step already allows every tool it used (otherwise the result names the `missing_tools`) and only at the version the owner turned on for workflows (`workflow_version`, Settings → Advanced → Custom tools → Use in workflows). A tool kept on a turn that read outside content could otherwise carry injected code into an unattended run, so keeping stays automatic and works in chat at once, but workflows wait for the owner; a newer save doesn't change the version workflows run, and pruning never drops it. Each step's `run_script` description lists the saved tools that step may run; chat asks `list_saved_tools`. Every save of changed content is a new version (the newest 20 are kept, plus the one that ran until then, so a rolled-back version the owner trusts survives later saves), every run is recorded (`saved_tool_runs`, the newest 200 per tool), and the owner can turn a tool off or switch it back to an earlier version on Settings → Advanced → Saved tools (`/saved-tools` routes, the owner's alone). A turned-off tool never runs, and a new version saved by the model does not turn it back on. `SAVED_TOOLS_ENABLED=false` stops saving and running saved tools everywhere.\n\n**Targets are chosen at run time — and a new one is confirmed once.** Approving a workflow approves its *tools*; which sheet, doc, recipient or URL each call hits is chosen by the model at run time, by design (a tab per month, a reply to whoever sent the invoice, a doc per client). What bounds that is the allowlist, the gateway's recipient gates, the audit digest, and **first-write confirmation**: a `TargetPolicy` (one per run) checks every call to a tool that may change things. `resource_targets` walks its arguments recursively for resource keys (snake- or camel-case ids, `to`/`cc`/`bcc`, recipients, addresses, attendees, members, users, owners, parents, URLs/links/hrefs, paths, channels, spaces, rooms, phones, hosts, buckets, tables, spreadsheet/document/folder/calendar/file); a matching key marks everything beneath it, even a `name`. Outside a resource, only a new item's own `name`/`title`/`subject`, message/thread/draft/label ids, `range`/`sheet` and workspace-mcp's acting `user_google_email` are skipped — and whatever the key, a bare value shaped like an email address, a URL or an international phone number is a target, except inside what the call writes (`rows`, `values`, `body`, `text` …). Key names are a heuristic, so this is a best-effort guard layered on the allowlist, the gateway gates and the audit. Float ids are compared as integers. Arguments too deep, naming too many targets, or holding an over-long value **fail closed** (the call is refused). A target is trusted only when it was approved for this workflow before (`workflow_approved_targets`, by value) or is an id a write in this run created — a top-level id/link field (`id`, `spreadsheetId`, `webViewLink` …) of the **structured JSON object** result of a tool whose name says it creates (create / insert / upload …) and that takes no URL — a tool whose schema couldn't be read is assumed to (free text, nested records and readers' or updaters' results are never read, so a fetched page, an echoed title, a shared page's links or a stranger in `ccRecipients` can't plant one); those survive a pause in the resume payload (`run_created`). Values written in the workflow's own text are *not* trusted, since anyone who can edit the workflow could change them without review: they are asked once, then remembered. Approvals are by value, for any of the workflow's tools, and are **cleared when the workflow's tool set changes** (a newly added tool must earn them again). Any other target makes the call **held**: it is not run and costs no budget, the model is told it is waiting for approval and carries on, and it is audited `held for approval` (at most 10 held per step, 16 KB each; an identical repeat is held once). Whether a call is checked at all follows the read-only label, which now never marks a tool whose name carries a write verb anywhere (`find_and_replace_doc`). After the step finishes, the run pauses with a `WaitForHumanEvent` to the workflow's **owner** (`owner_person_id`, the person who created it on the Workflows page or in chat; falling back to the principal if unknown or archived), `on_timeout=auto_proceed`, 48 h, and a `WorkflowResumeState` of `kind=\"held_writes\"` carrying the exact held calls. On resume (`_resume_held_writes`, fingerprint-checked like a gate, with the remaining steps' tools checked first), only `approve` runs them — each still has to be in the live step's allowlist and resolve; its targets are remembered first — and anything else (decline, timeout, unreadable) skips them; either way a *Held for approval* section is added to the step's output and the run continues at the next step. With no one to ask, held writes are skipped and noted; a step that fails or crashes after holding, or a resume that stops early (definition changed, a later tool missing), audits its held writes as dropped and says they did not run. The question quotes each target JSON-escaped (a value can't add its own lines) and always shows a URL's full scheme and host, saying how much of the rest is hidden. The owner answers by chat reply or with **Approve / Decline** on the run page (`POST /workflows/runs/{id}/decision`, which the principal may also use); remembered targets are listed and removable on the workflow page.\n\n`oe__read_file` extracts text (PDF, Word, Excel, CSV, Markdown, text) only from files under `WORKFLOW_FILE_DIRS` (default: workspace-mcp's attachment folder), resolving symlinks and `..` before the check (`tool_catalog.resolve_readable_file`, shared with the Executive's `read_document` tool). A scanned PDF is converted by `knowledge.pdf_reader` instead of failing as \"may be a scanned image\"; one that still cannot be read returns the reason. Action steps are allowed in scheduled workflows. Because they have external side effects, a resumed run heartbeats its claim (`touch_resume_claim`, at most once a minute as events flow — each tool call emits one; a busy database is retried on the next heartbeat, never treated as a lost claim; the sweep's requeue re-checks the claim's age in the same UPDATE, so a heartbeat landing between the sweep's read and its write wins), so the stale-claim sweep never requeues and replays a slow but live run, and a worker that finds its claim superseded stops at its next event. A worker that actually crashes mid-resume is still requeued; its action steps then run again, so goals should say how to avoid duplicates (the actor reads current state before writing). `GET /workflows/tools/search?q=` and `GET /workflows/tools/describe?names=` back the advanced editor's tool picker and the review card's labels.\n\nAn 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. A gate followed by further steps pauses at `awaiting_human` and then resumes once answered, so gates no longer have to sit immediately before synthesis. They remain forbidden in cadence-enabled definitions: a scheduled fire has no interactive human to ask.\n\nBuilt-ins the system runs on its own (`morning_brief`, `end_of_day_digest`, `executive_reflection`, `executive_research`) set `background = True`, surfaced as `WorkflowMeta.background`; the `/jobs` ready-made list files them under a **System** chip instead of the default view. They stay runnable by hand.\n\n**Quick workflows** (`workflows/quick.py`) are one per playbook in effect that no built-in or custom workflow follows (switched-off custom ones count). They are derived whenever the catalog is read, never stored: `list_workflows()` returns built-ins, then Quick ones, then active custom ones, and `get_workflow` resolves a `quick_<playbook>` name after the registry (custom workflows may not take the `quick_` prefix). Each has one required field, `request`, and two steps: **Load context** (company profile plus RAG for the playbook category's specialist) and **Draft** (that specialist writes one Markdown document following the playbook). `WorkflowMeta.quick` is true for them. The 8 built-in playbooks no built-in follows are Quick workflows: board update memo, 1:1 agenda, layoff comms plan, positioning statement, post-mortem, customer interview plan, feature prioritization and market sizing. A company's own playbook shows up as one, hiding a built-in drops it, and a custom workflow that starts following one replaces it. If custom workflows can't be read, none are offered, since their followers are unknown.\n\n**Workflows vs. playbooks.** `/jobs` has two tabs: **Build** (`?tab=catalog`, the default) and **Runs** (`/skills` redirects to `/jobs`). A playbook is a skill (`knowledge/skills_repo.py`): *how* the Executive does a piece of work, with no inputs, schedule or side effects. A workflow is the runnable job. Workflows **follow** playbooks: a step that follows one gets its body appended to the step prompt via `workflows/playbooks.py` (`load_playbook` + `playbook_clause`). Six built-ins do — `board_prep` (`board-prep-deck`), `quarterly_plan` (`quarterly-okr-set`, `quarterly-forecast`), `mbr` (`monthly-business-review`, in the financial, KPI and function steps), `competitive_teardown` (`competitive-teardown`, in the four analysis steps), `fundraising_prep` (`fundraise-narrative`, narrative step) and `exec_search_brief` (`role-scorecard`, profile step). Each declares them in `Workflow.playbooks`; a unit test holds that declaration equal to the `load_playbook(\"…\")` calls in the module, and `WorkflowMeta.playbooks` exposes it. A custom workflow's `specialist` step may name a `playbook` (validated to exist at save; appended after `{field}` rendering, so braces in a playbook are never treated as placeholders). The lookup resolves the playbook in effect, so a company's customized copy changes the workflow's output, and a hidden, missing or malformed one falls back to the step's own prompt plus RAG — a workflow never fails over a playbook (`load_playbook` catches everything; a custom step whose playbook is unavailable emits a `progress` event saying so). Because an approved scheduled workflow reads its playbook at each run, chat never creates or changes a playbook: it saves repeatable work as a workflow (`draft_workflow`, confirmed by the user), and only a person can change what a workflow follows: a workflow's page shows each playbook it follows as **How it's done** (`components/jobs/HowItsDone.tsx`), with **Edit** (`PUT /skills/{name}`; on a built-in that saves the company's customized copy) and, for a customized copy, **Reset to original** (`DELETE`, which reverts). The chat summary of a drafted workflow names each step's playbook. `playbook_users()` maps each playbook to the workflows that follow it — built-ins, every custom workflow (switched-off ones included: turning one on approves its definition) and the Quick ones; the skills API reports it as `used_by`, and the Executive's `search_skills` hits carry it as `workflows`.\n\nCompleted artifacts are discoverable in the unified artifacts section (`/artifacts`, labelled **Documents** in the UI) alongside their run-detail page at `/jobs/runs/{run_id}`. A run someone starts by hand (`POST /workflows/{name}/runs`, `run_workflow`, research in chat) stores them as `workflow_runs.owner_person_id` and its history and output are theirs alone (plus the person a gate waits on); scheduled and system runs keep no owner and stay the team's. Workflow output stays Markdown — the scheduler DMs it and reflection rereads it as text — and gains other formats only on the way out: any run can be downloaded as Word (`/artifacts/run:<id>/download?as=docx`), and the Executive can repackage one with `get_artifact` → `draft_artifact(format=…, supersedes=\"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.\n\nWith Take the lead as the Executive on (`orchestrator.take_the_lead`), reflection and research build their toolkit through `unattended_toolkit(..., source=...)`. That keeps solo's booking and `run_workflow` tools and an unrestricted `message_person` (teammates as well as the principal). Every acting tool goes through the gate, and a held action waits on Today as a `take_the_lead_action` decision. Reflection also gets the MCP gateway's `search_tools` and `call_tool` (`_with_lead_tools`; `call_tool` behind the gate, `load_mcp_server` left out), so it can find and use whatever the deployment has connected, such as building a sheet to track something. A note in the user turn (never the cached system prompt) tells it to act rather than only report, and it gets more room: 10 iterations, 4000 tokens, and tool results up to 4000 characters. The grounding check still refuses outward text naming people or figures the pass didn't see. New mail and chat also wake the reflection early (scheduler section). In training (`take_the_lead.training`) every acting call that isn't allowed waits too, as a training card for the principal, and both passes append `take_the_lead.learned_note()` to their user turn: that it's in training, and the principal's own edits on earlier cards as examples of how they want those done (never in the cached system blocks).",
+ "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 25 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`, `exec_search_brief` — people and org artifacts (the last is an advisory hiring brief / scorecard from the CHRO, with input from the hired function's specialist — `sales` for a sales role — kept when the recruiting pipeline was removed).\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` (`department_check_in.persist_goal_verdicts`, shared with `weekly_review`).\n- `weekly_review` — the principal's weekly look back and ahead (see *Weekly review* below).\n\n**Standing facts in unattended output.** `end_of_day_digest`, the weekly review's top-three call and the morning reflection append the standing facts (`memory.facts.with_standing_facts`; a teammate's marked `(per <name>)`) to their user turn, and the morning brief gets them through `render_briefing_context`. A workflow step that consults a specialist gets them through `route_to_specialist`. A correction made in chat therefore holds in every recurring brief and run. The morning brief also reads `facts.render_teammate_changes(since)` off the event loop and passes it to both `render_briefing_context` (a TEAMMATE CORRECTIONS SINCE LAST BRIEF block) and `build_brief_fingerprint`, so the principal hears of each correction a teammate made in the window, and that alone un-suppresses an otherwise unchanged brief. Proposals waiting for approval are listed only in a brief the principal reads privately (`include_proposed=_private_ok()`), and then mark the run private to them. The principal's own Always in the loop notes (`memory.history_brief`, only with their switch on) come in by a stricter rule, only on the scheduler's delivery (`PRINCIPAL_DELIVERY`), never a run from chat, whose tool result reaches the turn's shared audit row and peer memory: the morning brief's FROM YOUR NOTES — DUE SOON block and the end-of-day digest's FROM YOUR NOTES — TODAY block (what they committed to since the last digest, then what is due tomorrow). Either marks the run `private_to_principal` and moves its fingerprint; the digest, which had no private reads before, now emits that flag too. In the install's first week (`briefing.first_week`, seven days from the principal's People row) the morning brief also passes a GETTING STARTED block to `render_briefing_context(getting_started=)` and its keys to `build_brief_fingerprint`: onboarding goals, departments with no leader and, on the scheduler's delivery with Act as me and Draft replies to my inbox on, who wrote to the owner's own mailbox (sender and subject only) and, with Read my calendar on, today's meetings on their own calendar (time and title), either of which marks the run `private_to_principal`. The brief opens with **Getting started** and is never the quiet line while the block has anything in it (see Today).\n\n### Change-aware principal briefs\n\n`morning_brief` and `end_of_day_digest` are the two recurring briefs the scheduler sends 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). The morning brief also reads the principal's **live world** since that window opened (`briefing.live_signals.gather_live_signals`): mail and chat the Executive handled (INBOUND, grouped by sender and subject, each email from the roster marked replied or not, earlier days dated), under a NOW line and THE PRINCIPAL line that names its reader so the brief writes \"you\" (the end-of-day digest gets the same line, and the team reflection a YOUR PRINCIPAL line under its roster; the reflection flags only what today's input still shows), what got stuck (STUCK: a reply the outbound gate held, a non-roster sender who got no reply, a Google Chat message left unanswered, chat drafts still in the principal's Gmail, after `live_signals.settle_principal_drafts` has marked the ones they since sent or deleted there), the principal's own chats, and — in both modes now, unless the solo top three already listed it — today's calendar, read fresh (`live_signals.refresh_calendar(max_age=0)`). The 07:30 reflection's **Flagged for the brief** bullets are carried across (`brief_state.reflection_flags_since`, the latest reflection run finished inside the window) instead of surviving only as an activity line with the run's title, and the rhythm runs themselves (`today.RHYTHM_WORKFLOWS`) are dropped from the brief's activity: their dated titles were noise and moved the fingerprint every day. At-risk departments name their slipping goals and each proposal carries its age. The period is the principal's local date. Section order: top call → **today** (the calendar's shape and anything stuck) → what changed (inbound first, naming who wrote) → handled overnight → needs you (new only) → waiting on → at risk (the slipping goal, or the department left out — never \"no detail yet\"). Quoted mail, chat, invite and reflection text is marked as data, never instructions. **Privacy:** the brief reads what is private to the principal — their contacts' alerts and mail, their drafts, their chats and their calendar — only on a run for them: the scheduler's (`morning_brief.PRINCIPAL_DELIVERY`) or the principal's own verified chat turn in a conversation only they can read (`delegation.settings.private_conversation`: the web chat, a Slack or Discord DM, a private Telegram chat — never a shared channel, where the reply is posted for everyone). A run anyone else starts (a teammate from chat in team mode, `POST /workflows/…/runs`) reads what everyone may see, as before. A run that did read a private row says so on its `result` event (`private_to_principal`: its live read differs from the shared one in any key or count), and the scheduler, `run_workflow` and `POST /workflows/{name}/runs` all then keep `persistence.PRIVATE_RUN_ARTIFACT` in the run history instead of the text. Text another pass wrote (the reflection's flags) renders as quoted ` > ` lines and every goal and headline field is one-lined, so none can start a line that reads as a block header. The fingerprint carries the live signals' time-free keys (who wrote about what, what is stuck, the calendar's shape) and the reflection flags when there are any, so \"nothing new\" means the principal's world was quiet too; the context summary is logged at INFO (`morning_brief: context since=… inbound=… stuck=… suppressed=…`). In **solo mode** (one person using Open Executive for themselves) both briefs speak to the principal, whatever their role: the morning brief runs top call → top three today → what changed (inbound and stuck first) → handled overnight → needs you → due this week (the principal's open loops overdue or due within 7 days, from `open_loops.principal_due_soon`) → goals at risk (named by area), the end-of-day digest what I did → open decisions → goals at risk tomorrow → sleep on this, over a context with goals at risk by area and no people-waiting or department block; the fingerprint carries the mode and ignores who is awaiting, and carries the due items as `(loop_id, state)` pairs when there are any. **Top three today** is picked in code, not by the model (`briefing.top_three`: overdue then due-today commitments, off-track then at-risk goals, commitments due later this week, then active projects, stalest first). The solo Briefing's *Top three today* card shows the same pick from the same code (`GET /today/top-three`, see Today). When the MCP gateway runs the Google Workspace server, one `google_workspace__get_events` call (4 s timeout) lists today's events on the principal's calendar — their address as the calendar id, read with the Executive's account (`primary` when the Executive is signed in as them) — and on a business day (`calendar_tools.is_business_day`, the rule the booking tools apply; at the weekend the day's events are still listed but no slot is suggested) each item gets its own free block inside `CALENDAR_BUSINESS_HOURS_START`–`_END`, rendered with a TODAY'S CALENDAR block — only a date-only event is all day, a zero-length one blocks nothing, and one whose times can't be read is left out; no gateway, no principal address, an error, a timeout or a reply it cannot read all mean no calendar and no slots, never a failed brief; the log records only the reply's length or the error's type, never calendar text. The fingerprint carries the three items' keys (no dates, no slot times) and only a coarse hash of the day (busy blocks rounded to 15 minutes, no titles, no dates), so an unchanged day still suppresses. A day whose calendar read fails after one that worked (or the reverse) changes the fingerprint once, so that brief is written in full. 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**Brief delivery.** `scheduler.runner._deliver_to_principal` maps the principal's `preferred_channel` (`slack` / `discord` / `telegram` / `email`) to its delivery channel and tries it first, then the other chat channels the principal has an id for, in the order Slack → Discord → Telegram. Email goes through the active MCP gateway (`google_workspace__send_gmail_message` as the Executive's own address, to the principal, subject `<title> — <date>`) and is used only for an explicit `email` preference, or for `any` when no chat channel resolves — an owner linked by email at setup has `any`, so one who also has Slack does not start getting two emails a day. When nothing can deliver (a web-only principal, or email with no gateway), the brief is still generated and stored as a run with its artifact, as before — a web-only principal reads it on the Artifacts page — it is just not delivered (audited), so the window does not advance, and the next occurrence is chained. The same delivery path carries the client-rotation digest and the weekly review.\n\n**Grounding.** Nothing an unattended pass writes is read by anyone before it goes, so `openexecutive.briefing.grounding` checks it deterministically — no model judges the model. A name (a run of two or more capitalised words once section headers, weekdays, imperative openers and org nouns are trimmed, or one capitalised word in a person slot like \"ask Marcus\" or \"Marcus wrote\") is grounded only when a single line of the pass's inputs holds all of it, or it belongs to a roster person some input mentions — being on the roster alone is not enough. A figure (money, a percentage, a k/M/B number, any bare number of 11 or more; never a date, time, year, duration, id, list marker, `Q3` or small count) is grounded when an input number matches it within the precision it is written with (`$1.2M` matches `$1,234,567`; `47 units` does not match 48). The inputs are the rendered context split into lines labelled by section (a header also carries its bullet count), the company profile and the department titles. `morning_brief` renders its context itself and hands it to the synthesizer as `rendered_context`, so the check reads exactly what the model read; after the quiet fallback, `ground_brief` runs on both briefs. When something is ungrounded it makes one repair call to the fast model (same system prompt, the list of items, \"remove or correct using only the context\"), re-checks, then drops each line still ungrounded and any header left empty, and appends \"_I left out N lines that named people or figures I couldn't match to your data. They're under Left out of your brief on Home._\" (everything ungrounded → one held-back line). Every held line goes in the `grounding` audit row's untruncated `full` payload (up to 30, 400 chars each; `details` keeps a five-line preview), and `grounding.recent_held_back` reads the last day's back for `GET /today`'s `held_back`, which Home lists under **Left out of your brief** for the principal alone — after the narrative inputs are taken, so the held lines never reach a prompt. Then each grounded figure gets a server-chosen ` [n]` — the matching input line with the most words in common with the figure's clause — and a `**Sources**` list closes the brief (`- [n] <section> — <snippet>`, at most 9, snippets quote inbound mail, so links are masked (\"(link removed)\"), Markdown, angle brackets and @-mentions stripped, and they are cut to 90 chars; never `[n]:` at a line start, which Markdown reads as a link definition). Text with nothing to change comes back byte-identical, the fingerprint hashes the inputs so suppression is unaffected, and the grounded text is what is delivered, stored and recorded as delivered. Both brief prompts and the digest prompts say the rule up front. `executive_reflection` wraps its handlers in a `GroundingScope`: `create_alert`, `message_person`, `send_department_message`, `send_company_broadcast` and `schedule_followup` refuse text with an ungrounded name or figure, returning a JSON error that names the items so the model can look the person up or leave the figure out (every tool result joins the inputs, so a `lookup_person` answer grounds the DM after it; the recipient's own name always counts). Its **Flagged for the brief** bullets are filtered the same way before the tool log is appended — the next brief quotes them, where they would ground themselves — and `brief_state.reflection_flags_since` now stops at the tool log's `---`. The reflection's `grounding` rows are private when a private-to-principal alert reached its context, and the digest's always are (its HANDLED block can quote one). Everything fails open. `GROUNDING_CHECKS=enforce` (default) acts, `report` only writes the `grounding` audit rows, `off` skips it; `GROUNDING_CITATIONS=false` drops the markers. Not yet grounded: the /today header (its cards sit beside it), `weekly_review`, the research synthesis, dates and meetings, and a real person named in the wrong role.\n\n### Weekly review (solo)\n\n`weekly_review` (background, inputs all defaulted) closes out the principal's week in six steps. **Goals**: every area with goals is graded by its own specialist, concurrently, with the department check-in's verdict contract (`_parse_verdicts`) and write-back (`persist_goal_verdicts` → `record_goal_review`, one `goal_status_review` audit row per area with actor `weekly_review`); an area with no goals is skipped, one without a specialist is listed ungraded, and one whose specialist fails is shown as last recorded. **Commitments**: `open_loops.principal_due_soon` — overdue or due within 7 days. **Projects**: active initiatives with no update for 7+ days. **Decisions**: the week's (`episodic.decisions_since`). **Revisit**: up to three decisions older than 30 days with an empty outcome (`episodic.decisions_awaiting_outcome`, newest first), listed as `[decision N]` under *How did these turn out?* — the principal's answer is recorded with `record_decision_outcome` (see Agents). **Assemble**: every section always renders (a one-line note when empty), ending with *Next week's top 3* from one fast-model call that follows the `weekly-review` playbook (a constant system prompt; the playbook rides in the user turn), trimmed to at most three list items — or, when that call fails or returns nothing, the same ranked pick the morning brief uses. In solo mode the scheduler fires it weekly (`principal_weekly_review`, see Scheduler) and delivers it through `_deliver_to_principal` like the briefs, recording the delivery outcome. The solo Briefing also shows the latest completed run to the principal (`GET /today/weekly-review`, see Today): `weekly_review.summarize_review` reads the artifact's title line (`TITLE_PREFIX`) and its last `TOP_THREE_HEADING` section back as plain text, so a principal no channel reaches still sees next week's top three. Wording is role-neutral; run by hand in team mode it says *department* instead of *area*.\n\n**Principal-only workflows.** A workflow can name the workspace modes in which only the principal may start it (`Workflow.principal_only_modes`): `weekly_review` in both modes (built from the principal's decision log, commitments and goals, and it re-grades the goals) and `morning_brief` in solo (built from the principal's commitments and calendar). Team `morning_brief` and every other workflow can be started by anyone as before. This decides who may start or trigger a run, not who may read one: stored runs, the scheduled briefs and weekly reviews included, are read under the existing `/workflows/runs` rules — which is why a morning brief that drew on the principal's private rows is stored as `PRIVATE_RUN_ARTIFACT`, not as its text.\n\n- **From chat**, `run_workflow` checks at dispatch, before any run row is created, that the turn is the principal on a verified surface — `create_goal`'s rule — and otherwise refuses with a plain error that does not spell out the rule.\n- **Over HTTP**, the Jobs page's `POST /workflows/{name}/runs` and `POST /evals/runs` (a workflow scenario runs the workflow on live data) call `refuse_principal_only_run`: only a caller signed in as the principal, or a request with no caller email (the CLI or local login), may start the run. Unlike the workspace settings, an install with no principal on the roster lets no signed-in caller in, as in chat. Anyone else gets a 403 (\"Only the principal can run this workflow.\") before any run row exists. The mode is the stored one, or an eval scenario's own `workspace_mode`. The eval route runs exactly the scenario list it checked.\n\nEvery refusal is audited `refused=true` with the workflow, the mode and the caller. The checks fail closed: a mode that cannot be read counts as principal-only, and a check that cannot read the roster refuses.\n\n**Knowledge in the reflection.** A chat turn looks the knowledge base up before the Executive answers; the reflection reads the org's state instead, so nothing looked it up for it. It now carries its own `search_knowledge` tool (`orchestrator.knowledge_tools`, not in the shared `_ALL_SKILL_TOOLS`), which runs the same `knowledge.retriever.retrieve` as chat — the review gate, the synced Drive / OneDrive / Confluence / Notion collections and the published-artifact rule (the pass has no viewer, so no one's private document comes back). The prompt (`_KNOWLEDGE_RULE`, both modes) asks it to search before acting on or flagging something that turns on a customer's or supplier's terms, a price, a policy, a plan or a past decision. Its passages come back up to 4,000 characters (`execute_tool_calls(wide_results=...)`) while other tools stay at their short preview, its result counts as grounding input like any tool result, and the run's tool log keeps each line to 160 characters. Read-only, so Take the lead never gates it. The loop has 5 iterations (was 4) to leave room for a search before acting.\n\nNeither the nightly reflection nor the research synthesis can call `ack_alert`: both run unattended with open alerts rendered into their context, and those headlines are minted from inbound mail and chat, so an injected \"the principal already dismissed 13\" would be acted on with nobody watching. Closing an alert is the alert review's job, with evidence.\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. It also renders an **OPEN LOOPS** block (up to 10, soonest due first, overdue flagged) from Attunement so the standup can connect a slipped promise to the rest of the org state; the nudge engine already chases overdue loops, so the prompt tells it not to DM about a loop merely for being overdue. A **WHAT LANDS** block (from the Attunement outcome ledger) shows, per person, how often each kind of proactive DM got answered over 30 days; the prompt steers DMs toward kinds that land and away from kinds a person reliably ignores. Reflection and research tag their tool execution as proactive (`tag_proactive`) so their DMs are counted. Resolving a wait-for-human approval (`resumer.apply_resolution`) marks the nudges that chased it `acted`. `close_open_loop` is withheld from reflection for the same reason as `ack_alert`: loop text is quoted from what people wrote. `unattended_toolkit` also drops `schedule_tools.UNATTENDED_WITHHELD_TOOLS` (today `create_goal`) from both passes in both modes: a goal is the principal's own decision, and these passes see only inbound text. A turn private to the principal (mail from one of their contacts, or mail they forwarded) cannot start a workflow either: `run_workflow` and `run_executive_research` are in `schedule_tools.PRIVATE_TURN_WITHHELD_TOOLS`, which the chat loop neither offers nor runs on such a turn, since a workflow's steps can reach anyone.\n\nIn **solo mode** the reflection is framed for the principal, whatever their role: they are the only person who uses Open Executive and the only one it takes direction from, it prefers `create_alert` and `schedule_followup` to the principal, and it never messages anyone else from an unattended pass — the people in the principal's world are contacts, so anything they should hear is flagged for the principal to raise. The team roster is replaced by one YOUR PRINCIPAL line (person_id and follow-up channels), its follow-up guard is seeded from the principal only, and department risk renders as areas with goals at risk. The research synthesis follows the same rule — its routing menu and roster name only the principal. In both, `send_department_message`, `send_company_broadcast` and `set_department_head` are withheld, and so are `create_calendar_event`, `create_instant_meeting` and `run_workflow` — a booking reaches its attendees and a workflow can do anything its steps do, so the principal books and starts workflows from chat — and `message_person` refuses anyone but the principal. These passes run unattended with inbound text in their context, so the rules are enforced in code, not only in the prompt.\n\nIn either mode, both passes now dispatch only the tools they offer: the handler map is built from the offered list, so a name the model emits without being offered it is skipped as an unknown tool. They used to look names up in the full handler registry, so tools they deliberately withhold — the raw DM tools (`send_slack_dm` has no roster check), `ack_alert`, `close_open_loop`, and in research the watchlist writes and `run_workflow` — still ran when the model emitted them. Both read the mode before binding their own session (so a caller's override, such as an eval's, counts) and pin it on that session, so their tool handlers use the same mode. They carry the principal's role across the same way (`effective_principal_role` of the caller's session, pinned as `turn_principal_role`), so a specialist or workflow started from either pass sees the role of the turn that started it. Team runs are unchanged.\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: the runner calls `save_checkpoint`, the `workflow_runs` row moves to `status='awaiting_human'`, and the serialized `WaitForHumanEvent` is stored in `state_json`. (Department authority is a *separate* mechanism — `propose_only` departments file a briefing alert via `departments.authority.propose_via_alert` and mark the scheduled action done; they do not route through this gate.)\n\n**Delivery.** Both checkpoint sites — the SSE route and the `run_workflow` chat tool — call `workflows.gate_delivery.deliver_gate_question` immediately *before* checkpointing, so `state_json` carries the routing fields a reply is matched against. Two modes. When the approver is the person already in the conversation (the chat session's `origin_channel` is set — to anything but `email`, whose answer is no chat reply and would never be sent — and its `caller_person_id` is the gate's `person_id`), nothing is sent — the question rides in the Executive's own reply — and the gate records `origin_session_id` plus the session's channel. The resolver compares base ids (`memory.conversation_ids.base_session_id`), so a question asked in one conversation of a Telegram chat or a DM is still answered by a reply after a quiet gap or /new has started the next. Otherwise the question is delivered through `schedule_tools.handle_message_person`, which picks the person's preferred channel, falls through on a failed send, and falls back to a briefing alert; the gate then records the channel, address and provider message id that send returned, plus the id of the DM session it landed in — that send is always 1:1, so the answer belongs in that conversation and nowhere else. Without it the gate matched on person and channel alone, so an unrelated @mention in a public channel resolved it and had the acknowledgement, run title included, posted where everyone could read it. The question is sent with `notifications.approval_send`, so the person's quiet hours and *In my briefs* never hold it, whatever their urgent setting: only a reply to it resolves the gate. Delivery is not guaranteed: the outbound guard can suppress it (duplicate, rate cap, quiet hours) and an unreachable person gets the alert fallback. Both cases leave the routing fields empty and report `delivery` as `suppressed` / `alerted` rather than claiming someone was asked, and the chat tool's presentation hint changes accordingly.\n\n**Matching a reply.** Each inbound adapter passes the message to `inbound_resolver.resolve_inbound_message` with its `session_id`. Matching is three-tier: an explicit `in_reply_to` against a stored `outbound_message_id`; otherwise a single open run on that channel; otherwise one utility-fast disambiguation call gated at 0.85 confidence. An unmatched explicit reference rules out only the candidates that carry a stored outbound id — the ones it could have matched — and the rest continue; rejecting outright meant an adapter that passes a thread id on every message (Slack's `thread_ts`) short-circuited the later tiers forever, and a global test let one delivered gate's id block an unrelated self-approval gate. Channel names are normalized (`slack_dm` ≡ `slack`), the delivered address is compared when both sides know it, a row whose `state_json` will not parse is refused (a corrupt row otherwise presents as a legacy one), and an empty stored channel is treated as a wildcard only for rows checkpointed before gate delivery existed. Two guards keep an open gate from swallowing unrelated traffic: a gate carrying an `origin_session_id` matches replies only from the conversations the adapter names (a Slack or Discord thread offers its parent channel session too, mirroring the history double-write, since a gate raised on a mention recorded that session while the answer arrives under the thread's — on Slack only when that person rooted the thread, or the alias would reach into a colleague's), and the parser can return `unrelated`, which declines to resolve and lets the message reach the normal chat path. The parser is handed the gate's own question, so a bare \"yes\" is judged against something. Its fallback is flagged by a key the model cannot emit rather than by a magic note string it could, and a fallback declines to resolve on *every* reply shape — recording the empty string a `free_text` fallback fabricates would close a sign-off on a parser outage. Every shape can answer `unrelated`, not just `approve_reject`: without it an open `free_text` gate turned the person's next message into its answer verbatim, and a `numeric` one swallowed any message containing a number. The parser has one caller outside workflows: its `roster_identity` shape — `{decision: approve|link|decline|unrelated, name, kind: team|contact|null}`, with `name` only as the person wrote it (never inferred) and a fallback of `unrelated` — reads the principal's emailed answer to a roster request (who a new sender is; see Org). It is not a gate reply shape, and a fallback or `unrelated` leaves the request waiting. `resumer.apply_resolution` then 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 outcome surfaces on the Today dashboard.\n\n**Resuming past the gate.** A paused run continues on its own. Re-entering it was long assumed to mean serializing a Python generator frame; it does not. The only state alive across a dynamic workflow's steps is its inputs (already persisted), a company-profile block that is recomputed, the completed steps' output strings, and the loop cursor — so the engine hands the checkpoint a small JSON `WorkflowResumeState` (workflow name, the gate's id and index, the next index, the outputs so far), stored in `workflow_runs.resume_state_json`, and `DynamicWorkflow.resume` replays its step loop from the recorded index. `run()` and `resume()` share that one loop, which is why a second gate needs no special handling — it is simply another pause raised from the same place. The payload rides on a `WaitForHumanEvent` field declared `exclude=True`, so it can never leak into `state_json`, whose exact key set the resolver branches on. A gate with no payload is *pause-only*: the decision is recorded and the run stops, which is what every caller got before resume existed.\n\n`resumer._process_resumable` claims a resolved run with one guarded UPDATE — `resolved` → `running`, stamping `resumed_at` and minting a claim token — and drives it to a terminal row. It runs two ways: immediately, via a task `apply_resolution` kicks off so a Slack approval starts moving in seconds, and every 60s from the poll loop as the durable backstop. Both share the claim, so a run executes exactly once even with two resumers against one database. The kicked task binds no chat session (`set_session(None)`), exactly like the poll loop: it is created inside the inbound handler that recorded the answer and would otherwise inherit that person's live turn — so a run resumed because the principal replied on Slack does not act with the principal's identity (it cannot, for example, reach the principal's contacts). It drops the handler's audit scope too (`audit.context.unscoped_audit_rows`): inherited, the principal's scope would make private every row of the run that names a contact, and whoever started the run would see those rows vanish after the approval. The poll runs the executor *after* the timeout loop, which is what finally makes `on_timeout='auto_proceed'` do what its name says: the timeout resolves the run and the same tick executes it. While the Executive is paused (`scheduler.pause`) the resumer does nothing — no startup sweep, no timeouts, no resumes — and `apply_resolution` still records the decision but skips the immediate kick; the first unpaused iteration catches up on all of it, so a timeout that lapsed during the pause applies its `on_timeout` policy then.\n\n**The claim is fenced, because it is not a lease.** The stale sweep decides a worker is dead from a wall-clock guess, so a slow but *alive* worker will eventually be declared dead and replaced. Every write the executor makes carries its claim token and is refused once superseded — otherwise the replaced worker's late completion lands on top of its replacement's result, or its checkpoint at a later gate resurrects an already-finished run and asks the approver a second time. The retry budget resets at each new gate (a gate is new work, not a retry), and a run that exhausts it is *ended* rather than dropped: an exhausted run sits in `running` with a payload, in neither queue, and would otherwise show as in-progress forever.\n\n**The gate fails closed.** Continuing is an allowlist — `approve` and the synthetic `auto_proceed` — not \"anything that is not a stop word\". `decision` is whatever a fast model extracted from free-form chat and it drifts; under a denylist, \"rejected\", \"Reject\", \"decline\" and \"no\" would all continue, so the approver declines and the deliverable is produced anyway. Reply shapes that ask a question rather than seek permission always continue, since the answer *is* the value. A stop ends the run at `error` with the human's note. Either way the decision becomes the gate step's own output, so it reads as a section *in* the artifact — capped and blockquoted, because that text reaches the synthesis specialist as prompt context.\n\n**A definition edited during the pause is refused.** Resume re-validates the payload's version, the recorded gate, *and* a fingerprint of the whole step list, and derives the index to continue at rather than reading it from the payload. Pinning only the gate would not be enough: definitions are overwritten by name and any rostered user can save one, so someone could keep the gate identical and replace every step after it — and the approver's sign-off would be recorded against work they never saw, which defeats the one thing an approval gate is for. No built-in workflow yields the gate; only user-created dynamic workflows do.\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 — literally the same code, since both call `workflows.gate.checkpoint_gate`, which delivers the question and writes the checkpoint in one place. It never hangs waiting on a human, and it reports both whether the question reached them and whether the run will continue by itself once answered. The runners that *cannot* pause — the schedulers, evals, client rotation, onboarding, the research tools — call `gate.ensure_workflow_event`, which raises on a gate rather than letting one be swallowed; the scheduler's dynamic-workflow branch used to ignore it and record a successful run containing nothing. `executive_research` is excluded (it has the dedicated `run_executive_research` tool). Running a workflow from chat delivers nothing on its own — it renders the artifact into the conversation, and the recurring principal briefs (`morning_brief`, `end_of_day_digest`) reach anyone only via the scheduler's own `_deliver_to_principal`. The tool description used to claim those two DM the principal when run and to confirm before firing them, which had the model soliciting a confirmation on a false premise; it now names `executive_reflection` as the one workflow that really does execute tool calls of its own (DMs to heads, broadcasts, alerts). 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, the conversational wizard at `/jobs/new`, or the step-by-step advanced editor — without shipping code. The Workflows page (`/jobs`) opens on a *Start here* panel that leads to all three: the user describes the job in a sentence and *Start* opens the wizard with that text sent as its first message (handed over in `sessionStorage`, so a link cannot make the wizard send text the user never typed; where storage is blocked it falls back to `/jobs/new?describe=`, which only fills the composer and sends nothing), or picks *Step by step* (advanced editor) or *Talk it through in chat* (`/?new=1&draft=`). Below it come the user's own workflows, then four ready-made starter picks with the full built-in list folded behind *Browse all* (`?browse=1`). The picks and the example chips follow the workspace mode: a team gets the investor update, board prep, MBR and competitive teardown (and a board pre-read chip); a solo owner-operator gets the MBR, pricing review, churn deep dive and quarterly plan, with chips for a Friday cash and pipeline check, customers who stopped buying and a competitor digest (`lib/workflowStarters.ts`; a unit test pins every pick to a startable `WORKFLOW_REGISTRY` entry). 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 four kinds: **specialist** (consult a specialist with a goal prompt, optionally grounded by RAG), **action** (get something done with tools — see below), **approval_gate** (a `wait_for_human` pause), and a terminal **synthesis** step that assembles the artifact. At least one specialist or action step is required. `validate_definition` enforces the structural rules: exactly one terminal synthesis step, valid specialists, `{placeholder}` tokens that reference declared input fields, rostered approval/cadence people (team members — never one of the principal's contacts, whom an unattended run may not message), 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 step-by-step advanced editor drives the `/workflows/custom` CRUD endpoints directly.\n\n**The New workflow wizard** (`/jobs/new`) is the default way to create one from the UI. It works like conversational onboarding: the user describes the job, the `workflow_designer` Council agent (`openexecutive/workflows/designer.py`) asks one clarifying question per turn — deliverable, per-run inputs, sign-off, schedule, recipient — with up to four clickable suggested answers, then emits a complete definition plus a plain-language summary and the assumptions it made. Every turn offers the model exactly three fixed, name-sorted tools (`ask_clarifying_question`, `emit_workflow_draft` — reusing the chat tool's `DEFINITION_SCHEMA` — and `search_available_tools`, which is answered inside the same turn from the tool catalog, up to four searches per turn, with the tool_use/tool_result pairs never stored in the plain-text transcript; every tool a search returns is remembered on the session and replayed into later turns, so a forced draft or a repair turn — which cannot search — still has the exact names); `tool_choice` flips to the emit tool once, when the six-question budget is spent or the user clicks *Draft it now*. The emitted definition goes through `validate_definition`, the tool-availability check, and a check against saved custom names, with one repair turn that feeds the errors back. The system prompt is a cached constant; the live context — specialists, the roster with person ids, the user's timezone (the one set through `PUT /workspace`, else `USER_TIMEZONE`; cadences stay UTC), and taken names — is rendered once per session into the first user turn, and while refining, the exact current draft is prepended to the latest user turn so the model edits it rather than re-deriving it. Roster names and roles are flattened to one line and capped at 80 characters before they enter that context, and the system prompt tells the model to treat the whole block as data, never instructions. Sessions live in memory (`/workflows/designer/*`, 2 h TTL, 50-session cap), run one model turn at a time (a second concurrent `/message` or `/draft` gets 409, and a failed turn is rolled back by identity), and never write: the review card saves through the same `POST /workflows/custom`, which re-validates, and *Edit details* opens the draft in the advanced editor (`/jobs/new?designer=<id>`) before saving.\n\n**Editing is a conversation too.** *Edit* on a saved workflow (`/jobs/new?edit=<name>`) opens the same designer through `POST /workflows/designer/edit`: the stored definition is the starting draft, so the user's first message (\"have Mark sign off and run it Fridays\") is applied to it like any refinement, and a note in the context block (a user turn, never the cached system block) tells the model it is changing a saved workflow. The draft always keeps the workflow's name — `_check_draft` puts it back and skips the taken-name check — and the route keeps its on/off state, so an edit can neither fork a copy nor switch on a tool workflow waiting for approval. The stored draft is handed to the model marked as data, not instructions. The review card lists *What changes* in plain words against the saved version (`lib/workflowChanges.ts`): every field is compared, with named sentences for the sign-off person and what it asks for — a sign-off moved off approve/reject is called out because the run then continues whatever the answer — the schedule, steps added/removed/reordered, inputs, tools and the tool-call budget, and a catch-all line for any other field. It names only the newly added tools that may change things. *Save changes* calls `POST /workflows/custom/{name}/save-edit`, which saves the session's own draft after re-validating it, only when it is the draft the card showed (the card sends what it displayed; a message that landed since is a 409), and only if the stored workflow has not changed since the conversation opened (409 otherwise), so an edit started before someone switched the workflow off cannot switch it back on. The step-by-step form stays as the advanced editor (`/jobs/new?edit=<name>&mode=advanced`).\n\n**Action steps (workflows that act).** An `action` step (`ActionStepSpec`: `goal`, `tools`, `max_tool_calls` 1–50, default 20) is run by the `workflow_actor` Council agent (`openexecutive/workflows/action_step.py`) as a bounded tool-use loop. Its `tools` list is an allowlist of exact tool names — MCP gateway tools (`server__tool`, e.g. `google_workspace__append_table_rows`) and a small set of built-ins (`oe__read_file`, `oe__message_person`, `oe__create_alert` — which, in a workflow a team member created, raises the alert as theirs (`alert_tools.raised_for_workflow_owner`: source `team_member`, \"Raised by <name>\", never a company-wide broadcast) — plus any installed extension's tools registered with `workflow=True`, as `oe__<name>`, run inside `extensions.workflow_step(name)`; a built-in wins a name clash, and an extension tool counts as reading only when it says so) — and **clicking Create is the user's approval** of that list: the review card shows every tool, flags the ones that may change things (anything whose name doesn't say it reads, and any tool with a URL/URI/endpoint/webhook parameter anywhere in its schema, or whose schema couldn't be read, since a URL can carry data out), and names them in a \"this workflow can use these without asking again\" notice. Because that card is the approval, a workflow with action steps saved from chat (`draft_workflow`/`save_workflow`, whose confirmation is a token the model holds itself) is stored **switched off** (`is_active=false`) and `save_workflow` returns `status: saved_pending_review` with a `/jobs/{name}` link. An inactive workflow can't run or schedule (`get_workflow` and the scheduler skip it); `/jobs/{name}` shows it on the same review card, where **Turn on workflow** (`POST /workflows/custom/{name}/activate`, which re-validates the tools) is the approval — the click sends the definition the card showed, and the server refuses (409) if the stored one has changed since, so chat overwriting it while the card is open can't get new tools switched on. Chat may revise a switched-off workflow but refuses to replace a switched-on one that has action steps (an inbound email steering the Executive could otherwise switch off an approved job and stage new tools under its name); those edits happen in the advanced editor. The Workflows catalog (`/jobs`) lists switched-off workflows in a compact *Waiting for your approval* strip, and saving edits in the advanced editor keeps one off. `tool_catalog.py` resolves names to schemas through the gateway's `search_tools` (extensible-mcp's Markdown output is parsed; resolving is also the per-session discovery its `call_tool` requires) and validates availability at save time (`POST`/`PUT /workflows/custom`, chat `draft_workflow`/`save_workflow`, designer drafts) — an unknown, misspelled or deny-listed tool is a 422. The gateway meta-tools (`search_tools`, `call_tool`, `load_mcp_server`) can never be step tools. `run()` resolves every action step's tools before any step runs, so a vanished tool stops the run before an earlier step acts; `resume()` checks only the steps still to run, after the gate and decision are validated. The last turn of an action step always switches tools off so the agent can report. At run time only the allowlisted tools are offered (sorted; constant cached system block, per-run goal/inputs/earlier results in the user turn), every `tool_use` is re-checked against the allowlist, MCP calls go through `MCPGateway.call_tool` so the config deny-list and the Gmail/Calendar/Drive recipient gates still apply, the call budget is enforced (then a final tools-off turn asks for the report; running out of turns fails the step and lists what was already done), tool errors (the gateway's `Error:` / `Error calling tool` / `Tool error:` prefixes, or a truthy `error` field) return to the model as `is_error` results, each call emits a `progress` event and an audit row (`workflow_tool_call`: tool and outcome; for tools that may change things also a short digest of target arguments — ids, recipients, URLs, paths — so a redirected write is visible; content arguments are never logged), and the step's output is the agent's report plus an \"Actions taken\" list. Tool output is framed as data, never instructions.\n\n**Scripts in action steps.** Besides the step's own tools, the agent is offered one more, `run_script` (`openexecutive/workflows/step_script.py`), for work that repeats over many items — every file in a folder, every row, every email — or chains calls with simple logic. It writes a short Python script once instead of spending a model turn per call; each of the step's tools is a function in the script (`drive__move_file(file_id=…)`, or `call_tool(name, arguments)` by exact name), and only the script's final value and printed output come back. The script runs in **Monty** (`pydantic-monty`), a sandboxed Python interpreter for model-written code, in a worker process spawned per script: no files, network, environment, subprocesses or third-party imports — the step's tools are the only things it can reach. **A script is a faster way to make the same calls, never a way around them:** every call it makes goes through the same per-call path as a direct `tool_use` (`action_step._StepCalls`) — the allowlist, a call budget (a script's calls have their own: 10× the step's `max_tool_calls`, capped at `WORKFLOW_SCRIPT_MAX_CALLS`, default 500, because they cost no model turn each — so a step can work through a folder of hundreds of files while its direct calls stay capped at 1–50), the first-write target check (a held write comes back to the script as `{\"status\": \"held\", …}`) and one `workflow_tool_call` audit row per call — and the script itself is audited as `run_script`, with how many calls it made and how long it took. The step's \"Actions taken\" list collapses repeats into one line with a count. A step whose direct calls are spent keeps its tools on while the script budget has room, so it can still script the rest (a direct call is refused as over budget). When a tool returns a list of five or more items and the round didn't use `run_script`, the step adds the same `FANOUT_HINT` as chat (once a step), pointing the per-item work at one script. The worker is stepped from the step's own task (each call pauses it and is answered there), so cancelling the run stops the script and its in-flight call together, and each call's progress shows as it happens. At most `SCRIPT_MAX_WORKERS` (default 2) scripts run at once across the server, chat and workflows together; another waits for a slot within its own wall clock, else returns \"the server was busy\". A worker exists only while its script runs (about 8 MB idle). Execution time (excluding time waiting on tools), memory and recursion depth are capped inside the worker, the script has a wall-clock limit, and its text is size-capped; printed output past its cap is dropped. A failing script returns its error to the agent as an `is_error` result, with the calls it already made listed first (ahead of any long result, so a cut never drops them) so a fixed re-run doesn't repeat writes; a call cut off by the time limit is listed as `may_have_run`, and gets a `cancelled (may have run)` audit row. A workflow definition still holds no code; a script lives on only if the agent saves it as a tool (below). Because a step can loop at run time, the workflow designer keeps work that repeats over items (each email, file, row or listed follow-up) in ONE action step whose goal spells out the items, rather than a step per item; `run_script` is never a step tool, and a definition that lists it is rejected (`validate_definition`) so the designer's repair turn removes it. `WORKFLOW_STEP_SCRIPTS=false` turns the tool off, and a step then only calls its tools one by one.\n\n**Python jobs (`run_python_job`, `openexecutive/workflows/python_job.py`).** Monty can't run libraries, so library work on files (split or merge PDFs with pypdf, spreadsheets with openpyxl and pandas, charts with matplotlib, images with Pillow, and documents made from scratch or from files: Word with python-docx, PowerPoint with python-pptx, laid-out PDFs with fpdf2) runs as a Python job: Pyodide (Python in WebAssembly) executed by **Deno** in a process of its own per job. Pyodide alone is not a sandbox — its Python can call into the JavaScript runtime, which under plain Node reaches the server's environment, files and network — so Deno is what isolates it: it is started with read access to the sandbox folder and the worker script only, with no network, environment, writes or processes, and an empty process environment. Files go in on stdin and results come back on stdout. A job gets only what the call names: Knowledge-library files, the files attached to the chat message being answered (`attachment_files`, the uploads as sent, bound for that turn only by `POST /chat/upload` in `workflows/turn_files.py`, so the model never retypes an attachment's text), text the caller passes, and `inputs` (a dict the code reads); result files are kept 7 days under the company folder and served to the principal at `GET /python-jobs/{job}/{file}`, which the Executive links in its reply. A deployment can instead send jobs to a separate runner (`PYTHON_JOB_RUNNER_URL`, with `PYTHON_JOB_RUNNER_KEY` as a bearer token): `run_job` POSTs the same job (code, inputs, files, caps, time and memory limits) and reads back the same result object, at most as large as a local job's output, keeping only its known fields, so kept results, links and metering are unchanged; the local sandbox is then not needed, and the runner is trusted to isolate jobs. A runner can turn a job away with `{\"run_locally\": true}` (and an optional `reason`) in a non-200 reply, for example when the deployment's allowance for it is used up: the job then runs in the local sandbox if this machine has one, and otherwise fails with the runner's reason. Any other non-200 reply stays a job error, so a busy or broken runner never moves every job onto the machine. A runner with more libraries lists them in `PYTHON_JOB_EXTRA_LIBRARIES`, which the job tool's description then names, so the Executive doesn't refuse a job that needs one. The tool sits in the `workflows` tool group, labelled for jobs with or without attached files. The library set is fixed at build time: the API image installs Pyodide and Deno from npm and the compiled libraries from Pyodide's CDN, each checked against the sha256 in Pyodide's lock file, and a build smoke runs a job. Pyodide can't infer the compiled packages the pure-Python libraries import (lxml, Pillow, fonttools), so the worker loads them when a job imports docx, pptx or fpdf. Pyodide, Deno and the pure-Python libraries are pinned by hash too (an npm lock installed with `npm ci`, pip `--require-hashes`). One job runs at a time per process (200–450 MB each), with a `PYTHON_JOB_TIMEOUT_S` limit and a memory cap (`PYTHON_JOB_MEMORY_MB`, default 1536, as the process's data limit, plus V8 heap and WebAssembly memory caps); the worker returns at most 20 result files and 25 MB, and the API stops the job as soon as its reply passes that. The job runs at a lower CPU priority and is first in line if the machine runs out of memory, so a heavy job slows or loses itself rather than the API; Deno's own caches go in a temporary folder removed with the job; and kept results are capped at 200 MB in all, oldest first. The tool is chat-only, offered only on the principal's own turns (`PRINCIPAL_ONLY_TOOLS`), withheld on private turns, unattended passes and under the Act as me lockdown, and not offered at all without the sandbox (`PYTHON_JOBS_ENABLED`, `PYTHON_SANDBOX_DIR`).\n\nA job that worked can be kept the same way as a script (below): `save_as` and `description` keep its code as a Custom tool of kind `python`, and `run_python_job(tool=<name>, inputs={...})` with its files runs it again, recording the run, so a job done before costs no code-writing tokens. Python tools run only on the principal's own chat turns: they are never listed for workflow steps and never turn on for workflows (`PUT /saved-tools/{name}` answers 409), and `run_script` refuses one (and `run_python_job` a script tool). Every job writes one `python_job` audit row (`ok`, `duration_ms`, `cpu_ms` and `peak_mb` read from the process's /proc entry just before it is stopped, files and bytes in and out, attachments, the Custom tool it ran or kept), which `GET /audit/usage` sums into `python_jobs` with the model usage of the turns that ran one.\n\n**Saved tools.** A script that works can be kept to run again by name (`openexecutive/workflows/saved_tools.py`); each tool has a `kind`, `script` (`run_script`) or `python` (`run_python_job`, above). `run_script` takes `save_as` and `description` with a new script: if the script succeeds it is saved, with the set of tools it actually called, and a failed script is never saved. Later, `run_script(tool=<name>, inputs={...})` runs the saved script instead of new code, with `inputs` available to it as a dict. Only the principal's own turns save: a chat turn where the principal is speaking on a verified, interactive surface (the same test as `load_mcp_server`), never an inbound email, a teammate, an unattended run or a workflow step — a step is offered `tool=` but not `save_as`. A saved tool runs with the authority of whoever runs it, so its author must be trusted at least as much as anyone who may run it. For the same reason only a workflow step (its tools owner-approved) or the principal's own turn may run one: anyone else's chat turn is refused `tool=` and not offered `list_saved_tools`, so a stranger can neither list the principal's automations nor run one with inputs they choose. Descriptions are kept to one line of printable text (they are shown to models), and every save writes a `saved_tool_changed` audit row (`actor: executive`) beside the owner's own changes. Saving needs no approval beyond that, because a saved tool can do no more than the context running it: its calls go through the same per-call path as any script (in a step: the allowlist, budget, target check and audit), and a step runs one only when the step already allows every tool it used (otherwise the result names the `missing_tools`) and only at the version the owner turned on for workflows (`workflow_version`, Settings → Advanced → Custom tools → Use in workflows). A tool kept on a turn that read outside content could otherwise carry injected code into an unattended run, so keeping stays automatic and works in chat at once, but workflows wait for the owner; a newer save doesn't change the version workflows run, and pruning never drops it. Each step's `run_script` description lists the saved tools that step may run; chat asks `list_saved_tools`. Every save of changed content is a new version (the newest 20 are kept, plus the one that ran until then, so a rolled-back version the owner trusts survives later saves), every run is recorded (`saved_tool_runs`, the newest 200 per tool), and the owner can turn a tool off or switch it back to an earlier version on Settings → Advanced → Saved tools (`/saved-tools` routes, the owner's alone). A turned-off tool never runs, and a new version saved by the model does not turn it back on. `SAVED_TOOLS_ENABLED=false` stops saving and running saved tools everywhere.\n\n**Targets are chosen at run time — and a new one is confirmed once.** Approving a workflow approves its *tools*; which sheet, doc, recipient or URL each call hits is chosen by the model at run time, by design (a tab per month, a reply to whoever sent the invoice, a doc per client). What bounds that is the allowlist, the gateway's recipient gates, the audit digest, and **first-write confirmation**: a `TargetPolicy` (one per run) checks every call to a tool that may change things. `resource_targets` walks its arguments recursively for resource keys (snake- or camel-case ids, `to`/`cc`/`bcc`, recipients, addresses, attendees, members, users, owners, parents, URLs/links/hrefs, paths, channels, spaces, rooms, phones, hosts, buckets, tables, spreadsheet/document/folder/calendar/file); a matching key marks everything beneath it, even a `name`. Outside a resource, only a new item's own `name`/`title`/`subject`, message/thread/draft/label ids, `range`/`sheet` and workspace-mcp's acting `user_google_email` are skipped — and whatever the key, a bare value shaped like an email address, a URL or an international phone number is a target, except inside what the call writes (`rows`, `values`, `body`, `text` …). Key names are a heuristic, so this is a best-effort guard layered on the allowlist, the gateway gates and the audit. Float ids are compared as integers. Arguments too deep, naming too many targets, or holding an over-long value **fail closed** (the call is refused). A target is trusted only when it was approved for this workflow before (`workflow_approved_targets`, by value) or is an id a write in this run created — a top-level id/link field (`id`, `spreadsheetId`, `webViewLink` …) of the **structured JSON object** result of a tool whose name says it creates (create / insert / upload …) and that takes no URL — a tool whose schema couldn't be read is assumed to (free text, nested records and readers' or updaters' results are never read, so a fetched page, an echoed title, a shared page's links or a stranger in `ccRecipients` can't plant one); those survive a pause in the resume payload (`run_created`). Values written in the workflow's own text are *not* trusted, since anyone who can edit the workflow could change them without review: they are asked once, then remembered. Approvals are by value, for any of the workflow's tools, and are **cleared when the workflow's tool set changes** (a newly added tool must earn them again). Any other target makes the call **held**: it is not run and costs no budget, the model is told it is waiting for approval and carries on, and it is audited `held for approval` (at most 10 held per step, 16 KB each; an identical repeat is held once). Whether a call is checked at all follows the read-only label, which now never marks a tool whose name carries a write verb anywhere (`find_and_replace_doc`). After the step finishes, the run pauses with a `WaitForHumanEvent` to the workflow's **owner** (`owner_person_id`, the person who created it on the Workflows page or in chat; falling back to the principal if unknown or archived), `on_timeout=auto_proceed`, 48 h, and a `WorkflowResumeState` of `kind=\"held_writes\"` carrying the exact held calls. On resume (`_resume_held_writes`, fingerprint-checked like a gate, with the remaining steps' tools checked first), only `approve` runs them — each still has to be in the live step's allowlist and resolve; its targets are remembered first — and anything else (decline, timeout, unreadable) skips them; either way a *Held for approval* section is added to the step's output and the run continues at the next step. With no one to ask, held writes are skipped and noted; a step that fails or crashes after holding, or a resume that stops early (definition changed, a later tool missing), audits its held writes as dropped and says they did not run. The question quotes each target JSON-escaped (a value can't add its own lines) and always shows a URL's full scheme and host, saying how much of the rest is hidden. The owner answers by chat reply or with **Approve / Decline** on the run page (`POST /workflows/runs/{id}/decision`, which the principal may also use); remembered targets are listed and removable on the workflow page.\n\n`oe__read_file` extracts text (PDF, Word, Excel, CSV, Markdown, text) only from files under `WORKFLOW_FILE_DIRS` (default: workspace-mcp's attachment folder), resolving symlinks and `..` before the check (`tool_catalog.resolve_readable_file`, shared with the Executive's `read_document` tool). A scanned PDF is converted by `knowledge.pdf_reader` instead of failing as \"may be a scanned image\"; one that still cannot be read returns the reason. Action steps are allowed in scheduled workflows. Because they have external side effects, a resumed run heartbeats its claim (`touch_resume_claim`, at most once a minute as events flow — each tool call emits one; a busy database is retried on the next heartbeat, never treated as a lost claim; the sweep's requeue re-checks the claim's age in the same UPDATE, so a heartbeat landing between the sweep's read and its write wins), so the stale-claim sweep never requeues and replays a slow but live run, and a worker that finds its claim superseded stops at its next event. A worker that actually crashes mid-resume is still requeued; its action steps then run again, so goals should say how to avoid duplicates (the actor reads current state before writing). `GET /workflows/tools/search?q=` and `GET /workflows/tools/describe?names=` back the advanced editor's tool picker and the review card's labels.\n\nAn 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. A gate followed by further steps pauses at `awaiting_human` and then resumes once answered, so gates no longer have to sit immediately before synthesis. They remain forbidden in cadence-enabled definitions: a scheduled fire has no interactive human to ask.\n\nBuilt-ins the system runs on its own (`morning_brief`, `end_of_day_digest`, `executive_reflection`, `executive_research`) set `background = True`, surfaced as `WorkflowMeta.background`; the `/jobs` ready-made list files them under a **System** chip instead of the default view. They stay runnable by hand.\n\n**Quick workflows** (`workflows/quick.py`) are one per playbook in effect that no built-in or custom workflow follows (switched-off custom ones count). They are derived whenever the catalog is read, never stored: `list_workflows()` returns built-ins, then Quick ones, then active custom ones, and `get_workflow` resolves a `quick_<playbook>` name after the registry (custom workflows may not take the `quick_` prefix). Each has one required field, `request`, and two steps: **Load context** (company profile plus RAG for the playbook category's specialist) and **Draft** (that specialist writes one Markdown document following the playbook). `WorkflowMeta.quick` is true for them. The 8 built-in playbooks no built-in follows are Quick workflows: board update memo, 1:1 agenda, layoff comms plan, positioning statement, post-mortem, customer interview plan, feature prioritization and market sizing. A company's own playbook shows up as one, hiding a built-in drops it, and a custom workflow that starts following one replaces it. If custom workflows can't be read, none are offered, since their followers are unknown.\n\n**Workflows vs. playbooks.** `/jobs` has two tabs: **Build** (`?tab=catalog`, the default) and **Runs** (`/skills` redirects to `/jobs`). A playbook is a skill (`knowledge/skills_repo.py`): *how* the Executive does a piece of work, with no inputs, schedule or side effects. A workflow is the runnable job. Workflows **follow** playbooks: a step that follows one gets its body appended to the step prompt via `workflows/playbooks.py` (`load_playbook` + `playbook_clause`). Six built-ins do — `board_prep` (`board-prep-deck`), `quarterly_plan` (`quarterly-okr-set`, `quarterly-forecast`), `mbr` (`monthly-business-review`, in the financial, KPI and function steps), `competitive_teardown` (`competitive-teardown`, in the four analysis steps), `fundraising_prep` (`fundraise-narrative`, narrative step) and `exec_search_brief` (`role-scorecard`, profile step). Each declares them in `Workflow.playbooks`; a unit test holds that declaration equal to the `load_playbook(\"…\")` calls in the module, and `WorkflowMeta.playbooks` exposes it. A custom workflow's `specialist` step may name a `playbook` (validated to exist at save; appended after `{field}` rendering, so braces in a playbook are never treated as placeholders). The lookup resolves the playbook in effect, so a company's customized copy changes the workflow's output, and a hidden, missing or malformed one falls back to the step's own prompt plus RAG — a workflow never fails over a playbook (`load_playbook` catches everything; a custom step whose playbook is unavailable emits a `progress` event saying so). Because an approved scheduled workflow reads its playbook at each run, chat never creates or changes a playbook: it saves repeatable work as a workflow (`draft_workflow`, confirmed by the user), and only a person can change what a workflow follows: a workflow's page shows each playbook it follows as **How it's done** (`components/jobs/HowItsDone.tsx`), with **Edit** (`PUT /skills/{name}`; on a built-in that saves the company's customized copy) and, for a customized copy, **Reset to original** (`DELETE`, which reverts). The chat summary of a drafted workflow names each step's playbook. `playbook_users()` maps each playbook to the workflows that follow it — built-ins, every custom workflow (switched-off ones included: turning one on approves its definition) and the Quick ones; the skills API reports it as `used_by`, and the Executive's `search_skills` hits carry it as `workflows`.\n\nCompleted artifacts are discoverable in the unified artifacts section (`/artifacts`, labelled **Documents** in the UI) alongside their run-detail page at `/jobs/runs/{run_id}`. A run someone starts by hand (`POST /workflows/{name}/runs`, `run_workflow`, research in chat) stores them as `workflow_runs.owner_person_id` and its history and output are theirs alone (plus the person a gate waits on); scheduled and system runs keep no owner and stay the team's. Workflow output stays Markdown — the scheduler DMs it and reflection rereads it as text — and gains other formats only on the way out: any run can be downloaded as Word (`/artifacts/run:<id>/download?as=docx`), and the Executive can repackage one with `get_artifact` → `draft_artifact(format=…, supersedes=\"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.\n\nWith Take the lead as the Executive on (`orchestrator.take_the_lead`), reflection and research build their toolkit through `unattended_toolkit(..., source=...)`. That keeps solo's booking and `run_workflow` tools and an unrestricted `message_person` (teammates as well as the principal). Every acting tool goes through the gate, and a held action waits on Today as a `take_the_lead_action` decision. Reflection also gets the MCP gateway's `search_tools` and `call_tool` (`_with_lead_tools`; `call_tool` behind the gate, `load_mcp_server` left out), so it can find and use whatever the deployment has connected, such as building a sheet to track something. A note in the user turn (never the cached system prompt) tells it to act rather than only report, and it gets more room: 10 iterations, 4000 tokens, and tool results up to 4000 characters. The grounding check still refuses outward text naming people or figures the pass didn't see. New mail and chat also wake the reflection early (scheduler section). In training (`take_the_lead.training`) every acting call that isn't allowed waits too, as a training card for the principal, and both passes append `take_the_lead.learned_note()` to their user turn: that it's in training, and the principal's own edits on earlier cards as examples of how they want those done (never in the cached system blocks).",
"mermaid": "flowchart TD\n Input[\"Structured input\"]\n Steps[\"Ordered named steps\"]\n Wait[\"wait_for_human pause\"]\n Sched[\"workflow_runs<br/>(awaiting_human)\"]\n Resolver[\"inbound_resolver<br/>+ resumer\"]\n Artifact[\"Markdown artifact<br/>(workflow_runs.artifact)\"]\n Today[\"Today / Documents\"]\n Input --> Steps\n Steps --> Wait\n Wait --> Sched\n Sched -- \"human reply\" --> Resolver\n Resolver -- \"resolved → claim\" --> 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-10-15T14:55:56Z"
+ "generated_at": "2026-10-16T14:02:44Z"
}
diff --git a/packages/core/openexecutive/guide/prebuilt/today.json b/packages/core/openexecutive/guide/prebuilt/today.json
index b22b9959..a2d73cac 100644
--- a/packages/core/openexecutive/guide/prebuilt/today.json
+++ b/packages/core/openexecutive/guide/prebuilt/today.json
@@ -1,7 +1,7 @@
{
"section_id": "today",
"title": "Today / Morning Brief",
- "markdown": "**What it is:** A single screen of *what needs you right now* — the proactive digest the Executive prepares so you're not the one chasing status. In the app it's **Home**, the screen the app opens on.\n\n**What it does:**\n\n- Opens with a greeting, one line summing up the day (click a part of it — *2 awaiting reply*, *1 department at risk* — to open that list), and an **Ask your Executive anything…** box that starts a chat. On a quiet day the line names one **Move today:** instead.\n- Puts what's waiting on your call up front under **Needs you**: the first card large, the next two below it, and **Show N more** for the rest.\n- Gathers everything else under **Everything else** as a row of count tiles — **Departments**, **People**, **Across the team** (waiting on someone else), **Under way**, **Handled overnight**, **Monitoring**, and **Across your clients** when you look after client companies — shown only when they have something in them. Click a tile to open its full list in a side panel.\n- The **Departments** tile shows each department's goal health — on-track, at-risk, or off-track — with the at-risk goals called out.\n- The **People** tile lists people with open items, their reply counts, SLA status, and whether they're on leave.\n- **Read today's brief** (next to **Needs you**) opens the written brief — what's going on across the company — in a side panel.\n- If your latest morning brief, end-of-day digest or weekly review couldn't be sent to you, a line at the top says why and what to connect. It goes away once that's fixed.\n- When your morning brief or end-of-day digest left out lines that named people or figures the Executive couldn't match to your data, **Left out of your brief** under **Needs you** lists them for a day. **Hide** clears it.\n- With **Delegate → Act as me → What it writes as you** at **For my inbox too**, the replies the Executive wrote as you for mail that needs you come first in **Needs you**, marked **Reply waiting** (or **Follow-up waiting** when nobody answered an email you sent). Only you see them.\n- Actions the Executive suggested from your email (a meeting, a message to someone, a new contact) appear as cards in **Needs you**, each spelled out with a box to untick. **Approve** does the ticked ones (**Approve N** when you untick some), **Approve + allow** also lets it do that kind of action on its own from now on (shown while it is still learning), and **Dismiss** drops the card. Only you see them.\n- A send or edit a team member asked for in chat that their department held waits as a card marked **Waiting on you**, with the reason and the exact details. **Approve** carries it out as shown; **Decline** drops it.\n- Under **Take the lead**, something the Executive wanted to do on its own that you haven't allowed yet comes as a card: **Approve** does it once, **Approve + allow** also lets it do the same thing with the same person from now on, **Edit** changes it first (tick **Do it like this next time** to keep your edit as an example and allow it), and **Decline** drops it.\n- Surfaces proposals and alerts you can click to open a chat thread with full context.\n\n**How to use:**\n\n1. Click **Home** in the sidebar (or the Open Executive logo). On a phone, **Home** is the first button in the bar at the bottom.\n2. Work **Needs you** from the top. Each card has one main button and **Discuss**; everything else is in the card's **⋯** menu:\n - **Approve** — accept the recommendation; the Executive carries it out right away. A line at the top of **Needs you** shows it working and then done, with a link to the chat where it did the work. If it didn't work, **Try again** is on that line. Usually the main button.\n - **Discuss** — open a chat with the context already filled in.\n - **Edit & approve** (in **⋯**) — reword the action first, then **Send approval**; your text is used exactly as written.\n - **Dismiss** (in **⋯**) — drop it and stay on Home. When the Executive thinks a card is stale, **Dismiss** is the main button instead.\n - **Snooze until …** (in **⋯**) — three hours from now (while that is still today), **tomorrow 9:00**, or **Monday 9:00** (not offered on a Sunday). The card leaves Home and comes back on its own then; *Snoozed until …* with **Undo** under **Needs you** brings it back now.\n - **Nudge *name*** — the main button when the best move is chasing someone for a reply; **Run *workflow*** when the best move is a workflow.\n - **Open *name*'s page** (in **⋯**) — the person the item is waiting on.\n - A **Monitoring** signal leads with **Discuss**; its **⋯** has **Dismiss signal**.\n3. Some cards are simpler: when a scheduled run didn't finish (a department check-in, or a workflow you set to run on a schedule), its card's main button is **Run again**, which runs it now and sends the result where it normally goes (**Open the run** in **⋯** shows what went wrong); a document card's main button is **Open document** (**Mark reviewed** is in its **⋯**, and **Open in app** when the document lives in another app), and a calendar-booking card books (or declines) the meeting directly when you click Approve or Dismiss. Only the person a booking was sent to for approval, or the owner, can approve or decline it.\n4. Keep it tidy from the **⋯** next to **Needs you**: **Dismiss N older than 7 days** clears stale items, and **Re-check relevance** asks the Executive to review every open item now.\n5. Open the **Departments** tile and click a department to ask for its status in chat.\n6. Work the replies waiting to be sent (they come first in **Needs you**). Each card shows who wrote (and *Address not verified* when the address couldn't be confirmed), **What they wrote** (click to open), **Your draft** with who it goes to, *Why it waited for you* when Handle it for me left it for you, **Decide before sending** (what the draft leaves for you to answer) and any warnings. The buttons:\n - **Send** asks once, naming who the reply goes to, then **Send now** sends it from your own mailbox (Gmail or Outlook). If the recipients changed or they wrote again since, it asks again, says what changed, and offers **Send anyway**.\n - **Send + allow** (shown while replies are still being learned) sends it and lets replies to that person go on their own from now on while Handle it for me is on.\n - **Edit** changes the words right on the card; **Save** keeps them (and updates the draft in your mailbox when it is kept there too). When it is learning how you write, **Do it like this next time (if you changed it)** appears as you send.\n - **Open in Gmail** (or Outlook) opens the draft there, when it is kept in your Drafts.\n - **Dismiss** drops the card, and deletes the draft from your Drafts unless you changed it there.\n On a server, Send needs signed sign-ins; until they're set up, send from your mailbox. A card goes away on its own once you send or delete the draft in your mailbox, or reply yourself, and after 7 days.\n\n**Example:** in a Discuss thread, just say *\"go ahead\"* to approve the proposal or *\"drop it\"* to dismiss it — no need to go back to the card. (Calendar bookings still need the Approve button.)\n\n**Just for yourself?** If you use Open Executive just for yourself (**Settings → Workspace → Personal**), Home leaves out the team parts: there are no Departments, People or Across the team tiles — everything that needs a decision is in **Needs you**. When a goal is slipping, the summary line at the top says how many goals are at risk; click it to open **Goals**. Instead, the tiles are **Due soon**, **Your projects** and **This week's review**, each opening its list in a side panel. **Your projects** lists the projects the Executive is tracking for you. Click **Done** when one is finished, or **Drop** to stop tracking it (it asks first, and removes the project from Pulse). **Due soon** lists what you've promised by a date and what others have asked of you, due in the next week — say *\"I'll send Northwind the proposal by Friday\"* in the web chat or your own Slack or Discord and it shows up here, and the Executive reminds you when it's due. Click **Done** once it's handled; **All open items** opens the full list. **Top three today**, right under **Needs you**, shows the three things to focus on today — the same three your morning brief opens with — each with a free slot in today's working hours when the Executive can read your calendar. **This week's review** shows your latest weekly review: when it ran and next week's top three. Click **Read the review** to see all of it.\n\nYour morning brief also opens with a **top three for today**, picked from what's overdue or due, goals that are slipping and the projects you're driving. When Google Workspace is connected and the Executive can read your calendar (it is your own account, or you shared your calendar with it), each of the three gets a free slot in today's working hours and the brief lists today's meetings; otherwise the three come without times. Every Friday afternoon (in your time zone) a **weekly review** arrives the same way: your goals graded by area, what's due or overdue, projects that went quiet, the week's decisions, a few older decisions to look back on, and next week's top three. Both also show up on Home (see above), so you see them even when no chat app or email is connected. When it asks how an older decision turned out, just tell the Executive in the web chat or your own Slack or Discord and it records the outcome against that decision.\n\n*Note: proposals are routed to the right person automatically based on who has authority over them.*",
+ "markdown": "**What it is:** A single screen of *what needs you right now* — the proactive digest the Executive prepares so you're not the one chasing status. In the app it's **Home**, the screen the app opens on.\n\n**What it does:**\n\n- Opens with a greeting, one line summing up the day (click a part of it — *2 awaiting reply*, *1 department at risk* — to open that list), and an **Ask your Executive anything…** box that starts a chat. On a quiet day the line names one **Move today:** instead.\n- Puts what's waiting on your call up front under **Needs you**: the first card large, the next two below it, and **Show N more** for the rest.\n- Gathers everything else under **Everything else** as a row of count tiles — **Departments**, **People**, **Across the team** (waiting on someone else), **Under way**, **Handled overnight**, **Monitoring**, and **Across your clients** when you look after client companies — shown only when they have something in them. Click a tile to open its full list in a side panel.\n- The **Departments** tile shows each department's goal health — on-track, at-risk, or off-track — with the at-risk goals called out.\n- The **People** tile lists people with open items, their reply counts, SLA status, and whether they're on leave.\n- **Read today's brief** (next to **Needs you**) opens the written brief — what's going on across the company — in a side panel.\n- If your latest morning brief, end-of-day digest or weekly review couldn't be sent to you, a line at the top says why and what to connect. It goes away once that's fixed.\n- When your morning brief or end-of-day digest left out lines that named people or figures the Executive couldn't match to your data, **Left out of your brief** under **Needs you** lists them for a day. **Hide** clears it.\n- With **Delegate → Act as me → What it writes as you** at **For my inbox too**, the replies the Executive wrote as you for mail that needs you come first in **Needs you**, marked **Reply waiting** (or **Follow-up waiting** when nobody answered an email you sent). Only you see them.\n- Actions the Executive suggested from your email (a meeting, a message to someone, a new contact) appear as cards in **Needs you**, each spelled out with a box to untick. **Approve** does the ticked ones (**Approve N** when you untick some), **Approve + allow** also lets it do that kind of action on its own from now on (shown while it is still learning), and **Dismiss** drops the card. Only you see them.\n- A send or edit a team member asked for in chat that their department held waits as a card marked **Waiting on you**, with the reason and the exact details. **Approve** carries it out as shown; **Decline** drops it.\n- An item a team member asked the Executive to raise starts with **Raised by** and their name. It goes to a person or a department, never to the whole company. Team members can dismiss only items assigned to them; the owner can dismiss any item.\n- Under **Take the lead**, something the Executive wanted to do on its own that you haven't allowed yet comes as a card: **Approve** does it once, **Approve + allow** also lets it do the same thing with the same person from now on, **Edit** changes it first (tick **Do it like this next time** to keep your edit as an example and allow it), and **Decline** drops it.\n- Surfaces proposals and alerts you can click to open a chat thread with full context.\n\n**How to use:**\n\n1. Click **Home** in the sidebar (or the Open Executive logo). On a phone, **Home** is the first button in the bar at the bottom.\n2. Work **Needs you** from the top. Each card has one main button and **Discuss**; everything else is in the card's **⋯** menu:\n - **Approve** — accept the recommendation; the Executive carries it out right away. A line at the top of **Needs you** shows it working and then done, with a link to the chat where it did the work. If it didn't work, **Try again** is on that line. Usually the main button.\n - **Discuss** — open a chat with the context already filled in.\n - **Edit & approve** (in **⋯**) — reword the action first, then **Send approval**; your text is used exactly as written.\n - **Dismiss** (in **⋯**) — drop it and stay on Home. When the Executive thinks a card is stale, **Dismiss** is the main button instead.\n - **Snooze until …** (in **⋯**) — three hours from now (while that is still today), **tomorrow 9:00**, or **Monday 9:00** (not offered on a Sunday). The card leaves Home and comes back on its own then; *Snoozed until …* with **Undo** under **Needs you** brings it back now.\n - **Nudge *name*** — the main button when the best move is chasing someone for a reply; **Run *workflow*** when the best move is a workflow.\n - **Open *name*'s page** (in **⋯**) — the person the item is waiting on.\n - A **Monitoring** signal leads with **Discuss**; its **⋯** has **Dismiss signal**.\n3. Some cards are simpler: when a scheduled run didn't finish (a department check-in, or a workflow you set to run on a schedule), its card's main button is **Run again**, which runs it now and sends the result where it normally goes (**Open the run** in **⋯** shows what went wrong); a document card's main button is **Open document** (**Mark reviewed** is in its **⋯**, and **Open in app** when the document lives in another app), and a calendar-booking card books (or declines) the meeting directly when you click Approve or Dismiss. Only the person a booking was sent to for approval, or the owner, can approve or decline it.\n4. Keep it tidy from the **⋯** next to **Needs you**: **Dismiss N older than 7 days** clears stale items, and **Re-check relevance** asks the Executive to review every open item now.\n5. Open the **Departments** tile and click a department to ask for its status in chat.\n6. Work the replies waiting to be sent (they come first in **Needs you**). Each card shows who wrote (and *Address not verified* when the address couldn't be confirmed), **What they wrote** (click to open), **Your draft** with who it goes to, *Why it waited for you* when Handle it for me left it for you, **Decide before sending** (what the draft leaves for you to answer) and any warnings. The buttons:\n - **Send** asks once, naming who the reply goes to, then **Send now** sends it from your own mailbox (Gmail or Outlook). If the recipients changed or they wrote again since, it asks again, says what changed, and offers **Send anyway**.\n - **Send + allow** (shown while replies are still being learned) sends it and lets replies to that person go on their own from now on while Handle it for me is on.\n - **Edit** changes the words right on the card; **Save** keeps them (and updates the draft in your mailbox when it is kept there too). When it is learning how you write, **Do it like this next time (if you changed it)** appears as you send.\n - **Open in Gmail** (or Outlook) opens the draft there, when it is kept in your Drafts.\n - **Dismiss** drops the card, and deletes the draft from your Drafts unless you changed it there.\n On a server, Send needs signed sign-ins; until they're set up, send from your mailbox. A card goes away on its own once you send or delete the draft in your mailbox, or reply yourself, and after 7 days.\n\n**Example:** in a Discuss thread, just say *\"go ahead\"* to approve the proposal or *\"drop it\"* to dismiss it — no need to go back to the card. (Calendar bookings still need the Approve button.)\n\n**Just for yourself?** If you use Open Executive just for yourself (**Settings → Workspace → Personal**), Home leaves out the team parts: there are no Departments, People or Across the team tiles — everything that needs a decision is in **Needs you**. When a goal is slipping, the summary line at the top says how many goals are at risk; click it to open **Goals**. Instead, the tiles are **Due soon**, **Your projects** and **This week's review**, each opening its list in a side panel. **Your projects** lists the projects the Executive is tracking for you. Click **Done** when one is finished, or **Drop** to stop tracking it (it asks first, and removes the project from Pulse). **Due soon** lists what you've promised by a date and what others have asked of you, due in the next week — say *\"I'll send Northwind the proposal by Friday\"* in the web chat or your own Slack or Discord and it shows up here, and the Executive reminds you when it's due. Click **Done** once it's handled; **All open items** opens the full list. **Top three today**, right under **Needs you**, shows the three things to focus on today — the same three your morning brief opens with — each with a free slot in today's working hours when the Executive can read your calendar. **This week's review** shows your latest weekly review: when it ran and next week's top three. Click **Read the review** to see all of it.\n\nYour morning brief also opens with a **top three for today**, picked from what's overdue or due, goals that are slipping and the projects you're driving. When Google Workspace is connected and the Executive can read your calendar (it is your own account, or you shared your calendar with it), each of the three gets a free slot in today's working hours and the brief lists today's meetings; otherwise the three come without times. Every Friday afternoon (in your time zone) a **weekly review** arrives the same way: your goals graded by area, what's due or overdue, projects that went quiet, the week's decisions, a few older decisions to look back on, and next week's top three. Both also show up on Home (see above), so you see them even when no chat app or email is connected. When it asks how an older decision turned out, just tell the Executive in the web chat or your own Slack or Discord and it records the outcome against that decision.\n\n*Note: proposals are routed to the right person automatically based on who has authority over them.*",
"mermaid": null,
"generated_at": "2026-10-15T21:00:00Z"
}
diff --git a/packages/core/openexecutive/orchestrator/alert_tools.py b/packages/core/openexecutive/orchestrator/alert_tools.py
index d5887105..4acee4a6 100644
--- a/packages/core/openexecutive/orchestrator/alert_tools.py
+++ b/packages/core/openexecutive/orchestrator/alert_tools.py
@@ -1,10 +1,15 @@
from __future__ import annotations
import contextlib
+import contextvars
import json
import logging
+import uuid
+from collections.abc import Iterator
from typing import Any
+from openexecutive.people.models import Person
+
logger = logging.getLogger(__name__)
CREATE_ALERT_TOOL: dict[str, Any] = {
@@ -67,6 +72,72 @@ def _routable_person(person_id: int) -> bool:
return person is None or person.kind == "team"
+# Who created the saved workflow whose step is raising an alert now
+# (``workflows.action_step``). A workflow runs with no chat turn — from the
+# Jobs page or on its cadence — so its creator stands in for the speaker.
+_workflow_owner: contextvars.ContextVar[int | None] = contextvars.ContextVar(
+ "create_alert_workflow_owner", default=None
+)
+
+
+def raised_for_workflow_owner(person_id: int | None) -> Iterator[None]:
+ """Run the block as a step of a workflow ``person_id`` created."""
+ token = _workflow_owner.set(person_id)
+ try:
+ yield
+ finally:
+ _workflow_owner.reset(token)
+
+
+def team_member_speaker(session: Any) -> Person | None:
+ """The team member (not the owner) whose turn this is, or None. Their
+ alerts are labelled as theirs and never broadcast company-wide, and they
+ may dismiss only the alerts assigned to them (``schedule_tools``)."""
+ from openexecutive.orchestrator import department_gate
+
+ return department_gate.speaker(session)
+
+
+def _team_member_raising(session: Any) -> Person | None:
+ """The team member an alert raised now comes from: the speaker, else the
+ creator of the workflow raising it, unless that is the principal. A
+ creator the roster can't place still counts as a team member."""
+ speaker = team_member_speaker(session)
+ if speaker is not None:
+ return speaker
+ owner_id = _workflow_owner.get()
+ if owner_id is None:
+ return None
+ try:
+ from openexecutive.people.store import get_person
+
+ owner = get_person(owner_id)
+ except Exception:
+ logger.warning("create_alert: couldn't read the workflow's creator", exc_info=True)
+ owner = None
+ if owner is None:
+ return Person(id=owner_id, full_name="", kind="team")
+ return None if owner.is_principal else owner
+
+
+def _origin_for(speaker: Person | None, tool_input: dict[str, Any]) -> tuple[str, str, str, str]:
+ """(source, external_id, from, raised_by) for the alert. A team member's
+ own words decide none of the first three: an alert they raise names them
+ and claims no source or message id a real alert could arrive with."""
+ if speaker is None:
+ return (
+ str(tool_input.get("source") or "unknown"),
+ str(tool_input.get("external_id") or ""),
+ str(tool_input.get("from_address") or ""),
+ "",
+ )
+ from openexecutive.alerts.models import TEAM_RAISED_SOURCE
+
+ name = (speaker.full_name or "").strip() or "a team member"
+ return TEAM_RAISED_SOURCE, uuid.uuid4().hex, speaker.email or name, name
+
+
async def handle_create_alert(tool_input: dict[str, Any]) -> str:
from openexecutive.alerts.models import AlertEvent
from openexecutive.alerts.pipeline import schedule_evaluation
@@ -92,14 +163,24 @@ async def handle_create_alert(tool_input: dict[str, Any]) -> str:
"source": "email",
"from_address": sender,
}
+ source, external_id, from_address = (
+ str(tool_input.get("source") or "unknown"),
+ str(tool_input.get("external_id") or ""),
+ str(tool_input.get("from_address") or ""),
+ )
try:
- event = AlertEvent(
- source=tool_input.get("source", "unknown"),
- external_id=tool_input.get("external_id", ""),
- subject=tool_input["subject"],
- body=tool_input["body"],
- **{"from": tool_input.get("from_address", "")},
+ source, external_id, from_address, raised_by = _origin_for(
+ _team_member_raising(current_session.get()), tool_input,
)
+ event = AlertEvent.model_validate({
+ "source": source,
+ "external_id": external_id,
+ "subject": tool_input["subject"],
+ "body": tool_input["body"],
+ "from": from_address,
+ "raised_by": raised_by,
+ "user": raised_by or None,
+ })
# Carry department and person routing hints via the channel field
# (AlertEvent.channel is a free-text tag used by the pipeline).
dept = str(tool_input.get("department") or "").strip()
@@ -121,9 +202,10 @@ async def handle_create_alert(tool_input: dict[str, Any]) -> str:
f"Alert: {str(tool_input['subject'])[:200]}",
actor="executive",
details={
- "source": tool_input.get("source", "unknown"),
- "external_id": tool_input.get("external_id", ""),
- "from": tool_input.get("from_address", ""),
+ "source": source,
+ "external_id": external_id,
+ "from": from_address,
+ "raised_by": raised_by,
"body_preview": str(tool_input.get("body", ""))[:300],
},
private=event.private,
@@ -136,8 +218,8 @@ async def handle_create_alert(tool_input: dict[str, Any]) -> str:
f"Alert FAILED: {str(tool_input.get('subject', ''))[:160]} — {exc}",
actor="executive",
details={
- "source": tool_input.get("source", "unknown"),
- "external_id": tool_input.get("external_id", ""),
+ "source": source,
+ "external_id": external_id,
"error": str(exc)[:300],
"ok": False,
},
diff --git a/packages/core/openexecutive/orchestrator/schedule_tools.py b/packages/core/openexecutive/orchestrator/schedule_tools.py
index 377fbc1b..9131da2b 100644
--- a/packages/core/openexecutive/orchestrator/schedule_tools.py
+++ b/packages/core/openexecutive/orchestrator/schedule_tools.py
@@ -2765,6 +2765,23 @@ async def handle_ack_alert(tool_input: dict[str, Any]) -> str:
# Someone else's drafted document answers as if it did not exist.
if existing is None or not visible_alert(existing, current_viewer()):
return json.dumps({"error": f"alert {alert_id} not found"})
+ # A team member clears only what is assigned to them; the rest of the
+ # board is the owner's to clear, and a dismiss also lowers a watch's trust.
+ from openexecutive.orchestrator.alert_tools import team_member_speaker
+
+ teammate = team_member_speaker(_session)
+ if teammate is not None and (
+ teammate.id is None or existing.routed_to_person_id != teammate.id
+ ):
+ logger.warning(
+ "ack_alert: refused alert_id=%s for team member %s — not assigned to them",
+ alert_id, teammate.id,
+ )
+ return json.dumps({"error": (
+ f"alert {alert_id} is not assigned to this person, so they can't "
+ "clear it. Only the principal can clear items assigned to someone else "
+ "or to nobody. Say so; do not retry."
+ )})
prior_status = existing.status
if prior_status == status:
return json.dumps(
diff --git a/packages/core/openexecutive/workflows/action_step.py b/packages/core/openexecutive/workflows/action_step.py
index e6e0c18f..a15534d3 100644
--- a/packages/core/openexecutive/workflows/action_step.py
+++ b/packages/core/openexecutive/workflows/action_step.py
@@ -397,11 +397,21 @@ def _audit(
)
-async def _dispatch(name: str, arguments: dict[str, Any], info: tool_catalog.ToolInfo) -> str:
+async def _dispatch(
+ name: str, arguments: dict[str, Any], info: tool_catalog.ToolInfo, workflow_name: str,
+) -> str:
if info.source == "builtin":
handler = tool_catalog.builtin_handler(name)
if handler is None: # resolve() only returns names with handlers
return json.dumps({"error": "tool is not available"})
+ if name == "oe__create_alert":
+ # An alert a team member's saved workflow raises is theirs, as
+ # it would be from their chat (orchestrator.alert_tools).
+ from openexecutive.orchestrator.alert_tools import raised_for_workflow_owner
+ from openexecutive.workflows.dynamic_store import get_owner
+
+ with raised_for_workflow_owner(get_owner(workflow_name)):
+ return await handler(arguments)
return await handler(arguments)
from openexecutive.orchestrator.mcp_gateway import get_active_gateway
@@ -418,12 +428,12 @@ async def _dispatch(name: str, arguments: dict[str, Any], info: tool_catalog.Too
async def _call_tool(
- name: str, arguments: dict[str, Any], info: tool_catalog.ToolInfo
+ name: str, arguments: dict[str, Any], info: tool_catalog.ToolInfo, workflow_name: str,
) -> tuple[str, bool]:
"""Run one approved tool call. Returns (result text, is_error); never raises."""
try:
content = await asyncio.wait_for(
- _dispatch(name, arguments, info), timeout=_TOOL_CALL_TIMEOUT_S
+ _dispatch(name, arguments, info, workflow_name), timeout=_TOOL_CALL_TIMEOUT_S
)
except TimeoutError:
return json.dumps({"error": "the tool timed out"}), True
@@ -516,7 +526,7 @@ class _StepCalls:
budget.used += 1
self._events.append(("progress", f"Using {name}…"))
try:
- content, is_error = await _call_tool(name, arguments, info)
+ content, is_error = await _call_tool(name, arguments, info, self._workflow_name)
except asyncio.CancelledError:
# Stopped mid-call (a script's clock, or the run): it may
# have taken effect, so it still gets its audit row.
@@ -847,7 +857,9 @@ async def run_held_calls(
outcome = "skipped (the tool is no longer available to this step)"
else:
remember(workflow_name, call.targets, run_id=run_id)
- content, is_error = await _call_tool(call.tool, call.arguments, resolved[call.tool])
+ content, is_error = await _call_tool(
+ call.tool, call.arguments, resolved[call.tool], workflow_name,
+ )
outcome = "error" if is_error else "done"
if policy is not None:
policy.approve(call.targets)
diff --git a/packages/core/tests/unit/test_people_contacts.py b/packages/core/tests/unit/test_people_contacts.py
index 6c15f88f..f0359819 100644
--- a/packages/core/tests/unit/test_people_contacts.py
+++ b/packages/core/tests/unit/test_people_contacts.py
@@ -1227,13 +1227,14 @@ def _alerts_db(db: Path, monkeypatch: pytest.MonkeyPatch) -> None:
alert_store.initialize_db(db)
-def _insert(headline: str, *, private: bool) -> int:
+def _insert(headline: str, *, private: bool, routed_to: int | None = None) -> int:
from openexecutive.alerts import store as alert_store
from openexecutive.alerts.models import PRIVATE_ALERT_TAG
alert_id = alert_store.insert_alert(
source="email", external_id=headline, severity="high", headline=headline,
body=f"{headline} body", topic_tags=[PRIVATE_ALERT_TAG] if private else ["customer"],
+ routed_to_person_id=routed_to,
)
assert alert_id is not None
return alert_id
@@ -1362,8 +1363,8 @@ def test_alert_routes_keep_private_alerts_to_the_principal(
from openexecutive.api.routes import alerts as alerts_route
_alerts_db(db, monkeypatch)
- private_id = _insert("Board seat for Jordan", private=True)
- public_id = _insert("Server down", private=False)
+ private_id = _insert("Board seat for Jordan", private=True, routed_to=roster.teammate)
+ public_id = _insert("Server down", private=False, routed_to=roster.teammate)
app = FastAPI()
app.include_router(alerts_route.router)
client = TestClient(app)
@@ -1386,6 +1387,52 @@ def test_alert_routes_keep_private_alerts_to_the_principal(
).status_code == 200
+def test_a_team_member_clears_only_alerts_assigned_to_them(
+ db: Path, roster: SimpleNamespace, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ from openexecutive.alerts import store as alert_store
+ from openexecutive.api.routes import alerts as alerts_route
+
+ _alerts_db(db, monkeypatch)
+ theirs = _insert("Renewal call", private=False, routed_to=roster.teammate)
+ unassigned = _insert("Server down", private=False)
+ owners = _insert("Board prep", private=False, routed_to=roster.principal)
+ app = FastAPI()
+ app.include_router(alerts_route.router)
+ client = TestClient(app)
+ teammate = _as(TEAM_EMAIL)
+
+ for other in (unassigned, owners):
+ refused = client.post(f"/alerts/{other}/ack", json={"status": "dismissed"}, headers=teammate)
+ assert refused.status_code == 403
+ row = alert_store.get_alert(other)
+ assert row is not None and row.status == "unread"
+ # Marking one read is not clearing it.
+ assert client.post(
+ f"/alerts/{unassigned}/ack", json={"status": "read"}, headers=teammate
+ ).status_code == 200
+
+ swept = client.post(
+ "/alerts/bulk-ack", json={"status": "dismissed", "alert_ids": [owners]}, headers=teammate,
+ )
+ assert swept.json() == {"count": 0}
+ assert client.post(
+ "/alerts/bulk-ack", json={"status": "dismissed", "older_than_days": 1}, headers=teammate,
+ ).status_code == 403
+
+ # Their own: cleared, but a mute (which silences the topic for everyone)
+ # is the owner's call.
+ done = client.post(
+ f"/alerts/{theirs}/ack", json={"status": "dismissed", "mute_topic": True}, headers=teammate,
+ )
+ assert done.status_code == 200
+ assert alert_store.list_mutes() == []
+
+ assert client.post(
+ f"/alerts/{owners}/ack", json={"status": "dismissed"}, headers=_as(OWNER_EMAIL)
+ ).status_code == 200
+
+
def test_alert_review_never_touches_a_private_alert(
db: Path, roster: SimpleNamespace, monkeypatch: pytest.MonkeyPatch
) -> None:
diff --git a/packages/core/tests/unit/test_team_raised_alerts.py b/packages/core/tests/unit/test_team_raised_alerts.py
new file mode 100644
index 00000000..cd71d43c
--- /dev/null
+++ b/packages/core/tests/unit/test_team_raised_alerts.py
@@ -0,0 +1,289 @@
+"""Alerts a team member raises from chat, and what they may clear.
+
+`create_alert` takes a free-form source, sender and message id. On a team
+member's turn none of those are theirs to choose: the alert names who raised
+it, claims no id a real alert could arrive with, and never goes out as a
+company-wide broadcast. `ack_alert` lets them clear only what is assigned to
+them. The principal's turns are unchanged.
+"""
+from __future__ import annotations
+
+import asyncio
+import json
+from pathlib import Path
+from typing import Any
+from unittest.mock import MagicMock, patch
+
+import pytest
+
+from openexecutive.alerts import store as alert_store
+from openexecutive.alerts.models import (
+ TEAM_RAISED_SOURCE,
+ AlertChannel,
+ AlertEvent,
+ AlertSeverity,
+ TriageDecision,
+)
+from openexecutive.orchestrator.alert_tools import handle_create_alert
+from openexecutive.orchestrator.schedule_tools import current_session, handle_ack_alert
+from openexecutive.orchestrator.session import Session
+from openexecutive.people.models import Person
+
+_SPEAKER = "openexecutive.orchestrator.department_gate.speaker"
+
+
[email protected](autouse=True)
+def _clear_session() -> Any:
+ token = current_session.set(Session(session_id="s1", trusted_alert_ids={42}))
+ yield
+ current_session.reset(token)
+
+
+def _teammate(person_id: int | None = 7) -> Person:
+ return Person(id=person_id, full_name="Dana Reyes", email="[email protected]", kind="team")
+
+
+def _raise(tool_input: dict[str, Any], speaker: Person | None) -> AlertEvent:
+ scheduled: list[AlertEvent] = []
+ with (
+ patch(_SPEAKER, return_value=speaker),
+ patch("openexecutive.alerts.pipeline.schedule_evaluation", scheduled.append),
+ patch("openexecutive.audit.log_event"),
+ ):
+ out = json.loads(asyncio.run(handle_create_alert(tool_input)))
+ assert out["status"] == "alert_scheduled"
+ assert len(scheduled) == 1
+ return scheduled[0]
+
+
+_POSING = {
+ "subject": "Urgent: wire the funds today",
+ "body": "The CEO needs this done now.",
+ "source": "email",
+ "external_id": "msg-123",
+ "from_address": "[email protected]",
+}
+
+
+def test_team_member_cannot_choose_source_sender_or_id() -> None:
+ event = _raise(dict(_POSING), _teammate())
+
+ assert event.source == TEAM_RAISED_SOURCE
+ assert event.external_id not in ("", "msg-123")
+ assert event.from_ == "[email protected]"
+ assert event.raised_by == "Dana Reyes"
+
+
+def test_team_member_alerts_get_their_own_ids() -> None:
+ a = _raise(dict(_POSING), _teammate())
+ b = _raise(dict(_POSING), _teammate())
+ assert a.external_id != b.external_id
+
+
+def test_unnamed_team_member_is_still_labelled() -> None:
+ event = _raise(dict(_POSING), Person(id=None, full_name="", kind="team"))
+ assert event.source == TEAM_RAISED_SOURCE
+ assert event.raised_by == "a team member"
+
+
+def test_team_member_can_still_route_to_a_person_and_department() -> None:
+ with patch("openexecutive.orchestrator.alert_tools._routable_person", return_value=True):
+ event = _raise(
+ {**_POSING, "department": "finance", "assigned_to_person_id": 9}, _teammate(),
+ )
+ assert event.channel == "department:finance"
+ assert event.routed_to_person_id == 9
+
+
+def test_principal_turn_keeps_the_given_origin() -> None:
+ event = _raise(dict(_POSING), None)
+
+ assert event.source == "email"
+ assert event.external_id == "msg-123"
+ assert event.from_ == "[email protected]"
+ assert event.raised_by == ""
+
+
+# --------------------------------------------------------------------------- #
+# Pipeline
+
+
+def db(tmp_path: Path) -> Path:
+ path = tmp_path / "alerts.db"
+ alert_store.initialize_db(path)
+ return path
+
+
+def _run_pipeline(monkeypatch: pytest.MonkeyPatch, db: Path, event: AlertEvent) -> tuple[list, int | None]:
+ from openexecutive.agents import triage as triage_module
+ from openexecutive.alerts import dispatcher, pipeline
+
+ async def fake_triage(self, event, **kwargs): # noqa: ARG001
+ return TriageDecision(
+ alert=True,
+ severity=AlertSeverity.URGENT,
+ channels=[
+ AlertChannel.PERSISTED,
+ AlertChannel.DEPARTMENT_CHANNEL,
+ AlertChannel.COMPANY_BROADCAST,
+ ],
+ headline="Wire the funds",
+ body="Funds need to go out today.",
+ dedup_key="wire",
+ department_slug="finance",
+ broadcast_integration="slack",
+ )
+
+ sent: list = []
+
+ async def fake_dispatch(alert, channels, **kw): # noqa: ARG001
+ sent.append(list(channels))
+
+ monkeypatch.setattr(triage_module.TriageAgent, "triage", fake_triage)
+ monkeypatch.setattr(dispatcher, "dispatch_all", fake_dispatch)
+ monkeypatch.setattr(
+ pipeline.preferences, "resolve_channels",
+ lambda requested, *a, **k: list(requested), # noqa: ARG005
+ )
+ monkeypatch.setattr(pipeline, "_ground_decision", lambda d, *a: d)
+ _, alert_id = asyncio.run(pipeline.evaluate_and_dispatch(event, db_path=db))
+ return sent, alert_id
+
+
+def test_team_raised_alert_is_never_broadcast_company_wide(monkeypatch, db: Path) -> None:
+ event = AlertEvent(
+ source=TEAM_RAISED_SOURCE, external_id="x1", subject="s", body="b",
+ raised_by="Dana Reyes",
+ )
+ sent, alert_id = _run_pipeline(monkeypatch, db, event)
+
+ assert sent == [[AlertChannel.PERSISTED, AlertChannel.DEPARTMENT_CHANNEL]]
+ row = alert_store.get_alert(alert_id, db_path=db) # type: ignore[arg-type]
+ assert row is not None
+ assert row.body.startswith("Raised by Dana Reyes.")
+ assert row.source == TEAM_RAISED_SOURCE
+
+
+def test_other_alerts_still_broadcast(monkeypatch, db: Path) -> None:
+ event = AlertEvent(source="email", external_id="e1", subject="s", body="b")
+ sent, alert_id = _run_pipeline(monkeypatch, db, event)
+
+ assert AlertChannel.COMPANY_BROADCAST in sent[0]
+ row = alert_store.get_alert(alert_id, db_path=db) # type: ignore[arg-type]
+ assert row is not None
+ assert not row.body.startswith("Raised by")
+
+
+# --------------------------------------------------------------------------- #
+# ack_alert
+
+
+def _ack(routed_to: int | None, speaker: Person | None) -> tuple[dict[str, Any], MagicMock]:
+ alert = MagicMock()
+ alert.id = 42
+ alert.status = "unread"
+ alert.source = "email"
+ alert.routed_to_person_id = routed_to
+ set_status = MagicMock(return_value=True)
+ with (
+ patch(_SPEAKER, return_value=speaker),
+ patch("openexecutive.alerts.store.get_alert", return_value=alert),
+ patch("openexecutive.alerts.models.visible_alert", return_value=True),
+ patch("openexecutive.alerts.store.set_status", set_status),
+ patch("openexecutive.alerts.lifecycle.record_ack_feedback"),
+ patch("openexecutive.audit.log_event"),
+ ):
+ out = json.loads(asyncio.run(handle_ack_alert({"alert_id": 42, "status": "dismissed"})))
+ return out, set_status
+
+
+def test_team_member_can_dismiss_an_alert_assigned_to_them() -> None:
+ out, set_status = _ack(7, _teammate(7))
+ assert out["status"] == "dismissed"
+ set_status.assert_called_once()
+
+
[email protected]("routed_to", [None, 8])
+def test_team_member_cannot_dismiss_others_or_unassigned(routed_to: int | None) -> None:
+ out, set_status = _ack(routed_to, _teammate(7))
+ assert "error" in out
+ set_status.assert_not_called()
+
+
+def test_unmatched_team_member_cannot_dismiss_anything() -> None:
+ out, set_status = _ack(None, Person(id=None, full_name="", kind="team"))
+ assert "error" in out
+ set_status.assert_not_called()
+
+
[email protected]("routed_to", [None, 8])
+def test_principal_can_dismiss_anything(routed_to: int | None) -> None:
+ out, set_status = _ack(routed_to, None)
+ assert out["status"] == "dismissed"
+ set_status.assert_called_once()
+
+
+# --------------------------------------------------------------------------- #
+# Saved workflows and per-person cards
+
+
+def _raise_in_workflow(owner: int | None, person: Person | None) -> AlertEvent:
+ from openexecutive.orchestrator.alert_tools import raised_for_workflow_owner
+
+ current_session.set(None)
+ scheduled: list[AlertEvent] = []
+ with (
+ raised_for_workflow_owner(owner),
+ patch("openexecutive.people.store.get_person", return_value=person),
+ patch("openexecutive.alerts.pipeline.schedule_evaluation", scheduled.append),
+ patch("openexecutive.audit.log_event"),
+ ):
+ asyncio.run(handle_create_alert(dict(_POSING)))
+ return scheduled[0]
+
+
+def test_a_team_members_workflow_raises_alerts_as_them() -> None:
+ event = _raise_in_workflow(7, _teammate(7))
+ assert event.source == TEAM_RAISED_SOURCE
+ assert event.raised_by == "Dana Reyes"
+
+
+def test_the_principals_workflow_keeps_the_given_origin() -> None:
+ event = _raise_in_workflow(1, Person(id=1, full_name="Olivia", kind="team", is_principal=True))
+ assert event.source == "email"
+ assert event.external_id == "msg-123"
+
+
+def test_a_built_in_workflow_keeps_the_given_origin() -> None:
+ assert _raise_in_workflow(None, None).source == "email"
+
+
+def test_action_step_binds_the_workflows_creator(monkeypatch: pytest.MonkeyPatch) -> None:
+ from openexecutive.orchestrator import alert_tools
+ from openexecutive.workflows import action_step, tool_catalog
+
+ seen: list[int | None] = []
+
+ async def handler(_: dict[str, Any]) -> str:
+ seen.append(alert_tools._workflow_owner.get())
+ return "{}"
+
+ monkeypatch.setattr(tool_catalog, "builtin_handler", lambda name: handler)
+ monkeypatch.setattr("openexecutive.workflows.dynamic_store.get_owner", lambda name: 7)
+ info = MagicMock(source="builtin")
+ asyncio.run(action_step._dispatch("oe__create_alert", {}, info, "wf"))
+ assert seen == [7]
+ assert alert_tools._workflow_owner.get() is None
+
+
+def test_one_team_members_alert_never_folds_into_anothers(monkeypatch, db: Path) -> None:
+ def event(who: str, ext: str) -> AlertEvent:
+ return AlertEvent(
+ source=TEAM_RAISED_SOURCE, external_id=ext, subject="s", body="b",
+ raised_by=who, **{"from": f"{who.lower()}@example.com"},
+ )
+
+ _, first = _run_pipeline(monkeypatch, db, event("Dana", "x1"))
+ _, second = _run_pipeline(monkeypatch, db, event("Sam", "x2"))
+ assert first is not None and second is not None and first != second