Skip to content

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

feat(ui): open workflows on a start-here panel (#236)

Rufusab37898471e1
diff --git a/packages/core/openexecutive/architecture/architecture-facts.yaml b/packages/core/openexecutive/architecture/architecture-facts.yaml
index f2a79c33..bd9d9b71 100644
--- a/packages/core/openexecutive/architecture/architecture-facts.yaml
+++ b/packages/core/openexecutive/architecture/architecture-facts.yaml
@@ -4504,7 +4504,16 @@ workflows:
dynamic_user_created: |
Users 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 a Workflow subclass. A dynamic
+ without shipping a Workflow subclass. /jobs opens on a "Start here" panel
+ (components/jobs/StartHere.tsx) that leads to all three: "Start" hands the
+ typed description to the wizard through sessionStorage
+ (lib/workflowStarters.ts, stamped and honoured for 5 minutes) and the
+ wizard sends it as the first message. A `/jobs/new?describe=` link only
+ prefills the composer, so a crafted link can't send text the user never
+ typed; it is also the fallback when storage is blocked, so then nothing
+ is sent until the user presses Start. Below the panel: the user's custom
+ workflows, four ready-made starter picks, and the full built-in list
+ folded behind "Browse all" (`?browse=1`). A dynamic
workflow is a stored JSON definition (the `dynamic_workflows` table;
`openexecutive.workflows.dynamic_store`) interpreted at runtime by ONE
generic engine, `openexecutive.workflows.dynamic.DynamicWorkflow`, which
diff --git a/packages/core/openexecutive/architecture/prebuilt/workflows.json b/packages/core/openexecutive/architecture/prebuilt/workflows.json
index bd1020fc..a5e62687 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### 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). Section order: top call → what changed → handled overnight → needs you (new only) → waiting on → at risk. 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 → 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### 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.\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\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 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. 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. 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. `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. 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**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`) — 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**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. 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` catalog files them under a **System** chip instead of the default view. They stay runnable by hand.\n\n**Workflows vs. playbooks.** `/jobs` has three tabs: **Catalog**, **Runs**, and **Playbooks** (`?tab=playbooks`; `/skills` redirects there). 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, the chat tools refuse to edit or delete any playbook a workflow follows, or to create one under a name a workflow still follows after its playbook was deleted; if the workflow list can't be read they refuse (`unverifiable`) rather than assume nothing follows it. Only a person on the Playbooks tab can change what a workflow follows, and 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 and every custom workflow, switched-off ones included (turning one on approves its definition, so what it follows must not have changed from chat meanwhile); 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}`. 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.",
+ "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### 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). Section order: top call → what changed → handled overnight → needs you (new only) → waiting on → at risk. 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 → 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### 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.\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\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 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. 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. 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. `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`). 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**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`) — 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**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. 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**Workflows vs. playbooks.** `/jobs` has three tabs: **Build** (`?tab=catalog`, the default), **Runs**, and **Playbooks** (`?tab=playbooks`; `/skills` redirects there). 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, the chat tools refuse to edit or delete any playbook a workflow follows, or to create one under a name a workflow still follows after its playbook was deleted; if the workflow list can't be read they refuse (`unverifiable`) rather than assume nothing follows it. Only a person on the Playbooks tab can change what a workflow follows, and 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 and every custom workflow, switched-off ones included (turning one on approves its definition, so what it follows must not have changed from chat meanwhile); 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}`. 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.",
"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-09-25T19:50:17Z"
}
diff --git a/packages/core/openexecutive/guide/prebuilt/jobs.json b/packages/core/openexecutive/guide/prebuilt/jobs.json
index 036d32a8..0dd0aa19 100644
--- a/packages/core/openexecutive/guide/prebuilt/jobs.json
+++ b/packages/core/openexecutive/guide/prebuilt/jobs.json
@@ -1,7 +1,7 @@
{
"section_id": "jobs",
"title": "Workflows",
- "markdown": "**What it is:** Structured, multi-step workflows that produce a *deliverable* — a board deck, a go-to-market plan, a performance review — or *get something done* with your connected tools, like filing emailed bills into a spreadsheet, rather than just a chat reply.\n\n**What it does:**\n\n- Browse the workflow catalog as compact cards; filter by area with the chips at the top (**Custom** holds yours, **System** holds the workflows Open Executive runs on its own, like the morning brief).\n- Start a run and watch it stream its progress step by step.\n- See your runs split into **Active**, **Awaiting sign-off**, **Done**, and **Error**, and search them by name.\n- Create your own **custom workflow** by describing it: the assistant asks a few clarifying questions, then drafts it for you to review.\n- Let a workflow **use tools** — Gmail, Google Sheets, Drive and anything else connected — to actually do the work, not just write about it.\n- Put a custom workflow on a **schedule** (e.g. every Monday at 09:00) so it runs without being asked.\n- Each finished run produces a document you can read and keep.\n- Manage **Playbooks** on their own tab — the methods and templates the Executive follows in chat and inside workflows (see **Playbooks** in this guide). A workflow page lists the playbooks it follows, and a custom workflow's specialist step can **Follow a playbook** too.\n\n**How to use:**\n\n*Run a workflow*\n\n1. Open **Workflows** and click a workflow in the **Catalog** — narrow the list with the chips or the search box.\n2. Fill in the fields (required ones have a red \\*). **Insert example** or **Load sample run** fills in realistic values if you just want to try it.\n3. Click **Continue**, then **Run workflow**. Progress streams step by step; when it finishes you land on the run page, with **Copy** and **Download .md**.\n\n*Build your own*\n\n1. Click **+ New workflow** and describe the job in plain words — what it should produce, who it's for, and how often — or pick one of the starter suggestions.\n2. Answer the clarifying questions (usually two or three) by typing or by clicking a suggested answer. **Draft it now** skips the rest.\n3. Review the draft: its steps, schedule, what you fill in each run, the assumptions it made, and the **tools** each action step will use (ones that can change things are marked).\n4. Click **Create workflow** — this approves those tools, and runs use them without asking again — or **Keep refining** and type what to change, or **Edit details** to fine-tune it field by field. It appears under **Custom** in the Catalog, with **Edit** and **Delete**.\n\n*Advanced editor* — reached from **Edit** on a custom workflow, **Edit details** on a draft, or **Use the advanced editor**:\n\n1. **Details:** a unique **Name** in snake_case (e.g. `weekly_competitor_watch`; 3–49 characters, starting with a letter), a title, description, section and estimated minutes.\n2. **Input fields:** click **+ Add field** for anything the person running it must supply. Use a field in a step's goal as `{field_name}`.\n3. **Steps:** add **+ Specialist** steps (pick a specialist, write its goal), **+ Action** steps (write what to get done and where, then **Search tools** and **+ Add** the ones it may use), and, if someone must sign off, an **+ Approval gate** (who to ask, the question, a timeout, and what happens on timeout). New steps are added at the bottom — use **↑** to move them above the synthesis step, which pulls everything together and must stay last; put an approval gate just before it. Up to 12 steps and 16 input fields.\n4. **Schedule (optional):** tick **Run on a schedule**, enter a cadence, and choose who the result is delivered to. Scheduled workflows can't have required inputs or approval gates.\n5. Click **Create workflow** (**Save changes** when editing).\n\nCadences are written like this (times are UTC): `daily@09:00`, `weekly@mon@09:00`, or `quarterly@01-09:00` (the 1st of January, April, July and October).\n\n*Workflows that use tools* — describe the job and where things live, e.g. *\"Every morning, find the bills I email you, read each PDF and add a row (vendor, amount, due date) to my Bill tracker sheet.\"* The assistant finds the right tools (here Gmail search and attachments, reading PDFs, and appending rows to Google Sheets) and asks about anything it needs, like which sheet. While a run works, the run page shows each tool as it's used, and the result lists every action taken. A workflow can only use the tools you approved, and every tool call is recorded in the audit log. You can also ask for one in chat: a workflow that uses tools is saved **switched off**, and the Executive gives you a link. It shows under *Waiting for your approval* at the top of the catalog; open it, check the steps and tools, and click **Turn on workflow** — until then it can't run or follow a schedule.\n\n*Signing off a paused run* — when a run reaches an approval gate it moves to **Awaiting sign-off** and the approver is messaged directly. They answer by replying on Slack, Discord or Telegram — \"yes\", \"LGTM\", \"no\", \"not now\" — or with **Approve** / **Decline** on the run page (the principal can answer any sign-off there too). \"No\" or \"not now\" ends the run.\n\n*The first write somewhere new* — a workflow that uses tools picks where to write each time it runs (this month's tab, the sender of an invoice, a new doc per client). The first time it wants to write somewhere it hasn't written before — a different spreadsheet, a new recipient — that one write waits, the rest of the run carries on, and whoever created the workflow is asked: yes lets it write there now and in future runs, no skips it. The places a workflow may write without asking are listed under **Approved targets** on its page; remove one and it asks again.\n\n**From chat:**\n\n- *\"What workflows can you run?\"* or *\"Run a competitive teardown of Acme.\"* — the Executive runs it and brings the result back into the conversation.\n- *\"Build me a workflow called weekly_competitor_watch: the CMO checks our top three competitors for pricing and product changes, then summarise. Run it every Monday at 09:00 UTC and send it to me.\"* — the Executive drafts it, shows you a summary, and saves it once you say yes.\n\n*Note: outputs are listed in Documents. Ask OE can also fill in the advanced editor form for you.*",
+ "markdown": "**What it is:** Structured, multi-step workflows that produce a *deliverable* — a board deck, a go-to-market plan, a performance review — or *get something done* with your connected tools, like filing emailed bills into a spreadsheet, rather than just a chat reply.\n\n**What it does:**\n\n- Start from **Start here** at the top of the **Build** tab: say what you want done, and pick how to build it.\n- Your own workflows sit under **Your workflows**; below them are a few **ready-made** picks, and **Browse all** opens the full list with search and area chips (**System** holds the workflows Open Executive runs on its own, like the morning brief).\n- Start a run and watch it stream its progress step by step.\n- See your runs split into **Active**, **Awaiting sign-off**, **Done**, and **Error**, and search them by name.\n- Create your own **custom workflow** by describing it: the assistant asks a few clarifying questions, then drafts it for you to review.\n- Let a workflow **use tools** — Gmail, Google Sheets, Drive and anything else connected — to actually do the work, not just write about it.\n- Put a custom workflow on a **schedule** (e.g. every Monday at 09:00) so it runs without being asked.\n- Each finished run produces a document you can read and keep.\n- Manage **Playbooks** on their own tab — the methods and templates the Executive follows in chat and inside workflows (see **Playbooks** in this guide). A workflow page lists the playbooks it follows, and a custom workflow's specialist step can **Follow a playbook** too.\n\n**How to use:**\n\n*Run a workflow*\n\n1. Open **Workflows** and click one of the ready-made picks on the **Build** tab, or **Browse all ready-made workflows** and narrow the list with the chips or the search box.\n2. Fill in the fields (required ones have a red \\*). **Insert example** or **Load sample run** fills in realistic values if you just want to try it.\n3. Click **Continue**, then **Run workflow**. Progress streams step by step; when it finishes you land on the run page, with **Copy** and **Download .md**.\n\n*Build your own*\n\n1. Under **Start here**, describe the job in plain words — what it should produce, who it's for, and how often — or pick one of the suggestions, then click **Start**. (**+ New workflow** opens the same conversation; **Step by step** opens the advanced editor, and **Talk it through in chat** starts a chat.)\n2. Answer the clarifying questions (usually two or three) by typing or by clicking a suggested answer. **Draft it now** skips the rest.\n3. Review the draft: its steps, schedule, what you fill in each run, the assumptions it made, and the **tools** each action step will use (ones that can change things are marked).\n4. Click **Create workflow** — this approves those tools, and runs use them without asking again — or **Keep refining** and type what to change, or **Edit details** to fine-tune it field by field. It appears under **Your workflows**, with **Edit** and **Delete**.\n\n*Advanced editor* — reached from **Step by step** under **Start here**, **Edit** on a custom workflow, **Edit details** on a draft, or **Use the advanced editor**:\n\n1. **Details:** a unique **Name** in snake_case (e.g. `weekly_competitor_watch`; 3–49 characters, starting with a letter), a title, description, section and estimated minutes.\n2. **Input fields:** click **+ Add field** for anything the person running it must supply. Use a field in a step's goal as `{field_name}`.\n3. **Steps:** add **+ Specialist** steps (pick a specialist, write its goal), **+ Action** steps (write what to get done and where, then **Search tools** and **+ Add** the ones it may use), and, if someone must sign off, an **+ Approval gate** (who to ask, the question, a timeout, and what happens on timeout). New steps are added at the bottom — use **↑** to move them above the synthesis step, which pulls everything together and must stay last; put an approval gate just before it. Up to 12 steps and 16 input fields.\n4. **Schedule (optional):** tick **Run on a schedule**, enter a cadence, and choose who the result is delivered to. Scheduled workflows can't have required inputs or approval gates.\n5. Click **Create workflow** (**Save changes** when editing).\n\nCadences are written like this (times are UTC): `daily@09:00`, `weekly@mon@09:00`, or `quarterly@01-09:00` (the 1st of January, April, July and October).\n\n*Workflows that use tools* — describe the job and where things live, e.g. *\"Every morning, find the bills I email you, read each PDF and add a row (vendor, amount, due date) to my Bill tracker sheet.\"* The assistant finds the right tools (here Gmail search and attachments, reading PDFs, and appending rows to Google Sheets) and asks about anything it needs, like which sheet. While a run works, the run page shows each tool as it's used, and the result lists every action taken. A workflow can only use the tools you approved, and every tool call is recorded in the audit log. You can also ask for one in chat: a workflow that uses tools is saved **switched off**, and the Executive gives you a link. It shows under *Waiting for your approval* at the top of the **Build** tab; open it, check the steps and tools, and click **Turn on workflow** — until then it can't run or follow a schedule.\n\n*Signing off a paused run* — when a run reaches an approval gate it moves to **Awaiting sign-off** and the approver is messaged directly. They answer by replying on Slack, Discord or Telegram — \"yes\", \"LGTM\", \"no\", \"not now\" — or with **Approve** / **Decline** on the run page (the principal can answer any sign-off there too). \"No\" or \"not now\" ends the run.\n\n*The first write somewhere new* — a workflow that uses tools picks where to write each time it runs (this month's tab, the sender of an invoice, a new doc per client). The first time it wants to write somewhere it hasn't written before — a different spreadsheet, a new recipient — that one write waits, the rest of the run carries on, and whoever created the workflow is asked: yes lets it write there now and in future runs, no skips it. The places a workflow may write without asking are listed under **Approved targets** on its page; remove one and it asks again.\n\n**From chat:**\n\n- *\"What workflows can you run?\"* or *\"Run a competitive teardown of Acme.\"* — the Executive runs it and brings the result back into the conversation.\n- *\"Build me a workflow called weekly_competitor_watch: the CMO checks our top three competitors for pricing and product changes, then summarise. Run it every Monday at 09:00 UTC and send it to me.\"* — the Executive drafts it, shows you a summary, and saves it once you say yes.\n\n*Note: outputs are listed in Documents. Ask OE can also fill in the advanced editor form for you.*",
"mermaid": null,
"generated_at": "2026-09-24T00:00:00Z"
}
diff --git a/packages/core/tests/unit/test_top_three.py b/packages/core/tests/unit/test_top_three.py
index 9f21730e..02607076 100644
--- a/packages/core/tests/unit/test_top_three.py
+++ b/packages/core/tests/unit/test_top_three.py
@@ -399,6 +399,10 @@ def test_solo_brief_with_a_calendar_gets_slots_and_the_days_events(
_seed_solo_state()
calls = _stub_brief(monkeypatch)
_connect(monkeypatch, _Gateway(_TEXT_REPLY))
+ # Slots are only suggested on business days; don't depend on today's date.
+ monkeypatch.setattr(
+ "openexecutive.orchestrator.calendar_tools.is_business_day", lambda _d: True
+ )
_brief()
(call,) = calls
context = call["messages"][0]["content"]
diff --git a/packages/ui/src/app/jobs/page.tsx b/packages/ui/src/app/jobs/page.tsx
index e0d3f0f1..03d7d379 100644
--- a/packages/ui/src/app/jobs/page.tsx
+++ b/packages/ui/src/app/jobs/page.tsx
@@ -23,6 +23,7 @@ import {
listWorkflows,
} from "@/lib/api";
import PlaybooksBrowser from "@/components/jobs/PlaybooksBrowser";
+import StartHere from "@/components/jobs/StartHere";
import {
RunBucket,
runStatusBadgeColor,
@@ -40,9 +41,10 @@ const SECTION_ORDER: WorkflowSection[] = [
"Operating Cadence",
];
-// Chip labels. "All" hides the background (system-run) jobs; they get their
-// own chip so the default view is only what a user starts by hand.
-type SectionFilter = "all" | "custom" | "system" | WorkflowSection;
+// Chip labels for the ready-made list. "All" hides the background
+// (system-run) jobs; they get their own chip so the default view is only what
+// a user starts by hand. Custom workflows have their own list above it.
+type SectionFilter = "all" | "system" | WorkflowSection;
const SECTION_CHIP_LABEL: Record<WorkflowSection, string> = {
Board: "Board",
@@ -57,7 +59,6 @@ const SECTION_CHIP_LABEL: Record<WorkflowSection, string> = {
function isSectionFilter(v: string | null): v is SectionFilter {
return (
v === "all" ||
- v === "custom" ||
v === "system" ||
(SECTION_ORDER as string[]).includes(v ?? "")
);
@@ -68,10 +69,30 @@ function inSectionFilter(w: WorkflowMeta, f: SectionFilter): boolean {
if (f === "system") return !!w.background;
if (w.background) return false;
if (f === "all") return true;
- if (f === "custom") return !!w.is_custom;
- return !w.is_custom && w.section === f;
+ return w.section === f;
}
+// Ready-made workflows shown up front, each with a plain line on when to
+// use it. The full list sits behind "Browse all".
+const STARTER_PICKS: { name: string; useFor: string }[] = [
+ {
+ name: "investor_update",
+ useFor: "Send investors a short monthly email: highlights, numbers, asks.",
+ },
+ {
+ name: "board_prep",
+ useFor: "Get a full board deck drafted before your next meeting.",
+ },
+ {
+ name: "mbr",
+ useFor: "Review last month against plan and flag what needs a decision.",
+ },
+ {
+ name: "competitive_teardown",
+ useFor: "Size up a competitor and get battle-card material for sales.",
+ },
+];
+
// Runs shown per workflow group before "Show more".
const RUNS_PER_GROUP = 5;
@@ -139,6 +160,9 @@ function JobsPageInner() {
const status: RunStatus | null = isStatus(statusParam) ? statusParam : null;
const sectionParam = searchParams.get("section");
const section: SectionFilter = isSectionFilter(sectionParam) ? sectionParam : "all";
+ // The full ready-made list is folded behind "Browse all"; a chip in the URL
+ // means someone was already browsing it.
+ const browsing = searchParams.get("browse") === "1" || section !== "all";
const [workflows, setWorkflows] = useState<WorkflowMeta[]>([]);
// Custom workflows that are switched off (e.g. saved from chat with tool
@@ -152,6 +176,7 @@ function JobsPageInner() {
const [runsQuery, setRunsQuery] = useState("");
const [collapsed, setCollapsed] = useState<Record<string, boolean>>({});
const [expanded, setExpanded] = useState<Record<string, boolean>>({});
+ const readyMadeRef = useRef<HTMLElement>(null);
const refresh = useCallback(async () => {
setError(null);
@@ -193,6 +218,11 @@ function JobsPageInner() {
[pathname, router, searchParams]
);
+ const browseReadyMade = useCallback(() => {
+ setParam({ browse: "1" });
+ readyMadeRef.current?.scrollIntoView({ behavior: "smooth", block: "start" });
+ }, [setParam]);
+
const runCounts = useMemo(() => {
const c = { active: 0, awaiting: 0, done: 0, error: 0 };
for (const r of runs) c[runStatusBucket(r.status)]++;
@@ -246,8 +276,7 @@ function JobsPageInner() {
<TabButton
active={tab === "catalog"}
onClick={() => setParam({ tab: "catalog" })}
- label="Catalog"
- count={workflows.length}
+ label="Build"
/>
<TabButton
active={tab === "runs"}
@@ -274,15 +303,48 @@ function JobsPageInner() {
<OffWorkflowsStrip items={offWorkflows} onDelete={handleDeleteCustom} />
)}
+ {tab === "catalog" && (
+ <StartHere onBrowseReadyMade={browseReadyMade} />
+ )}
+
{!loading && tab === "catalog" && (
- <CatalogView
- workflows={workflows}
- query={catalogQuery}
- onQueryChange={setCatalogQuery}
- section={section}
- onSectionChange={(s) => setParam({ section: s === "all" ? null : s })}
- onDeleteCustom={handleDeleteCustom}
- />
+ <>
+ <YourWorkflows
+ workflows={workflows.filter((w) => w.is_custom && !w.background)}
+ onDeleteCustom={handleDeleteCustom}
+ />
+ <section ref={readyMadeRef} className="scroll-mt-4">
+ <h2 className="text-sm font-semibold text-fg">Ready-made workflows</h2>
+ <p className="mb-3 text-xs text-fg-muted">
+ Templates you can run as they are: fill in a few details and go.
+ </p>
+ {browsing ? (
+ <>
+ <CatalogView
+ workflows={workflows.filter((w) => !w.is_custom)}
+ query={catalogQuery}
+ onQueryChange={setCatalogQuery}
+ section={section}
+ onSectionChange={(s) =>
+ setParam({ browse: "1", section: s === "all" ? null : s })
+ }
+ />
+ <button
+ type="button"
+ onClick={() => setParam({ browse: null, section: null })}
+ className="mt-4 text-xs text-indigo-400 hover:text-indigo-300"
+ >
+ Show fewer
+ </button>
+ </>
+ ) : (
+ <StarterPicks
+ workflows={workflows}
+ onBrowseAll={() => setParam({ browse: "1" })}
+ />
+ )}
+ </section>
+ </>
)}
{tab === "playbooks" && (
@@ -406,46 +468,15 @@ function OffWorkflowsStrip({
);
}
-function CatalogView({
- workflows,
- query,
- onQueryChange,
- section,
- onSectionChange,
+function WorkflowCard({
+ workflow: w,
onDeleteCustom,
}: {
- workflows: WorkflowMeta[];
- query: string;
- onQueryChange: (v: string) => void;
- section: SectionFilter;
- onSectionChange: (s: SectionFilter) => void;
- onDeleteCustom: (name: string) => void;
+ workflow: WorkflowMeta;
+ onDeleteCustom?: (name: string) => void;
}) {
- const matching = workflows.filter((w) =>
- matchesQuery(query, w.title, w.description)
- );
- const known = new Set<string>(SECTION_ORDER);
- const chips: { key: SectionFilter; label: string; count: number }[] = [
- { key: "all" as SectionFilter, label: "All", count: 0 },
- { key: "custom" as SectionFilter, label: "Custom", count: 0 },
- ...SECTION_ORDER.map((s) => ({
- key: s as SectionFilter,
- label: SECTION_CHIP_LABEL[s],
- count: 0,
- })),
- { key: "system" as SectionFilter, label: "System", count: 0 },
- ]
- .map((c) => ({ ...c, count: matching.filter((w) => inSectionFilter(w, c.key)).length }))
- // Keep the active chip even at zero so the selection stays visible.
- .filter((c) => c.key === "all" || c.key === section || c.count > 0);
-
- const visible = matching.filter((w) => inSectionFilter(w, section));
-
- const renderCard = (w: WorkflowMeta) => (
- <div
- key={w.name}
- className="group relative min-w-0 rounded-md border border-line bg-surface/40 hover:border-line-strong hover:bg-surface-elevated/40 transition"
- >
+ return (
+ <div className="group relative min-w-0 rounded-md border border-line bg-surface/40 hover:border-line-strong hover:bg-surface-elevated/40 transition">
<Link
href={`/jobs/${encodeURIComponent(w.name)}`}
className="block px-3 py-2.5"
@@ -457,7 +488,7 @@ function CatalogView({
{w.steps.length} steps · ~{w.estimated_minutes} min
</p>
</Link>
- {w.is_custom && (
+ {w.is_custom && onDeleteCustom && (
<div className="absolute top-2 right-2 flex items-center gap-2 text-[11px]">
<Link
href={`/jobs/new?edit=${encodeURIComponent(w.name)}`}
@@ -476,24 +507,137 @@ function CatalogView({
)}
</div>
);
+}
- const grid = (items: WorkflowMeta[]) => (
- <div className="grid sm:grid-cols-2 lg:grid-cols-3 gap-2">{items.map(renderCard)}</div>
+function WorkflowGrid({
+ items,
+ onDeleteCustom,
+}: {
+ items: WorkflowMeta[];
+ onDeleteCustom?: (name: string) => void;
+}) {
+ return (
+ <div className="grid sm:grid-cols-2 lg:grid-cols-3 gap-2">
+ {items.map((w) => (
+ <WorkflowCard key={w.name} workflow={w} onDeleteCustom={onDeleteCustom} />
+ ))}
+ </div>
);
+}
+
+/** The user's own workflows, above the ready-made list. Hidden until they have one. */
+function YourWorkflows({
+ workflows,
+ onDeleteCustom,
+}: {
+ workflows: WorkflowMeta[];
+ onDeleteCustom: (name: string) => void;
+}) {
+ if (workflows.length === 0) return null;
+ return (
+ <section className="mb-6">
+ <h2 className="mb-2 text-sm font-semibold text-fg">
+ Your workflows
+ <span className="ml-2 text-xs font-normal text-fg-subtle">{workflows.length}</span>
+ </h2>
+ <WorkflowGrid items={workflows} onDeleteCustom={onDeleteCustom} />
+ </section>
+ );
+}
+
+/** A few ready-made workflows with a plain "use this to" line, and the way into the rest. */
+function StarterPicks({
+ workflows,
+ onBrowseAll,
+}: {
+ workflows: WorkflowMeta[];
+ onBrowseAll: () => void;
+}) {
+ const byName = new Map(workflows.map((w) => [w.name, w] as const));
+ const picks = STARTER_PICKS.flatMap((p) => {
+ const w = byName.get(p.name);
+ return w && !w.is_custom ? [{ workflow: w, useFor: p.useFor }] : [];
+ });
+ const total = workflows.filter((w) => !w.is_custom && !w.background).length;
+ return (
+ <div>
+ {picks.length > 0 && (
+ <div className="grid gap-2 sm:grid-cols-2">
+ {picks.map(({ workflow: w, useFor }) => (
+ <Link
+ key={w.name}
+ href={`/jobs/${encodeURIComponent(w.name)}`}
+ className="rounded-md border border-line bg-surface/40 px-3 py-2.5 hover:border-line-strong hover:bg-surface-elevated/40 transition"
+ >
+ <span className="block text-sm font-medium text-fg">{w.title}</span>
+ <span className="mt-0.5 block text-xs text-fg-muted">{useFor}</span>
+ <span className="mt-1 block text-[11px] text-fg-subtle">
+ ~{w.estimated_minutes} min
+ </span>
+ </Link>
+ ))}
+ </div>
+ )}
+ {total > 0 ? (
+ <button
+ type="button"
+ onClick={onBrowseAll}
+ className="mt-3 text-sm text-indigo-400 hover:text-indigo-300"
+ >
+ Browse all {total} ready-made workflows →
+ </button>
+ ) : (
+ <div className="text-sm text-fg-muted">No ready-made workflows available.</div>
+ )}
+ </div>
+ );
+}
+
+/** The full ready-made list: search, section chips, and grouped cards. */
+function CatalogView({
+ workflows,
+ query,
+ onQueryChange,
+ section,
+ onSectionChange,
+}: {
+ workflows: WorkflowMeta[];
+ query: string;
+ onQueryChange: (v: string) => void;
+ section: SectionFilter;
+ onSectionChange: (s: SectionFilter) => void;
+}) {
+ const matching = workflows.filter((w) =>
+ matchesQuery(query, w.title, w.description)
+ );
+ const known = new Set<string>(SECTION_ORDER);
+ const chips: { key: SectionFilter; label: string; count: number }[] = [
+ { key: "all" as SectionFilter, label: "All", count: 0 },
+ ...SECTION_ORDER.map((s) => ({
+ key: s as SectionFilter,
+ label: SECTION_CHIP_LABEL[s],
+ count: 0,
+ })),
+ { key: "system" as SectionFilter, label: "System", count: 0 },
+ ]
+ .map((c) => ({ ...c, count: matching.filter((w) => inSectionFilter(w, c.key)).length }))
+ // Keep the active chip even at zero so the selection stays visible.
+ .filter((c) => c.key === "all" || c.key === section || c.count > 0);
+
+ const visible = matching.filter((w) => inSectionFilter(w, section));
// Under "All", keep light section headings so the list stays scannable;
// any single chip is already one group, so it renders as a flat grid.
const grouped: { label: string; items: WorkflowMeta[] }[] =
section === "all"
? [
- { label: "Custom", items: visible.filter((w) => w.is_custom) },
...SECTION_ORDER.map((s) => ({
label: s as string,
- items: visible.filter((w) => !w.is_custom && w.section === s),
+ items: visible.filter((w) => w.section === s),
})),
{
label: "Other",
- items: visible.filter((w) => !w.is_custom && !known.has(w.section)),
+ items: visible.filter((w) => !known.has(w.section)),
},
].filter((g) => g.items.length > 0)
: [];
@@ -504,7 +648,7 @@ function CatalogView({
<SearchInput
value={query}
onChange={onQueryChange}
- placeholder="Search workflows…"
+ placeholder="Search ready-made workflows…"
/>
</div>
<div className="mb-4 flex flex-wrap gap-1.5">
@@ -541,12 +685,12 @@ function CatalogView({
{g.items.length}
</span>
</h2>
- {grid(g.items)}
+ <WorkflowGrid items={g.items} />
</div>
))}
</div>
) : (
- grid(visible)
+ <WorkflowGrid items={visible} />
)}
</div>
);
@@ -762,8 +906,8 @@ export default function JobsPage() {
<div className="min-w-0">
<h1 className="text-xl font-semibold text-fg">Workflows</h1>
<p className="text-sm text-fg-muted">
- Workflows are the jobs that run and produce a deliverable;
- playbooks are the methods the Executive follows.
+ Jobs the Executive runs for you, start to finish — each one
+ ends in a finished document or a task done.
</p>
</div>
<Link
diff --git a/packages/ui/src/components/jobs/StartHere.tsx b/packages/ui/src/components/jobs/StartHere.tsx
new file mode 100644
index 00000000..861e52e2
--- /dev/null
+++ b/packages/ui/src/components/jobs/StartHere.tsx
@@ -0,0 +1,123 @@
+"use client";
+
+import { useRef, useState } from "react";
+import Link from "next/link";
+import { useRouter } from "next/navigation";
+import { WORKFLOW_STARTERS, stashWorkflowDescription } from "@/lib/workflowStarters";
+
+const CHAT_DRAFT = "Help me set up a workflow that ";
+
+/**
+ * The front door of /jobs: ask what the user wants done, and offer the ways
+ * to build it — describe it (the wizard), step by step (the advanced
+ * editor), in chat, or from a ready-made workflow further down the page.
+ */
+export default function StartHere({ onBrowseReadyMade }: { onBrowseReadyMade: () => void }) {
+ const router = useRouter();
+ const [text, setText] = useState("");
+ const inputRef = useRef<HTMLTextAreaElement>(null);
+
+ const start = () => {
+ const message = text.trim();
+ if (!message) return;
+ router.push(
+ stashWorkflowDescription(message)
+ ? "/jobs/new"
+ : `/jobs/new?describe=${encodeURIComponent(message)}`
+ );
+ };
+
+ return (
+ <section className="mb-6 rounded-xl border border-line bg-surface-elevated p-5 sm:p-6">
+ <p className="text-[10px] font-semibold uppercase tracking-wide text-indigo-300">
+ Start here
+ </p>
+ <h2 className="mt-1 text-lg font-semibold text-fg">What do you want to get done?</h2>
+ <p className="mt-1 text-sm text-fg-muted">
+ A workflow is a job you want done regularly or on demand — a report, a
+ review, a check-in. Describe it in a sentence; I&rsquo;ll ask a few
+ questions and set it up for you to review.
+ </p>
+
+ <div className="mt-4">
+ <textarea
+ ref={inputRef}
+ value={text}
+ onChange={(e) => setText(e.target.value)}
+ onKeyDown={(e) => {
+ if (e.key === "Enter" && !e.shiftKey) {
+ e.preventDefault();
+ start();
+ }
+ }}
+ rows={2}
+ aria-label="Describe the workflow you want"
+ placeholder="e.g. Every Monday, send me what our top competitors shipped"
+ className="w-full rounded-lg border border-line-strong bg-surface-overlay px-3 py-2 text-sm text-fg placeholder-fg-subtle focus:outline-none focus:ring-2 focus:ring-indigo-500/50 focus:border-indigo-500/50 resize-none transition-colors"
+ />
+ <div className="mt-2 flex flex-wrap items-center gap-2">
+ <button
+ type="button"
+ onClick={start}
+ disabled={!text.trim()}
+ className="rounded-md bg-indigo-600 px-4 py-1.5 text-sm font-medium text-white hover:bg-indigo-500 disabled:opacity-40 transition-colors"
+ >
+ Start
+ </button>
+ <span className="text-xs text-fg-subtle">or try one:</span>
+ {WORKFLOW_STARTERS.map((s) => (
+ <button
+ key={s}
+ type="button"
+ onClick={() => {
+ setText(s);
+ inputRef.current?.focus();
+ }}
+ className="rounded-full border border-line px-3 py-1 text-left text-xs text-fg-muted hover:text-fg hover:border-line-strong transition"
+ >
+ {s}
+ </button>
+ ))}
+ </div>
+ </div>
+
+ <p className="mt-5 mb-2 text-xs font-semibold uppercase tracking-wide text-fg-subtle">
+ Or build it another way
+ </p>
+ <div className="grid gap-2 sm:grid-cols-3">
+ <WayCard
+ href="/jobs/new?mode=advanced"
+ title="Step by step"
+ body="Pick each step yourself: which specialist, which tools, where you sign off."
+ />
+ <WayCard
+ href={`/?new=1&draft=${encodeURIComponent(CHAT_DRAFT)}`}
+ title="Talk it through in chat"
+ body="Explain it to the Executive in your own words and it will draft the workflow."
+ />
+ <button
+ type="button"
+ onClick={onBrowseReadyMade}
+ className="rounded-lg border border-line bg-surface/40 px-3 py-2.5 text-left hover:border-line-strong hover:bg-surface-elevated/40 transition"
+ >
+ <span className="block text-sm font-medium text-fg">Start from a ready-made one</span>
+ <span className="mt-0.5 block text-xs text-fg-muted">
+ Board decks, investor updates, business reviews and more — run as-is.
+ </span>
+ </button>
+ </div>
+ </section>
+ );
+}
+
+function WayCard({ href, title, body }: { href: string; title: string; body: string }) {
+ return (
+ <Link
+ href={href}
+ className="rounded-lg border border-line bg-surface/40 px-3 py-2.5 hover:border-line-strong hover:bg-surface-elevated/40 transition"
+ >
+ <span className="block text-sm font-medium text-fg">{title}</span>
+ <span className="mt-0.5 block text-xs text-fg-muted">{body}</span>
+ </Link>
+ );
+}
diff --git a/packages/ui/src/components/jobs/WorkflowWizard.tsx b/packages/ui/src/components/jobs/WorkflowWizard.tsx
index 82185d14..308217ca 100644
--- a/packages/ui/src/components/jobs/WorkflowWizard.tsx
+++ b/packages/ui/src/components/jobs/WorkflowWizard.tsx
@@ -12,14 +12,11 @@ import {
sendWorkflowDesignerMessage,
startWorkflowDesigner,
} from "@/lib/api";
+import { WORKFLOW_STARTERS, takeWorkflowDescription } from "@/lib/workflowStarters";
import WorkflowDraftReview from "./WorkflowDraftReview";
-const STARTERS = [
- "A weekly competitor digest sent to me every Monday morning",
- "A board pre-read I kick off before each meeting, with the CFO signing off",
- "A monthly hiring-plan review across all open roles",
- "A launch readiness check I run before every product release",
-];
+// Same cap chat applies to its `?draft=` prefill.
+const MAX_DESCRIBE_PARAM_CHARS = 2000;
/**
* Conversational "New workflow": describe the job, answer a few clarifying
@@ -44,6 +41,15 @@ export default function WorkflowWizard() {
// The session this component already holds, so mirroring it into the URL
// does not trigger a redundant resume fetch.
const heldSessionRef = useRef<string | null>(null);
+ // A turn can finish after the user has left (e.g. "Back to workflows" while
+ // the first message is still in flight); don't pull them back via the URL.
+ const mountedRef = useRef(true);
+ useEffect(() => {
+ mountedRef.current = true;
+ return () => {
+ mountedRef.current = false;
+ };
+ }, []);
useEffect(() => {
listPeople()
@@ -76,7 +82,7 @@ export default function WorkflowWizard() {
const next = await op();
setTurn(next);
setInput("");
- if (next.session_id !== heldSessionRef.current) {
+ if (mountedRef.current && next.session_id !== heldSessionRef.current) {
heldSessionRef.current = next.session_id;
router.replace(`${pathname}?session=${encodeURIComponent(next.session_id)}`, {
scroll: false,
@@ -93,6 +99,30 @@ export default function WorkflowWizard() {
[pathname, router]
);
+ // Arriving from the "Start here" panel on /jobs: send what the user typed
+ // there as the first message. A `?describe=` link only fills the composer.
+ // The ref keeps StrictMode's second effect run from starting a second session.
+ const describeParam = searchParams.get("describe");
+ const handoffRef = useRef(false);
+ useEffect(() => {
+ if (handoffRef.current) return;
+ handoffRef.current = true;
+ // Always consumed, so a leftover never fires on a later visit.
+ const handedOff = takeWorkflowDescription()?.trim();
+ if (resumeId) return;
+ if (handedOff) {
+ // Kept in the composer until the first turn succeeds, so a failed
+ // start leaves the text ready to retry.
+ setInput(handedOff);
+ void run(() => startWorkflowDesigner(handedOff), handedOff);
+ return;
+ }
+ if (describeParam) {
+ setInput(describeParam.slice(0, MAX_DESCRIBE_PARAM_CHARS));
+ router.replace(pathname, { scroll: false });
+ }
+ }, [resumeId, describeParam, run, router, pathname]);
+
const send = (text: string) => {
const message = text.trim();
if (!message || busy) return;
@@ -137,7 +167,7 @@ export default function WorkflowWizard() {
workflow for you to review.
</p>
<div className="flex flex-wrap gap-2">
- {STARTERS.map((s) => (
+ {WORKFLOW_STARTERS.map((s) => (
<button
key={s}
type="button"
diff --git a/packages/ui/src/lib/workflowStarters.ts b/packages/ui/src/lib/workflowStarters.ts
new file mode 100644
index 00000000..20124973
--- /dev/null
+++ b/packages/ui/src/lib/workflowStarters.ts
@@ -0,0 +1,47 @@
+/**
+ * Example one-liners for describing a new workflow. Shared by the "Start
+ * here" panel on /jobs and the conversational wizard at /jobs/new.
+ */
+export const WORKFLOW_STARTERS = [
+ "A weekly competitor digest sent to me every Monday morning",
+ "A board pre-read I kick off before each meeting, with the CFO signing off",
+ "A monthly hiring-plan review across all open roles",
+ "A launch readiness check I run before every product release",
+];
+
+const HANDOFF_KEY = "oe.workflowWizard.describe";
+// A hand-off older than this is from a Start the user walked away from, and
+// must not fire on a later visit to the wizard.
+const HANDOFF_TTL_MS = 5 * 60 * 1000;
+
+/**
+ * Hand a description typed on /jobs to the wizard, which sends it as the
+ * first message. Session storage rather than the URL, so a link cannot make
+ * the wizard send text the user never typed. Returns false when storage is
+ * unavailable; the caller then falls back to `?describe=`, which only
+ * prefills the composer.
+ */
+export function stashWorkflowDescription(text: string): boolean {
+ try {
+ // Cleared first, so a failed write can't leave an older hand-off behind.
+ window.sessionStorage.removeItem(HANDOFF_KEY);
+ window.sessionStorage.setItem(HANDOFF_KEY, JSON.stringify({ text, at: Date.now() }));
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+/** Read and clear the handed-off description, so a refresh doesn't resend it. */
+export function takeWorkflowDescription(): string | null {
+ try {
+ const raw = window.sessionStorage.getItem(HANDOFF_KEY);
+ window.sessionStorage.removeItem(HANDOFF_KEY);
+ if (!raw) return null;
+ const { text, at } = JSON.parse(raw) as { text?: unknown; at?: unknown };
+ const age = Date.now() - Number(at);
+ return typeof text === "string" && age >= 0 && age < HANDOFF_TTL_MS ? text : null;
+ } catch {
+ return null;
+ }
+}