Skip to content

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

feat(workflows): let action steps use the Executive's chat tools (#599)

Rufus18449b7b9f2d
diff --git a/packages/core/openexecutive/architecture/architecture-facts.yaml b/packages/core/openexecutive/architecture/architecture-facts.yaml
index 263d0703..a0de9c9e 100644
--- a/packages/core/openexecutive/architecture/architecture-facts.yaml
+++ b/packages/core/openexecutive/architecture/architecture-facts.yaml
@@ -2363,7 +2363,7 @@ knowledge:
loader.read_document_text / extract_text_from_file_async are the async
entry points; ingest_file (uploads, reconcile_company_docs), the
/documents/{filename} preview, intake uploads, integrations.attachments,
- the email poller, oe__read_file and read_document all use them. The sync
+ the email poller and read_document (a workflow step's oe__read_document) use them. The sync
extract_text_from_file serves its other callers (see parse_isolation).
Where files reach the Executive:
@@ -7251,10 +7251,32 @@ workflows:
list_saved_tools is allowed under the Act as me lockdown (local read)
and withheld on a turn private to the principal, like run_script.
+ Chat's tools in action steps (workflows/chat_tools.py): one list,
+ `ACCESS`, labels every tool chat offers — use (a step may call it as
+ oe__<name>), as_me (Act as me; chat-only for now), covered (the step
+ already has its own path: gateway tools, run_script, specialist steps) or
+ chat_only (it changes what the Executive knows or who is on the team, or
+ acts on the person's screen). A unit test fails when a new chat tool has
+ no label, so a new chat tool can't skip the decision. A "use" tool runs
+ through the SAME chat handler, as an unattended chat turn would: an
+ unattended Session bound as current_session, the workspace-mode filter
+ (solo withholds department/broadcast tools), and, when a team member
+ created the workflow, their department gate. Channels the instance has no
+ token for are not offered. A saved workflow is the person's permission, so
+ Take the lead's approval gates and the solo principal-only rules are not
+ applied (no change for workflows that worked before). run_workflow refuses
+ a workflow already in its own chain and nests at most 3 deep;
+ run_workflow / run_executive_research get a 15-minute call timeout.
+ oe__web_search is the model's own server search (appended after the sorted
+ tools; paused turns are sent back as-is). Workflows have no tool
+ handlers of their own: oe__message_person / oe__create_alert are the chat
+ tools under the same names, and oe__read_file (LEGACY_NAMES) still
+ resolves to read_document for saved workflows but isn't offered.
+
Action steps (workflows that act): `ActionStepSpec` {goal, tools,
max_tool_calls 1-50, default 20} in dynamic_models. `tools` is an allowlist
- of exact names — MCP gateway tools (`server__tool`) and built-ins
- `oe__read_file`, `oe__message_person`, `oe__create_alert` — and the user's
+ of exact names — MCP gateway tools (`server__tool`) and built-ins (the
+ chat's own tools as oe__<name>, below) — and the user's
click on Create IS the approval (the review card lists every tool, flags
ones that may change things, and names them in a "can use these without
asking again" notice). Gateway meta-tools (search_tools / call_tool /
@@ -7270,8 +7292,8 @@ workflows:
budget enforced, then a tools-off (`tool_choice: none`) final turn; tool
errors return as is_error; each call emits a `progress` WorkflowEvent and a
`workflow_tool_call` audit row (tool + outcome, never arguments). Output =
- the agent's report + an "Actions taken" list. `oe__read_file` reads only
- under WORKFLOW_FILE_DIRS (default workspace-mcp's attachment dir), resolving
+ the agent's report + an "Actions taken" list. `oe__read_document` reads only
+ under WORKFLOW_FILE_DIRS (or the company docs folder) (default workspace-mcp's attachment dir), resolving
symlinks/`..` first. Action steps are allowed in cadence workflows. The
designer gained a third constant tool, `search_available_tools`, answered
inside the same `advance` call (≤4 per turn; tool_use/tool_result pairs are
diff --git a/packages/core/openexecutive/architecture/prebuilt/workflows.json b/packages/core/openexecutive/architecture/prebuilt/workflows.json
index 86f40226..cb72be86 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`. The activity feed never shows a run's log title (`\"Executive Research (periodic)\"`): `workflows/run_outcome.py` gives each finished run a plain name (\"Researched your market\", \"Checked in with Sales\", or the name it started with, less its date) and one line on what came of it, read from that stored artifact, so older runs read the same and nothing extra is written or called. 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` and the weekly `goal_review`, which grades the goals no check-in covers; see Scheduler).\n- `weekly_review` — the principal's weekly look back and ahead (see *Weekly review* below).\n\n**Standing facts in unattended output.** `end_of_day_digest`, the weekly review's top-three call and the morning reflection append the standing facts (`memory.facts.with_standing_facts`; a teammate's marked `(per <name>)`) to their user turn, and the morning brief gets them through `render_briefing_context`. A workflow step that consults a specialist gets them through `route_to_specialist`. A correction made in chat therefore holds in every recurring brief and run. The morning brief also reads `facts.render_teammate_changes(since)` off the event loop and passes it to both `render_briefing_context` (a TEAMMATE CORRECTIONS SINCE LAST BRIEF block) and `build_brief_fingerprint`, so the principal hears of each correction a teammate made in the window, and that alone un-suppresses an otherwise unchanged brief. Proposals waiting for approval are listed only in a brief the principal reads privately (`include_proposed=_private_ok()`), and then mark the run private to them. The principal's own Always in the loop notes (`memory.history_brief`, only with their switch on) come in by a stricter rule, only on the scheduler's delivery (`PRINCIPAL_DELIVERY`), never a run from chat, whose tool result reaches the turn's shared audit row and peer memory: the morning brief's FROM YOUR NOTES — DUE SOON block and the end-of-day digest's FROM YOUR NOTES — TODAY block (what they committed to since the last digest, then what is due tomorrow). Either marks the run `private_to_principal` and moves its fingerprint; the digest, which had no private reads before, now emits that flag too. In the install's first week (`briefing.first_week`, seven days from the principal's People row) the morning brief also passes a GETTING STARTED block to `render_briefing_context(getting_started=)` and its keys to `build_brief_fingerprint`: onboarding goals, departments with no leader and, on the scheduler's delivery with Act as me and Draft replies to my inbox on, who wrote to the owner's own mailbox (sender and subject only) and, with Read my calendar on, today's meetings on their own calendar (time and title), either of which marks the run `private_to_principal`. The brief opens with **Getting started** and is never the quiet line while the block has anything in it (see Today).\n\n### Change-aware principal briefs\n\n`morning_brief` and `end_of_day_digest` are the two recurring briefs the scheduler sends to the principal. Both are written with `briefing.narrative.brief_model()`, the Executive's own model (its Council pick, else `DEFAULT_MODEL`), since a brief is the Executive speaking; only the grounding repair stays on the fast model. Both are now a *delta*, not a re-list: the window is \"since the last **delivered** brief\" (`briefing.brief_state.since_for`; 24 h on a cold store, clamped to 7 days), activity comes from `_build_activity(limit, since=…)`, proposals (action category only) split into *new since last brief* — enumerated, with each item's why-now and next move — versus a one-line carried-over count, a *rewritten* block lists carried items the review rewrote inside the window (`brief_state.rewritten_since`: verdict `changed`, still open — the brief reports them under \"what changed\", never as done), and a *handled overnight* block lists what the Executive's alert review **completed** on its own (`brief_state.handled_since`; the `changed` verdict is excluded because the alert is still open). The morning brief also reads the principal's **live world** since that window opened (`briefing.live_signals.gather_live_signals`): mail and chat the Executive handled (INBOUND, grouped by sender and subject, each email from the roster marked replied or not, earlier days dated), under a NOW line and THE PRINCIPAL line that names its reader so the brief writes \"you\" (the end-of-day digest gets the same line, and the team reflection a YOUR PRINCIPAL line under its roster; the reflection flags only what today's input still shows), what got stuck (STUCK: a reply the outbound gate held, a non-roster sender who got no reply, a Google Chat message left unanswered, chat drafts still in the principal's Gmail, after `live_signals.settle_principal_drafts` has marked the ones they since sent or deleted there), the principal's own chats, and — in both modes now, unless the solo top three already listed it — today's calendar, read fresh (`live_signals.refresh_calendar(max_age=0)`). The 07:30 reflection's **Flagged for the brief** bullets are carried across (`brief_state.reflection_flags_since`, the latest reflection run finished inside the window) instead of surviving only as an activity line with the run's title, and the rhythm runs themselves (`today.RHYTHM_WORKFLOWS`) are dropped from the brief's activity: their dated titles were noise and moved the fingerprint every day. At-risk departments name their slipping goals and each proposal carries its age. The period is the principal's local date. Section order: top call → **today** (the calendar's shape and anything stuck) → what changed (inbound first, naming who wrote) → handled overnight → needs you (new only) → waiting on → at risk (the slipping goal, or the department left out — never \"no detail yet\"). Quoted mail, chat, invite and reflection text is marked as data, never instructions. **Privacy:** the brief reads what is private to the principal — their contacts' alerts and mail, their drafts, their chats and their calendar — only on a run for them: the scheduler's (`morning_brief.PRINCIPAL_DELIVERY`) or the principal's own verified chat turn in a conversation only they can read (`delegation.settings.private_conversation`: the web chat, a Slack or Discord DM, a private Telegram chat — never a shared channel, where the reply is posted for everyone). A run anyone else starts (a teammate from chat in team mode, `POST /workflows/…/runs`) reads what everyone may see, as before. A run that did read a private row says so on its `result` event (`private_to_principal`: its live read differs from the shared one in any key or count), and the scheduler, `run_workflow` and `POST /workflows/{name}/runs` all then keep `persistence.PRIVATE_RUN_ARTIFACT` in the run history instead of the text. Text another pass wrote (the reflection's flags) renders as quoted ` > ` lines and every goal and headline field is one-lined, so none can start a line that reads as a block header. The fingerprint carries the live signals' time-free keys (who wrote about what, what is stuck, the calendar's shape) and the reflection flags when there are any, so \"nothing new\" means the principal's world was quiet too; the context summary is logged at INFO (`morning_brief: context since=… inbound=… stuck=… suppressed=…`). In **solo mode** (one person using Open Executive for themselves) both briefs speak to the principal, whatever their role: the morning brief runs top call → top three today → what changed (inbound and stuck first) → handled overnight → needs you → due this week (the principal's open loops overdue or due within 7 days, from `open_loops.principal_due_soon`) → goals at risk (named by area), the end-of-day digest what I did → open decisions → goals at risk tomorrow → sleep on this, over a context with goals at risk by area and no people-waiting or department block; the fingerprint carries the mode and ignores who is awaiting, and carries the due items as `(loop_id, state)` pairs when there are any. **Top three today** is picked in code, not by the model (`briefing.top_three`: overdue then due-today commitments, off-track then at-risk goals, commitments due later this week, then active projects, stalest first). The solo Briefing's *Top three today* card shows the same pick from the same code (`GET /today/top-three`, see Today). When the MCP gateway runs the Google Workspace server, one `google_workspace__get_events` call (4 s timeout) lists today's events on the principal's calendar — their address as the calendar id, read with the Executive's account (`primary` when the Executive is signed in as them) — and on a business day (`calendar_tools.is_business_day`, the rule the booking tools apply; at the weekend the day's events are still listed but no slot is suggested) each item gets its own free block inside `CALENDAR_BUSINESS_HOURS_START`–`_END`, rendered with a TODAY'S CALENDAR block — only a date-only event is all day, a zero-length one blocks nothing, and one whose times can't be read is left out; no gateway, no principal address, an error, a timeout or a reply it cannot read all mean no calendar and no slots, never a failed brief; the log records only the reply's length or the error's type, never calendar text. When the principal has Act as me and **Read my calendar** on (`delegation.calendar`) and their mailbox opens as theirs, `top_three.read_todays_calendar` also reads their own calendar through their own sign-in (Gmail or Outlook, same 4 s timeout, declined events left out), at the same time as the Executive's read, and merges the two: an event with the same title and times on both is listed once, and either read alone is enough. This read feeds the morning brief, the /today calendar cache (`live_signals.refresh_calendar`) and so the end-of-day digest and Right now; the solo top three adds it only on a run for the principal (`build_top_three(include_own=private_ok)`). 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. Both are written to their reader in code (`briefing.reader`): the principal's full name and addresses are masked to \"the reader\" throughout the context under a THE READER line, the prompt says \"you\" for the reader, nobody is \"the principal\" and the Executive is \"I\" / \"me\", and a draft that still slips is rewritten once (the morning brief) and fixed in code. **The end-of-day digest reads the day itself.** On the scheduler's delivery to the principal alone it leads with TODAY WITH YOU (`session_store.own_conversation_since`: the principal's own conversations with the Executive since the last digest, their words and its replies, never a conversation someone else owns) and the live blocks (`live_signals.render_live_blocks`: mail in, what got stuck), then COMING UP (the Executive's own follow-ups due in the next two days). It leaves out its own rhythm runs (`today.RHYTHM_WORKFLOWS`) and gets the reader's leave-out list (`brief_requests.render_parts`). Its shape is **Today**, **Done for you**, **Next** and an optional **Sleep on this**, at most 150 words, with no header for an empty section. Before this it read only the Executive's own bookkeeping, so on a day of real work it reported its own briefs and missed every number decided in chat.\n\n**Brief delivery.** `scheduler.runner._deliver_to_principal` maps the principal's `preferred_channel` (`slack` / `discord` / `telegram` / `email`) to its delivery channel and tries it first, then the other chat channels the principal has an id for, in the order Slack → Discord → Telegram. Email goes through the active MCP gateway (`google_workspace__send_gmail_message` as the Executive's own address, to the principal, subject `<title> — <date>`) and is used only for an explicit `email` preference, or for `any` when no chat channel resolves — an owner linked by email at setup has `any`, so one who also has Slack does not start getting two emails a day. When nothing can deliver (a web-only principal, or email with no gateway), the brief is still generated and stored as a run with its artifact, as before — a web-only principal reads it on the Artifacts page — it is just not delivered (audited), so the window does not advance, and the next occurrence is chained. The same delivery path carries the client-rotation digest and the weekly review.\n\n**Grounding.** Nothing an unattended pass writes is read by anyone before it goes, so `openexecutive.briefing.grounding` checks it deterministically — no model judges the model. A name (a run of two or more capitalised words once section headers, weekdays, imperative openers and org nouns are trimmed, or one capitalised word in a person slot like \"ask Marcus\" or \"Marcus wrote\") is grounded only when a single line of the pass's inputs holds all of it, or it belongs to a roster person some input mentions — being on the roster alone is not enough. A figure (money, a percentage, a k/M/B number, any bare number of 11 or more; never a date, time, year, duration, id, list marker, `Q3` or small count) is grounded when an input number matches it within the precision it is written with (`$1.2M` matches `$1,234,567`; `47 units` does not match 48). The inputs are the rendered context split into lines labelled by section (a header also carries its bullet count), the company profile and the department titles. `morning_brief` renders its context itself and hands it to the synthesizer as `rendered_context`, so the check reads exactly what the model read; after the quiet fallback, `ground_brief` runs on both briefs. When something is ungrounded it makes one repair call to the fast model (same system prompt, the list of items, \"remove or correct using only the context\"), re-checks, then drops each line still ungrounded and any header left empty, and appends \"_I left out N lines that named people or figures I couldn't match to your data. They're under Left out of your brief on Home._\" (everything ungrounded → one held-back line). Every held line goes in the `grounding` audit row's untruncated `full` payload (up to 30, 400 chars each; `details` keeps a five-line preview), and `grounding.recent_held_back` reads the last day's back for `GET /today`'s `held_back`, which Home lists under **Left out of your brief** for the principal alone — after the narrative inputs are taken, so the held lines never reach a prompt. Then each grounded figure gets a server-chosen ` [n]` — the matching input line with the most words in common with the figure's clause — and a `**Sources**` list closes the brief (`- [n] <section> — <snippet>`, at most 9, snippets quote inbound mail, so links are masked (\"(link removed)\"), Markdown, angle brackets and @-mentions stripped, and they are cut to 90 chars; never `[n]:` at a line start, which Markdown reads as a link definition). Text with nothing to change comes back byte-identical, the fingerprint hashes the inputs so suppression is unaffected, and the grounded text is what is delivered, stored and recorded as delivered. Both brief prompts and the digest prompts say the rule up front. `executive_reflection` wraps its handlers in a `GroundingScope`: `create_alert`, `message_person`, `send_department_message`, `send_company_broadcast` and `schedule_followup` refuse text with an ungrounded name or figure, returning a JSON error that names the items so the model can look the person up or leave the figure out (every tool result joins the inputs, so a `lookup_person` answer grounds the DM after it; the recipient's own name always counts). Its **Flagged for the brief** bullets are filtered the same way before the tool log is appended — the next brief quotes them, where they would ground themselves — and `brief_state.reflection_flags_since` now stops at the tool log's `---`. The reflection's `grounding` rows are private when a private-to-principal alert reached its context, and the digest's always are (its HANDLED block can quote one). Everything fails open. `GROUNDING_CHECKS=enforce` (default) acts, `report` only writes the `grounding` audit rows, `off` skips it; `GROUNDING_CITATIONS=false` drops the markers. Not yet grounded: the /today header (its cards sit beside it), `weekly_review`, the research synthesis, dates and meetings, and a real person named in the wrong role.\n\n### Weekly review (solo)\n\n`weekly_review` (background, inputs all defaulted) closes out the principal's week in six steps. **Goals**: every area with goals is graded by its own specialist, concurrently, with the department check-in's verdict contract (`_parse_verdicts`) and write-back (`persist_goal_verdicts` → `record_goal_review`, one `goal_status_review` audit row per area with actor `weekly_review`); an area with no goals is skipped, one without a specialist is listed ungraded, and one whose specialist fails is shown as last recorded. **Commitments**: `open_loops.principal_due_soon` — overdue or due within 7 days. **Projects**: active initiatives with no update for 7+ days. **Decisions**: the week's (`episodic.decisions_since`). **Revisit**: up to three decisions older than 30 days with an empty outcome (`episodic.decisions_awaiting_outcome`, newest first), listed as `[decision N]` under *How did these turn out?* — the principal's answer is recorded with `record_decision_outcome` (see Agents). **Assemble**: every section always renders (a one-line note when empty), ending with *Next week's top 3* from one fast-model call that follows the `weekly-review` playbook (a constant system prompt; the playbook rides in the user turn), trimmed to at most three list items — or, when that call fails or returns nothing, the same ranked pick the morning brief uses. In solo mode the scheduler fires it weekly (`principal_weekly_review`, see Scheduler) and delivers it through `_deliver_to_principal` like the briefs, recording the delivery outcome. The solo Briefing also shows the latest completed run to the principal (`GET /today/weekly-review`, see Today): `weekly_review.summarize_review` reads the artifact's title line (`TITLE_PREFIX`) and its last `TOP_THREE_HEADING` section back as plain text, so a principal no channel reaches still sees next week's top three. Wording is role-neutral; run by hand in team mode it says *department* instead of *area*.\n\n**Principal-only workflows.** A workflow can name the workspace modes in which only the principal may start it (`Workflow.principal_only_modes`): `weekly_review` in both modes (built from the principal's decision log, commitments and goals, and it re-grades the goals) and `morning_brief` in solo (built from the principal's commitments and calendar). Team `morning_brief` and every other workflow can be started by anyone as before. This decides who may start or trigger a run, not who may read one: stored runs, the scheduled briefs and weekly reviews included, are read under the existing `/workflows/runs` rules — which is why a morning brief that drew on the principal's private rows is stored as `PRIVATE_RUN_ARTIFACT`, not as its text.\n\n- **From chat**, `run_workflow` checks at dispatch, before any run row is created, that the turn is the principal on a verified surface — `create_goal`'s rule — and otherwise refuses with a plain error that does not spell out the rule.\n- **Over HTTP**, the Jobs page's `POST /workflows/{name}/runs` and `POST /evals/runs` (a workflow scenario runs the workflow on live data) call `refuse_principal_only_run`: only a caller signed in as the principal, or a request with no caller email (the CLI or local login), may start the run. Unlike the workspace settings, an install with no principal on the roster lets no signed-in caller in, as in chat. Anyone else gets a 403 (\"Only the principal can run this workflow.\") before any run row exists. The mode is the stored one, or an eval scenario's own `workspace_mode`. The eval route runs exactly the scenario list it checked.\n\nEvery refusal is audited `refused=true` with the workflow, the mode and the caller. The checks fail closed: a mode that cannot be read counts as principal-only, and a check that cannot read the roster refuses.\n\n**Knowledge in the reflection.** A chat turn looks the knowledge base up before the Executive answers; the reflection reads the org's state instead, so nothing looked it up for it. It now carries its own `search_knowledge` tool (`orchestrator.knowledge_tools`, not in the shared `_ALL_SKILL_TOOLS`), which runs the same `knowledge.retriever.retrieve` as chat — the review gate, the synced Drive / OneDrive / Confluence / Notion collections and the published-artifact rule (the pass has no viewer, so no one's private document comes back). The prompt (`_KNOWLEDGE_RULE`, both modes) asks it to search before acting on or flagging something that turns on a customer's or supplier's terms, a price, a policy, a plan or a past decision. Its passages come back up to 4,000 characters (`execute_tool_calls(wide_results=...)`) while other tools stay at their short preview, its result counts as grounding input like any tool result, and the run's tool log keeps each line to 160 characters. Read-only, so Take the lead never gates it. The loop has 5 iterations (was 4) to leave room for a search before acting.\n\nNeither the nightly reflection nor the research synthesis can call `ack_alert`: both run unattended with open alerts rendered into their context, and those headlines are minted from inbound mail and chat, so an injected \"the principal already dismissed 13\" would be acted on with nobody watching. Closing an alert is the alert review's job, with evidence.\n\n`executive_reflection` now carries memory: yesterday's standup (the previous completed run's artifact) is rendered into the context and the prompt forbids re-acting on anything listed there unless it changed; open alerts render with their id, review verdict and recommended move. Reflection never closes alerts — the alert review does, with evidence. It also renders an **OPEN LOOPS** block (up to 10, soonest due first, overdue flagged) from Attunement so the standup can connect a slipped promise to the rest of the org state; the nudge engine already chases overdue loops, so the prompt tells it not to DM about a loop merely for being overdue. A **WHAT LANDS** block (from the Attunement outcome ledger) shows, per person, how often each kind of proactive DM got answered over 30 days; the prompt steers DMs toward kinds that land and away from kinds a person reliably ignores. Reflection and research tag their tool execution as proactive (`tag_proactive`) so their DMs are counted. Resolving a wait-for-human approval (`resumer.apply_resolution`) marks the nudges that chased it `acted`. `close_open_loop` is withheld from reflection for the same reason as `ack_alert`: loop text is quoted from what people wrote. `unattended_toolkit` also drops `schedule_tools.UNATTENDED_WITHHELD_TOOLS` (today `create_goal`) from both passes in both modes: a goal is the principal's own decision, and these passes see only inbound text. A turn private to the principal (mail from one of their contacts, or mail they forwarded) cannot start a workflow either: `run_workflow` and `run_executive_research` are in `schedule_tools.PRIVATE_TURN_WITHHELD_TOOLS`, which the chat loop neither offers nor runs on such a turn, since a workflow's steps can reach anyone.\n\nIn **solo mode** the reflection is framed for the principal, whatever their role: they are the only person who uses Open Executive and the only one it takes direction from, it prefers `create_alert` and `schedule_followup` to the principal, and it never messages anyone else from an unattended pass — the people in the principal's world are contacts, so anything they should hear is flagged for the principal to raise. The team roster is replaced by one YOUR PRINCIPAL line (person_id and follow-up channels), its follow-up guard is seeded from the principal only, and department risk renders as areas with goals at risk. The research synthesis follows the same rule — its routing menu and roster name only the principal. In both, `send_department_message`, `send_company_broadcast` and `set_department_head` are withheld, and so are `create_calendar_event`, `create_instant_meeting` and `run_workflow` — a booking reaches its attendees and a workflow can do anything its steps do, so the principal books and starts workflows from chat — and `message_person` refuses anyone but the principal. These passes run unattended with inbound text in their context, so the rules are enforced in code, not only in the prompt.\n\nIn either mode, both passes now dispatch only the tools they offer: the handler map is built from the offered list, so a name the model emits without being offered it is skipped as an unknown tool. They used to look names up in the full handler registry, so tools they deliberately withhold — the raw DM tools (`send_slack_dm` has no roster check), `ack_alert`, `close_open_loop`, and in research the watchlist writes and `run_workflow` — still ran when the model emitted them. Both read the mode before binding their own session (so a caller's override, such as an eval's, counts) and pin it on that session, so their tool handlers use the same mode. They carry the principal's role across the same way (`effective_principal_role` of the caller's session, pinned as `turn_principal_role`), so a specialist or workflow started from either pass sees the role of the turn that started it. Team runs are unchanged.\n\n### Wait-for-human pause\n\n`wait_for_human` (`openexecutive/workflows/wait_for_human.py`) is a first-class step primitive that pauses a run: the runner calls `save_checkpoint`, the `workflow_runs` row moves to `status='awaiting_human'`, and the serialized `WaitForHumanEvent` is stored in `state_json`. (Department authority is a *separate* mechanism — `propose_only` departments file a briefing alert via `departments.authority.propose_via_alert` and mark the scheduled action done; they do not route through this gate.)\n\n**Delivery.** Both checkpoint sites — the SSE route and the `run_workflow` chat tool — call `workflows.gate_delivery.deliver_gate_question` immediately *before* checkpointing, so `state_json` carries the routing fields a reply is matched against. Two modes. When the approver is the person already in the conversation (the chat session's `origin_channel` is set — to anything but `email`, whose answer is no chat reply and would never be sent — and its `caller_person_id` is the gate's `person_id`), nothing is sent — the question rides in the Executive's own reply — and the gate records `origin_session_id` plus the session's channel. The resolver compares base ids (`memory.conversation_ids.base_session_id`), so a question asked in one conversation of a Telegram chat or a DM is still answered by a reply after a quiet gap or /new has started the next. Otherwise the question is delivered through `schedule_tools.handle_message_person`, which picks the person's preferred channel, falls through on a failed send, and falls back to a briefing alert; the gate then records the channel, address and provider message id that send returned, plus the id of the DM session it landed in — that send is always 1:1, so the answer belongs in that conversation and nowhere else. Without it the gate matched on person and channel alone, so an unrelated @mention in a public channel resolved it and had the acknowledgement, run title included, posted where everyone could read it. The question is sent with `notifications.approval_send`, so the person's quiet hours and *In my briefs* never hold it, whatever their urgent setting: only a reply to it resolves the gate. Delivery is not guaranteed: the outbound guard can suppress it (duplicate, rate cap, quiet hours) and an unreachable person gets the alert fallback. Both cases leave the routing fields empty and report `delivery` as `suppressed` / `alerted` rather than claiming someone was asked, and the chat tool's presentation hint changes accordingly.\n\n**Matching a reply.** Each inbound adapter passes the message to `inbound_resolver.resolve_inbound_message` with its `session_id`. Matching is three-tier: an explicit `in_reply_to` against a stored `outbound_message_id`; otherwise a single open run on that channel; otherwise one utility-fast disambiguation call gated at 0.85 confidence. An unmatched explicit reference rules out only the candidates that carry a stored outbound id — the ones it could have matched — and the rest continue; rejecting outright meant an adapter that passes a thread id on every message (Slack's `thread_ts`) short-circuited the later tiers forever, and a global test let one delivered gate's id block an unrelated self-approval gate. Channel names are normalized (`slack_dm` ≡ `slack`), the delivered address is compared when both sides know it, a row whose `state_json` will not parse is refused (a corrupt row otherwise presents as a legacy one), and an empty stored channel is treated as a wildcard only for rows checkpointed before gate delivery existed. Two guards keep an open gate from swallowing unrelated traffic: a gate carrying an `origin_session_id` matches replies only from the conversations the adapter names (a Slack or Discord thread offers its parent channel session too, mirroring the history double-write, since a gate raised on a mention recorded that session while the answer arrives under the thread's — on Slack only when that person rooted the thread, or the alias would reach into a colleague's), and the parser can return `unrelated`, which declines to resolve and lets the message reach the normal chat path. The parser is handed the gate's own question, so a bare \"yes\" is judged against something. Its fallback is flagged by a key the model cannot emit rather than by a magic note string it could, and a fallback declines to resolve on *every* reply shape — recording the empty string a `free_text` fallback fabricates would close a sign-off on a parser outage. Every shape can answer `unrelated`, not just `approve_reject`: without it an open `free_text` gate turned the person's next message into its answer verbatim, and a `numeric` one swallowed any message containing a number. The parser has one caller outside workflows: its `roster_identity` shape — `{decision: approve|link|decline|unrelated, name, kind: team|contact|null}`, with `name` only as the person wrote it (never inferred) and a fallback of `unrelated` — reads the principal's emailed answer to a roster request (who a new sender is; see Org). It is not a gate reply shape, and a fallback or `unrelated` leaves the request waiting. `resumer.apply_resolution` then records the decision, marks the run `resolved`, and writes an audit row. A timeout applies the step's `on_timeout` policy (escalate / auto_proceed / fail). The outcome surfaces on the Today dashboard.\n\n**Resuming past the gate.** A paused run continues on its own. Re-entering it was long assumed to mean serializing a Python generator frame; it does not. The only state alive across a dynamic workflow's steps is its inputs (already persisted), a company-profile block that is recomputed, the completed steps' output strings, and the loop cursor — so the engine hands the checkpoint a small JSON `WorkflowResumeState` (workflow name, the gate's id and index, the next index, the outputs so far), stored in `workflow_runs.resume_state_json`, and `DynamicWorkflow.resume` replays its step loop from the recorded index. `run()` and `resume()` share that one loop, which is why a second gate needs no special handling — it is simply another pause raised from the same place. The payload rides on a `WaitForHumanEvent` field declared `exclude=True`, so it can never leak into `state_json`, whose exact key set the resolver branches on. A gate with no payload is *pause-only*: the decision is recorded and the run stops, which is what every caller got before resume existed.\n\n`resumer._process_resumable` claims a resolved run with one guarded UPDATE — `resolved` → `running`, stamping `resumed_at` and minting a claim token — and drives it to a terminal row. It runs two ways: immediately, via a task `apply_resolution` kicks off so a Slack approval starts moving in seconds, and every 60s from the poll loop as the durable backstop. Both share the claim, so a run executes exactly once even with two resumers against one database. The kicked task binds no chat session (`set_session(None)`), exactly like the poll loop: it is created inside the inbound handler that recorded the answer and would otherwise inherit that person's live turn — so a run resumed because the principal replied on Slack does not act with the principal's identity (it cannot, for example, reach the principal's contacts). It drops the handler's audit scope too (`audit.context.unscoped_audit_rows`): inherited, the principal's scope would make private every row of the run that names a contact, and whoever started the run would see those rows vanish after the approval. The poll runs the executor *after* the timeout loop, which is what finally makes `on_timeout='auto_proceed'` do what its name says: the timeout resolves the run and the same tick executes it. While the Executive is paused (`scheduler.pause`) the resumer does nothing — no startup sweep, no timeouts, no resumes — and `apply_resolution` still records the decision but skips the immediate kick; the first unpaused iteration catches up on all of it, so a timeout that lapsed during the pause applies its `on_timeout` policy then.\n\n**The claim is fenced, because it is not a lease.** The stale sweep decides a worker is dead from a wall-clock guess, so a slow but *alive* worker will eventually be declared dead and replaced. Every write the executor makes carries its claim token and is refused once superseded — otherwise the replaced worker's late completion lands on top of its replacement's result, or its checkpoint at a later gate resurrects an already-finished run and asks the approver a second time. The retry budget resets at each new gate (a gate is new work, not a retry), and a run that exhausts it is *ended* rather than dropped: an exhausted run sits in `running` with a payload, in neither queue, and would otherwise show as in-progress forever.\n\n**The gate fails closed.** Continuing is an allowlist — `approve` and the synthetic `auto_proceed` — not \"anything that is not a stop word\". `decision` is whatever a fast model extracted from free-form chat and it drifts; under a denylist, \"rejected\", \"Reject\", \"decline\" and \"no\" would all continue, so the approver declines and the deliverable is produced anyway. Reply shapes that ask a question rather than seek permission always continue, since the answer *is* the value. A stop ends the run at `error` with the human's note. Either way the decision becomes the gate step's own output, so it reads as a section *in* the artifact — capped and blockquoted, because that text reaches the synthesis specialist as prompt context.\n\n**A definition edited during the pause is refused.** Resume re-validates the payload's version, the recorded gate, *and* a fingerprint of the whole step list, and derives the index to continue at rather than reading it from the payload. Pinning only the gate would not be enough: definitions are overwritten by name and any rostered user can save one, so someone could keep the gate identical and replace every step after it — and the approver's sign-off would be recorded against work they never saw, which defeats the one thing an approval gate is for. No built-in workflow yields the gate; only user-created dynamic workflows do.\n\n### Launching from chat\n\nWorkflows are not only reachable from the `/jobs` UI — the Executive can list and run any of them mid-conversation. `openexecutive.orchestrator.workflow_run_tools` wires two tools into the main chat loop: `list_workflows` (the launchable catalog, with each workflow's input fields) and `run_workflow` (runs one to completion and returns its Markdown artifact, using the same engine as `POST /workflows/{name}/runs`). `run_workflow` resolves both built-ins and custom workflows via `get_workflow`, validates `inputs` against the workflow's input model, persists the run (`create_run` → `complete_run` / `fail_run`), and on an approval-gate step checkpoints the run as `awaiting_human` exactly as the HTTP route does — literally the same code, since both call `workflows.gate.checkpoint_gate`, which delivers the question and writes the checkpoint in one place. It never hangs waiting on a human, and it reports both whether the question reached them and whether the run will continue by itself once answered. The runners that *cannot* pause — the schedulers, evals, client rotation, onboarding, the research tools — call `gate.ensure_workflow_event`, which raises on a gate rather than letting one be swallowed; the scheduler's dynamic-workflow branch used to ignore it and record a successful run containing nothing. `executive_research` is excluded (it has the dedicated `run_executive_research` tool). Running a workflow from chat delivers nothing on its own — it renders the artifact into the conversation, and the recurring principal briefs (`morning_brief`, `end_of_day_digest`) reach anyone only via the scheduler's own `_deliver_to_principal`. The tool description used to claim those two DM the principal when run and to confirm before firing them, which had the model soliciting a confirmation on a false premise; it now names `executive_reflection` as the one workflow that really does execute tool calls of its own (DMs to heads, broadcasts, alerts). A successful run surfaces an `action_taken` chip linking to `/jobs/runs/{run_id}`.\n\n### Dynamic (user-created) workflows\n\nUsers create reusable workflows on the fly — from the executive chat, the conversational wizard at `/jobs/new`, or the step-by-step advanced editor — without shipping code. The Workflows page (`/jobs`) opens on a *Start here* panel that leads to all three: the user describes the job in a sentence and *Start* opens the wizard with that text sent as its first message (handed over in `sessionStorage`, so a link cannot make the wizard send text the user never typed; where storage is blocked it falls back to `/jobs/new?describe=`, which only fills the composer and sends nothing), or picks *Step by step* (advanced editor) or *Talk it through in chat* (`/?new=1&draft=`). Below it come the user's own workflows, then four ready-made starter picks with the full built-in list folded behind *Browse all* (`?browse=1`). The picks and the example chips follow the workspace mode: a team gets the investor update, board prep, MBR and competitive teardown (and a board pre-read chip); a solo owner-operator gets the MBR, pricing review, churn deep dive and quarterly plan, with chips for a Friday cash and pipeline check, customers who stopped buying and a competitor digest (`lib/workflowStarters.ts`; a unit test pins every pick to a startable `WORKFLOW_REGISTRY` entry). A dynamic workflow is a stored JSON definition (the `dynamic_workflows` table) interpreted at runtime by one generic `DynamicWorkflow` engine (`openexecutive/workflows/dynamic.py`) that implements the same `Workflow` ABC as the built-ins, so the run path, SSE streaming, run persistence, and `/jobs/[name]` form rendering are unchanged. `get_workflow` / `list_workflows` fall through to the dynamic store after the static registry (built-ins win on a name collision).\n\nA definition declares free-text input fields and an ordered step list of four kinds: **specialist** (consult a specialist with a goal prompt, optionally grounded by RAG), **action** (get something done with tools — see below), **approval_gate** (a `wait_for_human` pause), and a terminal **synthesis** step that assembles the artifact. At least one specialist or action step is required. `validate_definition` enforces the structural rules: exactly one terminal synthesis step, valid specialists, `{placeholder}` tokens that reference declared input fields, rostered approval/cadence people (team members — never one of the principal's contacts, whom an unattended run may not message), and a parseable cadence.\n\nAuthoring from chat uses a **draft → confirm** handshake: the Executive calls `draft_workflow` (validate; return a `confirm_token` plus a plan summary), shows the user the plan, then calls `save_workflow` with the same definition and token — a token mismatch is rejected, so the saved workflow is exactly what the user approved. The step-by-step advanced editor drives the `/workflows/custom` CRUD endpoints directly.\n\n**The New workflow wizard** (`/jobs/new`) is the default way to create one from the UI. It works like conversational onboarding: the user describes the job, the `workflow_designer` Council agent (`openexecutive/workflows/designer.py`) asks one clarifying question per turn — deliverable, per-run inputs, sign-off, schedule, recipient — with up to four clickable suggested answers, then emits a complete definition plus a plain-language summary and the assumptions it made. Every turn offers the model exactly three fixed, name-sorted tools (`ask_clarifying_question`, `emit_workflow_draft` — reusing the chat tool's `DEFINITION_SCHEMA` — and `search_available_tools`, which is answered inside the same turn from the tool catalog, up to four searches per turn, with the tool_use/tool_result pairs never stored in the plain-text transcript; every tool a search returns is remembered on the session and replayed into later turns, so a forced draft or a repair turn — which cannot search — still has the exact names); `tool_choice` flips to the emit tool once, when the six-question budget is spent or the user clicks *Draft it now*. The emitted definition goes through `validate_definition`, the tool-availability check, and a check against saved custom names, with one repair turn that feeds the errors back. The system prompt is a cached constant; the live context — specialists, the roster with person ids, the user's timezone (the one set through `PUT /workspace`, else `USER_TIMEZONE`; cadences stay UTC), and taken names — is rendered once per session into the first user turn, and while refining, the exact current draft is prepended to the latest user turn so the model edits it rather than re-deriving it. Roster names and roles are flattened to one line and capped at 80 characters before they enter that context, and the system prompt tells the model to treat the whole block as data, never instructions. Sessions live in memory (`/workflows/designer/*`, 2 h TTL, 50-session cap), run one model turn at a time (a second concurrent `/message` or `/draft` gets 409, and a failed turn is rolled back by identity), and never write: the review card saves through the same `POST /workflows/custom`, which re-validates, and *Edit details* opens the draft in the advanced editor (`/jobs/new?designer=<id>`) before saving.\n\n**Editing is a conversation too.** *Edit* on a saved workflow (`/jobs/new?edit=<name>`) opens the same designer through `POST /workflows/designer/edit`: the stored definition is the starting draft, so the user's first message (\"have Mark sign off and run it Fridays\") is applied to it like any refinement, and a note in the context block (a user turn, never the cached system block) tells the model it is changing a saved workflow. The draft always keeps the workflow's name — `_check_draft` puts it back and skips the taken-name check — and the route keeps its on/off state, so an edit can neither fork a copy nor switch on a tool workflow waiting for approval. The stored draft is handed to the model marked as data, not instructions. The review card lists *What changes* in plain words against the saved version (`lib/workflowChanges.ts`): every field is compared, with named sentences for the sign-off person and what it asks for — a sign-off moved off approve/reject is called out because the run then continues whatever the answer — the schedule, steps added/removed/reordered, inputs, tools and the tool-call budget, and a catch-all line for any other field. It names only the newly added tools that may change things. *Save changes* calls `POST /workflows/custom/{name}/save-edit`, which saves the session's own draft after re-validating it, only when it is the draft the card showed (the card sends what it displayed; a message that landed since is a 409), and only if the stored workflow has not changed since the conversation opened (409 otherwise), so an edit started before someone switched the workflow off cannot switch it back on. The step-by-step form stays as the advanced editor (`/jobs/new?edit=<name>&mode=advanced`).\n\n**Action steps (workflows that act).** An `action` step (`ActionStepSpec`: `goal`, `tools`, `max_tool_calls` 1–50, default 20) is run by the `workflow_actor` Council agent (`openexecutive/workflows/action_step.py`) as a bounded tool-use loop. Its `tools` list is an allowlist of exact tool names — MCP gateway tools (`server__tool`, e.g. `google_workspace__append_table_rows`) and a small set of built-ins (`oe__read_file`, `oe__message_person`, `oe__create_alert` — which, in a workflow a team member created, raises the alert as theirs (`alert_tools.raised_for_workflow_owner`: source `team_member`, \"Raised by <name>\", never a company-wide broadcast) — plus any installed extension's tools registered with `workflow=True`, as `oe__<name>`, run inside `extensions.workflow_step(name)`; a built-in wins a name clash, and an extension tool counts as reading only when it says so) — and **clicking Create is the user's approval** of that list: the review card shows every tool, flags the ones that may change things (anything whose name doesn't say it reads, and any tool with a URL/URI/endpoint/webhook parameter anywhere in its schema, or whose schema couldn't be read, since a URL can carry data out), and names them in a \"this workflow can use these without asking again\" notice. Because that card is the approval, a workflow with action steps saved from chat (`draft_workflow`/`save_workflow`, whose confirmation is a token the model holds itself) is stored **switched off** (`is_active=false`) and `save_workflow` returns `status: saved_pending_review` with a `/jobs/{name}` link. An inactive workflow can't run or schedule (`get_workflow` and the scheduler skip it); `/jobs/{name}` shows it on the same review card, where **Turn on workflow** (`POST /workflows/custom/{name}/activate`, which re-validates the tools) is the approval — the click sends the definition the card showed, and the server refuses (409) if the stored one has changed since, so chat overwriting it while the card is open can't get new tools switched on. Chat may revise a switched-off workflow but refuses to replace a switched-on one that has action steps (an inbound email steering the Executive could otherwise switch off an approved job and stage new tools under its name); those edits happen in the advanced editor. The Workflows catalog (`/jobs`) lists switched-off workflows in a compact *Waiting for your approval* strip, and saving edits in the advanced editor keeps one off. `tool_catalog.py` resolves names to schemas through the gateway's `search_tools` (extensible-mcp's Markdown output is parsed; resolving is also the per-session discovery its `call_tool` requires) and validates availability at save time (`POST`/`PUT /workflows/custom`, chat `draft_workflow`/`save_workflow`, designer drafts) — an unknown, misspelled or deny-listed tool is a 422. The gateway meta-tools (`search_tools`, `call_tool`, `load_mcp_server`) can never be step tools. `run()` resolves every action step's tools before any step runs, so a vanished tool stops the run before an earlier step acts; `resume()` checks only the steps still to run, after the gate and decision are validated. The last turn of an action step always switches tools off so the agent can report. At run time only the allowlisted tools are offered (sorted; constant cached system block, per-run goal/inputs/earlier results in the user turn), every `tool_use` is re-checked against the allowlist, MCP calls go through `MCPGateway.call_tool` so the config deny-list and the Gmail/Calendar/Drive recipient gates still apply, the call budget is enforced (then a final tools-off turn asks for the report; running out of turns fails the step and lists what was already done), tool errors (the gateway's `Error:` / `Error calling tool` / `Tool error:` prefixes, or a truthy `error` field) return to the model as `is_error` results, each call emits a `progress` event and an audit row (`workflow_tool_call`: tool and outcome; for tools that may change things also a short digest of target arguments — ids, recipients, URLs, paths — so a redirected write is visible; content arguments are never logged), and the step's output is the agent's report plus an \"Actions taken\" list. Tool output is framed as data, never instructions.\n\n**Scripts in action steps.** Besides the step's own tools, the agent is offered one more, `run_script` (`openexecutive/workflows/step_script.py`), for work that repeats over many items — every file in a folder, every row, every email — or chains calls with simple logic. It writes a short Python script once instead of spending a model turn per call; each of the step's tools is a function in the script (`drive__move_file(file_id=…)`, or `call_tool(name, arguments)` by exact name), and only the script's final value and printed output come back. The script runs in **Monty** (`pydantic-monty`), a sandboxed Python interpreter for model-written code, in a worker process spawned per script: no files, network, environment, subprocesses or third-party imports — the step's tools are the only things it can reach. **A script is a faster way to make the same calls, never a way around them:** every call it makes goes through the same per-call path as a direct `tool_use` (`action_step._StepCalls`) — the allowlist, a call budget (a script's calls have their own: 10× the step's `max_tool_calls`, capped at `WORKFLOW_SCRIPT_MAX_CALLS`, default 500, because they cost no model turn each — so a step can work through a folder of hundreds of files while its direct calls stay capped at 1–50), the first-write target check (a held write comes back to the script as `{\"status\": \"held\", …}`) and one `workflow_tool_call` audit row per call — and the script itself is audited as `run_script`, with how many calls it made and how long it took. The step's \"Actions taken\" list collapses repeats into one line with a count. A step whose direct calls are spent keeps its tools on while the script budget has room, so it can still script the rest (a direct call is refused as over budget). When a tool returns a list of five or more items and the round didn't use `run_script`, the step adds the same `FANOUT_HINT` as chat (once a step), pointing the per-item work at one script. The worker is stepped from the step's own task (each call pauses it and is answered there), so cancelling the run stops the script and its in-flight call together, and each call's progress shows as it happens. At most `SCRIPT_MAX_WORKERS` (default 2) scripts run at once across the server, chat and workflows together; another waits for a slot within its own wall clock, else returns \"the server was busy\". A worker exists only while its script runs (about 8 MB idle). Execution time (excluding time waiting on tools), memory and recursion depth are capped inside the worker, the script has a wall-clock limit, and its text is size-capped; printed output past its cap is dropped. A failing script returns its error to the agent as an `is_error` result, with the calls it already made listed first (ahead of any long result, so a cut never drops them) so a fixed re-run doesn't repeat writes; a call cut off by the time limit is listed as `may_have_run`, and gets a `cancelled (may have run)` audit row. A workflow definition still holds no code; a script lives on only if the agent saves it as a tool (below). Because a step can loop at run time, the workflow designer keeps work that repeats over items (each email, file, row or listed follow-up) in ONE action step whose goal spells out the items, rather than a step per item; `run_script` is never a step tool, and a definition that lists it is rejected (`validate_definition`) so the designer's repair turn removes it. `WORKFLOW_STEP_SCRIPTS=false` turns the tool off, and a step then only calls its tools one by one.\n\n**Python jobs (`run_python_job`, `openexecutive/workflows/python_job.py`).** Monty can't run libraries, so library work on files (split or merge PDFs with pypdf, spreadsheets with openpyxl and pandas, charts with matplotlib, images with Pillow, and documents made from scratch or from files: Word with python-docx, PowerPoint with python-pptx, laid-out PDFs with fpdf2) runs as a Python job: Pyodide (Python in WebAssembly) executed by **Deno** in a process of its own per job. Pyodide alone is not a sandbox — its Python can call into the JavaScript runtime, which under plain Node reaches the server's environment, files and network — so Deno is what isolates it: it is started with read access to the sandbox folder and the worker script only, with no network, environment, writes or processes, and an empty process environment. Files go in on stdin and results come back on stdout. A job gets only what the call names: Knowledge-library files, the files attached to the chat message being answered (`attachment_files`, the uploads as sent, bound for that turn only by `POST /chat/upload` in `workflows/turn_files.py`, so the model never retypes an attachment's text), text the caller passes, and `inputs` (a dict the code reads); result files are kept 7 days under the company folder and served to the principal at `GET /python-jobs/{job}/{file}`, which the Executive links in its reply. A deployment can instead send jobs to a separate runner (`PYTHON_JOB_RUNNER_URL`, with `PYTHON_JOB_RUNNER_KEY` as a bearer token): `run_job` POSTs the same job (code, inputs, files, caps, time and memory limits) and reads back the same result object, at most as large as a local job's output, keeping only its known fields, so kept results, links and metering are unchanged; the local sandbox is then not needed, and the runner is trusted to isolate jobs. A runner can turn a job away with `{\"run_locally\": true}` (and an optional `reason`) in a non-200 reply, for example when the deployment's allowance for it is used up: the job then runs in the local sandbox if this machine has one, and otherwise fails with the runner's reason. Any other non-200 reply stays a job error, so a busy or broken runner never moves every job onto the machine. A runner with more libraries lists them in `PYTHON_JOB_EXTRA_LIBRARIES`, which the job tool's description then names, so the Executive doesn't refuse a job that needs one. The tool sits in the `workflows` tool group, labelled for jobs with or without attached files. The library set is fixed at build time: the API image installs Pyodide and Deno from npm and the compiled libraries from Pyodide's CDN, each checked against the sha256 in Pyodide's lock file, and a build smoke runs a job. Pyodide can't infer the compiled packages the pure-Python libraries import (lxml, Pillow, fonttools), so the worker loads them when a job imports docx, pptx or fpdf. Pyodide, Deno and the pure-Python libraries are pinned by hash too (an npm lock installed with `npm ci`, pip `--require-hashes`). One job runs at a time per process (200–450 MB each), with a `PYTHON_JOB_TIMEOUT_S` limit and a memory cap (`PYTHON_JOB_MEMORY_MB`, default 1536, as the process's data limit, plus V8 heap and WebAssembly memory caps); the worker returns at most 20 result files and 25 MB, and the API stops the job as soon as its reply passes that. The job runs at a lower CPU priority and is first in line if the machine runs out of memory, so a heavy job slows or loses itself rather than the API; Deno's own caches go in a temporary folder removed with the job; and kept results are capped at 200 MB in all, oldest first. The tool is chat-only, offered only on the principal's own turns (`PRINCIPAL_ONLY_TOOLS`), withheld on private turns, unattended passes and under the Act as me lockdown, and not offered at all without the sandbox (`PYTHON_JOBS_ENABLED`, `PYTHON_SANDBOX_DIR`).\n\nA job that worked can be kept the same way as a script (below): `save_as` and `description` keep its code as a Custom tool of kind `python`, and `run_python_job(tool=<name>, inputs={...})` with its files runs it again, recording the run, so a job done before costs no code-writing tokens. Python tools run only on the principal's own chat turns: they are never listed for workflow steps and never turn on for workflows (`PUT /saved-tools/{name}` answers 409), and `run_script` refuses one (and `run_python_job` a script tool). Every job writes one `python_job` audit row (`ok`, `duration_ms`, `cpu_ms` and `peak_mb` read from the process's /proc entry just before it is stopped, files and bytes in and out, attachments, the Custom tool it ran or kept), which `GET /audit/usage` sums into `python_jobs` with the model usage of the turns that ran one.\n\n**Saved tools.** A script that works can be kept to run again by name (`openexecutive/workflows/saved_tools.py`); each tool has a `kind`, `script` (`run_script`) or `python` (`run_python_job`, above). `run_script` takes `save_as` and `description` with a new script: if the script succeeds it is saved, with the set of tools it actually called, and a failed script is never saved. Later, `run_script(tool=<name>, inputs={...})` runs the saved script instead of new code, with `inputs` available to it as a dict. Only the principal's own turns save: a chat turn where the principal is speaking on a verified, interactive surface (the same test as `load_mcp_server`), never an inbound email, a teammate, an unattended run or a workflow step — a step is offered `tool=` but not `save_as`. A saved tool runs with the authority of whoever runs it, so its author must be trusted at least as much as anyone who may run it. For the same reason only a workflow step (its tools owner-approved) or the principal's own turn may run one: anyone else's chat turn is refused `tool=` and not offered `list_saved_tools`, so a stranger can neither list the principal's automations nor run one with inputs they choose. Descriptions are kept to one line of printable text (they are shown to models), and every save writes a `saved_tool_changed` audit row (`actor: executive`) beside the owner's own changes. Saving needs no approval beyond that, because a saved tool can do no more than the context running it: its calls go through the same per-call path as any script (in a step: the allowlist, budget, target check and audit), and a step runs one only when the step already allows every tool it used (otherwise the result names the `missing_tools`) and only at the version the owner turned on for workflows (`workflow_version`, Settings → Advanced → Custom tools → Use in workflows). A tool kept on a turn that read outside content could otherwise carry injected code into an unattended run, so keeping stays automatic and works in chat at once, but workflows wait for the owner; a newer save doesn't change the version workflows run, and pruning never drops it. Each step's `run_script` description lists the saved tools that step may run; chat asks `list_saved_tools`. Every save of changed content is a new version (the newest 20 are kept, plus the one that ran until then, so a rolled-back version the owner trusts survives later saves), every run is recorded (`saved_tool_runs`, the newest 200 per tool), and the owner can turn a tool off or switch it back to an earlier version on Settings → Advanced → Saved tools (`/saved-tools` routes, the owner's alone). A turned-off tool never runs, and a new version saved by the model does not turn it back on. `SAVED_TOOLS_ENABLED=false` stops saving and running saved tools everywhere.\n\n**Targets are chosen at run time — and a new one is confirmed once.** Approving a workflow approves its *tools*; which sheet, doc, recipient or URL each call hits is chosen by the model at run time, by design (a tab per month, a reply to whoever sent the invoice, a doc per client). What bounds that is the allowlist, the gateway's recipient gates, the audit digest, and **first-write confirmation**: a `TargetPolicy` (one per run) checks every call to a tool that may change things. `resource_targets` walks its arguments recursively for resource keys (snake- or camel-case ids, `to`/`cc`/`bcc`, recipients, addresses, attendees, members, users, owners, parents, URLs/links/hrefs, paths, channels, spaces, rooms, phones, hosts, buckets, tables, spreadsheet/document/folder/calendar/file); a matching key marks everything beneath it, even a `name`. Outside a resource, only a new item's own `name`/`title`/`subject`, message/thread/draft/label ids, `range`/`sheet` and workspace-mcp's acting `user_google_email` are skipped — and whatever the key, a bare value shaped like an email address, a URL or an international phone number is a target, except inside what the call writes (`rows`, `values`, `body`, `text` …). Key names are a heuristic, so this is a best-effort guard layered on the allowlist, the gateway gates and the audit. Float ids are compared as integers. Arguments too deep, naming too many targets, or holding an over-long value **fail closed** (the call is refused). A target is trusted only when it was approved for this workflow before (`workflow_approved_targets`, by value) or is an id a write in this run created — a top-level id/link field (`id`, `spreadsheetId`, `webViewLink` …) of the **structured JSON object** result of a tool whose name says it creates (create / insert / upload …) and that takes no URL — a tool whose schema couldn't be read is assumed to (free text, nested records and readers' or updaters' results are never read, so a fetched page, an echoed title, a shared page's links or a stranger in `ccRecipients` can't plant one); those survive a pause in the resume payload (`run_created`). Values written in the workflow's own text are *not* trusted, since anyone who can edit the workflow could change them without review: they are asked once, then remembered. Approvals are by value, for any of the workflow's tools, and are **cleared when the workflow's tool set changes** (a newly added tool must earn them again). Any other target makes the call **held**: it is not run and costs no budget, the model is told it is waiting for approval and carries on, and it is audited `held for approval` (at most 10 held per step, 16 KB each; an identical repeat is held once). Whether a call is checked at all follows the read-only label, which now never marks a tool whose name carries a write verb anywhere (`find_and_replace_doc`). After the step finishes, the run pauses with a `WaitForHumanEvent` to the workflow's **owner** (`owner_person_id`, the person who created it on the Workflows page or in chat; falling back to the principal if unknown or archived), `on_timeout=auto_proceed`, 48 h, and a `WorkflowResumeState` of `kind=\"held_writes\"` carrying the exact held calls. On resume (`_resume_held_writes`, fingerprint-checked like a gate, with the remaining steps' tools checked first), only `approve` runs them — each still has to be in the live step's allowlist and resolve; its targets are remembered first — and anything else (decline, timeout, unreadable) skips them; either way a *Held for approval* section is added to the step's output and the run continues at the next step. With no one to ask, held writes are skipped and noted; a step that fails or crashes after holding, or a resume that stops early (definition changed, a later tool missing), audits its held writes as dropped and says they did not run. The question quotes each target JSON-escaped (a value can't add its own lines) and always shows a URL's full scheme and host, saying how much of the rest is hidden. The owner answers by chat reply or with **Approve / Decline** on the run page (`POST /workflows/runs/{id}/decision`, which the principal may also use); remembered targets are listed and removable on the workflow page.\n\n`oe__read_file` extracts text (PDF, Word, Excel, CSV, Markdown, text) only from files under `WORKFLOW_FILE_DIRS` (default: workspace-mcp's attachment folder), resolving symlinks and `..` before the check (`tool_catalog.resolve_readable_file`, shared with the Executive's `read_document` tool). A scanned PDF is converted by `knowledge.pdf_reader` instead of failing as \"may be a scanned image\"; one that still cannot be read returns the reason. Action steps are allowed in scheduled workflows. Because they have external side effects, a resumed run heartbeats its claim (`touch_resume_claim`, at most once a minute as events flow — each tool call emits one; a busy database is retried on the next heartbeat, never treated as a lost claim; the sweep's requeue re-checks the claim's age in the same UPDATE, so a heartbeat landing between the sweep's read and its write wins), so the stale-claim sweep never requeues and replays a slow but live run, and a worker that finds its claim superseded stops at its next event. A worker that actually crashes mid-resume is still requeued; its action steps then run again, so goals should say how to avoid duplicates (the actor reads current state before writing). `GET /workflows/tools/search?q=` and `GET /workflows/tools/describe?names=` back the advanced editor's tool picker and the review card's labels.\n\nAn optional cadence (`daily@` / `weekly@` / `quarterly@`) re-uses the scheduler via the `dynamic_workflow` action kind, which runs the workflow on schedule and DMs the artifact to a rostered recipient. A gate followed by further steps pauses at `awaiting_human` and then resumes once answered, so gates no longer have to sit immediately before synthesis. They remain forbidden in cadence-enabled definitions: a scheduled fire has no interactive human to ask.\n\n`executive_research` keeps only its Markdown artifact in the run history; `parse_artifact_findings` reads its \"Findings reviewed\" lines back as `{severity, confidence, specialist, title, summary}` for Home's first-week card (see Today).\n\nBuilt-ins the system runs on its own (`morning_brief`, `end_of_day_digest`, `executive_reflection`, `executive_research`) set `background = True`, surfaced as `WorkflowMeta.background`; the `/jobs` ready-made list files them under a **System** chip instead of the default view. They stay runnable by hand.\n\n**Quick workflows** (`workflows/quick.py`) are one per playbook in effect that no built-in or custom workflow follows (switched-off custom ones count). They are derived whenever the catalog is read, never stored: `list_workflows()` returns built-ins, then Quick ones, then active custom ones, and `get_workflow` resolves a `quick_<playbook>` name after the registry (custom workflows may not take the `quick_` prefix). Each has one required field, `request`, and two steps: **Load context** (company profile plus RAG for the playbook category's specialist) and **Draft** (that specialist writes one Markdown document following the playbook). `WorkflowMeta.quick` is true for them. The 8 built-in playbooks no built-in follows are Quick workflows: board update memo, 1:1 agenda, layoff comms plan, positioning statement, post-mortem, customer interview plan, feature prioritization and market sizing. A company's own playbook shows up as one, hiding a built-in drops it, and a custom workflow that starts following one replaces it. If custom workflows can't be read, none are offered, since their followers are unknown.\n\n**Workflows vs. playbooks.** `/jobs` has two tabs: **Build** (`?tab=catalog`, the default) and **Runs** (`/skills` redirects to `/jobs`). A playbook is a skill (`knowledge/skills_repo.py`): *how* the Executive does a piece of work, with no inputs, schedule or side effects. A workflow is the runnable job. Workflows **follow** playbooks: a step that follows one gets its body appended to the step prompt via `workflows/playbooks.py` (`load_playbook` + `playbook_clause`). Six built-ins do — `board_prep` (`board-prep-deck`), `quarterly_plan` (`quarterly-okr-set`, `quarterly-forecast`), `mbr` (`monthly-business-review`, in the financial, KPI and function steps), `competitive_teardown` (`competitive-teardown`, in the four analysis steps), `fundraising_prep` (`fundraise-narrative`, narrative step) and `exec_search_brief` (`role-scorecard`, profile step). Each declares them in `Workflow.playbooks`; a unit test holds that declaration equal to the `load_playbook(\"…\")` calls in the module, and `WorkflowMeta.playbooks` exposes it. A custom workflow's `specialist` step may name a `playbook` (validated to exist at save; appended after `{field}` rendering, so braces in a playbook are never treated as placeholders). The lookup resolves the playbook in effect, so a company's customized copy changes the workflow's output, and a hidden, missing or malformed one falls back to the step's own prompt plus RAG — a workflow never fails over a playbook (`load_playbook` catches everything; a custom step whose playbook is unavailable emits a `progress` event saying so). Because an approved scheduled workflow reads its playbook at each run, chat never creates or changes a playbook: it saves repeatable work as a workflow (`draft_workflow`, confirmed by the user), and only a person can change what a workflow follows: a workflow's page shows each playbook it follows as **How it's done** (`components/jobs/HowItsDone.tsx`), with **Edit** (`PUT /skills/{name}`; on a built-in that saves the company's customized copy) and, for a customized copy, **Reset to original** (`DELETE`, which reverts). The chat summary of a drafted workflow names each step's playbook. `playbook_users()` maps each playbook to the workflows that follow it — built-ins, every custom workflow (switched-off ones included: turning one on approves its definition) and the Quick ones; the skills API reports it as `used_by`, and the Executive's `search_skills` hits carry it as `workflows`.\n\nCompleted artifacts are discoverable in the unified artifacts section (`/artifacts`, labelled **Documents** in the UI) alongside their run-detail page at `/jobs/runs/{run_id}`. A run someone starts by hand (`POST /workflows/{name}/runs`, `run_workflow`, research in chat) stores them as `workflow_runs.owner_person_id` and its history and output are theirs alone (plus the person a gate waits on); scheduled and system runs keep no owner and stay the team's. Workflow output stays Markdown — the scheduler DMs it and reflection rereads it as text — and gains other formats only on the way out: any run can be downloaded as Word (`/artifacts/run:<id>/download?as=docx`), and the Executive can repackage one with `get_artifact` → `draft_artifact(format=…, supersedes=\"run:<id>\")`.\n\n## Data-driven retrospectives\n\n`engagement_value_report` introduces a new workflow pattern: instead of the user typing the substance into a form (the `investor_update` / `mbr` shape), the workflow **reads its substance from the database**. A deterministic gatherer (`clients/engagement_activity.py`) pulls the period's decisions, initiatives, advisory consultations, delivered workflow artifacts (excluding prior value reports), follow-through counts, and alerts handled — from the live DB for the active client, or a parked client slot's `state.db` opened read-only. A single board-comms call narrates those facts (the prompt forbids inventing anything not in them; an empty period skips the LLM entirely), and the artifact's lists are assembled deterministically. Built for renewal conversations — the engagement record is the evidence.\n\nWith Take the lead as the Executive on (`orchestrator.take_the_lead`), reflection and research build their toolkit through `unattended_toolkit(..., source=...)`. That keeps solo's booking and `run_workflow` tools and an unrestricted `message_person` (teammates as well as the principal). Every acting tool goes through the gate, and a held action waits on Today as a `take_the_lead_action` decision. Reflection also gets the MCP gateway's `search_tools` and `call_tool` (`_with_lead_tools`; `call_tool` behind the gate, `load_mcp_server` left out), so it can find and use whatever the deployment has connected, such as building a sheet to track something. A note in the user turn (never the cached system prompt) tells it to act rather than only report, and it gets more room: 10 iterations, 4000 tokens, and tool results up to 4000 characters. The grounding check still refuses outward text naming people or figures the pass didn't see. New mail and chat also wake the reflection early (scheduler section). In training (`take_the_lead.training`) every acting call that isn't allowed waits too, as a training card for the principal, and both passes append `take_the_lead.learned_note()` to their user turn: that it's in training, and the principal's own edits on earlier cards as examples of how they want those done (never in the cached system blocks).",
+ "markdown": "Workflows are deterministic, multi-step orchestrations. The built-ins are registered in `openexecutive.workflows.WORKFLOW_REGISTRY`; user-created (dynamic) workflows are stored as data (see below). Each follows the same contract: structured input feeds an ordered list of named steps that render a Markdown artifact, persisted via `complete_run` into `workflow_runs.artifact`. The activity feed never shows a run's log title (`\"Executive Research (periodic)\"`): `workflows/run_outcome.py` gives each finished run a plain name (\"Researched your market\", \"Checked in with Sales\", or the name it started with, less its date) and one line on what came of it, read from that stored artifact, so older runs read the same and nothing extra is written or called. 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` and the weekly `goal_review`, which grades the goals no check-in covers; see Scheduler).\n- `weekly_review` — the principal's weekly look back and ahead (see *Weekly review* below).\n\n**Standing facts in unattended output.** `end_of_day_digest`, the weekly review's top-three call and the morning reflection append the standing facts (`memory.facts.with_standing_facts`; a teammate's marked `(per <name>)`) to their user turn, and the morning brief gets them through `render_briefing_context`. A workflow step that consults a specialist gets them through `route_to_specialist`. A correction made in chat therefore holds in every recurring brief and run. The morning brief also reads `facts.render_teammate_changes(since)` off the event loop and passes it to both `render_briefing_context` (a TEAMMATE CORRECTIONS SINCE LAST BRIEF block) and `build_brief_fingerprint`, so the principal hears of each correction a teammate made in the window, and that alone un-suppresses an otherwise unchanged brief. Proposals waiting for approval are listed only in a brief the principal reads privately (`include_proposed=_private_ok()`), and then mark the run private to them. The principal's own Always in the loop notes (`memory.history_brief`, only with their switch on) come in by a stricter rule, only on the scheduler's delivery (`PRINCIPAL_DELIVERY`), never a run from chat, whose tool result reaches the turn's shared audit row and peer memory: the morning brief's FROM YOUR NOTES — DUE SOON block and the end-of-day digest's FROM YOUR NOTES — TODAY block (what they committed to since the last digest, then what is due tomorrow). Either marks the run `private_to_principal` and moves its fingerprint; the digest, which had no private reads before, now emits that flag too. In the install's first week (`briefing.first_week`, seven days from the principal's People row) the morning brief also passes a GETTING STARTED block to `render_briefing_context(getting_started=)` and its keys to `build_brief_fingerprint`: onboarding goals, departments with no leader and, on the scheduler's delivery with Act as me and Draft replies to my inbox on, who wrote to the owner's own mailbox (sender and subject only) and, with Read my calendar on, today's meetings on their own calendar (time and title), either of which marks the run `private_to_principal`. The brief opens with **Getting started** and is never the quiet line while the block has anything in it (see Today).\n\n### Change-aware principal briefs\n\n`morning_brief` and `end_of_day_digest` are the two recurring briefs the scheduler sends to the principal. Both are written with `briefing.narrative.brief_model()`, the Executive's own model (its Council pick, else `DEFAULT_MODEL`), since a brief is the Executive speaking; only the grounding repair stays on the fast model. Both are now a *delta*, not a re-list: the window is \"since the last **delivered** brief\" (`briefing.brief_state.since_for`; 24 h on a cold store, clamped to 7 days), activity comes from `_build_activity(limit, since=…)`, proposals (action category only) split into *new since last brief* — enumerated, with each item's why-now and next move — versus a one-line carried-over count, a *rewritten* block lists carried items the review rewrote inside the window (`brief_state.rewritten_since`: verdict `changed`, still open — the brief reports them under \"what changed\", never as done), and a *handled overnight* block lists what the Executive's alert review **completed** on its own (`brief_state.handled_since`; the `changed` verdict is excluded because the alert is still open). The morning brief also reads the principal's **live world** since that window opened (`briefing.live_signals.gather_live_signals`): mail and chat the Executive handled (INBOUND, grouped by sender and subject, each email from the roster marked replied or not, earlier days dated), under a NOW line and THE PRINCIPAL line that names its reader so the brief writes \"you\" (the end-of-day digest gets the same line, and the team reflection a YOUR PRINCIPAL line under its roster; the reflection flags only what today's input still shows), what got stuck (STUCK: a reply the outbound gate held, a non-roster sender who got no reply, a Google Chat message left unanswered, chat drafts still in the principal's Gmail, after `live_signals.settle_principal_drafts` has marked the ones they since sent or deleted there), the principal's own chats, and — in both modes now, unless the solo top three already listed it — today's calendar, read fresh (`live_signals.refresh_calendar(max_age=0)`). The 07:30 reflection's **Flagged for the brief** bullets are carried across (`brief_state.reflection_flags_since`, the latest reflection run finished inside the window) instead of surviving only as an activity line with the run's title, and the rhythm runs themselves (`today.RHYTHM_WORKFLOWS`) are dropped from the brief's activity: their dated titles were noise and moved the fingerprint every day. At-risk departments name their slipping goals and each proposal carries its age. The period is the principal's local date. Section order: top call → **today** (the calendar's shape and anything stuck) → what changed (inbound first, naming who wrote) → handled overnight → needs you (new only) → waiting on → at risk (the slipping goal, or the department left out — never \"no detail yet\"). Quoted mail, chat, invite and reflection text is marked as data, never instructions. **Privacy:** the brief reads what is private to the principal — their contacts' alerts and mail, their drafts, their chats and their calendar — only on a run for them: the scheduler's (`morning_brief.PRINCIPAL_DELIVERY`) or the principal's own verified chat turn in a conversation only they can read (`delegation.settings.private_conversation`: the web chat, a Slack or Discord DM, a private Telegram chat — never a shared channel, where the reply is posted for everyone). A run anyone else starts (a teammate from chat in team mode, `POST /workflows/…/runs`) reads what everyone may see, as before. A run that did read a private row says so on its `result` event (`private_to_principal`: its live read differs from the shared one in any key or count), and the scheduler, `run_workflow` and `POST /workflows/{name}/runs` all then keep `persistence.PRIVATE_RUN_ARTIFACT` in the run history instead of the text. Text another pass wrote (the reflection's flags) renders as quoted ` > ` lines and every goal and headline field is one-lined, so none can start a line that reads as a block header. The fingerprint carries the live signals' time-free keys (who wrote about what, what is stuck, the calendar's shape) and the reflection flags when there are any, so \"nothing new\" means the principal's world was quiet too; the context summary is logged at INFO (`morning_brief: context since=… inbound=… stuck=… suppressed=…`). In **solo mode** (one person using Open Executive for themselves) both briefs speak to the principal, whatever their role: the morning brief runs top call → top three today → what changed (inbound and stuck first) → handled overnight → needs you → due this week (the principal's open loops overdue or due within 7 days, from `open_loops.principal_due_soon`) → goals at risk (named by area), the end-of-day digest what I did → open decisions → goals at risk tomorrow → sleep on this, over a context with goals at risk by area and no people-waiting or department block; the fingerprint carries the mode and ignores who is awaiting, and carries the due items as `(loop_id, state)` pairs when there are any. **Top three today** is picked in code, not by the model (`briefing.top_three`: overdue then due-today commitments, off-track then at-risk goals, commitments due later this week, then active projects, stalest first). The solo Briefing's *Top three today* card shows the same pick from the same code (`GET /today/top-three`, see Today). When the MCP gateway runs the Google Workspace server, one `google_workspace__get_events` call (4 s timeout) lists today's events on the principal's calendar — their address as the calendar id, read with the Executive's account (`primary` when the Executive is signed in as them) — and on a business day (`calendar_tools.is_business_day`, the rule the booking tools apply; at the weekend the day's events are still listed but no slot is suggested) each item gets its own free block inside `CALENDAR_BUSINESS_HOURS_START`–`_END`, rendered with a TODAY'S CALENDAR block — only a date-only event is all day, a zero-length one blocks nothing, and one whose times can't be read is left out; no gateway, no principal address, an error, a timeout or a reply it cannot read all mean no calendar and no slots, never a failed brief; the log records only the reply's length or the error's type, never calendar text. When the principal has Act as me and **Read my calendar** on (`delegation.calendar`) and their mailbox opens as theirs, `top_three.read_todays_calendar` also reads their own calendar through their own sign-in (Gmail or Outlook, same 4 s timeout, declined events left out), at the same time as the Executive's read, and merges the two: an event with the same title and times on both is listed once, and either read alone is enough. This read feeds the morning brief, the /today calendar cache (`live_signals.refresh_calendar`) and so the end-of-day digest and Right now; the solo top three adds it only on a run for the principal (`build_top_three(include_own=private_ok)`). 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. Both are written to their reader in code (`briefing.reader`): the principal's full name and addresses are masked to \"the reader\" throughout the context under a THE READER line, the prompt says \"you\" for the reader, nobody is \"the principal\" and the Executive is \"I\" / \"me\", and a draft that still slips is rewritten once (the morning brief) and fixed in code. **The end-of-day digest reads the day itself.** On the scheduler's delivery to the principal alone it leads with TODAY WITH YOU (`session_store.own_conversation_since`: the principal's own conversations with the Executive since the last digest, their words and its replies, never a conversation someone else owns) and the live blocks (`live_signals.render_live_blocks`: mail in, what got stuck), then COMING UP (the Executive's own follow-ups due in the next two days). It leaves out its own rhythm runs (`today.RHYTHM_WORKFLOWS`) and gets the reader's leave-out list (`brief_requests.render_parts`). Its shape is **Today**, **Done for you**, **Next** and an optional **Sleep on this**, at most 150 words, with no header for an empty section. Before this it read only the Executive's own bookkeeping, so on a day of real work it reported its own briefs and missed every number decided in chat.\n\n**Brief delivery.** `scheduler.runner._deliver_to_principal` maps the principal's `preferred_channel` (`slack` / `discord` / `telegram` / `email`) to its delivery channel and tries it first, then the other chat channels the principal has an id for, in the order Slack → Discord → Telegram. Email goes through the active MCP gateway (`google_workspace__send_gmail_message` as the Executive's own address, to the principal, subject `<title> — <date>`) and is used only for an explicit `email` preference, or for `any` when no chat channel resolves — an owner linked by email at setup has `any`, so one who also has Slack does not start getting two emails a day. When nothing can deliver (a web-only principal, or email with no gateway), the brief is still generated and stored as a run with its artifact, as before — a web-only principal reads it on the Artifacts page — it is just not delivered (audited), so the window does not advance, and the next occurrence is chained. The same delivery path carries the client-rotation digest and the weekly review.\n\n**Grounding.** Nothing an unattended pass writes is read by anyone before it goes, so `openexecutive.briefing.grounding` checks it deterministically — no model judges the model. A name (a run of two or more capitalised words once section headers, weekdays, imperative openers and org nouns are trimmed, or one capitalised word in a person slot like \"ask Marcus\" or \"Marcus wrote\") is grounded only when a single line of the pass's inputs holds all of it, or it belongs to a roster person some input mentions — being on the roster alone is not enough. A figure (money, a percentage, a k/M/B number, any bare number of 11 or more; never a date, time, year, duration, id, list marker, `Q3` or small count) is grounded when an input number matches it within the precision it is written with (`$1.2M` matches `$1,234,567`; `47 units` does not match 48). The inputs are the rendered context split into lines labelled by section (a header also carries its bullet count), the company profile and the department titles. `morning_brief` renders its context itself and hands it to the synthesizer as `rendered_context`, so the check reads exactly what the model read; after the quiet fallback, `ground_brief` runs on both briefs. When something is ungrounded it makes one repair call to the fast model (same system prompt, the list of items, \"remove or correct using only the context\"), re-checks, then drops each line still ungrounded and any header left empty, and appends \"_I left out N lines that named people or figures I couldn't match to your data. They're under Left out of your brief on Home._\" (everything ungrounded → one held-back line). Every held line goes in the `grounding` audit row's untruncated `full` payload (up to 30, 400 chars each; `details` keeps a five-line preview), and `grounding.recent_held_back` reads the last day's back for `GET /today`'s `held_back`, which Home lists under **Left out of your brief** for the principal alone — after the narrative inputs are taken, so the held lines never reach a prompt. Then each grounded figure gets a server-chosen ` [n]` — the matching input line with the most words in common with the figure's clause — and a `**Sources**` list closes the brief (`- [n] <section> — <snippet>`, at most 9, snippets quote inbound mail, so links are masked (\"(link removed)\"), Markdown, angle brackets and @-mentions stripped, and they are cut to 90 chars; never `[n]:` at a line start, which Markdown reads as a link definition). Text with nothing to change comes back byte-identical, the fingerprint hashes the inputs so suppression is unaffected, and the grounded text is what is delivered, stored and recorded as delivered. Both brief prompts and the digest prompts say the rule up front. `executive_reflection` wraps its handlers in a `GroundingScope`: `create_alert`, `message_person`, `send_department_message`, `send_company_broadcast` and `schedule_followup` refuse text with an ungrounded name or figure, returning a JSON error that names the items so the model can look the person up or leave the figure out (every tool result joins the inputs, so a `lookup_person` answer grounds the DM after it; the recipient's own name always counts). Its **Flagged for the brief** bullets are filtered the same way before the tool log is appended — the next brief quotes them, where they would ground themselves — and `brief_state.reflection_flags_since` now stops at the tool log's `---`. The reflection's `grounding` rows are private when a private-to-principal alert reached its context, and the digest's always are (its HANDLED block can quote one). Everything fails open. `GROUNDING_CHECKS=enforce` (default) acts, `report` only writes the `grounding` audit rows, `off` skips it; `GROUNDING_CITATIONS=false` drops the markers. Not yet grounded: the /today header (its cards sit beside it), `weekly_review`, the research synthesis, dates and meetings, and a real person named in the wrong role.\n\n### Weekly review (solo)\n\n`weekly_review` (background, inputs all defaulted) closes out the principal's week in six steps. **Goals**: every area with goals is graded by its own specialist, concurrently, with the department check-in's verdict contract (`_parse_verdicts`) and write-back (`persist_goal_verdicts` → `record_goal_review`, one `goal_status_review` audit row per area with actor `weekly_review`); an area with no goals is skipped, one without a specialist is listed ungraded, and one whose specialist fails is shown as last recorded. **Commitments**: `open_loops.principal_due_soon` — overdue or due within 7 days. **Projects**: active initiatives with no update for 7+ days. **Decisions**: the week's (`episodic.decisions_since`). **Revisit**: up to three decisions older than 30 days with an empty outcome (`episodic.decisions_awaiting_outcome`, newest first), listed as `[decision N]` under *How did these turn out?* — the principal's answer is recorded with `record_decision_outcome` (see Agents). **Assemble**: every section always renders (a one-line note when empty), ending with *Next week's top 3* from one fast-model call that follows the `weekly-review` playbook (a constant system prompt; the playbook rides in the user turn), trimmed to at most three list items — or, when that call fails or returns nothing, the same ranked pick the morning brief uses. In solo mode the scheduler fires it weekly (`principal_weekly_review`, see Scheduler) and delivers it through `_deliver_to_principal` like the briefs, recording the delivery outcome. The solo Briefing also shows the latest completed run to the principal (`GET /today/weekly-review`, see Today): `weekly_review.summarize_review` reads the artifact's title line (`TITLE_PREFIX`) and its last `TOP_THREE_HEADING` section back as plain text, so a principal no channel reaches still sees next week's top three. Wording is role-neutral; run by hand in team mode it says *department* instead of *area*.\n\n**Principal-only workflows.** A workflow can name the workspace modes in which only the principal may start it (`Workflow.principal_only_modes`): `weekly_review` in both modes (built from the principal's decision log, commitments and goals, and it re-grades the goals) and `morning_brief` in solo (built from the principal's commitments and calendar). Team `morning_brief` and every other workflow can be started by anyone as before. This decides who may start or trigger a run, not who may read one: stored runs, the scheduled briefs and weekly reviews included, are read under the existing `/workflows/runs` rules — which is why a morning brief that drew on the principal's private rows is stored as `PRIVATE_RUN_ARTIFACT`, not as its text.\n\n- **From chat**, `run_workflow` checks at dispatch, before any run row is created, that the turn is the principal on a verified surface — `create_goal`'s rule — and otherwise refuses with a plain error that does not spell out the rule.\n- **Over HTTP**, the Jobs page's `POST /workflows/{name}/runs` and `POST /evals/runs` (a workflow scenario runs the workflow on live data) call `refuse_principal_only_run`: only a caller signed in as the principal, or a request with no caller email (the CLI or local login), may start the run. Unlike the workspace settings, an install with no principal on the roster lets no signed-in caller in, as in chat. Anyone else gets a 403 (\"Only the principal can run this workflow.\") before any run row exists. The mode is the stored one, or an eval scenario's own `workspace_mode`. The eval route runs exactly the scenario list it checked.\n\nEvery refusal is audited `refused=true` with the workflow, the mode and the caller. The checks fail closed: a mode that cannot be read counts as principal-only, and a check that cannot read the roster refuses.\n\n**Knowledge in the reflection.** A chat turn looks the knowledge base up before the Executive answers; the reflection reads the org's state instead, so nothing looked it up for it. It now carries its own `search_knowledge` tool (`orchestrator.knowledge_tools`, not in the shared `_ALL_SKILL_TOOLS`), which runs the same `knowledge.retriever.retrieve` as chat — the review gate, the synced Drive / OneDrive / Confluence / Notion collections and the published-artifact rule (the pass has no viewer, so no one's private document comes back). The prompt (`_KNOWLEDGE_RULE`, both modes) asks it to search before acting on or flagging something that turns on a customer's or supplier's terms, a price, a policy, a plan or a past decision. Its passages come back up to 4,000 characters (`execute_tool_calls(wide_results=...)`) while other tools stay at their short preview, its result counts as grounding input like any tool result, and the run's tool log keeps each line to 160 characters. Read-only, so Take the lead never gates it. The loop has 5 iterations (was 4) to leave room for a search before acting.\n\nNeither the nightly reflection nor the research synthesis can call `ack_alert`: both run unattended with open alerts rendered into their context, and those headlines are minted from inbound mail and chat, so an injected \"the principal already dismissed 13\" would be acted on with nobody watching. Closing an alert is the alert review's job, with evidence.\n\n`executive_reflection` now carries memory: yesterday's standup (the previous completed run's artifact) is rendered into the context and the prompt forbids re-acting on anything listed there unless it changed; open alerts render with their id, review verdict and recommended move. Reflection never closes alerts — the alert review does, with evidence. It also renders an **OPEN LOOPS** block (up to 10, soonest due first, overdue flagged) from Attunement so the standup can connect a slipped promise to the rest of the org state; the nudge engine already chases overdue loops, so the prompt tells it not to DM about a loop merely for being overdue. A **WHAT LANDS** block (from the Attunement outcome ledger) shows, per person, how often each kind of proactive DM got answered over 30 days; the prompt steers DMs toward kinds that land and away from kinds a person reliably ignores. Reflection and research tag their tool execution as proactive (`tag_proactive`) so their DMs are counted. Resolving a wait-for-human approval (`resumer.apply_resolution`) marks the nudges that chased it `acted`. `close_open_loop` is withheld from reflection for the same reason as `ack_alert`: loop text is quoted from what people wrote. `unattended_toolkit` also drops `schedule_tools.UNATTENDED_WITHHELD_TOOLS` (today `create_goal`) from both passes in both modes: a goal is the principal's own decision, and these passes see only inbound text. A turn private to the principal (mail from one of their contacts, or mail they forwarded) cannot start a workflow either: `run_workflow` and `run_executive_research` are in `schedule_tools.PRIVATE_TURN_WITHHELD_TOOLS`, which the chat loop neither offers nor runs on such a turn, since a workflow's steps can reach anyone.\n\nIn **solo mode** the reflection is framed for the principal, whatever their role: they are the only person who uses Open Executive and the only one it takes direction from, it prefers `create_alert` and `schedule_followup` to the principal, and it never messages anyone else from an unattended pass — the people in the principal's world are contacts, so anything they should hear is flagged for the principal to raise. The team roster is replaced by one YOUR PRINCIPAL line (person_id and follow-up channels), its follow-up guard is seeded from the principal only, and department risk renders as areas with goals at risk. The research synthesis follows the same rule — its routing menu and roster name only the principal. In both, `send_department_message`, `send_company_broadcast` and `set_department_head` are withheld, and so are `create_calendar_event`, `create_instant_meeting` and `run_workflow` — a booking reaches its attendees and a workflow can do anything its steps do, so the principal books and starts workflows from chat — and `message_person` refuses anyone but the principal. These passes run unattended with inbound text in their context, so the rules are enforced in code, not only in the prompt.\n\nIn either mode, both passes now dispatch only the tools they offer: the handler map is built from the offered list, so a name the model emits without being offered it is skipped as an unknown tool. They used to look names up in the full handler registry, so tools they deliberately withhold — the raw DM tools (`send_slack_dm` has no roster check), `ack_alert`, `close_open_loop`, and in research the watchlist writes and `run_workflow` — still ran when the model emitted them. Both read the mode before binding their own session (so a caller's override, such as an eval's, counts) and pin it on that session, so their tool handlers use the same mode. They carry the principal's role across the same way (`effective_principal_role` of the caller's session, pinned as `turn_principal_role`), so a specialist or workflow started from either pass sees the role of the turn that started it. Team runs are unchanged.\n\n### Wait-for-human pause\n\n`wait_for_human` (`openexecutive/workflows/wait_for_human.py`) is a first-class step primitive that pauses a run: the runner calls `save_checkpoint`, the `workflow_runs` row moves to `status='awaiting_human'`, and the serialized `WaitForHumanEvent` is stored in `state_json`. (Department authority is a *separate* mechanism — `propose_only` departments file a briefing alert via `departments.authority.propose_via_alert` and mark the scheduled action done; they do not route through this gate.)\n\n**Delivery.** Both checkpoint sites — the SSE route and the `run_workflow` chat tool — call `workflows.gate_delivery.deliver_gate_question` immediately *before* checkpointing, so `state_json` carries the routing fields a reply is matched against. Two modes. When the approver is the person already in the conversation (the chat session's `origin_channel` is set — to anything but `email`, whose answer is no chat reply and would never be sent — and its `caller_person_id` is the gate's `person_id`), nothing is sent — the question rides in the Executive's own reply — and the gate records `origin_session_id` plus the session's channel. The resolver compares base ids (`memory.conversation_ids.base_session_id`), so a question asked in one conversation of a Telegram chat or a DM is still answered by a reply after a quiet gap or /new has started the next. Otherwise the question is delivered through `schedule_tools.handle_message_person`, which picks the person's preferred channel, falls through on a failed send, and falls back to a briefing alert; the gate then records the channel, address and provider message id that send returned, plus the id of the DM session it landed in — that send is always 1:1, so the answer belongs in that conversation and nowhere else. Without it the gate matched on person and channel alone, so an unrelated @mention in a public channel resolved it and had the acknowledgement, run title included, posted where everyone could read it. The question is sent with `notifications.approval_send`, so the person's quiet hours and *In my briefs* never hold it, whatever their urgent setting: only a reply to it resolves the gate. Delivery is not guaranteed: the outbound guard can suppress it (duplicate, rate cap, quiet hours) and an unreachable person gets the alert fallback. Both cases leave the routing fields empty and report `delivery` as `suppressed` / `alerted` rather than claiming someone was asked, and the chat tool's presentation hint changes accordingly.\n\n**Matching a reply.** Each inbound adapter passes the message to `inbound_resolver.resolve_inbound_message` with its `session_id`. Matching is three-tier: an explicit `in_reply_to` against a stored `outbound_message_id`; otherwise a single open run on that channel; otherwise one utility-fast disambiguation call gated at 0.85 confidence. An unmatched explicit reference rules out only the candidates that carry a stored outbound id — the ones it could have matched — and the rest continue; rejecting outright meant an adapter that passes a thread id on every message (Slack's `thread_ts`) short-circuited the later tiers forever, and a global test let one delivered gate's id block an unrelated self-approval gate. Channel names are normalized (`slack_dm` ≡ `slack`), the delivered address is compared when both sides know it, a row whose `state_json` will not parse is refused (a corrupt row otherwise presents as a legacy one), and an empty stored channel is treated as a wildcard only for rows checkpointed before gate delivery existed. Two guards keep an open gate from swallowing unrelated traffic: a gate carrying an `origin_session_id` matches replies only from the conversations the adapter names (a Slack or Discord thread offers its parent channel session too, mirroring the history double-write, since a gate raised on a mention recorded that session while the answer arrives under the thread's — on Slack only when that person rooted the thread, or the alias would reach into a colleague's), and the parser can return `unrelated`, which declines to resolve and lets the message reach the normal chat path. The parser is handed the gate's own question, so a bare \"yes\" is judged against something. Its fallback is flagged by a key the model cannot emit rather than by a magic note string it could, and a fallback declines to resolve on *every* reply shape — recording the empty string a `free_text` fallback fabricates would close a sign-off on a parser outage. Every shape can answer `unrelated`, not just `approve_reject`: without it an open `free_text` gate turned the person's next message into its answer verbatim, and a `numeric` one swallowed any message containing a number. The parser has one caller outside workflows: its `roster_identity` shape — `{decision: approve|link|decline|unrelated, name, kind: team|contact|null}`, with `name` only as the person wrote it (never inferred) and a fallback of `unrelated` — reads the principal's emailed answer to a roster request (who a new sender is; see Org). It is not a gate reply shape, and a fallback or `unrelated` leaves the request waiting. `resumer.apply_resolution` then records the decision, marks the run `resolved`, and writes an audit row. A timeout applies the step's `on_timeout` policy (escalate / auto_proceed / fail). The outcome surfaces on the Today dashboard.\n\n**Resuming past the gate.** A paused run continues on its own. Re-entering it was long assumed to mean serializing a Python generator frame; it does not. The only state alive across a dynamic workflow's steps is its inputs (already persisted), a company-profile block that is recomputed, the completed steps' output strings, and the loop cursor — so the engine hands the checkpoint a small JSON `WorkflowResumeState` (workflow name, the gate's id and index, the next index, the outputs so far), stored in `workflow_runs.resume_state_json`, and `DynamicWorkflow.resume` replays its step loop from the recorded index. `run()` and `resume()` share that one loop, which is why a second gate needs no special handling — it is simply another pause raised from the same place. The payload rides on a `WaitForHumanEvent` field declared `exclude=True`, so it can never leak into `state_json`, whose exact key set the resolver branches on. A gate with no payload is *pause-only*: the decision is recorded and the run stops, which is what every caller got before resume existed.\n\n`resumer._process_resumable` claims a resolved run with one guarded UPDATE — `resolved` → `running`, stamping `resumed_at` and minting a claim token — and drives it to a terminal row. It runs two ways: immediately, via a task `apply_resolution` kicks off so a Slack approval starts moving in seconds, and every 60s from the poll loop as the durable backstop. Both share the claim, so a run executes exactly once even with two resumers against one database. The kicked task binds no chat session (`set_session(None)`), exactly like the poll loop: it is created inside the inbound handler that recorded the answer and would otherwise inherit that person's live turn — so a run resumed because the principal replied on Slack does not act with the principal's identity (it cannot, for example, reach the principal's contacts). It drops the handler's audit scope too (`audit.context.unscoped_audit_rows`): inherited, the principal's scope would make private every row of the run that names a contact, and whoever started the run would see those rows vanish after the approval. The poll runs the executor *after* the timeout loop, which is what finally makes `on_timeout='auto_proceed'` do what its name says: the timeout resolves the run and the same tick executes it. While the Executive is paused (`scheduler.pause`) the resumer does nothing — no startup sweep, no timeouts, no resumes — and `apply_resolution` still records the decision but skips the immediate kick; the first unpaused iteration catches up on all of it, so a timeout that lapsed during the pause applies its `on_timeout` policy then.\n\n**The claim is fenced, because it is not a lease.** The stale sweep decides a worker is dead from a wall-clock guess, so a slow but *alive* worker will eventually be declared dead and replaced. Every write the executor makes carries its claim token and is refused once superseded — otherwise the replaced worker's late completion lands on top of its replacement's result, or its checkpoint at a later gate resurrects an already-finished run and asks the approver a second time. The retry budget resets at each new gate (a gate is new work, not a retry), and a run that exhausts it is *ended* rather than dropped: an exhausted run sits in `running` with a payload, in neither queue, and would otherwise show as in-progress forever.\n\n**The gate fails closed.** Continuing is an allowlist — `approve` and the synthetic `auto_proceed` — not \"anything that is not a stop word\". `decision` is whatever a fast model extracted from free-form chat and it drifts; under a denylist, \"rejected\", \"Reject\", \"decline\" and \"no\" would all continue, so the approver declines and the deliverable is produced anyway. Reply shapes that ask a question rather than seek permission always continue, since the answer *is* the value. A stop ends the run at `error` with the human's note. Either way the decision becomes the gate step's own output, so it reads as a section *in* the artifact — capped and blockquoted, because that text reaches the synthesis specialist as prompt context.\n\n**A definition edited during the pause is refused.** Resume re-validates the payload's version, the recorded gate, *and* a fingerprint of the whole step list, and derives the index to continue at rather than reading it from the payload. Pinning only the gate would not be enough: definitions are overwritten by name and any rostered user can save one, so someone could keep the gate identical and replace every step after it — and the approver's sign-off would be recorded against work they never saw, which defeats the one thing an approval gate is for. No built-in workflow yields the gate; only user-created dynamic workflows do.\n\n### Launching from chat\n\nWorkflows are not only reachable from the `/jobs` UI — the Executive can list and run any of them mid-conversation. `openexecutive.orchestrator.workflow_run_tools` wires two tools into the main chat loop: `list_workflows` (the launchable catalog, with each workflow's input fields) and `run_workflow` (runs one to completion and returns its Markdown artifact, using the same engine as `POST /workflows/{name}/runs`). `run_workflow` resolves both built-ins and custom workflows via `get_workflow`, validates `inputs` against the workflow's input model, persists the run (`create_run` → `complete_run` / `fail_run`), and on an approval-gate step checkpoints the run as `awaiting_human` exactly as the HTTP route does — literally the same code, since both call `workflows.gate.checkpoint_gate`, which delivers the question and writes the checkpoint in one place. It never hangs waiting on a human, and it reports both whether the question reached them and whether the run will continue by itself once answered. The runners that *cannot* pause — the schedulers, evals, client rotation, onboarding, the research tools — call `gate.ensure_workflow_event`, which raises on a gate rather than letting one be swallowed; the scheduler's dynamic-workflow branch used to ignore it and record a successful run containing nothing. `executive_research` is excluded (it has the dedicated `run_executive_research` tool). Running a workflow from chat delivers nothing on its own — it renders the artifact into the conversation, and the recurring principal briefs (`morning_brief`, `end_of_day_digest`) reach anyone only via the scheduler's own `_deliver_to_principal`. The tool description used to claim those two DM the principal when run and to confirm before firing them, which had the model soliciting a confirmation on a false premise; it now names `executive_reflection` as the one workflow that really does execute tool calls of its own (DMs to heads, broadcasts, alerts). A successful run surfaces an `action_taken` chip linking to `/jobs/runs/{run_id}`.\n\n### Dynamic (user-created) workflows\n\nUsers create reusable workflows on the fly — from the executive chat, the conversational wizard at `/jobs/new`, or the step-by-step advanced editor — without shipping code. The Workflows page (`/jobs`) opens on a *Start here* panel that leads to all three: the user describes the job in a sentence and *Start* opens the wizard with that text sent as its first message (handed over in `sessionStorage`, so a link cannot make the wizard send text the user never typed; where storage is blocked it falls back to `/jobs/new?describe=`, which only fills the composer and sends nothing), or picks *Step by step* (advanced editor) or *Talk it through in chat* (`/?new=1&draft=`). Below it come the user's own workflows, then four ready-made starter picks with the full built-in list folded behind *Browse all* (`?browse=1`). The picks and the example chips follow the workspace mode: a team gets the investor update, board prep, MBR and competitive teardown (and a board pre-read chip); a solo owner-operator gets the MBR, pricing review, churn deep dive and quarterly plan, with chips for a Friday cash and pipeline check, customers who stopped buying and a competitor digest (`lib/workflowStarters.ts`; a unit test pins every pick to a startable `WORKFLOW_REGISTRY` entry). A dynamic workflow is a stored JSON definition (the `dynamic_workflows` table) interpreted at runtime by one generic `DynamicWorkflow` engine (`openexecutive/workflows/dynamic.py`) that implements the same `Workflow` ABC as the built-ins, so the run path, SSE streaming, run persistence, and `/jobs/[name]` form rendering are unchanged. `get_workflow` / `list_workflows` fall through to the dynamic store after the static registry (built-ins win on a name collision).\n\nA definition declares free-text input fields and an ordered step list of four kinds: **specialist** (consult a specialist with a goal prompt, optionally grounded by RAG), **action** (get something done with tools — see below), **approval_gate** (a `wait_for_human` pause), and a terminal **synthesis** step that assembles the artifact. At least one specialist or action step is required. `validate_definition` enforces the structural rules: exactly one terminal synthesis step, valid specialists, `{placeholder}` tokens that reference declared input fields, rostered approval/cadence people (team members — never one of the principal's contacts, whom an unattended run may not message), and a parseable cadence.\n\nAuthoring from chat uses a **draft → confirm** handshake: the Executive calls `draft_workflow` (validate; return a `confirm_token` plus a plan summary), shows the user the plan, then calls `save_workflow` with the same definition and token — a token mismatch is rejected, so the saved workflow is exactly what the user approved. The step-by-step advanced editor drives the `/workflows/custom` CRUD endpoints directly.\n\n**The New workflow wizard** (`/jobs/new`) is the default way to create one from the UI. It works like conversational onboarding: the user describes the job, the `workflow_designer` Council agent (`openexecutive/workflows/designer.py`) asks one clarifying question per turn — deliverable, per-run inputs, sign-off, schedule, recipient — with up to four clickable suggested answers, then emits a complete definition plus a plain-language summary and the assumptions it made. Every turn offers the model exactly three fixed, name-sorted tools (`ask_clarifying_question`, `emit_workflow_draft` — reusing the chat tool's `DEFINITION_SCHEMA` — and `search_available_tools`, which is answered inside the same turn from the tool catalog, up to four searches per turn, with the tool_use/tool_result pairs never stored in the plain-text transcript; every tool a search returns is remembered on the session and replayed into later turns, so a forced draft or a repair turn — which cannot search — still has the exact names); `tool_choice` flips to the emit tool once, when the six-question budget is spent or the user clicks *Draft it now*. The emitted definition goes through `validate_definition`, the tool-availability check, and a check against saved custom names, with one repair turn that feeds the errors back. The system prompt is a cached constant; the live context — specialists, the roster with person ids, the user's timezone (the one set through `PUT /workspace`, else `USER_TIMEZONE`; cadences stay UTC), and taken names — is rendered once per session into the first user turn, and while refining, the exact current draft is prepended to the latest user turn so the model edits it rather than re-deriving it. Roster names and roles are flattened to one line and capped at 80 characters before they enter that context, and the system prompt tells the model to treat the whole block as data, never instructions. Sessions live in memory (`/workflows/designer/*`, 2 h TTL, 50-session cap), run one model turn at a time (a second concurrent `/message` or `/draft` gets 409, and a failed turn is rolled back by identity), and never write: the review card saves through the same `POST /workflows/custom`, which re-validates, and *Edit details* opens the draft in the advanced editor (`/jobs/new?designer=<id>`) before saving.\n\n**Editing is a conversation too.** *Edit* on a saved workflow (`/jobs/new?edit=<name>`) opens the same designer through `POST /workflows/designer/edit`: the stored definition is the starting draft, so the user's first message (\"have Mark sign off and run it Fridays\") is applied to it like any refinement, and a note in the context block (a user turn, never the cached system block) tells the model it is changing a saved workflow. The draft always keeps the workflow's name — `_check_draft` puts it back and skips the taken-name check — and the route keeps its on/off state, so an edit can neither fork a copy nor switch on a tool workflow waiting for approval. The stored draft is handed to the model marked as data, not instructions. The review card lists *What changes* in plain words against the saved version (`lib/workflowChanges.ts`): every field is compared, with named sentences for the sign-off person and what it asks for — a sign-off moved off approve/reject is called out because the run then continues whatever the answer — the schedule, steps added/removed/reordered, inputs, tools and the tool-call budget, and a catch-all line for any other field. It names only the newly added tools that may change things. *Save changes* calls `POST /workflows/custom/{name}/save-edit`, which saves the session's own draft after re-validating it, only when it is the draft the card showed (the card sends what it displayed; a message that landed since is a 409), and only if the stored workflow has not changed since the conversation opened (409 otherwise), so an edit started before someone switched the workflow off cannot switch it back on. The step-by-step form stays as the advanced editor (`/jobs/new?edit=<name>&mode=advanced`).\n\n**Action steps (workflows that act).** An `action` step (`ActionStepSpec`: `goal`, `tools`, `max_tool_calls` 1–50, default 20) is run by the `workflow_actor` Council agent (`openexecutive/workflows/action_step.py`) as a bounded tool-use loop. Its `tools` list is an allowlist of exact tool names — MCP gateway tools (`server__tool`, e.g. `google_workspace__append_table_rows`) and built-ins: the Executive's own chat tools as `oe__<name>` (see *Chat's tools in action steps* below; `oe__create_alert`, in a workflow a team member created, raises the alert as theirs (`alert_tools.raised_for_workflow_owner`: source `team_member`, \"Raised by <name>\", never a company-wide broadcast) — plus any installed extension's tools registered with `workflow=True`, as `oe__<name>`, run inside `extensions.workflow_step(name)`; a built-in wins a name clash, and an extension tool counts as reading only when it says so) — and **clicking Create is the user's approval** of that list: the review card shows every tool, flags the ones that may change things (anything whose name doesn't say it reads, and any tool with a URL/URI/endpoint/webhook parameter anywhere in its schema, or whose schema couldn't be read, since a URL can carry data out), and names them in a \"this workflow can use these without asking again\" notice. Because that card is the approval, a workflow with action steps saved from chat (`draft_workflow`/`save_workflow`, whose confirmation is a token the model holds itself) is stored **switched off** (`is_active=false`) and `save_workflow` returns `status: saved_pending_review` with a `/jobs/{name}` link. An inactive workflow can't run or schedule (`get_workflow` and the scheduler skip it); `/jobs/{name}` shows it on the same review card, where **Turn on workflow** (`POST /workflows/custom/{name}/activate`, which re-validates the tools) is the approval — the click sends the definition the card showed, and the server refuses (409) if the stored one has changed since, so chat overwriting it while the card is open can't get new tools switched on. Chat may revise a switched-off workflow but refuses to replace a switched-on one that has action steps (an inbound email steering the Executive could otherwise switch off an approved job and stage new tools under its name); those edits happen in the advanced editor. The Workflows catalog (`/jobs`) lists switched-off workflows in a compact *Waiting for your approval* strip, and saving edits in the advanced editor keeps one off. `tool_catalog.py` resolves names to schemas through the gateway's `search_tools` (extensible-mcp's Markdown output is parsed; resolving is also the per-session discovery its `call_tool` requires) and validates availability at save time (`POST`/`PUT /workflows/custom`, chat `draft_workflow`/`save_workflow`, designer drafts) — an unknown, misspelled or deny-listed tool is a 422. The gateway meta-tools (`search_tools`, `call_tool`, `load_mcp_server`) can never be step tools. `run()` resolves every action step's tools before any step runs, so a vanished tool stops the run before an earlier step acts; `resume()` checks only the steps still to run, after the gate and decision are validated. The last turn of an action step always switches tools off so the agent can report. At run time only the allowlisted tools are offered (sorted; constant cached system block, per-run goal/inputs/earlier results in the user turn), every `tool_use` is re-checked against the allowlist, MCP calls go through `MCPGateway.call_tool` so the config deny-list and the Gmail/Calendar/Drive recipient gates still apply, the call budget is enforced (then a final tools-off turn asks for the report; running out of turns fails the step and lists what was already done), tool errors (the gateway's `Error:` / `Error calling tool` / `Tool error:` prefixes, or a truthy `error` field) return to the model as `is_error` results, each call emits a `progress` event and an audit row (`workflow_tool_call`: tool and outcome; for tools that may change things also a short digest of target arguments — ids, recipients, URLs, paths — so a redirected write is visible; content arguments are never logged), and the step's output is the agent's report plus an \"Actions taken\" list. Tool output is framed as data, never instructions.\n\n**Chat's tools in action steps.** A step can use almost everything the Executive uses in chat, so an idea from a conversation can become a workflow without a missing tool. `workflows/chat_tools.py` holds one list, `ACCESS`, that labels every chat tool: **use** (a step may list it as `oe__<name>`, e.g. `oe__send_slack_dm`, `oe__run_workflow`, `oe__update_department_goal`, `oe__web_search`), **as me** (Act as me tools, not yet in workflows), **covered** (the step already has its own path: gateway tools, `run_script`, specialist steps) or **chat only** (memory, company profile, roster changes, open loops, follow-up corrections and screen actions). A unit test fails when chat gains a tool without a label, so new chat tools reach workflows by one line rather than a second copy. A **use** tool runs through chat's own handler as an unattended chat turn would: an unattended `Session` bound as `current_session`, the workspace-mode filter (solo withholds department and company posts), and, in a team member's workflow, their department gate. Channels the instance has no token for are not offered. Saving the workflow is the person's permission, so Take the lead's approval gates don't apply, the same as the gateway tools before. `oe__run_workflow` refuses a workflow already running in its own chain and nests at most three deep. It and `oe__run_executive_research` get a 15-minute call timeout. `oe__web_search` is the model's server search: it is appended after the sorted tools, never called by the step, and a paused search turn is sent back as-is. Workflows have no tool handlers of their own any more: `oe__message_person` and `oe__create_alert` are the chat tools under the same names, and the old `oe__read_file` still resolves (to `read_document`) for saved workflows but isn't offered for new steps (`chat_tools.LEGACY_NAMES`). The designer lists every built-in by its first sentence, and chat's `draft_workflow` says chat tools are available as `oe__<name>`; the catalog's search ranks built-ins by how many query words they match.\n\n**Scripts in action steps.** Besides the step's own tools, the agent is offered one more, `run_script` (`openexecutive/workflows/step_script.py`), for work that repeats over many items — every file in a folder, every row, every email — or chains calls with simple logic. It writes a short Python script once instead of spending a model turn per call; each of the step's tools is a function in the script (`drive__move_file(file_id=…)`, or `call_tool(name, arguments)` by exact name), and only the script's final value and printed output come back. The script runs in **Monty** (`pydantic-monty`), a sandboxed Python interpreter for model-written code, in a worker process spawned per script: no files, network, environment, subprocesses or third-party imports — the step's tools are the only things it can reach. **A script is a faster way to make the same calls, never a way around them:** every call it makes goes through the same per-call path as a direct `tool_use` (`action_step._StepCalls`) — the allowlist, a call budget (a script's calls have their own: 10× the step's `max_tool_calls`, capped at `WORKFLOW_SCRIPT_MAX_CALLS`, default 500, because they cost no model turn each — so a step can work through a folder of hundreds of files while its direct calls stay capped at 1–50), the first-write target check (a held write comes back to the script as `{\"status\": \"held\", …}`) and one `workflow_tool_call` audit row per call — and the script itself is audited as `run_script`, with how many calls it made and how long it took. The step's \"Actions taken\" list collapses repeats into one line with a count. A step whose direct calls are spent keeps its tools on while the script budget has room, so it can still script the rest (a direct call is refused as over budget). When a tool returns a list of five or more items and the round didn't use `run_script`, the step adds the same `FANOUT_HINT` as chat (once a step), pointing the per-item work at one script. The worker is stepped from the step's own task (each call pauses it and is answered there), so cancelling the run stops the script and its in-flight call together, and each call's progress shows as it happens. At most `SCRIPT_MAX_WORKERS` (default 2) scripts run at once across the server, chat and workflows together; another waits for a slot within its own wall clock, else returns \"the server was busy\". A worker exists only while its script runs (about 8 MB idle). Execution time (excluding time waiting on tools), memory and recursion depth are capped inside the worker, the script has a wall-clock limit, and its text is size-capped; printed output past its cap is dropped. A failing script returns its error to the agent as an `is_error` result, with the calls it already made listed first (ahead of any long result, so a cut never drops them) so a fixed re-run doesn't repeat writes; a call cut off by the time limit is listed as `may_have_run`, and gets a `cancelled (may have run)` audit row. A workflow definition still holds no code; a script lives on only if the agent saves it as a tool (below). Because a step can loop at run time, the workflow designer keeps work that repeats over items (each email, file, row or listed follow-up) in ONE action step whose goal spells out the items, rather than a step per item; `run_script` is never a step tool, and a definition that lists it is rejected (`validate_definition`) so the designer's repair turn removes it. `WORKFLOW_STEP_SCRIPTS=false` turns the tool off, and a step then only calls its tools one by one.\n\n**Python jobs (`run_python_job`, `openexecutive/workflows/python_job.py`).** Monty can't run libraries, so library work on files (split or merge PDFs with pypdf, spreadsheets with openpyxl and pandas, charts with matplotlib, images with Pillow, and documents made from scratch or from files: Word with python-docx, PowerPoint with python-pptx, laid-out PDFs with fpdf2) runs as a Python job: Pyodide (Python in WebAssembly) executed by **Deno** in a process of its own per job. Pyodide alone is not a sandbox — its Python can call into the JavaScript runtime, which under plain Node reaches the server's environment, files and network — so Deno is what isolates it: it is started with read access to the sandbox folder and the worker script only, with no network, environment, writes or processes, and an empty process environment. Files go in on stdin and results come back on stdout. A job gets only what the call names: Knowledge-library files, the files attached to the chat message being answered (`attachment_files`, the uploads as sent, bound for that turn only by `POST /chat/upload` in `workflows/turn_files.py`, so the model never retypes an attachment's text), text the caller passes, and `inputs` (a dict the code reads); result files are kept 7 days under the company folder and served to the principal at `GET /python-jobs/{job}/{file}`, which the Executive links in its reply. A deployment can instead send jobs to a separate runner (`PYTHON_JOB_RUNNER_URL`, with `PYTHON_JOB_RUNNER_KEY` as a bearer token): `run_job` POSTs the same job (code, inputs, files, caps, time and memory limits) and reads back the same result object, at most as large as a local job's output, keeping only its known fields, so kept results, links and metering are unchanged; the local sandbox is then not needed, and the runner is trusted to isolate jobs. A runner can turn a job away with `{\"run_locally\": true}` (and an optional `reason`) in a non-200 reply, for example when the deployment's allowance for it is used up: the job then runs in the local sandbox if this machine has one, and otherwise fails with the runner's reason. Any other non-200 reply stays a job error, so a busy or broken runner never moves every job onto the machine. A runner with more libraries lists them in `PYTHON_JOB_EXTRA_LIBRARIES`, which the job tool's description then names, so the Executive doesn't refuse a job that needs one. The tool sits in the `workflows` tool group, labelled for jobs with or without attached files. The library set is fixed at build time: the API image installs Pyodide and Deno from npm and the compiled libraries from Pyodide's CDN, each checked against the sha256 in Pyodide's lock file, and a build smoke runs a job. Pyodide can't infer the compiled packages the pure-Python libraries import (lxml, Pillow, fonttools), so the worker loads them when a job imports docx, pptx or fpdf. Pyodide, Deno and the pure-Python libraries are pinned by hash too (an npm lock installed with `npm ci`, pip `--require-hashes`). One job runs at a time per process (200–450 MB each), with a `PYTHON_JOB_TIMEOUT_S` limit and a memory cap (`PYTHON_JOB_MEMORY_MB`, default 1536, as the process's data limit, plus V8 heap and WebAssembly memory caps); the worker returns at most 20 result files and 25 MB, and the API stops the job as soon as its reply passes that. The job runs at a lower CPU priority and is first in line if the machine runs out of memory, so a heavy job slows or loses itself rather than the API; Deno's own caches go in a temporary folder removed with the job; and kept results are capped at 200 MB in all, oldest first. The tool is chat-only, offered only on the principal's own turns (`PRINCIPAL_ONLY_TOOLS`), withheld on private turns, unattended passes and under the Act as me lockdown, and not offered at all without the sandbox (`PYTHON_JOBS_ENABLED`, `PYTHON_SANDBOX_DIR`).\n\nA job that worked can be kept the same way as a script (below): `save_as` and `description` keep its code as a Custom tool of kind `python`, and `run_python_job(tool=<name>, inputs={...})` with its files runs it again, recording the run, so a job done before costs no code-writing tokens. Python tools run only on the principal's own chat turns: they are never listed for workflow steps and never turn on for workflows (`PUT /saved-tools/{name}` answers 409), and `run_script` refuses one (and `run_python_job` a script tool). Every job writes one `python_job` audit row (`ok`, `duration_ms`, `cpu_ms` and `peak_mb` read from the process's /proc entry just before it is stopped, files and bytes in and out, attachments, the Custom tool it ran or kept), which `GET /audit/usage` sums into `python_jobs` with the model usage of the turns that ran one.\n\n**Saved tools.** A script that works can be kept to run again by name (`openexecutive/workflows/saved_tools.py`); each tool has a `kind`, `script` (`run_script`) or `python` (`run_python_job`, above). `run_script` takes `save_as` and `description` with a new script: if the script succeeds it is saved, with the set of tools it actually called, and a failed script is never saved. Later, `run_script(tool=<name>, inputs={...})` runs the saved script instead of new code, with `inputs` available to it as a dict. Only the principal's own turns save: a chat turn where the principal is speaking on a verified, interactive surface (the same test as `load_mcp_server`), never an inbound email, a teammate, an unattended run or a workflow step — a step is offered `tool=` but not `save_as`. A saved tool runs with the authority of whoever runs it, so its author must be trusted at least as much as anyone who may run it. For the same reason only a workflow step (its tools owner-approved) or the principal's own turn may run one: anyone else's chat turn is refused `tool=` and not offered `list_saved_tools`, so a stranger can neither list the principal's automations nor run one with inputs they choose. Descriptions are kept to one line of printable text (they are shown to models), and every save writes a `saved_tool_changed` audit row (`actor: executive`) beside the owner's own changes. Saving needs no approval beyond that, because a saved tool can do no more than the context running it: its calls go through the same per-call path as any script (in a step: the allowlist, budget, target check and audit), and a step runs one only when the step already allows every tool it used (otherwise the result names the `missing_tools`) and only at the version the owner turned on for workflows (`workflow_version`, Settings → Advanced → Custom tools → Use in workflows). A tool kept on a turn that read outside content could otherwise carry injected code into an unattended run, so keeping stays automatic and works in chat at once, but workflows wait for the owner; a newer save doesn't change the version workflows run, and pruning never drops it. Each step's `run_script` description lists the saved tools that step may run; chat asks `list_saved_tools`. Every save of changed content is a new version (the newest 20 are kept, plus the one that ran until then, so a rolled-back version the owner trusts survives later saves), every run is recorded (`saved_tool_runs`, the newest 200 per tool), and the owner can turn a tool off or switch it back to an earlier version on Settings → Advanced → Saved tools (`/saved-tools` routes, the owner's alone). A turned-off tool never runs, and a new version saved by the model does not turn it back on. `SAVED_TOOLS_ENABLED=false` stops saving and running saved tools everywhere.\n\n**Targets are chosen at run time — and a new one is confirmed once.** Approving a workflow approves its *tools*; which sheet, doc, recipient or URL each call hits is chosen by the model at run time, by design (a tab per month, a reply to whoever sent the invoice, a doc per client). What bounds that is the allowlist, the gateway's recipient gates, the audit digest, and **first-write confirmation**: a `TargetPolicy` (one per run) checks every call to a tool that may change things. `resource_targets` walks its arguments recursively for resource keys (snake- or camel-case ids, `to`/`cc`/`bcc`, recipients, addresses, attendees, members, users, owners, parents, URLs/links/hrefs, paths, channels, spaces, rooms, phones, hosts, buckets, tables, spreadsheet/document/folder/calendar/file); a matching key marks everything beneath it, even a `name`. Outside a resource, only a new item's own `name`/`title`/`subject`, message/thread/draft/label ids, `range`/`sheet` and workspace-mcp's acting `user_google_email` are skipped — and whatever the key, a bare value shaped like an email address, a URL or an international phone number is a target, except inside what the call writes (`rows`, `values`, `body`, `text` …). Key names are a heuristic, so this is a best-effort guard layered on the allowlist, the gateway gates and the audit. Float ids are compared as integers. Arguments too deep, naming too many targets, or holding an over-long value **fail closed** (the call is refused). A target is trusted only when it was approved for this workflow before (`workflow_approved_targets`, by value) or is an id a write in this run created — a top-level id/link field (`id`, `spreadsheetId`, `webViewLink` …) of the **structured JSON object** result of a tool whose name says it creates (create / insert / upload …) and that takes no URL — a tool whose schema couldn't be read is assumed to (free text, nested records and readers' or updaters' results are never read, so a fetched page, an echoed title, a shared page's links or a stranger in `ccRecipients` can't plant one); those survive a pause in the resume payload (`run_created`). Values written in the workflow's own text are *not* trusted, since anyone who can edit the workflow could change them without review: they are asked once, then remembered. Approvals are by value, for any of the workflow's tools, and are **cleared when the workflow's tool set changes** (a newly added tool must earn them again). Any other target makes the call **held**: it is not run and costs no budget, the model is told it is waiting for approval and carries on, and it is audited `held for approval` (at most 10 held per step, 16 KB each; an identical repeat is held once). Whether a call is checked at all follows the read-only label, which now never marks a tool whose name carries a write verb anywhere (`find_and_replace_doc`). After the step finishes, the run pauses with a `WaitForHumanEvent` to the workflow's **owner** (`owner_person_id`, the person who created it on the Workflows page or in chat; falling back to the principal if unknown or archived), `on_timeout=auto_proceed`, 48 h, and a `WorkflowResumeState` of `kind=\"held_writes\"` carrying the exact held calls. On resume (`_resume_held_writes`, fingerprint-checked like a gate, with the remaining steps' tools checked first), only `approve` runs them — each still has to be in the live step's allowlist and resolve; its targets are remembered first — and anything else (decline, timeout, unreadable) skips them; either way a *Held for approval* section is added to the step's output and the run continues at the next step. With no one to ask, held writes are skipped and noted; a step that fails or crashes after holding, or a resume that stops early (definition changed, a later tool missing), audits its held writes as dropped and says they did not run. The question quotes each target JSON-escaped (a value can't add its own lines) and always shows a URL's full scheme and host, saying how much of the rest is hidden. The owner answers by chat reply or with **Approve / Decline** on the run page (`POST /workflows/runs/{id}/decision`, which the principal may also use); remembered targets are listed and removable on the workflow page.\n\n`oe__read_document` (chat's `read_document`; saved workflows that list the old `oe__read_file` get the same tool) extracts text (PDF, Word, Excel, CSV, Markdown, text) only from files under `WORKFLOW_FILE_DIRS` or the company documents folder (default: workspace-mcp's attachment folder), resolving symlinks and `..` before the check (`tool_catalog.resolve_readable_file`, shared with the Executive's `read_document` tool). A scanned PDF is converted by `knowledge.pdf_reader` instead of failing as \"may be a scanned image\"; one that still cannot be read returns the reason. Action steps are allowed in scheduled workflows. Because they have external side effects, a resumed run heartbeats its claim (`touch_resume_claim`, at most once a minute as events flow — each tool call emits one; a busy database is retried on the next heartbeat, never treated as a lost claim; the sweep's requeue re-checks the claim's age in the same UPDATE, so a heartbeat landing between the sweep's read and its write wins), so the stale-claim sweep never requeues and replays a slow but live run, and a worker that finds its claim superseded stops at its next event. A worker that actually crashes mid-resume is still requeued; its action steps then run again, so goals should say how to avoid duplicates (the actor reads current state before writing). `GET /workflows/tools/search?q=` and `GET /workflows/tools/describe?names=` back the advanced editor's tool picker and the review card's labels.\n\nAn optional cadence (`daily@` / `weekly@` / `quarterly@`) re-uses the scheduler via the `dynamic_workflow` action kind, which runs the workflow on schedule and DMs the artifact to a rostered recipient. A gate followed by further steps pauses at `awaiting_human` and then resumes once answered, so gates no longer have to sit immediately before synthesis. They remain forbidden in cadence-enabled definitions: a scheduled fire has no interactive human to ask.\n\n`executive_research` keeps only its Markdown artifact in the run history; `parse_artifact_findings` reads its \"Findings reviewed\" lines back as `{severity, confidence, specialist, title, summary}` for Home's first-week card (see Today).\n\nBuilt-ins the system runs on its own (`morning_brief`, `end_of_day_digest`, `executive_reflection`, `executive_research`) set `background = True`, surfaced as `WorkflowMeta.background`; the `/jobs` ready-made list files them under a **System** chip instead of the default view. They stay runnable by hand.\n\n**Quick workflows** (`workflows/quick.py`) are one per playbook in effect that no built-in or custom workflow follows (switched-off custom ones count). They are derived whenever the catalog is read, never stored: `list_workflows()` returns built-ins, then Quick ones, then active custom ones, and `get_workflow` resolves a `quick_<playbook>` name after the registry (custom workflows may not take the `quick_` prefix). Each has one required field, `request`, and two steps: **Load context** (company profile plus RAG for the playbook category's specialist) and **Draft** (that specialist writes one Markdown document following the playbook). `WorkflowMeta.quick` is true for them. The 8 built-in playbooks no built-in follows are Quick workflows: board update memo, 1:1 agenda, layoff comms plan, positioning statement, post-mortem, customer interview plan, feature prioritization and market sizing. A company's own playbook shows up as one, hiding a built-in drops it, and a custom workflow that starts following one replaces it. If custom workflows can't be read, none are offered, since their followers are unknown.\n\n**Workflows vs. playbooks.** `/jobs` has two tabs: **Build** (`?tab=catalog`, the default) and **Runs** (`/skills` redirects to `/jobs`). A playbook is a skill (`knowledge/skills_repo.py`): *how* the Executive does a piece of work, with no inputs, schedule or side effects. A workflow is the runnable job. Workflows **follow** playbooks: a step that follows one gets its body appended to the step prompt via `workflows/playbooks.py` (`load_playbook` + `playbook_clause`). Six built-ins do — `board_prep` (`board-prep-deck`), `quarterly_plan` (`quarterly-okr-set`, `quarterly-forecast`), `mbr` (`monthly-business-review`, in the financial, KPI and function steps), `competitive_teardown` (`competitive-teardown`, in the four analysis steps), `fundraising_prep` (`fundraise-narrative`, narrative step) and `exec_search_brief` (`role-scorecard`, profile step). Each declares them in `Workflow.playbooks`; a unit test holds that declaration equal to the `load_playbook(\"…\")` calls in the module, and `WorkflowMeta.playbooks` exposes it. A custom workflow's `specialist` step may name a `playbook` (validated to exist at save; appended after `{field}` rendering, so braces in a playbook are never treated as placeholders). The lookup resolves the playbook in effect, so a company's customized copy changes the workflow's output, and a hidden, missing or malformed one falls back to the step's own prompt plus RAG — a workflow never fails over a playbook (`load_playbook` catches everything; a custom step whose playbook is unavailable emits a `progress` event saying so). Because an approved scheduled workflow reads its playbook at each run, chat never creates or changes a playbook: it saves repeatable work as a workflow (`draft_workflow`, confirmed by the user), and only a person can change what a workflow follows: a workflow's page shows each playbook it follows as **How it's done** (`components/jobs/HowItsDone.tsx`), with **Edit** (`PUT /skills/{name}`; on a built-in that saves the company's customized copy) and, for a customized copy, **Reset to original** (`DELETE`, which reverts). The chat summary of a drafted workflow names each step's playbook. `playbook_users()` maps each playbook to the workflows that follow it — built-ins, every custom workflow (switched-off ones included: turning one on approves its definition) and the Quick ones; the skills API reports it as `used_by`, and the Executive's `search_skills` hits carry it as `workflows`.\n\nCompleted artifacts are discoverable in the unified artifacts section (`/artifacts`, labelled **Documents** in the UI) alongside their run-detail page at `/jobs/runs/{run_id}`. A run someone starts by hand (`POST /workflows/{name}/runs`, `run_workflow`, research in chat) stores them as `workflow_runs.owner_person_id` and its history and output are theirs alone (plus the person a gate waits on); scheduled and system runs keep no owner and stay the team's. Workflow output stays Markdown — the scheduler DMs it and reflection rereads it as text — and gains other formats only on the way out: any run can be downloaded as Word (`/artifacts/run:<id>/download?as=docx`), and the Executive can repackage one with `get_artifact` → `draft_artifact(format=…, supersedes=\"run:<id>\")`.\n\n## Data-driven retrospectives\n\n`engagement_value_report` introduces a new workflow pattern: instead of the user typing the substance into a form (the `investor_update` / `mbr` shape), the workflow **reads its substance from the database**. A deterministic gatherer (`clients/engagement_activity.py`) pulls the period's decisions, initiatives, advisory consultations, delivered workflow artifacts (excluding prior value reports), follow-through counts, and alerts handled — from the live DB for the active client, or a parked client slot's `state.db` opened read-only. A single board-comms call narrates those facts (the prompt forbids inventing anything not in them; an empty period skips the LLM entirely), and the artifact's lists are assembled deterministically. Built for renewal conversations — the engagement record is the evidence.\n\nWith Take the lead as the Executive on (`orchestrator.take_the_lead`), reflection and research build their toolkit through `unattended_toolkit(..., source=...)`. That keeps solo's booking and `run_workflow` tools and an unrestricted `message_person` (teammates as well as the principal). Every acting tool goes through the gate, and a held action waits on Today as a `take_the_lead_action` decision. Reflection also gets the MCP gateway's `search_tools` and `call_tool` (`_with_lead_tools`; `call_tool` behind the gate, `load_mcp_server` left out), so it can find and use whatever the deployment has connected, such as building a sheet to track something. A note in the user turn (never the cached system prompt) tells it to act rather than only report, and it gets more room: 10 iterations, 4000 tokens, and tool results up to 4000 characters. The grounding check still refuses outward text naming people or figures the pass didn't see. New mail and chat also wake the reflection early (scheduler section). In training (`take_the_lead.training`) every acting call that isn't allowed waits too, as a training card for the principal, and both passes append `take_the_lead.learned_note()` to their user turn: that it's in training, and the principal's own edits on earlier cards as examples of how they want those done (never in the cached system blocks).",
"mermaid": "flowchart TD\n Input[\"Structured input\"]\n Steps[\"Ordered named steps\"]\n Wait[\"wait_for_human pause\"]\n Sched[\"workflow_runs<br/>(awaiting_human)\"]\n Resolver[\"inbound_resolver<br/>+ resumer\"]\n Artifact[\"Markdown artifact<br/>(workflow_runs.artifact)\"]\n Today[\"Today / Documents\"]\n Input --> Steps\n Steps --> Wait\n Wait --> Sched\n Sched -- \"human reply\" --> Resolver\n Resolver -- \"resolved → claim\" --> Steps\n Steps -- \"complete_run\" --> Artifact\n Artifact --> Today\n class Input entry\n class Steps compute\n class Wait compute\n class Sched storage\n class Resolver compute\n class Artifact storage\n class Today external",
- "generated_at": "2026-10-21T00:00:00Z"
+ "generated_at": "2026-10-21T17:54:33.773956+00:00"
}
diff --git a/packages/core/openexecutive/config.py b/packages/core/openexecutive/config.py
index a6af65ee..2b5a0efb 100644
--- a/packages/core/openexecutive/config.py
+++ b/packages/core/openexecutive/config.py
@@ -872,7 +872,7 @@ class Settings(BaseSettings):
mcp_servers_config_path: Path = Field(
_ROOT / "company" / "mcp_servers.json", alias="MCP_SERVERS_CONFIG_PATH"
)
- # Directories a workflow action step's `oe__read_file` tool may read —
+ # Directories `read_document` (a workflow step's `oe__read_document`) may read —
# where tools that download files (e.g. Gmail attachments via
# workspace-mcp) save them. Comma-separated. Empty means workspace-mcp's
# own default: $WORKSPACE_ATTACHMENT_DIR, else ~/.workspace-mcp/attachments.
diff --git a/packages/core/openexecutive/orchestrator/document_tools.py b/packages/core/openexecutive/orchestrator/document_tools.py
index fd1d2a9f..5aa423a6 100644
--- a/packages/core/openexecutive/orchestrator/document_tools.py
+++ b/packages/core/openexecutive/orchestrator/document_tools.py
@@ -10,7 +10,7 @@ deployment reaches it directly, local OCR otherwise — instead of coming back
empty.
Reads are confined to the tool download folders (``tool_catalog.
-resolve_readable_file``, the same check ``oe__read_file`` uses) and the
+resolve_readable_file``, the same check workflow steps use) and the
company documents folder. The tool is withheld on turns private to the
principal (``schedule_tools.PRIVATE_TURN_WITHHELD_TOOLS``): those come from a
contact's email, whose own attachments the poller has already read, and must
diff --git a/packages/core/openexecutive/orchestrator/workflow_authoring_tools.py b/packages/core/openexecutive/orchestrator/workflow_authoring_tools.py
index 94491265..40f405fb 100644
--- a/packages/core/openexecutive/orchestrator/workflow_authoring_tools.py
+++ b/packages/core/openexecutive/orchestrator/workflow_authoring_tools.py
@@ -69,7 +69,9 @@ DEFINITION_SCHEMA: dict[str, Any] = {
"advisor; playbook = name of an existing playbook the step follows), "
"'action' {id,title,goal,tools,max_tool_calls?} (gets something done with "
"tools — 'tools' is the exact list of tool names the step may call, e.g. "
- "'google_workspace__append_table_rows' or 'oe__read_file'; max_tool_calls "
+ "'google_workspace__append_table_rows' or 'oe__read_document'. The tools you "
+ "use in chat are available to steps as 'oe__<name>', e.g. "
+ "'oe__send_slack_dm', 'oe__web_search' or 'oe__run_workflow'; max_tool_calls "
"is optional — omit it for the default budget), "
"'approval_gate' {id,title,person_id,question,timeout_hours?,on_timeout?}, "
"or 'synthesis' {id,title,instructions?,specialist?}. "
diff --git a/packages/core/openexecutive/workflows/action_step.py b/packages/core/openexecutive/workflows/action_step.py
index a15534d3..b73fa74b 100644
--- a/packages/core/openexecutive/workflows/action_step.py
+++ b/packages/core/openexecutive/workflows/action_step.py
@@ -55,6 +55,9 @@ _MAX_TOKENS = 4096
# Model turns allowed beyond the tool budget: one for the final report, a
# little slack for a turn that only talks.
_EXTRA_TURNS = 3
+# A long web search can pause the model's turn (``pause_turn``); a paused
+# turn is not one of the step's turns, but at most this many are carried on.
+_MAX_PAUSES = 5
_TOOL_CALL_TIMEOUT_S = 120.0
_MAX_INPUT_CHARS = 2_000
_MAX_PRIOR_OUTPUT_CHARS = 6_000
@@ -153,9 +156,22 @@ def _block_to_dict(block: Any) -> dict[str, Any] | None:
"name": getattr(block, "name", ""),
"input": getattr(block, "input", {}) or {},
}
+ if kind in ("server_tool_use", "web_search_tool_result"):
+ # The model's own web search: echoed back as-is so it keeps what it
+ # searched (orchestrator.web_search_tool).
+ dump = getattr(block, "model_dump", None)
+ return dump(exclude_none=True) if callable(dump) else None
return None
+def _append_assistant(messages: list[dict[str, Any]], blocks: list[dict[str, Any]]) -> None:
+ """Add the model's turn, joined to the one before when that one paused."""
+ if messages and messages[-1]["role"] == "assistant":
+ messages[-1]["content"] = [*messages[-1]["content"], *blocks]
+ else:
+ messages.append({"role": "assistant", "content": blocks})
+
+
# Argument keys that say WHERE a call acts (which sheet, which recipient,
# which URL). Logged for tools that may change things, so a write redirected
# by injected content is visible in the audit trail. Content arguments (rows,
@@ -400,19 +416,26 @@ def _audit(
async def _dispatch(
name: str, arguments: dict[str, Any], info: tool_catalog.ToolInfo, workflow_name: str,
) -> str:
- if info.source == "builtin":
+ if info.source in ("builtin", "server"):
handler = tool_catalog.builtin_handler(name)
if handler is None: # resolve() only returns names with handlers
return json.dumps({"error": "tool is not available"})
- if name == "oe__create_alert":
- # An alert a team member's saved workflow raises is theirs, as
- # it would be from their chat (orchestrator.alert_tools).
- from openexecutive.orchestrator.alert_tools import raised_for_workflow_owner
- from openexecutive.workflows.dynamic_store import get_owner
-
- with raised_for_workflow_owner(get_owner(workflow_name)):
- return await handler(arguments)
- return await handler(arguments)
+ if info.source == "server":
+ return json.dumps({"error": "this tool is used by the model as it writes; it can't be called"})
+ from openexecutive.workflows import chat_tools
+ from openexecutive.workflows.dynamic_store import get_owner
+
+ owner = get_owner(workflow_name)
+ # A chat tool runs as a step of this workflow (workflows.chat_tools).
+ with chat_tools.in_workflow(workflow_name, owner):
+ if name == "oe__create_alert":
+ # An alert a team member's saved workflow raises is theirs, as
+ # it would be from their chat (orchestrator.alert_tools).
+ from openexecutive.orchestrator.alert_tools import raised_for_workflow_owner
+
+ with raised_for_workflow_owner(owner):
+ return await handler(arguments)
+ return await handler(arguments)
from openexecutive.orchestrator.mcp_gateway import get_active_gateway
gateway = get_active_gateway()
@@ -433,7 +456,8 @@ async def _call_tool(
"""Run one approved tool call. Returns (result text, is_error); never raises."""
try:
content = await asyncio.wait_for(
- _dispatch(name, arguments, info, workflow_name), timeout=_TOOL_CALL_TIMEOUT_S
+ _dispatch(name, arguments, info, workflow_name),
+ timeout=info.timeout_s or _TOOL_CALL_TIMEOUT_S,
)
except TimeoutError:
return json.dumps({"error": "the tool timed out"}), True
@@ -603,7 +627,7 @@ async def run_action_step(
resolved_model = model if model is not None else agent.effective_model()
provider = get_provider(resolved_model)
scripts = settings.workflow_step_scripts and step_script.available()
- tool_defs = [resolved[name].as_anthropic_tool() for name in step.tools]
+ tool_defs = [resolved[name].as_anthropic_tool() for name in step.tools if resolved[name].source != "server"]
if scripts:
tool_defs.append(
step_script.tool_definition(
@@ -615,6 +639,13 @@ async def run_action_step(
)
)
tools = sorted(tool_defs, key=lambda t: t["name"])
+ # The model's own server tools (web search) go after the sorted list.
+ if any(resolved[name].source == "server" for name in step.tools):
+ from openexecutive.orchestrator.web_search_tool import build_web_search_tool
+
+ web_search = build_web_search_tool()
+ if web_search is not None:
+ tools.append(web_search)
system = [
{"type": "text", "text": agent.effective_system_prompt(), "cache_control": {"type": "ephemeral"}}
]
@@ -649,7 +680,9 @@ async def run_action_step(
max_turns = step.max_tool_calls + _EXTRA_TURNS
fanout_hinted = False
- for turn in range(max_turns):
+ turn = 0
+ pauses = 0
+ while turn < max_turns:
kwargs: dict[str, Any] = {
"model": resolved_model,
"max_tokens": _MAX_TOKENS,
@@ -675,12 +708,24 @@ async def run_action_step(
blocks = [b for b in (_block_to_dict(b) for b in getattr(response, "content", []) or []) if b]
tool_uses = [b for b in blocks if b["type"] == "tool_use"]
+ if getattr(response, "stop_reason", None) == "pause_turn":
+ # A long web search paused mid-turn: send it back to carry on.
+ pauses += 1
+ if not blocks or pauses > _MAX_PAUSES:
+ yield ("error", f"step {step.id!r} stopped: its web search kept pausing without an answer")
+ return
+ _append_assistant(messages, blocks)
+ continue
+ turn += 1
if not tool_uses:
- report = "\n".join(b["text"] for b in blocks if b["type"] == "text").strip()
+ paused = messages[-1]["content"] if messages[-1]["role"] == "assistant" else []
+ report = "\n".join(
+ b["text"] for b in [*paused, *blocks] if b["type"] == "text"
+ ).strip()
yield ("output", _format_output(report, actions))
return
- messages.append({"role": "assistant", "content": blocks})
+ _append_assistant(messages, blocks)
results: list[dict[str, Any]] = []
for use in tool_uses:
name = str(use["name"])
diff --git a/packages/core/openexecutive/workflows/chat_tools.py b/packages/core/openexecutive/workflows/chat_tools.py
new file mode 100644
index 00000000..1b3f512f
--- /dev/null
+++ b/packages/core/openexecutive/workflows/chat_tools.py
@@ -0,0 +1,385 @@
+"""Chat's tools in workflow action steps: one list, chat's own handlers.
+
+Every tool the chat can offer is labelled here, once (``ACCESS``), and a unit
+test fails when a chat tool has no label, so a tool added to the chat is
+always decided for workflows too:
+
+- ``USE``: a step may name it as ``oe__<name>`` and it runs through the chat's
+ own handler (``tool_catalog`` lists these with the other built-ins).
+- ``AS_ME``: reads or writes the person's own mailbox or calendar (Act as
+ me). Not offered to workflows yet: it needs its own identity rules.
+- ``COVERED``: workflows do this their own way (a specialist step, naming a
+ gateway tool directly, the step's own ``run_script``).
+- ``CHAT_ONLY``: it needs the person: they are on screen, or it changes what
+ the Executive believes or who is on the team, which chat keeps to a turn
+ the person is in (most are ``schedule_tools.UNATTENDED_WITHHELD_TOOLS``). A
+ workflow reads outside text (mail, pages), and a line in it must not
+ quietly rewrite memory with nobody watching. Goal progress and the
+ watchlist are the exception, by the owner's choice: keeping them current
+ is what a scheduled workflow is for, the step has to be given the tool by
+ name when the workflow is saved, and each change is audited.
+
+**How a chat tool runs in a step.** The step's call goes through the usual
+checks first (the allowlist, the budget, the first-write target hold in
+``action_step``). Then the chat handler runs on a session of its own, as the
+chat's unattended runs do (``Session.unattended``: the scheduler's proactive
+run, the reflection): the handlers already know that nobody is in the
+conversation and refuse what needs someone there. The session's documents
+are those of the person the run is for (``artifact_records.current_viewer``),
+and a tool the workspace mode doesn't offer is refused
+(``filter_tools_for_workspace_mode``). Take the lead does not gate these
+calls: a saved workflow is its creator's own instruction, approved tool by
+tool when they saved it, as for the gateway tools. A workflow a team member
+created goes through their department's approval level, as their own chat
+turn would (``department_gate``). One with no creator on record (saved
+before creators were) runs as the principal's, as its tools always did.
+
+**Long and nested runs.** ``run_workflow`` and ``run_executive_research``
+get a longer timeout than other calls (``TIMEOUT_S``), and a workflow may not
+start itself or one already running above it, nor go more than
+``MAX_DEPTH`` workflows deep.
+
+**Web search** is the model's own server tool, not a handler: a step that
+names ``oe__web_search`` has it added to the model's tools
+(``action_step.run_action_step``).
+"""
+from __future__ import annotations
+
+import contextlib
+import contextvars
+import dataclasses
+import json
+import logging
+from collections.abc import Awaitable, Callable, Iterator
+from typing import Any
+
+logger = logging.getLogger(__name__)
+
+PREFIX = "oe__"
+
+USE = "use"
+AS_ME = "as_me"
+COVERED = "covered"
+CHAT_ONLY = "chat_only"
+
+WEB_SEARCH = "web_search"
+
+# Every tool the chat can offer: (label, why). Grouped by label.
+ACCESS: dict[str, tuple[str, str]] = {
+ # USE: runs in a step through the chat's own handler.
+ "search_skills": (USE, "find a playbook"),
+ "load_skill": (USE, "read a playbook"),
+ "search_knowledge": (USE, "search the company knowledge base"),
+ "read_document": (USE, "read an uploaded document"),
+ WEB_SEARCH: (USE, "search the web (the model's server tool)"),
+ "run_executive_research": (USE, "run the research council"),
+ "list_workflows": (USE, "list workflows"),
+ "run_workflow": (USE, "run another workflow"),
+ "run_python_job": (CHAT_ONLY, "reads the principal's Knowledge files; unattended runs never get it"),
+ "draft_artifact": (USE, "publish a document, sheet or report"),
+ "get_artifact": (USE, "read a past deliverable"),
+ "list_artifacts": (USE, "list past deliverables"),
+ "create_alert": (USE, "raise an alert"),
+ "find_alerts": (USE, "look up alerts"),
+ "message_person": (USE, "message someone on the roster"),
+ "send_slack_dm": (USE, "Slack direct message"),
+ "send_discord_dm": (USE, "Discord direct message"),
+ "send_telegram_message": (USE, "Telegram message"),
+ "send_department_message": (USE, "post to a department room"),
+ "send_company_broadcast": (USE, "post company-wide"),
+ "schedule_followup": (USE, "queue a follow-up message"),
+ "suggest_workflow": (USE, "suggest a workflow to run"),
+ "list_followups": (USE, "list pending follow-ups"),
+ "create_calendar_event": (USE, "book a meeting through the meeting gate"),
+ "create_instant_meeting": (USE, "start a meeting now"),
+ "cancel_calendar_event": (USE, "cancel a meeting it booked"),
+ "list_people": (USE, "read the roster"),
+ "lookup_person": (USE, "find someone on the roster"),
+ "ask_about_person": (USE, "ask what is known about someone"),
+ "list_open_loops": (USE, "list open loops"),
+ "list_department_goals": (USE, "list goals"),
+ "list_watchlist": (USE, "list the watchlist"),
+ "add_watchlist_entry": (USE, "watch something new"),
+ "tune_watchlist_entry": (USE, "tune what is watched"),
+ "remove_watchlist_entry": (USE, "stop watching something"),
+ "update_department_goal": (USE, "update a goal's progress"),
+ # AS_ME: the person's own mailbox and calendar.
+ "ghostwrite_email": (AS_ME, "write an email as the person"),
+ "search_my_email": (AS_ME, "search the person's own mailbox"),
+ "read_my_email": (AS_ME, "read the person's own mail"),
+ "read_my_email_attachment": (AS_ME, "read an attachment in the person's mail"),
+ "save_my_email_attachment": (AS_ME, "save an attachment from the person's mail"),
+ "my_email_awaiting_reply": (AS_ME, "the person's unanswered sent mail"),
+ "my_email_read_before": (AS_ME, "mail opened for the person before"),
+ "my_calendar": (AS_ME, "the person's own calendar"),
+ "remind_me": (AS_ME, "a reminder for the person"),
+ "propose_actions": (AS_ME, "an approval card from the person's mail"),
+ "recall_history": (AS_ME, "the person's own conversation notes"),
+ # COVERED: workflows have their own way.
+ "consult_specialist": (COVERED, "a specialist step"),
+ "search_tools": (COVERED, "a step names gateway tools directly"),
+ "call_tool": (COVERED, "a step names gateway tools directly"),
+ "load_mcp_server": (COVERED, "connections are set up outside a run"),
+ "run_script": (COVERED, "every action step has run_script"),
+ "list_saved_tools": (COVERED, "every action step's script lists them"),
+ "open_tools": (COVERED, "a step names its tools up front"),
+ "use_tool": (COVERED, "a step names its tools up front"),
+ # CHAT_ONLY: needs the person (module docstring).
+ "remember_fact": (CHAT_ONLY, "changes what the Executive takes as fact"),
+ "forget_fact": (CHAT_ONLY, "changes what the Executive takes as fact"),
+ "update_company_profile": (CHAT_ONLY, "changes the company profile"),
+ "create_goal": (CHAT_ONLY, "only the principal starts a goal"),
+ "record_decision_outcome": (CHAT_ONLY, "only the principal records an outcome"),
+ "assign_open_loop": (CHAT_ONLY, "takes the task in the speaker's own words"),
+ "close_open_loop": (CHAT_ONLY, "only the principal or the loop's owner closes it"),
+ "ack_alert": (CHAT_ONLY, "clears an alert on quoted text"),
+ "leave_out_of_brief": (CHAT_ONLY, "a correction the person asks for"),
+ "cancel_followup": (CHAT_ONLY, "a correction the person asks for"),
+ "move_followup": (CHAT_ONLY, "a correction the person asks for"),
+ "upsert_person": (CHAT_ONLY, "changes the roster"),
+ "archive_person": (CHAT_ONLY, "changes the roster"),
+ "set_department_head": (CHAT_ONLY, "changes the roster"),
+ "resolve_roster_request": (CHAT_ONLY, "answers a roster request"),
+ "do_in_app": (CHAT_ONLY, "acts in the app as the person"),
+ "find_in_app": (CHAT_ONLY, "acts in the app as the person"),
+ "propose_form_values": (CHAT_ONLY, "fills a form on the person's screen"),
+ "open_in_app": (CHAT_ONLY, "a link for the person on screen"),
+ "read_user_guide": (CHAT_ONLY, "explains the app to the person"),
+ "mark_draft_sent": (CHAT_ONLY, "the person says they sent it"),
+ "draft_workflow": (CHAT_ONLY, "a workflow does not build workflows"),
+ "save_workflow": (CHAT_ONLY, "a workflow does not build workflows"),
+}
+
+# Calls that run a whole job: longer than action_step's default timeout.
+# Workflow tool names saved workflows may still list, and the chat tool each
+# now runs. Not offered for new steps.
+LEGACY_NAMES: dict[str, str] = {"oe__read_file": "read_document"}
+
+TIMEOUT_S: dict[str, float] = {"run_workflow": 900.0, "run_executive_research": 900.0}
+MAX_DEPTH = 3
+
+
+def chat_tool_definitions() -> dict[str, dict[str, Any]]:
+ """Every tool the chat can offer, by name (definitions as chat offers
+ them; web search is the model's server tool and has none here)."""
+ from openexecutive.orchestrator import tool_groups
+ from openexecutive.orchestrator.delegation_tools import DELEGATION_TOOLS
+ from openexecutive.orchestrator.executive import _offered_skill_tools
+ from openexecutive.orchestrator.history_tools import HISTORY_TOOLS
+ from openexecutive.orchestrator.knowledge_tools import KNOWLEDGE_TOOLS
+ from openexecutive.orchestrator.mcp_gateway import MCP_TOOLS
+ from openexecutive.orchestrator.router import SPECIALIST_TOOLS
+ from openexecutive.workflows import step_script
+
+ tools = [
+ *SPECIALIST_TOOLS, *_offered_skill_tools(), *MCP_TOOLS, *DELEGATION_TOOLS,
+ *HISTORY_TOOLS, *KNOWLEDGE_TOOLS, tool_groups.USE_TOOL_TOOL,
+ {"name": tool_groups.OPEN_TOOLS},
+ {"name": step_script.RUN_SCRIPT_TOOL}, {"name": step_script.LIST_SAVED_TOOLS_TOOL},
+ ]
+ return {str(t["name"]): t for t in tools}
+
+
+def _chat_handlers() -> dict[str, Callable[[dict[str, Any]], Awaitable[str]]]:
+ from openexecutive.orchestrator.executive import _ALL_SKILL_HANDLERS
+ from openexecutive.orchestrator.knowledge_tools import KNOWLEDGE_TOOL_HANDLERS
+
+ return {**_ALL_SKILL_HANDLERS, **KNOWLEDGE_TOOL_HANDLERS}
+
+
+def label(name: str) -> str | None:
+ entry = ACCESS.get(name)
+ return entry[0] if entry else None
+
+
+def workflow_name_for(chat_name: str) -> str:
+ return f"{PREFIX}{chat_name}"
+
+
+# The workflows running in this task, outermost first, and the creator of
+# the innermost one (set by ``action_step._dispatch``).
+_chain: contextvars.ContextVar[tuple[str, ...]] = contextvars.ContextVar("workflow_chain", default=())
+_creator: contextvars.ContextVar[int | None] = contextvars.ContextVar("workflow_tool_creator", default=None)
+
+
+def in_workflow(workflow_name: str, creator_id: int | None) -> Iterator[None]:
+ """Run the block as a step of ``workflow_name``, created by ``creator_id``."""
+ chain = _chain.set((*_chain.get(), workflow_name))
+ creator = _creator.set(creator_id)
+ try:
+ yield
+ finally:
+ _creator.reset(creator)
+ _chain.reset(chain)
+
+
+def _error(message: str) -> str:
+ return json.dumps({"error": message})
+
+
+def _nested_run_refusal(tool_input: dict[str, Any]) -> str | None:
+ chain = _chain.get()
+ target = str(tool_input.get("name") or tool_input.get("workflow") or "").strip()
+ if target and target in chain:
+ return _error(f"{target!r} is already running in this chain of workflows, so it can't start again. Do not retry.")
+ if len(chain) >= MAX_DEPTH:
+ return _error(f"Workflows can start other workflows at most {MAX_DEPTH} deep. Do not retry.")
+ return None
+
+
+def _seen_channel_refs() -> set[tuple[str, str]]:
+ """The roster's own channels, as the reflection seeds them, so
+ ``schedule_followup`` reaches only a real person's channel."""
+ from openexecutive.people.store import list_people
+
+ seen: set[tuple[str, str]] = set()
+ for person in list_people():
+ if person.slack_user_id:
+ seen.add(("slack_dm", person.slack_user_id))
+ if person.discord_user_id:
+ seen.add(("discord_dm", person.discord_user_id))
+ if person.telegram_chat_id:
+ seen.add(("telegram", person.telegram_chat_id))
+ if person.email:
+ seen.add(("email", person.email))
+ return seen
+
+
+def _session(mode: str) -> Any:
+ from openexecutive.memory.workspace_settings import effective_principal_role
+ from openexecutive.onboarding.profile_builder import load_or_create_profile
+ from openexecutive.orchestrator.artifact_records import current_viewer
+ from openexecutive.orchestrator.session import Session
+
+ profile = load_or_create_profile()
+ return Session(
+ company_profile=profile if not profile.is_empty() else None,
+ seen_channel_refs=_seen_channel_refs(),
+ turn_workspace_mode=mode,
+ turn_principal_role=effective_principal_role(None),
+ unattended=True,
+ documents_viewer=current_viewer(),
+ )
+
+
+def _team_member(person_id: int | None) -> Any:
+ """The creator when they are a team member other than the principal."""
+ from openexecutive.people.store import get_person
+
+ if person_id is None:
+ return None
+ person = get_person(person_id)
+ if person is None or person.is_principal or person.kind != "team":
+ return None
+ return person
+
+
+async def run_chat_tool(name: str, tool_input: dict[str, Any]) -> str:
+ """Run the chat tool ``name`` for a workflow step (module docstring)."""
+ from openexecutive.memory.workspace_settings import effective_workspace_mode
+ from openexecutive.orchestrator import department_gate
+ from openexecutive.orchestrator.schedule_tools import (
+ current_session,
+ filter_tools_for_workspace_mode,
+ withheld_tool_error,
+ )
+
+ if label(name) != USE:
+ return _error(f"{name} is not available in workflows. Do not retry.")
+ handler = _chat_handlers().get(name)
+ if handler is None:
+ return _error(f"{name} is not available in workflows. Do not retry.")
+ if name == "run_workflow":
+ refused = _nested_run_refusal(tool_input)
+ if refused is not None:
+ return refused
+ mode = str(effective_workspace_mode(None))
+ if not filter_tools_for_workspace_mode([{"name": name}], mode):
+ return withheld_tool_error(name, mode)
+ session = _session(mode)
+ handlers: dict[str, Any] = {name: handler}
+ seat = _team_member(_creator.get())
+ if seat is not None:
+ handlers = department_gate.gated_handlers(handlers, seat, session_id=session.session_id)
+ token = current_session.set(session)
+ try:
+ return str(await handlers[name](tool_input))
+ finally:
+ current_session.reset(token)
+
+
+def _usable_definitions() -> list[dict[str, Any]]:
+ definitions = chat_tool_definitions()
+ return [definitions[n] for n, (lbl, _) in ACCESS.items() if lbl == USE and n in definitions]
+
+
+def not_offered() -> set[str]:
+ """Workflow tool names that resolve but aren't shown for new steps: the
+ old names, and channel tools this instance has no token for (a call
+ would only error)."""
+ from openexecutive.config import get_settings
+ from openexecutive.orchestrator.schedule_tools import filter_tools_for_configured_channels
+
+ usable = _usable_definitions()
+ try:
+ kept = {t["name"] for t in filter_tools_for_configured_channels(usable, get_settings())}
+ except Exception:
+ logger.warning("workflow chat tools: couldn't read the configured channels", exc_info=True)
+ kept = {t["name"] for t in usable}
+ dropped = {workflow_name_for(str(t["name"])) for t in usable if t["name"] not in kept}
+ return set(LEGACY_NAMES) | dropped
+
+
+def workflow_specs() -> dict[str, tuple[Any, Callable[[dict[str, Any]], Awaitable[str]]]]:
+ """``{oe__name: (ToolInfo, handler)}`` for every ``USE`` chat tool, plus
+ the old names in ``LEGACY_NAMES``. All of them resolve, so a saved
+ workflow keeps validating; ``not_offered`` says which to leave out of
+ what new steps are shown."""
+ from openexecutive.workflows.tool_catalog import ToolInfo, read_only_label
+
+ usable = _usable_definitions()
+ specs: dict[str, tuple[Any, Callable[[dict[str, Any]], Awaitable[str]]]] = {}
+ for tool in usable:
+ chat_name = str(tool["name"])
+ schema = dict(tool.get("input_schema") or {"type": "object", "properties": {}})
+
+ async def run(tool_input: dict[str, Any], _name: str = chat_name) -> str:
+ return await run_chat_tool(_name, tool_input)
+
+ specs[workflow_name_for(chat_name)] = (
+ ToolInfo(
+ name=workflow_name_for(chat_name),
+ description=str(tool.get("description") or ""),
+ input_schema=schema,
+ read_only=read_only_label(chat_name, schema),
+ source="builtin",
+ timeout_s=TIMEOUT_S.get(chat_name),
+ ),
+ run,
+ )
+ for legacy, chat_name in LEGACY_NAMES.items():
+ if workflow_name_for(chat_name) in specs:
+ info, handler = specs[workflow_name_for(chat_name)]
+ specs[legacy] = (dataclasses.replace(info, name=legacy), handler)
+ from openexecutive.orchestrator.web_search_tool import build_web_search_tool
+
+ if build_web_search_tool() is not None:
+ specs[workflow_name_for(WEB_SEARCH)] = (
+ ToolInfo(
+ name=workflow_name_for(WEB_SEARCH),
+ description=(
+ "Search the web for current facts, news, prices and sources. The "
+ "model searches as it writes; there is nothing to call."
+ ),
+ input_schema={"type": "object", "properties": {}},
+ read_only=None,
+ source="server",
+ ),
+ _web_search_not_callable,
+ )
+ return specs
+
+
+async def _web_search_not_callable(tool_input: dict[str, Any]) -> str:
+ return _error("Web search runs as the model writes; it can't be called from a script.")
diff --git a/packages/core/openexecutive/workflows/designer.py b/packages/core/openexecutive/workflows/designer.py
index 43bd878b..6348db04 100644
--- a/packages/core/openexecutive/workflows/designer.py
+++ b/packages/core/openexecutive/workflows/designer.py
@@ -62,6 +62,7 @@ MAX_OPTION_CHARS = 80
# name cannot smuggle a block of instructions into the context.
MAX_ROSTER_NAME_CHARS = 80
MAX_ROSTER_ROLE_CHARS = 80
+MAX_TOOL_DESCRIPTION_CHARS = 240
_MAX_TOKENS = 8000
_REPAIR_ECHO_CHARS = 4000
@@ -254,7 +255,9 @@ def build_context_block() -> str:
sections = [f"- {s.value}" for s in WorkflowSection]
- builtins = [f"- {t.name}: {t.description}" for t in tool_catalog.builtin_tools()]
+ builtins = [
+ f"- {t.name}: {_first_sentence(t.description)}" for t in tool_catalog.builtin_tools()
+ ]
gateway = (
"connected — use search_available_tools to find its tools"
if tool_catalog.gateway_available()
@@ -272,11 +275,24 @@ def build_context_block() -> str:
f"The user's timezone: {get_user_timezone().key}. Cadences are in UTC.\n\n"
"Sections:\n" + "\n".join(sections) + "\n\n"
f"External tool gateway (email, sheets, files, etc.): {gateway}.\n"
- "Built-in tools (always available):\n" + "\n".join(builtins) + "\n\n"
+ "Built-in tools (always available; the oe__ tools are the same tools "
+ "the Executive uses in chat, so anything it did in chat a step can "
+ "do too):\n" + "\n".join(builtins) + "\n\n"
"Workflow names already taken (do not reuse): " + ", ".join(taken)
)
+def _first_sentence(text: str) -> str:
+ """The first sentence of a tool description, kept to one short line.
+
+ Chat tools carry long descriptions written for chat; the designer only
+ needs enough to pick the right one.
+ """
+ line = _one_line(text, MAX_TOOL_DESCRIPTION_CHARS)
+ end = line.find(". ")
+ return line[: end + 1] if end > 0 else line
+
+
def _name_taken(name: str) -> bool:
"""True if a custom workflow already uses ``name``.
diff --git a/packages/core/openexecutive/workflows/tool_catalog.py b/packages/core/openexecutive/workflows/tool_catalog.py
index 640c5e50..a265b92e 100644
--- a/packages/core/openexecutive/workflows/tool_catalog.py
+++ b/packages/core/openexecutive/workflows/tool_catalog.py
@@ -116,7 +116,11 @@ class ToolInfo:
# True: only reads. None: may change something (unknown). Never False —
# we can't prove a tool writes, only that its name says it reads.
read_only: bool | None = None
- source: str = "mcp" # "mcp" | "builtin"
+ # "mcp" | "builtin" | "server" (the model's own tool: web search, added to
+ # the model's tools rather than called; ``workflows.chat_tools``)
+ source: str = "mcp"
+ # A call's timeout when it runs a whole job (None: the step's default).
+ timeout_s: float | None = None
def as_dict(self) -> dict[str, Any]:
return {
@@ -189,6 +193,11 @@ def _read_only_label(name: str, input_schema: dict[str, Any] | None = None) -> b
return True if name.split("__", 1)[-1].lower().startswith(_READ_VERBS) else None
+def read_only_label(name: str, input_schema: dict[str, Any] | None = None) -> bool | None:
+ """True when ``name`` only reads (see ``_read_only_label``), else None."""
+ return _read_only_label(name, input_schema)
+
+
# ── MCP: parse the gateway's search_tools output ────────────────────────────
#
# extensible-mcp (pinned in mcp_gateway.py) returns Markdown, one block per
@@ -346,89 +355,6 @@ def resolve_readable_file(
return resolved
-async def _read_file(tool_input: dict[str, Any]) -> str:
- """Extract text from a file a previous tool call downloaded.
-
- A scanned PDF is converted (``knowledge.pdf_reader``) rather than
- reported as unreadable.
- """
- from openexecutive.knowledge.loader import read_document_text
-
- resolved = resolve_readable_file(str(tool_input.get("path") or "").strip())
- if isinstance(resolved, str):
- return _err(resolved)
- try:
- result = await read_document_text(resolved)
- except Exception as exc:
- logger.warning("oe__read_file: extraction failed (%s)", type(exc).__name__)
- return _err("could not read that file")
- if not result.text.strip():
- return _err(result.note or "no text could be extracted")
- text = result.text
- cap = get_settings().tool_result_max_chars
- return text if len(text) <= cap else text[:cap] + "\n…[truncated]"
-
-
-async def _message_person(tool_input: dict[str, Any]) -> str:
- from openexecutive.orchestrator.schedule_tools import handle_message_person
-
- return await handle_message_person(tool_input)
-
-
-async def _create_alert(tool_input: dict[str, Any]) -> str:
- from openexecutive.orchestrator.alert_tools import handle_create_alert
-
- return await handle_create_alert(tool_input)
-
-
-def _builtin_specs() -> dict[str, tuple[ToolInfo, Handler]]:
- from openexecutive.orchestrator.alert_tools import CREATE_ALERT_TOOL
- from openexecutive.orchestrator.schedule_tools import MESSAGE_PERSON_TOOL
-
- return {
- "oe__read_file": (
- ToolInfo(
- name="oe__read_file",
- description=(
- "Read the text of a PDF, Word, Excel, CSV, Markdown or text "
- "file that another tool downloaded (e.g. an email "
- "attachment). Pass the file path that tool returned."
- ),
- input_schema={
- "type": "object",
- "properties": {
- "path": {"type": "string", "description": "Absolute file path."}
- },
- "required": ["path"],
- },
- read_only=True,
- source="builtin",
- ),
- _read_file,
- ),
- "oe__message_person": (
- ToolInfo(
- name="oe__message_person",
- description=MESSAGE_PERSON_TOOL["description"],
- input_schema=MESSAGE_PERSON_TOOL["input_schema"],
- read_only=None,
- source="builtin",
- ),
- _message_person,
- ),
- "oe__create_alert": (
- ToolInfo(
- name="oe__create_alert",
- description=CREATE_ALERT_TOOL["description"],
- input_schema=CREATE_ALERT_TOOL["input_schema"],
- read_only=None,
- source="builtin",
- ),
- _create_alert,
- ),
- }
-
-
def _extension_specs() -> dict[str, tuple[ToolInfo, Handler]]:
from openexecutive.orchestrator import extensions
@@ -454,13 +380,33 @@ def _extension_specs() -> dict[str, tuple[ToolInfo, Handler]]:
return specs
+def _chat_specs() -> dict[str, tuple[ToolInfo, Handler]]:
+ from openexecutive.workflows import chat_tools
+
+ try:
+ return chat_tools.workflow_specs()
+ except Exception:
+ logger.warning("tool_catalog: chat tools unavailable", exc_info=True)
+ return {}
+
+
def _all_builtin_specs() -> dict[str, tuple[ToolInfo, Handler]]:
- # Our own built-ins win a name clash.
- return {**_extension_specs(), **_builtin_specs()}
+ # The chat's tools (workflows.chat_tools) win a name clash with an
+ # extension's.
+ return {**_extension_specs(), **_chat_specs()}
def builtin_tools() -> list[ToolInfo]:
- return [info for info, _ in _all_builtin_specs().values()]
+ """The built-ins to offer for new steps (``chat_tools.not_offered``
+ still resolve, for saved workflows, but aren't shown)."""
+ from openexecutive.workflows.chat_tools import not_offered
+
+ try:
+ hidden = not_offered()
+ except Exception:
+ logger.warning("workflow tools: couldn't tell which to hide", exc_info=True)
+ hidden = set()
+ return [info for name, (info, _) in _all_builtin_specs().items() if name not in hidden]
def builtin_handler(name: str) -> Handler | None:
@@ -474,10 +420,15 @@ def builtin_handler(name: str) -> Handler | None:
async def search(query: str) -> list[ToolInfo]:
"""Tools matching a plain-language query: built-ins first, then the gateway."""
words = [w for w in re.split(r"\W+", query.lower()) if len(w) > 2]
- builtins = [
- t for t in builtin_tools()
- if not words or any(w in f"{t.name} {t.description}".lower() for w in words)
- ]
+ def hits(t: ToolInfo) -> int:
+ text = f"{t.name} {t.description}".lower()
+ return sum(w in text for w in words)
+
+ # Best match first: there are dozens of built-ins now that chat's tools
+ # are among them (workflows.chat_tools).
+ builtins = sorted(
+ (t for t in builtin_tools() if not words or hits(t)), key=lambda t: -hits(t)
+ )
gateway = _gateway()
mcp = await _gateway_search(gateway, query, _SEARCH_TOP_K) if gateway else []
return [*builtins, *mcp]
diff --git a/packages/core/tests/unit/test_action_step.py b/packages/core/tests/unit/test_action_step.py
index 9aaebd25..41170ae2 100644
--- a/packages/core/tests/unit/test_action_step.py
+++ b/packages/core/tests/unit/test_action_step.py
@@ -247,12 +247,12 @@ async def test_builtin_tools_run_locally(
seen.append(tool_input)
return "Invoice total 42"
- monkeypatch.setattr(tc, "builtin_handler", lambda name: _fake_read if name == "oe__read_file" else None)
+ monkeypatch.setattr(tc, "builtin_handler", lambda name: _fake_read if name == "oe__read_document" else None)
provider = _ScriptedProvider(
- [_resp(_use("oe__read_file", {"path": "/x/bill.pdf"}, "tu_1")), _resp(_text("Read it."))]
+ [_resp(_use("oe__read_document", {"path": "/x/bill.pdf"}, "tu_1")), _resp(_text("Read it."))]
)
_install(monkeypatch, provider)
- await _run(_step(tools=["oe__read_file"]))
+ await _run(_step(tools=["oe__read_document"]))
assert seen == [{"path": "/x/bill.pdf"}]
assert gateway.calls == []
diff --git a/packages/core/tests/unit/test_extensions.py b/packages/core/tests/unit/test_extensions.py
index 0fe2d3da..a6605870 100644
--- a/packages/core/tests/unit/test_extensions.py
+++ b/packages/core/tests/unit/test_extensions.py
@@ -492,7 +492,7 @@ def test_a_workflow_tool_joins_the_step_catalog_under_the_built_in_prefix() -> N
assert names["oe__read_widgets"].read_only is True and names["oe__read_widgets"].source == "builtin"
# Not saying it only reads means it may change something.
assert names["oe__make_widget"].read_only is None
- assert "oe__chat_only" not in names and "oe__read_file" in names
+ assert "oe__chat_only" not in names and "oe__read_document" in names
found = asyncio.run(tool_catalog.resolve(["oe__read_widgets", "oe__chat_only"]))
assert set(found) == {"oe__read_widgets"}
handler_for = tool_catalog.builtin_handler("oe__read_widgets")
@@ -506,8 +506,11 @@ def test_a_workflow_tool_joins_the_step_catalog_under_the_built_in_prefix() -> N
def test_a_workflow_tool_cannot_shadow_a_built_in_step_tool() -> None:
from openexecutive.workflows import tool_catalog
- extensions.register_tool(_tool("read_file", workflow=True))
- info = {t.name: t for t in tool_catalog.builtin_tools()}["oe__read_file"]
+ # Every built-in step tool is a chat tool, whose name an extension can't
+ # take; and should one get through, the chat's tool wins the clash.
+ with pytest.raises(ExtensionError, match="already taken"):
+ extensions.register_tool(_tool("read_document", workflow=True))
+ info = {t.name: t for t in tool_catalog.builtin_tools()}["oe__read_document"]
assert "PDF" in info.description
diff --git a/packages/core/tests/unit/test_tool_catalog.py b/packages/core/tests/unit/test_tool_catalog.py
index f20dba15..749764e3 100644
--- a/packages/core/tests/unit/test_tool_catalog.py
+++ b/packages/core/tests/unit/test_tool_catalog.py
@@ -1,5 +1,5 @@
"""The workflow tool catalog: gateway search parsing, exact-name resolution,
-save-time availability checks, and the ``oe__read_file`` built-in's
+save-time availability checks, and the ``oe__read_document`` built-in's
confinement to the download folders."""
from __future__ import annotations
@@ -152,7 +152,7 @@ async def test_search_merges_builtins_and_gateway(monkeypatch: pytest.MonkeyPatc
)
_use_gateway(monkeypatch, gateway)
names = [t.name for t in await tc.search("read a downloaded file")]
- assert names[0] == "oe__read_file"
+ assert names[0] == "oe__read_document"
assert "fetch__fetch" in names
@@ -188,7 +188,14 @@ async def test_validate_tools_says_when_gateway_is_down(monkeypatch: pytest.Monk
assert "gateway" in err and "not running" in err
-# --- oe__read_file -----------------------------------------------------------
+# --- oe__read_document (and saved workflows' oe__read_file) ------------------
+
+
+async def _read_file(tool_input: dict[str, Any]) -> str:
+ """What a step's oe__read_file / oe__read_document runs: chat's read_document."""
+ from openexecutive.orchestrator.document_tools import handle_read_document
+
+ return await handle_read_document(tool_input)
def _minimal_pdf(text: str) -> bytes:
@@ -229,14 +236,14 @@ def download_dir(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
async def test_read_file_extracts_pdf_text(download_dir: Path) -> None:
pdf = download_dir / "bill.pdf"
pdf.write_bytes(_minimal_pdf("Acme Power invoice total 123.45"))
- out = await tc._read_file({"path": str(pdf)})
+ out = await _read_file({"path": str(pdf)})
assert "Acme Power invoice total 123.45" in out
@pytest.mark.asyncio
async def test_read_file_reads_text_files(download_dir: Path) -> None:
(download_dir / "notes.csv").write_text("vendor,amount\nAcme,10\n")
- assert "Acme,10" in await tc._read_file({"path": str(download_dir / "notes.csv")})
+ assert "Acme,10" in await _read_file({"path": str(download_dir / "notes.csv")})
@pytest.mark.asyncio
@@ -246,7 +253,7 @@ async def test_read_file_refuses_paths_outside_the_download_dirs(
secret = tmp_path / "secret.txt"
secret.write_text("TOP SECRET")
for path in (str(secret), str(download_dir / ".." / "secret.txt")):
- out = await tc._read_file({"path": path})
+ out = await _read_file({"path": path})
assert "outside the folders" in out and "TOP SECRET" not in out
@@ -256,24 +263,24 @@ async def test_read_file_refuses_symlink_escape(download_dir: Path, tmp_path: Pa
secret.write_text("TOP SECRET")
link = download_dir / "innocent.txt"
link.symlink_to(secret)
- out = await tc._read_file({"path": str(link)})
+ out = await _read_file({"path": str(link)})
assert "outside the folders" in out and "TOP SECRET" not in out
@pytest.mark.asyncio
async def test_read_file_rejects_bad_input(download_dir: Path) -> None:
(download_dir / "run.sh").write_text("echo hi")
- assert "path is required" in await tc._read_file({})
- assert "not found" in await tc._read_file({"path": str(download_dir / "nope.pdf")})
- assert "unsupported file type" in await tc._read_file({"path": str(download_dir / "run.sh")})
- assert "not a file" in await tc._read_file({"path": str(download_dir)})
+ assert "pass `path`" in await _read_file({})
+ assert "not found" in await _read_file({"path": str(download_dir / "nope.pdf")})
+ assert "unsupported file type" in await _read_file({"path": str(download_dir / "run.sh")})
+ assert "not a file" in await _read_file({"path": str(download_dir)})
@pytest.mark.asyncio
async def test_read_file_size_cap(download_dir: Path, monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(tc, "_MAX_READ_FILE_BYTES", 10)
(download_dir / "big.txt").write_text("x" * 11)
- assert "larger than" in await tc._read_file({"path": str(download_dir / "big.txt")})
+ assert "larger than" in await _read_file({"path": str(download_dir / "big.txt")})
@pytest.mark.asyncio
@@ -293,7 +300,7 @@ async def test_read_file_converts_a_scanned_pdf(
monkeypatch.setattr(pdf_reader, "read_pdf_text", fake_read)
(download_dir / "scan.pdf").write_bytes(b"%PDF-scan")
- assert await tc._read_file({"path": str(download_dir / "scan.pdf")}) == "Invoice total 123.45"
+ assert (await _read_file({"path": str(download_dir / "scan.pdf")})).endswith("\nInvoice total 123.45")
# The path, not the bytes: the reader's child process opens the file.
assert seen == [download_dir / "scan.pdf"]
@@ -310,7 +317,7 @@ async def test_read_file_reports_why_a_pdf_is_unreadable(
monkeypatch.setattr(pdf_reader, "read_pdf_text", fake_read)
(download_dir / "scan.pdf").write_bytes(b"%PDF-scan")
- out = json.loads(await tc._read_file({"path": str(download_dir / "scan.pdf")}))
+ out = json.loads(await _read_file({"path": str(download_dir / "scan.pdf")}))
assert out == {"error": "no text could be read: OCR is off"}
diff --git a/packages/core/tests/unit/test_workflow_chat_tools.py b/packages/core/tests/unit/test_workflow_chat_tools.py
new file mode 100644
index 00000000..13258045
--- /dev/null
+++ b/packages/core/tests/unit/test_workflow_chat_tools.py
@@ -0,0 +1,368 @@
+"""Chat tools in workflow steps (workflows/chat_tools.py).
+
+Pins the parity contract (every tool chat offers is labelled, so a new chat
+tool can't silently skip the workflow decision), and that a step runs a chat
+tool the way an unattended chat turn would: the same handler, an unattended
+session, the workspace-mode filter, the creator's department gate, and no
+workflow starting itself.
+"""
+from __future__ import annotations
+
+import json
+import os
+from types import SimpleNamespace
+from typing import Any
+
+import pytest
+
+os.environ.setdefault("ANTHROPIC_API_KEY", "sk-test-not-used")
+
+from openexecutive.orchestrator.schedule_tools import current_session # noqa: E402
+from openexecutive.workflows import action_step as act # noqa: E402
+from openexecutive.workflows import chat_tools as ct # noqa: E402
+from openexecutive.workflows import tool_catalog as tc # noqa: E402
+from openexecutive.workflows.dynamic_models import ActionStepSpec # noqa: E402
+
+# ── Parity ───────────────────────────────────────────────────────────────────
+
+
+def test_every_chat_tool_is_labelled() -> None:
+ """A new chat tool must say whether workflows get it (ACCESS)."""
+ missing = sorted(set(ct.chat_tool_definitions()) - set(ct.ACCESS))
+ assert missing == [], f"label these in workflows/chat_tools.ACCESS: {missing}"
+
+
+def test_no_stale_labels() -> None:
+ stale = sorted(set(ct.ACCESS) - set(ct.chat_tool_definitions()) - {ct.WEB_SEARCH})
+ assert stale == [], f"these are no longer chat tools: {stale}"
+
+
+def test_every_usable_tool_has_a_chat_handler() -> None:
+ handlers = ct._chat_handlers()
+ usable = [n for n, (lbl, _) in ct.ACCESS.items() if lbl == ct.USE and n != ct.WEB_SEARCH]
+ assert sorted(n for n in usable if n not in handlers) == []
+
+
+def test_usable_tools_are_offered_to_workflows(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(
+ "openexecutive.orchestrator.schedule_tools.filter_tools_for_configured_channels",
+ lambda tools, settings: tools,
+ )
+ names = {t.name for t in tc.builtin_tools()}
+ for chat_name, (lbl, _) in ct.ACCESS.items():
+ if lbl == ct.USE and chat_name != ct.WEB_SEARCH:
+ assert ct.workflow_name_for(chat_name) in names, chat_name
+ for chat_name, (lbl, _) in ct.ACCESS.items():
+ if lbl != ct.USE:
+ assert ct.workflow_name_for(chat_name) not in names, chat_name
+
+
+async def test_workflow_tool_names_from_before_run_the_chat_tools(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """oe__message_person / oe__create_alert are the chat tools now, under the
+ same names; oe__read_file (saved workflows may list it) runs read_document
+ but isn't offered for new steps."""
+ ran: list[tuple[str, dict[str, Any]]] = []
+
+ async def run_chat_tool(name: str, tool_input: dict[str, Any]) -> str:
+ ran.append((name, tool_input))
+ return "ok"
+
+ monkeypatch.setattr(ct, "run_chat_tool", run_chat_tool)
+ for name in ("oe__message_person", "oe__create_alert", "oe__read_file"):
+ handler = tc.builtin_handler(name)
+ assert handler is not None, name
+ await handler({"x": name})
+ assert ran == [
+ ("message_person", {"x": "oe__message_person"}),
+ ("create_alert", {"x": "oe__create_alert"}),
+ ("read_document", {"x": "oe__read_file"}),
+ ]
+ offered = {t.name for t in tc.builtin_tools()}
+ assert "oe__read_file" not in offered and "oe__read_document" in offered
+ assert (await tc.resolve(["oe__read_file"]))["oe__read_file"].read_only is True
+
+
+def test_long_running_tools_get_a_longer_timeout() -> None:
+ specs = ct.workflow_specs()
+ assert specs["oe__run_workflow"][0].timeout_s == 900.0
+ assert specs["oe__run_executive_research"][0].timeout_s == 900.0
+ assert specs["oe__list_people"][0].timeout_s is None
+
+
+def test_web_search_is_a_server_tool_when_enabled(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(
+ "openexecutive.orchestrator.web_search_tool.build_web_search_tool",
+ lambda **_: {"type": "web_search_20250305", "name": "web_search"},
+ )
+ assert ct.workflow_specs()["oe__web_search"][0].source == "server"
+ monkeypatch.setattr(
+ "openexecutive.orchestrator.web_search_tool.build_web_search_tool", lambda **_: None
+ )
+ assert "oe__web_search" not in ct.workflow_specs()
+
+
+# ── Running a chat tool ──────────────────────────────────────────────────────
+
+
+def fake_session(monkeypatch: pytest.MonkeyPatch) -> list[str]:
+ modes: list[str] = []
+
+ def _session(mode: str) -> Any:
+ modes.append(mode)
+ return SimpleNamespace(session_id="wf-session", unattended=True)
+
+ monkeypatch.setattr(ct, "_session", _session)
+ monkeypatch.setattr(
+ "openexecutive.memory.workspace_settings.effective_workspace_mode", lambda _s: "team"
+ )
+ return modes
+
+
+def _handlers(monkeypatch: pytest.MonkeyPatch, **handlers: Any) -> None:
+ monkeypatch.setattr(ct, "_chat_handlers", lambda: handlers)
+
+
+async def test_runs_the_chat_handler_in_an_unattended_session(
+ monkeypatch: pytest.MonkeyPatch, fake_session: list[str]
+) -> None:
+ seen: list[Any] = []
+
+ async def list_people(tool_input: dict[str, Any]) -> str:
+ seen.append((tool_input, current_session.get()))
+ return "Ana, Ben"
+
+ _handlers(monkeypatch, list_people=list_people)
+ assert await ct.run_chat_tool("list_people", {"q": "a"}) == "Ana, Ben"
+ (tool_input, session), = seen
+ assert tool_input == {"q": "a"}
+ assert session.unattended is True
+ assert fake_session == ["team"]
+ assert current_session.get() is None
+
+
[email protected]("name", ["remember_fact", "ghostwrite_email", "consult_specialist", "nope"])
+async def test_tools_not_usable_in_workflows_are_refused(
+ monkeypatch: pytest.MonkeyPatch, fake_session: list[str], name: str
+) -> None:
+ called: list[str] = []
+
+ async def handler(tool_input: dict[str, Any]) -> str:
+ called.append(name)
+ return "ran"
+
+ _handlers(monkeypatch, **{name: handler})
+ out = json.loads(await ct.run_chat_tool(name, {}))
+ assert "not available in workflows" in out["error"]
+ assert called == []
+
+
+async def test_solo_mode_withholds_team_only_tools(
+ monkeypatch: pytest.MonkeyPatch, fake_session: list[str]
+) -> None:
+ monkeypatch.setattr(
+ "openexecutive.memory.workspace_settings.effective_workspace_mode", lambda _s: "solo"
+ )
+
+ async def handler(tool_input: dict[str, Any]) -> str:
+ raise AssertionError("must not run")
+
+ _handlers(monkeypatch, send_department_message=handler)
+ out = json.loads(await ct.run_chat_tool("send_department_message", {}))
+ assert "solo mode" in out["error"]
+
+
+async def test_a_workflow_cannot_start_itself_or_nest_too_deep(
+ monkeypatch: pytest.MonkeyPatch, fake_session: list[str]
+) -> None:
+ ran: list[str] = []
+
+ async def run_workflow(tool_input: dict[str, Any]) -> str:
+ ran.append(tool_input["name"])
+ return "started"
+
+ _handlers(monkeypatch, run_workflow=run_workflow)
+ with ct.in_workflow("weekly_report", None):
+ loop = json.loads(await ct.run_chat_tool("run_workflow", {"name": "weekly_report"}))
+ assert "already running" in loop["error"]
+ assert await ct.run_chat_tool("run_workflow", {"name": "other"}) == "started"
+ with ct.in_workflow("b", None), ct.in_workflow("c", None):
+ deep = json.loads(await ct.run_chat_tool("run_workflow", {"name": "d"}))
+ assert "at most" in deep["error"]
+ assert ran == ["other"]
+ assert ct._chain.get() == ()
+
+
+async def test_a_team_members_workflow_goes_through_their_department_gate(
+ monkeypatch: pytest.MonkeyPatch, fake_session: list[str]
+) -> None:
+ member = SimpleNamespace(id=7, is_principal=False, kind="team")
+ monkeypatch.setattr(
+ "openexecutive.people.store.get_person", lambda pid: member if pid == 7 else None
+ )
+ gated: list[Any] = []
+
+ def gated_handlers(handlers: dict[str, Any], person: Any, *, session_id: str | None = None) -> Any:
+ gated.append((person, session_id))
+
+ async def refused(tool_input: dict[str, Any]) -> str:
+ return "held for the department head"
+
+ return {name: refused for name in handlers}
+
+ monkeypatch.setattr(
+ "openexecutive.orchestrator.department_gate.gated_handlers", gated_handlers
+ )
+
+ async def message_person(tool_input: dict[str, Any]) -> str:
+ return "sent"
+
+ _handlers(monkeypatch, message_person=message_person)
+ with ct.in_workflow("wf", 7):
+ assert await ct.run_chat_tool("message_person", {}) == "held for the department head"
+ assert gated == [(member, "wf-session")]
+ # The principal's own workflow (no creator on record) is not gated.
+ assert await ct.run_chat_tool("message_person", {}) == "sent"
+ assert len(gated) == 1
+
+
+# ── In an action step ────────────────────────────────────────────────────────
+
+
+class _Provider:
+ def __init__(self, responses: list[Any]) -> None:
+ self._responses = list(responses)
+ self.calls: list[dict[str, Any]] = []
+
+ async def messages_create(self, **kwargs: Any) -> Any:
+ self.calls.append({**kwargs, "messages": [dict(m) for m in kwargs["messages"]]})
+ return self._responses.pop(0)
+
+
+class _Block(SimpleNamespace):
+ def model_dump(self, exclude_none: bool = False) -> dict[str, Any]:
+ return dict(vars(self))
+
+
+def step_env(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr("openexecutive.audit.log_event", lambda *a, **k: None)
+ monkeypatch.setattr("openexecutive.audit.usage.log_model_usage", lambda *a, **k: None)
+ monkeypatch.setattr(
+ "openexecutive.orchestrator.web_search_tool.build_web_search_tool",
+ lambda **_: {"type": "web_search_20250305", "name": "web_search"},
+ )
+ monkeypatch.setattr("openexecutive.workflows.dynamic_store.get_owner", lambda name: None)
+
+ async def _resolve(names: list[str]) -> dict[str, tc.ToolInfo]:
+ builtins = {t.name: t for t in tc.builtin_tools()}
+ return {n: builtins[n] for n in names if n in builtins}
+
+ monkeypatch.setattr(tc, "resolve", _resolve)
+
+
+async def _run_step(monkeypatch: pytest.MonkeyPatch, provider: _Provider, tools: list[str]) -> list[Any]:
+ monkeypatch.setattr("openexecutive.providers.registry.get_provider", lambda model: provider)
+ step = ActionStepSpec.model_validate(
+ {"id": "s", "title": "S", "goal": "Find the news.", "tools": tools}
+ )
+ return [
+ item
+ async for item in act.run_action_step(
+ step, workflow_name="wf", workflow_title="WF", goal=step.goal,
+ values={}, company_block="", prior_outputs={}, policy=None,
+ )
+ ]
+
+
+async def test_web_search_is_offered_as_the_models_own_tool(
+ monkeypatch: pytest.MonkeyPatch, step_env: None
+) -> None:
+ search = _Block(type="server_tool_use", id="srv_1", name="web_search", input={"query": "q"})
+ found = _Block(type="web_search_tool_result", tool_use_id="srv_1", content=[])
+ provider = _Provider([
+ SimpleNamespace(content=[search, found], stop_reason="pause_turn"),
+ SimpleNamespace(content=[SimpleNamespace(type="text", text="Here's the news.")], stop_reason="end_turn"),
+ ])
+ out = await _run_step(monkeypatch, provider, ["oe__list_people", "oe__web_search"])
+ tools = provider.calls[0]["tools"]
+ names = [t["name"] for t in tools]
+ assert "oe__web_search" not in names
+ assert names[-1] == "web_search" and names[:-1] == sorted(names[:-1])
+ assert tools[-1]["type"] == "web_search_20250305"
+ # The paused search is sent back as-is so the model carries on from it.
+ assert provider.calls[1]["messages"][-1] == {
+ "role": "assistant",
+ "content": [vars(search), vars(found)],
+ }
+ assert out[-1][0] == "output"
+ assert "Here's the news." in out[-1][1]
+
+
+async def test_a_chat_tool_step_runs_inside_its_workflow(
+ monkeypatch: pytest.MonkeyPatch, step_env: None, fake_session: list[str]
+) -> None:
+ chains: list[tuple[str, ...]] = []
+
+ async def list_people(tool_input: dict[str, Any]) -> str:
+ chains.append(ct._chain.get())
+ return "Ana"
+
+ _handlers(monkeypatch, list_people=list_people)
+ provider = _Provider([
+ SimpleNamespace(
+ content=[SimpleNamespace(type="tool_use", id="tu_1", name="oe__list_people", input={})],
+ stop_reason="tool_use",
+ ),
+ SimpleNamespace(content=[SimpleNamespace(type="text", text="Done.")], stop_reason="end_turn"),
+ ])
+ await _run_step(monkeypatch, provider, ["oe__list_people"])
+ assert chains == [("wf",)]
+ result = provider.calls[1]["messages"][-1]["content"][0]
+ assert result["content"] == "Ana" and result["is_error"] is False
+
+
+async def test_paused_web_searches_do_not_use_up_the_steps_turns(
+ monkeypatch: pytest.MonkeyPatch, step_env: None
+) -> None:
+ search = _Block(type="server_tool_use", id="srv_1", name="web_search", input={"query": "q"})
+ paused = SimpleNamespace(content=[search], stop_reason="pause_turn")
+ done = SimpleNamespace(content=[SimpleNamespace(type="text", text="Found it.")], stop_reason="end_turn")
+ # max_tool_calls 1 gives 4 turns; 5 pauses then the answer still finishes.
+ provider = _Provider([paused] * act._MAX_PAUSES + [done])
+ monkeypatch.setattr("openexecutive.providers.registry.get_provider", lambda model: provider)
+ step = ActionStepSpec.model_validate(
+ {"id": "s", "title": "S", "goal": "Find it.", "tools": ["oe__web_search"], "max_tool_calls": 1}
+ )
+ out = [
+ item async for item in act.run_action_step(
+ step, workflow_name="wf", workflow_title="WF", goal=step.goal,
+ values={}, company_block="", prior_outputs={}, policy=None,
+ )
+ ]
+ assert out[-1][0] == "output" and "Found it." in out[-1][1]
+
+
[email protected]("too_many", [False, True])
+async def test_an_empty_or_endless_pause_fails_the_step(
+ monkeypatch: pytest.MonkeyPatch, step_env: None, too_many: bool
+) -> None:
+ search = _Block(type="server_tool_use", id="srv_1", name="web_search", input={"query": "q"})
+ if too_many:
+ responses = [SimpleNamespace(content=[search], stop_reason="pause_turn")] * (act._MAX_PAUSES + 1)
+ else:
+ responses = [SimpleNamespace(content=[], stop_reason="pause_turn")]
+ out = await _run_step(monkeypatch, _Provider(responses), ["oe__web_search"])
+ assert out[-1][0] == "error" and "kept pausing" in out[-1][1]
diff --git a/packages/core/tests/unit/test_workflow_designer.py b/packages/core/tests/unit/test_workflow_designer.py
index 5c96e845..caa5b2a1 100644
--- a/packages/core/tests/unit/test_workflow_designer.py
+++ b/packages/core/tests/unit/test_workflow_designer.py
@@ -595,7 +595,7 @@ def test_context_block_reports_gateway_and_builtins(monkeypatch: pytest.MonkeyPa
)
monkeypatch.setattr(wd.tool_catalog, "gateway_available", lambda: False)
block = wd.build_context_block()
- assert "NOT running" in block and "oe__read_file" in block
+ assert "NOT running" in block and "oe__read_document" in block
monkeypatch.setattr(wd.tool_catalog, "gateway_available", lambda: True)
assert "connected" in wd.build_context_block()
diff --git a/packages/core/tests/unit/test_workflows_custom_routes.py b/packages/core/tests/unit/test_workflows_custom_routes.py
index b1c8f8a9..9dae0a98 100644
--- a/packages/core/tests/unit/test_workflows_custom_routes.py
+++ b/packages/core/tests/unit/test_workflows_custom_routes.py
@@ -270,7 +270,7 @@ def test_tool_search_endpoint(client: TestClient, monkeypatch: pytest.MonkeyPatc
assert client.get("/workflows/tools/search").json() == {"tools": []}
tools = client.get("/workflows/tools/search", params={"q": "read a file"}).json()["tools"]
assert tools[0] == {
- "name": "oe__read_file",
+ "name": "oe__read_document",
"description": tools[0]["description"],
"read_only": True,
"source": "builtin",