Skip to content

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

feat(workflows): confirm a workflow's first write to a new target (#199)

Rufusd63d11dcb570
diff --git a/packages/core/openexecutive/api/routes/workflows.py b/packages/core/openexecutive/api/routes/workflows.py
index c159c2d2..49afccba 100644
--- a/packages/core/openexecutive/api/routes/workflows.py
+++ b/packages/core/openexecutive/api/routes/workflows.py
@@ -33,7 +33,9 @@ from openexecutive.workflows.dynamic_store import (
activate_if_unchanged,
delete_definition,
get_definition,
+ get_owner,
list_definitions,
+ save_if_unchanged,
set_active,
upsert_definition,
)
@@ -93,6 +95,62 @@ async def delete_workflow_run(run_id: str) -> dict[str, str]:
return {"status": "deleted", "run_id": run_id}
+_WEB_DECISIONS = {"approve", "reject"}
+
+
[email protected]("/workflows/runs/{run_id}/decision")
+async def decide_workflow_run(run_id: str, request: Request) -> dict[str, Any]:
+ """Answer a run waiting for a yes/no sign-off from the web app.
+
+ The same resolution a chat reply produces, so the run resumes exactly as
+ it would have. Only the person the run is waiting on — or the principal —
+ may answer; free-text / numeric / document requests still need a reply in
+ chat, since there is nothing here to parse.
+ """
+ from openexecutive.api.routes.chat import _resolve_caller_person_id
+ from openexecutive.people.store import is_principal_or_self
+ from openexecutive.workflows.resumer import apply_resolution
+ from openexecutive.workflows.wait_for_human import WaitForHumanResolution
+
+ try:
+ body = await request.json()
+ except json.JSONDecodeError:
+ body = {}
+ decision = body.get("decision") if isinstance(body, dict) else None
+ if decision not in _WEB_DECISIONS:
+ raise HTTPException(status_code=422, detail="decision must be 'approve' or 'reject'")
+ run = get_run(run_id)
+ if run is None:
+ raise HTTPException(status_code=404, detail=f"Run {run_id} not found")
+ if run.get("status") != "awaiting_human":
+ raise HTTPException(status_code=409, detail="This run isn't waiting for an answer.")
+ try:
+ gate = json.loads(run.get("state_json") or "{}")
+ except json.JSONDecodeError:
+ gate = {}
+ if not isinstance(gate, dict) or gate.get("expected_reply_shape", "approve_reject") != "approve_reject":
+ raise HTTPException(
+ status_code=409, detail="This request needs a written reply — answer it in chat."
+ )
+ awaiting = run.get("awaiting_person_id")
+ caller = _resolve_caller_person_id(request)
+ if not is_principal_or_self(caller, awaiting):
+ raise HTTPException(
+ status_code=403, detail="Only the person this is waiting on, or the principal, can answer."
+ )
+ assert caller is not None # is_principal_or_self refuses an unresolved caller
+ resolution = WaitForHumanResolution(
+ run_id=run_id,
+ reply_text=f"[{decision} from the web app]",
+ source_channel="web",
+ parsed_decision={"decision": decision, "note": "answered in the web app"},
+ person_id=caller,
+ )
+ if not await apply_resolution(run_id, resolution):
+ raise HTTPException(status_code=409, detail="This run was answered already.")
+ return {"status": "resolved", "run_id": run_id, "decision": decision}
+
+
# -----------------------------------------------------------------------------
# Dynamic (user-created) workflow CRUD. Declared BEFORE "/workflows/{name}" so
# the literal "custom" segment isn't captured by the {name} path parameter.
@@ -137,26 +195,46 @@ async def describe_workflow_tools(names: str = "") -> dict[str, Any]:
return {"tools": [found[n].as_dict() for n in wanted if n in found]}
+def _with_owner(defn: DynamicWorkflowDef) -> dict[str, Any]:
+ """A definition as the UI sees it: its fields plus who created it.
+
+ ``owner_person_id`` is server-managed (a column, not a definition field),
+ so a client echoing it back in a body has no effect.
+ """
+ return {**defn.model_dump(), "owner_person_id": get_owner(defn.name)}
+
+
@router.get("/workflows/custom")
async def list_custom_workflows() -> dict[str, Any]:
"""All dynamic definitions (active and inactive) for the builder UI."""
- return {"definitions": [d.model_dump() for d in list_definitions(active_only=False)]}
+ return {"definitions": [_with_owner(d) for d in list_definitions(active_only=False)]}
@router.post("/workflows/custom", status_code=201)
async def create_custom_workflow(request: Request) -> dict[str, Any]:
- """Create a new dynamic workflow definition from a builder-UI submission."""
+ """Create a new dynamic workflow definition from a builder-UI submission.
+
+ The signed-in caller becomes its owner — the person asked to approve its
+ first write to a new target.
+ """
+ from openexecutive.api.routes.chat import _resolve_caller_person_id
+
defn = await _parse_definition(request)
+ exists = f"A custom workflow named {defn.name!r} already exists"
if get_definition(defn.name) is not None:
- raise HTTPException(
- status_code=409, detail=f"A custom workflow named {defn.name!r} already exists"
- )
+ raise HTTPException(status_code=409, detail=exists)
errors = await validate_definition_and_tools(defn)
if errors:
raise HTTPException(status_code=422, detail=errors)
- stored = upsert_definition(defn)
+ # Insert-only: a create racing another save of the same name is a 409,
+ # never a silent overwrite of someone else's workflow (or its owner).
+ stored = save_if_unchanged(
+ defn, None, owner_person_id=_resolve_caller_person_id(request)
+ )
+ if stored is None:
+ raise HTTPException(status_code=409, detail=exists)
_sync_cadence(stored)
- return stored.model_dump()
+ return _with_owner(stored)
@router.get("/workflows/custom/{name}")
@@ -164,7 +242,7 @@ async def get_custom_workflow(name: str) -> dict[str, Any]:
defn = get_definition(name)
if defn is None:
raise HTTPException(status_code=404, detail=f"Custom workflow {name!r} not found")
- return defn.model_dump()
+ return _with_owner(defn)
@router.put("/workflows/custom/{name}")
@@ -194,6 +272,26 @@ async def delete_custom_workflow(name: str) -> dict[str, str]:
return {"status": "deleted", "name": name}
[email protected]("/workflows/custom/{name}/targets")
+async def list_approved_targets(name: str) -> dict[str, Any]:
+ """Where this workflow's tool steps may write without asking again."""
+ from openexecutive.workflows.approved_targets import list_targets
+
+ if get_definition(name) is None:
+ raise HTTPException(status_code=404, detail=f"Custom workflow {name!r} not found")
+ return {"targets": list_targets(name)}
+
+
[email protected]("/workflows/custom/{name}/targets")
+async def forget_approved_target(name: str, value: str) -> dict[str, str]:
+ """Forget one approved target; the next write there asks again."""
+ from openexecutive.workflows.approved_targets import forget
+
+ if not forget(name, value):
+ raise HTTPException(status_code=404, detail="That target isn't approved for this workflow")
+ return {"status": "forgotten", "name": name}
+
+
# Fields a reviewer can't see or that the server manages; the rest is what the
# review card shows, and what an activation must match.
_REVIEW_EXCLUDE = {"is_active", "created_at", "updated_at"}
diff --git a/packages/core/openexecutive/architecture/architecture-facts.yaml b/packages/core/openexecutive/architecture/architecture-facts.yaml
index 943920e8..3c527162 100644
--- a/packages/core/openexecutive/architecture/architecture-facts.yaml
+++ b/packages/core/openexecutive/architecture/architecture-facts.yaml
@@ -3466,11 +3466,81 @@ workflows:
run()/resume() pre-flight all action tools; running out of turns fails the
step; resumes heartbeat their claim (persistence.touch_resume_claim, <=1/min)
and stop when superseded, so a live run is never requeued and replayed.
- Known residual risk: an approved write tool's TARGET (spreadsheet/doc id) is
- chosen by the model, so injected content could redirect a write — only the
- prompt rule, the allowlist and the audit bound it today. For detection,
- workflow_tool_call audit rows of non-read-only tools carry a bounded
- `targets` digest (keys like *_id/to/url/path/spreadsheet; never content).
+ Targets are chosen at run time BY DESIGN: approval covers the tools, not
+ which spreadsheet/doc/recipient/URL each call hits (tab per month, reply to
+ the sender, doc per client). Bounds: the allowlist, the gateway recipient
+ gates, the audit (workflow_tool_call rows of non-read-only tools carry a
+ bounded `targets` digest — keys like *_id/to/url/path/spreadsheet; never
+ content) and FIRST-WRITE CONFIRMATION:
+ - action_step.TargetPolicy (one per run) checks every call whose tool is
+ not labelled read-only; tool_catalog._read_only_label never labels a
+ name carrying a write verb anywhere (find_and_replace_doc,
+ check_and_merge_pr, get_or_create_folder …). resource_targets() walks
+ arguments recursively; a resource key (snake/camel ids, to/cc/bcc,
+ recipient, email, address, attendee, member, user, owner, parent,
+ url/uri/href/link, path, channel, space, room, phone, host, bucket,
+ table, spreadsheet, document, folder, calendar, file) marks its whole
+ subtree, names included. Outside one, exact name/title/subject/
+ file_name/display_name keys, message/thread/draft/label ids, range/sheet
+ and user_google_email are skipped; any bare email/URL/+phone-shaped
+ value is a target whatever its key, except under content keys (rows,
+ values, data, body, content, text, html, markdown, description, notes,
+ comment, summary, headline). Floats that are integers compare as ints.
+ Too deep (>8), too many (>100) or over-long (>2000 chars) FAILS CLOSED.
+ Key names are a heuristic: this is best-effort, layered on the tool
+ allowlist, gateway recipient gates and the audit.
+ - Trusted: values in workflow_approved_targets for this workflow (by
+ normalized value — emails lowercased — not by tool), and ids a write in
+ this run created: TOP-LEVEL id/link keys (id, *_id, *Id, *link, *url)
+ of the JSON-object result of a tool whose name says it creates
+ (tool_catalog.creates: create/insert/upload/add/copy/new/make/duplicate)
+ and that takes no URL (tool_catalog.takes_url; an unknown schema counts
+ as taking one) — never free text, nested records, or a reader's or
+ updater's result (a page, an echoed title, a shared doc's links or a
+ stranger in ccRecipients could plant one). Approvals are cleared when
+ the workflow's action-tool set changes (dynamic_store upsert /
+ save_if_unchanged), so a newly added tool never inherits them. Carried across pauses in
+ WorkflowResumeState.run_created (both gate and held-writes pauses).
+ Values in the workflow's own text are NOT trusted (anyone who can PUT
+ the workflow could change them without review) — asked once.
+ - The owner's question JSON-quotes each target (no injected lines) and
+ always shows a URL's scheme+host in full, saying how much is hidden.
+ - Anything else is HELD: not run, no budget spent, the model gets a
+ "held for approval, don't retry" result, audited "held for approval";
+ <= 10 per step, <= 16 KB args each, else refused; an identical repeat
+ is held once. Every exit that won't settle them (step error or crash,
+ resume refused for a changed definition / stale specialist / missing
+ later tool) audits them as "dropped (reason)" and says in the error
+ that N held writes did not run.
+ - After the step, the engine yields WaitForHumanEvent to
+ approved_targets.approver_for(name): the workflow's owner
+ (dynamic_workflows.owner_person_id — set on insert only from the web
+ caller on POST /workflows/custom or the chat session caller on
+ save_workflow; never from a body/definition; kept by PUT, overwrite,
+ activate), else the principal if the owner is unknown/archived.
+ on_timeout=auto_proceed, 48 h. WorkflowResumeState gains
+ kind="held_writes", held=[HeldCall(tool, arguments, targets)] and
+ deliver_to_person_id; old payloads parse as kind="gate".
+ - DynamicWorkflow._resume_held_writes (fingerprint + ActionStepSpec id
+ checked like a gate): only decision "approve" runs the held calls, each
+ re-checked against the LIVE step allowlist and resolve(); targets are
+ remembered first. reject/auto_proceed/defer/unknown skip. Either way a
+ "Held for approval" section is appended to the step output and the run
+ continues at idx+1. No approver at all: held writes skipped and noted.
+ - The principal can override from the web: POST
+ /workflows/runs/{id}/decision (is_principal_or_self on
+ awaiting_person_id; approve_reject gates only) -> apply_resolution. A
+ chat reply only matches the person asked (inbound_resolver filters on
+ awaiting_person_id).
+ - Scheduler: _run_dynamic_workflow checkpoints a held_writes pause
+ (checkpoint_gate) instead of raising, stamps deliver_to_person_id with
+ the cadence recipient, marks the row done and re-chains; the resumer
+ DMs the artifact after finish_resumed_run (and carries
+ deliver_to_person_id onto any later pause). Every other gate still
+ raises in the scheduler.
+ - Known limit: a daily cadence can raise a second question about the
+ same target while the first is unanswered; answering either remembers
+ the target for later runs.
Egress labelling walks the whole schema (nested/items/anyOf/$defs) and an
unparsed schema is never "reads only". requeue_run_for_resume takes
stale_before so a heartbeat between the sweep's SELECT and UPDATE wins.
diff --git a/packages/core/openexecutive/architecture/prebuilt/api.json b/packages/core/openexecutive/architecture/prebuilt/api.json
index 3e06f041..f0112219 100644
--- a/packages/core/openexecutive/architecture/prebuilt/api.json
+++ b/packages/core/openexecutive/architecture/prebuilt/api.json
@@ -1,7 +1,7 @@
{
"section_id": "api",
"title": "API Reference",
- "markdown": "The FastAPI surface lives in `openexecutive.api.main`, which mounts one router per topic. A shared-secret middleware gates every request via an `x-api-key` header, except `/health` and the `/webhook/*` callbacks (which carry their own verification). CORS is restricted to configured UI origins. The gate is off when `BACKEND_SHARED_SECRET` is unset — intended for local development only — so any internet-reachable deployment sets `OE_PUBLIC_DEPLOYMENT`, and `create_app()` then refuses to boot without the secret rather than serving an unauthenticated API.\n\nEndpoints grouped by router:\n\n| Router | Key endpoints | Purpose |\n|---|---|---|\n| `chat` | `POST /chat`, `POST /chat/stop` | SSE stream of a live Executive turn. The request body optionally carries `page_context` (route, page title, guide section id, and a form descriptor with current values) — sent only by the Ask OE side panel so the Executive can explain the current page or propose form values. When the Executive calls its `propose_form_values` tool, the stream emits a `form_patch` event (`{type, form_id, fields, rationale, iteration}`) that the panel applies into the on-screen form as highlighted suggestions; the user reviews and saves through the form's normal submit path. Each round of tool calls also emits an `activity` event (`{type, label, tool, iteration}`) naming what is running — progress only, forwarded verbatim and never persisted with the message, unlike an `action_taken` chip. The client mints a `client_turn_id` and sends it with the turn; `POST /chat/stop` takes that id and halts the turn mid-flight, so the button is live from the moment Send is pressed rather than only once the first SSE byte arrives. A stopped turn emits a `stopped` event and then the usual `done` over the same still-open stream — never an `error` — and whatever streamed so far is persisted and flagged. The endpoint returns 404 both for an unknown id and for another caller's turn, so it cannot be used to probe which turns are live. An optional `memory_text` (1–2000 chars) is what peer memory records as the caller's words instead of `message` — the briefing handoffs send it because their seed quotes the Executive's own card; `POST /chat/upload` derives it from the typed text and filenames. Since it never reaches the transcript, the `chat_turn` audit row keeps it beside `message`. |\n| `sessions` | `GET /sessions`, `GET /sessions/{id}/messages`, `POST /sessions/{id}/messages/{message_id}/feedback`, `GET /sessions/{id}/followup` | List and read saved chat sessions (assistant messages carry their row `id` and any `feedback`). The feedback route records 👍/👎 (`{\"feedback\": \"up\"|\"down\"|null}`) on one assistant reply; only the session's own caller or the principal may rate it (403 otherwise). The rater is stored (`feedback_by_person_id`), and a 👎 on a reply to the rater's own message triggers a working-style pass for them (paced; see attunement). The chat stream's `done` event carries `message_id` for the persisted reply. The followup route returns `{\"suggestion\": string|null}` — one suggested next user message, written by the utility-fast model from the last few turns, that the chat composer shows as its greyed placeholder (Tab / → or the inline chip fills it in without sending). It is null unless the session ends on a persisted assistant reply, and null (uncached) when the model fails. Same owner-or-principal 403 as feedback; successful suggestions are cached in-process per (session, reply id). |\n| `today` | `GET /today`, `GET /today/activity`, `GET /today/activity/daily` | Morning-brief aggregation, recent-action rail, and Pulse heartbeat heatmap (per-day activity counts). |\n| `people` | `GET\\|POST\\|PATCH /people`, `POST /people/{id}/archive`, `GET /people/{id}/open-loops`, `POST /open-loops/{loop_id}/close`, `GET /people/{id}/outreach`, `GET\\|PUT\\|DELETE /people/{id}/attunement` | Roster CRUD and scope lookups. Archiving a person closes their open loops. The open-loop routes list what a person owes (soonest due first) and close one (`reason`: done / not_needed / cancelled) — both the principal's or the owner's only (403 otherwise, via `people.store.is_principal_or_self`). `/outreach` returns, per kind of proactive outreach over 30 days, `sent` / `replied` / `acted` / `ignored` / `pending` (voided DMs are excluded) — same access rule, checked before the person lookup so it can't probe which ids exist. `/attunement` reads, replaces (`rules`: up to 4 strings, or omitted to only set `locked`) or resets the person's working-style rules — same access rule, 404 for an archived person; `PUT` rejects a rule that is not purely about style with 422. Archiving a person also drops their working style. |\n| `departments` | `GET\\|POST\\|PATCH\\|DELETE /departments`, `.../goals` | Department state and per-department goals. `PATCH /departments/{slug}` also takes `watched_entities` (≤50 names, `[]` clears) — the entities the research watch policy may add watches for and route to this department. A `cadences` spec that does not parse is rejected with a 422 (empty means no cadence). |\n| `agents` | `GET /agents`, `GET /agents/models`, `GET /agents/models/options`, `PATCH /agents/{id}`, `POST /agents/{id}/test` | Specialist metadata and Council overrides. `/agents/models` is the flat model allowlist the PATCH validator uses; `/agents/models/options` returns the same ids in the same order, each tagged with `provider`, `provider_label`, `route` (`direct` / `openrouter` / `local`) and a display `label`, for the Council's Provider → Model picker. |\n| `personas` | `GET\\|PUT\\|POST\\|DELETE /personas` | Executive persona definitions. |\n| `alerts` | `POST /alerts/{id}/ack`, `POST /alerts/bulk-ack`, `POST /alerts/{id}/reopen`, `POST /alerts/review` | Groom the briefing queue. `ack` (`read`/`ack`/`dismissed`, optional `mute_topic`) also teaches a watch-sourced alert's watch (`trust_score`); `bulk-ack` takes explicit `alert_ids` and/or `older_than_days` + `category` (exempt sources skipped); `reopen` is the Undo for a `resolved` / `expired` / `dismissed` alert (never `ack` or an artifact / decision row; back to `unread` with every review stamp cleared and its TTL anchor refreshed, so it is live again even if older than its TTL); `review` runs the Executive's relevance review on demand (ignores the interval; still honours `ALERT_REVIEW_ENABLED`, the per-pass caps, the single-flight lock and per-alert idempotency) and returns the move counts. `bulk-ack` caps ids at 500, needs `older_than_days >= 1`, and applies watch feedback per row; `mute_topic` must be one of the alert's tags or a scoped `external:` / `department:` pattern. Alerts still surface only through the briefing (`/today` reads the live view) — there is no list, prefs, mutes, or live-stream endpoint. |\n| `artifacts` | `GET /artifacts`, `POST /artifacts/{id}/archive` | Browsable research/document artifacts. |\n| `decisions` | `GET /decisions`, `POST /decisions/{id}/{approve,reject,cancel}`, `GET /audit/reliability` | Approval-gated decision instances (e.g. calendar bookings). A proposed booking is surfaced on the briefing as a companion alert; approve/reject/cancel here also clear that alert. Reviewed in the briefing — there is no separate proposals page. |\n| `audit` | `GET /audit/logs`, `GET /audit/logs/{id}`, `GET /audit/sessions/{id}`, `GET /audit/usage`, `POST /audit/log` | Durable audit trail of side effects. `/audit/sessions/{id}` adds a per-session token cost summary; `/audit/usage` aggregates token usage and OpenRouter cost across all sessions (totals, by day, by model, and by source — the part of the system that made the calls — including server-side web-search counts). |\n| `architecture` | `GET /architecture/sections`, `.../sections/{id}` | This documentation surface. |\n| `guide` | `GET /guide/sections`, `.../sections/{id}` | Plain-language user-guide content surface — mirrors `architecture` (static, version-controlled files; no LLM on the serving path). |\n| `health` | `GET /health`, `GET /health/honcho` | Liveness probes (unauthenticated). |\n| `documents` | `POST\\|GET\\|DELETE /documents`, `GET /documents/{filename}` | Upload, list, view extracted text, and delete indexed company docs. Upload is keyed on the filename, so re-uploading a document replaces its chunks rather than duplicating them, and `DELETE` removes the rows as well as the file. `domain` must be one of the eight specialist domains or `general`; anything else is a 400 rather than a 200 that indexes where no specialist can retrieve. |\n| `scheduled` | `GET\\|DELETE` scheduled actions (`?status=…&order=asc\\|desc`) | Pending and fired scheduled actions; `order` flips the `run_at` sort (asc=soonest-first for the upcoming queue, desc=most-recent-first for terminal-status history). |\n| `watchlist` | `GET\\|POST\\|PATCH\\|DELETE /watchlist`, `POST /watchlist/{slug}/approve`, `POST /watchlist/{slug}/decline` | External-monitoring watchlist + signals. Rows carry `origin` (`manual` \\| `executive` \\| `research` \\| `research_proposed`); `approve` turns a research suggestion (`research_proposed`, `dry_run`) into a live watch, `decline` `{reason: not_relevant \\| too_noisy \\| wrong_source}` removes it and records the decline (or, for `too_noisy`, keeps it live at a high floor), both 409 unless the row is a pending suggestion; `DELETE ?reason=` on a research-origin row records the decline too. |\n| `workflows` | `GET /workflows`, `POST /workflows/{name}/runs`, `GET\\|POST\\|PUT\\|DELETE /workflows/custom`, `GET /workflows/tools/search?q=`, `GET /workflows/tools/describe?names=` | Workflow catalog, run management, and user-created (dynamic) workflow CRUD. Custom create/update also rejects (422) any action-step tool that does not resolve, and so does `POST /workflows/custom/{name}/activate` when turning a workflow **on** — that click is the approval for a tool workflow chat saved switched off (turning off is never checked). Turning on a workflow with action steps requires the body `{is_active: true, definition}` carrying the definition the user reviewed; if the stored one differs (ignoring `is_active` and timestamps) it returns 409, and the switch itself is a compare-and-set on the validated revision (`dynamic_store.activate_if_unchanged`, keyed on `updated_at`), so a save that lands while the tool check awaits the gateway — even from another process — is a 409 too, so only what was shown gets switched on. `GET /workflows/custom` lists inactive definitions too; `GET /workflows/{name}` 404s for them. The two `tools` endpoints return `{tools: [{name, description, read_only, source}]}` for the advanced editor's tool picker and the review card; `read_only` is true only when the name says it reads (a label, not a control). The run stream adds a `progress` event (`step_id`, `summary`) while an action step uses tools. Each catalog entry (`WorkflowMeta`) carries `is_custom` and `background` (true for the system-run built-ins the UI files under “System”). The run endpoint streams SSE; its `awaiting_human` event carries `delivery` (`self` \\| `sent` \\| `suppressed` \\| `alerted` \\| `failed`) alongside `person_id` / `question` / `awaiting_until`, because the outbound guard or an unreachable approver means the question may never have been asked — a client must not render “waiting on them” for those. A paused run ends the stream with neither `done` nor `error`, so that `awaiting_human` frame carries `terminal: true` to say so explicitly, plus `resumable` — whether the run continues by itself once answered or stops at the gate. `GET /workflows/runs/{run_id}` returns the run row with the resume payload replaced by a small `resume_progress` summary (`gate_step_id`, `completed_step_ids`, or `null`): the payload holds every completed step's full text, and the run-detail page polls this endpoint while a run is unfinished. |\n| `knowledge` | `/knowledge/builtin`, `/external`, `/search` | MBA knowledge base and external sources. `/search` is the introspection parallel of `retriever.retrieve` and mirrors its filters — including the `general` catch-all on the company collection — so the panel cannot report a specialist seeing nothing that it does retrieve in chat. It accepts `general` in `domain_filter` for the same reason. `/search` applies the same review gate as `retrieve()` — withheld (pending or rejected) built-in, external and failure rows are dropped, so the panel never advertises knowledge the Executive cannot use; it degrades to unfiltered rather than failing if review state is unreadable. `POST /knowledge/builtin` refuses a name already held by shipped content, and `POST|DELETE /knowledge/failures` now register and deregister for review — without that a user-authored failure case study had no review row, so no SME decision could block it. |\n| `skills` | `/skills`, `/skills/search` | Skill registry CRUD and search. |\n| `evals` | `/evals/scenarios`, `/evals/runs` | Eval scenarios and run results. |\n| `memories` | `/memories/{decisions,initiatives,advice}`, `GET /memories/people`, `GET /memories/people/{person_id}/conclusions` | Episodic-memory record management, plus the read-only peer-memory overview the Pulse People tab reads (`{status: ok|disabled|error, people: [...], conclusion_total}`; `?recent=` 1–50, default 5) and one person's full conclusion list, paged newest first (`{status, person_id, items, page, size, total, has_more}`; `?page=` ≥1, `?size=` 1–100, default 50; 404 when the person has no peer). |\n| `review` | `/review/items`, `/review/stats`, `/review/trusted-defaults`, `POST /review/curate`, `POST /review/bulk-approve` | Knowledge review queue and annotations. Shipped knowledge registers as a trusted default (`approved` with a NULL `reviewed_at`), so the queue starts empty; `curate` (`{domain, action: start|stop}`, domain required) opts one domain in or out, and `trusted-defaults` returns domain → unreviewed count. `bulk-approve` takes a non-empty `domain`, `item_ids` (max 500) or `all_pending: true`, and 400s with no selector; it returns `{approved_count, item_ids}`. |\n| `onboarding` | `/onboard/interview/start`, `/onboard/interview/message`, `/onboard/interview/draft`, `/onboard/interview/{id}`, `/onboard/interview/commit` | Conversational company setup. The `onboarding_interviewer` agent asks clarifying questions, then emits a draft profile + people + departments. **Nothing is persisted until `POST /onboard/interview/commit`** — the interview itself never writes. `start` is multipart (description + optional deck/one-pager uploads). |\n| `workflow_designer` | `POST /workflows/designer/start`, `POST /workflows/designer/message`, `POST /workflows/designer/draft`, `GET /workflows/designer/{session_id}` | The conversational New workflow wizard. The `workflow_designer` agent asks clarifying questions (`phase: \"question\"`, with `hint` and up to four suggested `options`), then returns `phase: \"draft\"` with `draft.definition` (exactly the body `POST /workflows/custom` takes), `summary`, and `assumptions`; every response carries the `transcript`. **Nothing is persisted here** — sessions are in memory, and the UI saves through `POST /workflows/custom`. Errors are fixed strings (422 over the 8,000-char message cap or the transcript cap, 404 for an expired session, 409 while another turn on the same session is still running, 502/504 for model failure or timeout). Mounted ahead of the `workflows` router. |\n| `onboarding` (fallback) | `/onboard/start`, `/onboard/answer`, `/onboard/status/{id}` | The original 12-step form wizard, kept as a fallback (UI at `/onboard?mode=form`) and used by the `openexecutive onboard` CLI. |\n| `company-profile` | `GET\\|PATCH /company-profile` | Structured company profile. |\n| `auth` | `GET /auth/allowed-emails` | Non-archived people with an email, offered to the UI's sign-in gate. The gate takes the **union** of this roster and its own `ALLOWED_EMAILS` env list, so env entries always work (and are checked first, short-circuiting the fetch) and roster entries are additive — a roster change can never revoke a configured operator. |\n| `fixtures` | `/fixtures`, `/fixtures/{name}/load` | Demo-company fixture load/reset/snapshot. |\n| `clients` | `/clients`, `/clients/generate`, `/clients/cockpit`, `/clients/save`, `/clients/{slug}/activate` | Client-company slots — multi-client mode for fractional use; create from current/blank/AI-generated intake draft (pasted notes and/or file attachments, multipart on `/clients/generate`), save-back switching, engagement metadata (PATCH), cross-client cockpit, delete. See the Client Companies section. |\n| webhooks | `POST /webhook/telegram`, `POST /webhook/google-chat` | Inbound integration callbacks (self-verified). |\n| MCP server | `POST\\|GET /mcp` | Open Executive exposed as an MCP server (Streamable-HTTP). Not a router — a mounted FastMCP sub-app. Same shared-secret gate (`x-api-key`); exposes company context as resources and the specialist council as tools. See the MCP Server section. |",
+ "markdown": "The FastAPI surface lives in `openexecutive.api.main`, which mounts one router per topic. A shared-secret middleware gates every request via an `x-api-key` header, except `/health` and the `/webhook/*` callbacks (which carry their own verification). CORS is restricted to configured UI origins. The gate is off when `BACKEND_SHARED_SECRET` is unset — intended for local development only — so any internet-reachable deployment sets `OE_PUBLIC_DEPLOYMENT`, and `create_app()` then refuses to boot without the secret rather than serving an unauthenticated API.\n\nEndpoints grouped by router:\n\n| Router | Key endpoints | Purpose |\n|---|---|---|\n| `chat` | `POST /chat`, `POST /chat/stop` | SSE stream of a live Executive turn. The request body optionally carries `page_context` (route, page title, guide section id, and a form descriptor with current values) — sent only by the Ask OE side panel so the Executive can explain the current page or propose form values. When the Executive calls its `propose_form_values` tool, the stream emits a `form_patch` event (`{type, form_id, fields, rationale, iteration}`) that the panel applies into the on-screen form as highlighted suggestions; the user reviews and saves through the form's normal submit path. Each round of tool calls also emits an `activity` event (`{type, label, tool, iteration}`) naming what is running — progress only, forwarded verbatim and never persisted with the message, unlike an `action_taken` chip. The client mints a `client_turn_id` and sends it with the turn; `POST /chat/stop` takes that id and halts the turn mid-flight, so the button is live from the moment Send is pressed rather than only once the first SSE byte arrives. A stopped turn emits a `stopped` event and then the usual `done` over the same still-open stream — never an `error` — and whatever streamed so far is persisted and flagged. The endpoint returns 404 both for an unknown id and for another caller's turn, so it cannot be used to probe which turns are live. An optional `memory_text` (1–2000 chars) is what peer memory records as the caller's words instead of `message` — the briefing handoffs send it because their seed quotes the Executive's own card; `POST /chat/upload` derives it from the typed text and filenames. Since it never reaches the transcript, the `chat_turn` audit row keeps it beside `message`. |\n| `sessions` | `GET /sessions`, `GET /sessions/{id}/messages`, `POST /sessions/{id}/messages/{message_id}/feedback`, `GET /sessions/{id}/followup` | List and read saved chat sessions (assistant messages carry their row `id` and any `feedback`). The feedback route records 👍/👎 (`{\"feedback\": \"up\"|\"down\"|null}`) on one assistant reply; only the session's own caller or the principal may rate it (403 otherwise). The rater is stored (`feedback_by_person_id`), and a 👎 on a reply to the rater's own message triggers a working-style pass for them (paced; see attunement). The chat stream's `done` event carries `message_id` for the persisted reply. The followup route returns `{\"suggestion\": string|null}` — one suggested next user message, written by the utility-fast model from the last few turns, that the chat composer shows as its greyed placeholder (Tab / → or the inline chip fills it in without sending). It is null unless the session ends on a persisted assistant reply, and null (uncached) when the model fails. Same owner-or-principal 403 as feedback; successful suggestions are cached in-process per (session, reply id). |\n| `today` | `GET /today`, `GET /today/activity`, `GET /today/activity/daily` | Morning-brief aggregation, recent-action rail, and Pulse heartbeat heatmap (per-day activity counts). |\n| `people` | `GET\\|POST\\|PATCH /people`, `POST /people/{id}/archive`, `GET /people/{id}/open-loops`, `POST /open-loops/{loop_id}/close`, `GET /people/{id}/outreach`, `GET\\|PUT\\|DELETE /people/{id}/attunement` | Roster CRUD and scope lookups. Archiving a person closes their open loops. The open-loop routes list what a person owes (soonest due first) and close one (`reason`: done / not_needed / cancelled) — both the principal's or the owner's only (403 otherwise, via `people.store.is_principal_or_self`). `/outreach` returns, per kind of proactive outreach over 30 days, `sent` / `replied` / `acted` / `ignored` / `pending` (voided DMs are excluded) — same access rule, checked before the person lookup so it can't probe which ids exist. `/attunement` reads, replaces (`rules`: up to 4 strings, or omitted to only set `locked`) or resets the person's working-style rules — same access rule, 404 for an archived person; `PUT` rejects a rule that is not purely about style with 422. Archiving a person also drops their working style. |\n| `departments` | `GET\\|POST\\|PATCH\\|DELETE /departments`, `.../goals` | Department state and per-department goals. `PATCH /departments/{slug}` also takes `watched_entities` (≤50 names, `[]` clears) — the entities the research watch policy may add watches for and route to this department. A `cadences` spec that does not parse is rejected with a 422 (empty means no cadence). |\n| `agents` | `GET /agents`, `GET /agents/models`, `GET /agents/models/options`, `PATCH /agents/{id}`, `POST /agents/{id}/test` | Specialist metadata and Council overrides. `/agents/models` is the flat model allowlist the PATCH validator uses; `/agents/models/options` returns the same ids in the same order, each tagged with `provider`, `provider_label`, `route` (`direct` / `openrouter` / `local`) and a display `label`, for the Council's Provider → Model picker. |\n| `personas` | `GET\\|PUT\\|POST\\|DELETE /personas` | Executive persona definitions. |\n| `alerts` | `POST /alerts/{id}/ack`, `POST /alerts/bulk-ack`, `POST /alerts/{id}/reopen`, `POST /alerts/review` | Groom the briefing queue. `ack` (`read`/`ack`/`dismissed`, optional `mute_topic`) also teaches a watch-sourced alert's watch (`trust_score`); `bulk-ack` takes explicit `alert_ids` and/or `older_than_days` + `category` (exempt sources skipped); `reopen` is the Undo for a `resolved` / `expired` / `dismissed` alert (never `ack` or an artifact / decision row; back to `unread` with every review stamp cleared and its TTL anchor refreshed, so it is live again even if older than its TTL); `review` runs the Executive's relevance review on demand (ignores the interval; still honours `ALERT_REVIEW_ENABLED`, the per-pass caps, the single-flight lock and per-alert idempotency) and returns the move counts. `bulk-ack` caps ids at 500, needs `older_than_days >= 1`, and applies watch feedback per row; `mute_topic` must be one of the alert's tags or a scoped `external:` / `department:` pattern. Alerts still surface only through the briefing (`/today` reads the live view) — there is no list, prefs, mutes, or live-stream endpoint. |\n| `artifacts` | `GET /artifacts`, `POST /artifacts/{id}/archive` | Browsable research/document artifacts. |\n| `decisions` | `GET /decisions`, `POST /decisions/{id}/{approve,reject,cancel}`, `GET /audit/reliability` | Approval-gated decision instances (e.g. calendar bookings). A proposed booking is surfaced on the briefing as a companion alert; approve/reject/cancel here also clear that alert. Reviewed in the briefing — there is no separate proposals page. |\n| `audit` | `GET /audit/logs`, `GET /audit/logs/{id}`, `GET /audit/sessions/{id}`, `GET /audit/usage`, `POST /audit/log` | Durable audit trail of side effects. `/audit/sessions/{id}` adds a per-session token cost summary; `/audit/usage` aggregates token usage and OpenRouter cost across all sessions (totals, by day, by model, and by source — the part of the system that made the calls — including server-side web-search counts). |\n| `architecture` | `GET /architecture/sections`, `.../sections/{id}` | This documentation surface. |\n| `guide` | `GET /guide/sections`, `.../sections/{id}` | Plain-language user-guide content surface — mirrors `architecture` (static, version-controlled files; no LLM on the serving path). |\n| `health` | `GET /health`, `GET /health/honcho` | Liveness probes (unauthenticated). |\n| `documents` | `POST\\|GET\\|DELETE /documents`, `GET /documents/{filename}` | Upload, list, view extracted text, and delete indexed company docs. Upload is keyed on the filename, so re-uploading a document replaces its chunks rather than duplicating them, and `DELETE` removes the rows as well as the file. `domain` must be one of the eight specialist domains or `general`; anything else is a 400 rather than a 200 that indexes where no specialist can retrieve. |\n| `scheduled` | `GET\\|DELETE` scheduled actions (`?status=…&order=asc\\|desc`) | Pending and fired scheduled actions; `order` flips the `run_at` sort (asc=soonest-first for the upcoming queue, desc=most-recent-first for terminal-status history). |\n| `watchlist` | `GET\\|POST\\|PATCH\\|DELETE /watchlist`, `POST /watchlist/{slug}/approve`, `POST /watchlist/{slug}/decline` | External-monitoring watchlist + signals. Rows carry `origin` (`manual` \\| `executive` \\| `research` \\| `research_proposed`); `approve` turns a research suggestion (`research_proposed`, `dry_run`) into a live watch, `decline` `{reason: not_relevant \\| too_noisy \\| wrong_source}` removes it and records the decline (or, for `too_noisy`, keeps it live at a high floor), both 409 unless the row is a pending suggestion; `DELETE ?reason=` on a research-origin row records the decline too. |\n| `workflows` | `GET /workflows`, `POST /workflows/{name}/runs`, `GET\\|POST\\|PUT\\|DELETE /workflows/custom`, `GET\\|DELETE /workflows/custom/{name}/targets`, `POST /workflows/runs/{run_id}/decision`, `GET /workflows/tools/search?q=`, `GET /workflows/tools/describe?names=` | Workflow catalog, run management, and user-created (dynamic) workflow CRUD. Custom definitions come back with a server-managed `owner_person_id` (the creator — the web caller on `POST`, set on insert only; a client-sent value is ignored), who is asked to approve a workflow's first write to a new target. `GET /workflows/custom/{name}/targets` lists the targets its tool steps may write to without asking and `DELETE …/targets?value=` forgets one. `POST /workflows/runs/{run_id}/decision` with `{decision: \"approve\"|\"reject\"}` answers a run awaiting a yes/no sign-off from the web app — 403 unless the caller is the person it waits on or the principal, 409 if it isn't awaiting or needs a written reply — through the same `apply_resolution` a chat reply uses. Custom create/update also rejects (422) any action-step tool that does not resolve, and so does `POST /workflows/custom/{name}/activate` when turning a workflow **on** — that click is the approval for a tool workflow chat saved switched off (turning off is never checked). Turning on a workflow with action steps requires the body `{is_active: true, definition}` carrying the definition the user reviewed; if the stored one differs (ignoring `is_active` and timestamps) it returns 409, and the switch itself is a compare-and-set on the validated revision (`dynamic_store.activate_if_unchanged`, keyed on `updated_at`), so a save that lands while the tool check awaits the gateway — even from another process — is a 409 too, so only what was shown gets switched on. `GET /workflows/custom` lists inactive definitions too; `GET /workflows/{name}` 404s for them. The two `tools` endpoints return `{tools: [{name, description, read_only, source}]}` for the advanced editor's tool picker and the review card; `read_only` is true only when the name says it reads (a label, not a control). The run stream adds a `progress` event (`step_id`, `summary`) while an action step uses tools. Each catalog entry (`WorkflowMeta`) carries `is_custom` and `background` (true for the system-run built-ins the UI files under “System”). The run endpoint streams SSE; its `awaiting_human` event carries `delivery` (`self` \\| `sent` \\| `suppressed` \\| `alerted` \\| `failed`) alongside `person_id` / `question` / `awaiting_until`, because the outbound guard or an unreachable approver means the question may never have been asked — a client must not render “waiting on them” for those. A paused run ends the stream with neither `done` nor `error`, so that `awaiting_human` frame carries `terminal: true` to say so explicitly, plus `resumable` — whether the run continues by itself once answered or stops at the gate. `GET /workflows/runs/{run_id}` returns the run row with the resume payload replaced by a small `resume_progress` summary (`gate_step_id`, `completed_step_ids`, or `null`): the payload holds every completed step's full text, and the run-detail page polls this endpoint while a run is unfinished. |\n| `knowledge` | `/knowledge/builtin`, `/external`, `/search` | MBA knowledge base and external sources. `/search` is the introspection parallel of `retriever.retrieve` and mirrors its filters — including the `general` catch-all on the company collection — so the panel cannot report a specialist seeing nothing that it does retrieve in chat. It accepts `general` in `domain_filter` for the same reason. `/search` applies the same review gate as `retrieve()` — withheld (pending or rejected) built-in, external and failure rows are dropped, so the panel never advertises knowledge the Executive cannot use; it degrades to unfiltered rather than failing if review state is unreadable. `POST /knowledge/builtin` refuses a name already held by shipped content, and `POST|DELETE /knowledge/failures` now register and deregister for review — without that a user-authored failure case study had no review row, so no SME decision could block it. |\n| `skills` | `/skills`, `/skills/search` | Skill registry CRUD and search. |\n| `evals` | `/evals/scenarios`, `/evals/runs` | Eval scenarios and run results. |\n| `memories` | `/memories/{decisions,initiatives,advice}`, `GET /memories/people`, `GET /memories/people/{person_id}/conclusions` | Episodic-memory record management, plus the read-only peer-memory overview the Pulse People tab reads (`{status: ok|disabled|error, people: [...], conclusion_total}`; `?recent=` 1–50, default 5) and one person's full conclusion list, paged newest first (`{status, person_id, items, page, size, total, has_more}`; `?page=` ≥1, `?size=` 1–100, default 50; 404 when the person has no peer). |\n| `review` | `/review/items`, `/review/stats`, `/review/trusted-defaults`, `POST /review/curate`, `POST /review/bulk-approve` | Knowledge review queue and annotations. Shipped knowledge registers as a trusted default (`approved` with a NULL `reviewed_at`), so the queue starts empty; `curate` (`{domain, action: start|stop}`, domain required) opts one domain in or out, and `trusted-defaults` returns domain → unreviewed count. `bulk-approve` takes a non-empty `domain`, `item_ids` (max 500) or `all_pending: true`, and 400s with no selector; it returns `{approved_count, item_ids}`. |\n| `onboarding` | `/onboard/interview/start`, `/onboard/interview/message`, `/onboard/interview/draft`, `/onboard/interview/{id}`, `/onboard/interview/commit` | Conversational company setup. The `onboarding_interviewer` agent asks clarifying questions, then emits a draft profile + people + departments. **Nothing is persisted until `POST /onboard/interview/commit`** — the interview itself never writes. `start` is multipart (description + optional deck/one-pager uploads). |\n| `workflow_designer` | `POST /workflows/designer/start`, `POST /workflows/designer/message`, `POST /workflows/designer/draft`, `GET /workflows/designer/{session_id}` | The conversational New workflow wizard. The `workflow_designer` agent asks clarifying questions (`phase: \"question\"`, with `hint` and up to four suggested `options`), then returns `phase: \"draft\"` with `draft.definition` (exactly the body `POST /workflows/custom` takes), `summary`, and `assumptions`; every response carries the `transcript`. **Nothing is persisted here** — sessions are in memory, and the UI saves through `POST /workflows/custom`. Errors are fixed strings (422 over the 8,000-char message cap or the transcript cap, 404 for an expired session, 409 while another turn on the same session is still running, 502/504 for model failure or timeout). Mounted ahead of the `workflows` router. |\n| `onboarding` (fallback) | `/onboard/start`, `/onboard/answer`, `/onboard/status/{id}` | The original 12-step form wizard, kept as a fallback (UI at `/onboard?mode=form`) and used by the `openexecutive onboard` CLI. |\n| `company-profile` | `GET\\|PATCH /company-profile` | Structured company profile. |\n| `auth` | `GET /auth/allowed-emails` | Non-archived people with an email, offered to the UI's sign-in gate. The gate takes the **union** of this roster and its own `ALLOWED_EMAILS` env list, so env entries always work (and are checked first, short-circuiting the fetch) and roster entries are additive — a roster change can never revoke a configured operator. |\n| `fixtures` | `/fixtures`, `/fixtures/{name}/load` | Demo-company fixture load/reset/snapshot. |\n| `clients` | `/clients`, `/clients/generate`, `/clients/cockpit`, `/clients/save`, `/clients/{slug}/activate` | Client-company slots — multi-client mode for fractional use; create from current/blank/AI-generated intake draft (pasted notes and/or file attachments, multipart on `/clients/generate`), save-back switching, engagement metadata (PATCH), cross-client cockpit, delete. See the Client Companies section. |\n| webhooks | `POST /webhook/telegram`, `POST /webhook/google-chat` | Inbound integration callbacks (self-verified). |\n| MCP server | `POST\\|GET /mcp` | Open Executive exposed as an MCP server (Streamable-HTTP). Not a router — a mounted FastMCP sub-app. Same shared-secret gate (`x-api-key`); exposes company context as resources and the specialist council as tools. See the MCP Server section. |",
"mermaid": null,
- "generated_at": "2026-09-24T12:21:45.972791+00:00"
+ "generated_at": "2026-09-24T00:00:00Z"
}
diff --git a/packages/core/openexecutive/architecture/prebuilt/scheduler.json b/packages/core/openexecutive/architecture/prebuilt/scheduler.json
index 9a50fb0d..2e54f9a1 100644
--- a/packages/core/openexecutive/architecture/prebuilt/scheduler.json
+++ b/packages/core/openexecutive/architecture/prebuilt/scheduler.json
@@ -1,7 +1,7 @@
{
"section_id": "scheduler",
"title": "Scheduler & Cadences",
- "markdown": "The scheduler is an asyncio task started in the FastAPI lifespan (`openexecutive.scheduler.runner.run_scheduler`). It polls every 30s and reads due rows from `scheduled_actions` (in `episodic_memory.db`). The due query uses `claim_due_actions`, an UPDATE…RETURNING claim, so each row fires at most once per process — this assumes a single scheduler instance per database. Polls are gated on an active company profile via `_company_profile_active()`; before onboarding, due rows stay `pending`.\n\n### Cadence DSL\n\n`openexecutive.departments.cadence` supports, all in UTC:\n\n- `daily@HH:MM`\n- `weekly@DOW@HH:MM` or `weekly@DOW-HH:MM` (DOW is a 3-letter day, e.g. `weekly@thu@09:00`)\n- `quarterly@DD-HH:MM`\n\n`PATCH /departments/{slug}` rejects a spec that does not parse (bad format, unknown DOW, out-of-range time) with a 422 naming the valid formats, so a typo is caught at save time instead of silently never firing. An empty spec means no cadence.\n\nWhen a department cadence is due, the runner invokes the `department_check_in` workflow and chains the following occurrence via `cadence.enqueue_next()`. Deleting a department cancels its pending `dept_cadence` rows, and `cancel_orphaned_cadences()` sweeps orphans on boot.\n\nUser-created (dynamic) workflows can carry the same cadence DSL. A cadence-enabled definition enqueues a `dynamic_workflow` action (`workflows.dynamic_cadence`); when due, the runner runs the stored `DynamicWorkflow`, DMs the artifact to the definition's `cadence_person_id`, and re-chains the next occurrence. Saving/updating/deleting the definition reconciles its pending `dynamic_workflow` rows. A cadence definition may not contain an approval gate — a cron fire has no human to ask — and the runner now enforces that at execution too: it calls `workflows.gate.ensure_workflow_event`, which raises on a gate so the run is recorded as failed. It previously ignored the gate and stored a completed run with `\"(no artifact)\"` as its body, which looked like a success every period.\n\n### Channel routing & nudges\n\nThe delivery channel lives on the `scheduled_actions` row (`channel` / `channel_ref`); the runner dispatches through whichever was set at enqueue time — `telegram`, `slack_dm`, `discord_dm`, `email`, or `__internal__` (workflow steps and heartbeats bypass outbound dispatch). Rows left pending by the removed staff-onboarding kinds drain through that same `__internal__` short-circuit (marked done, no dispatch); the removed talent workflows' *ad-hoc* reminders sat on the principal's real DM channel instead, so a one-shot startup sweep (`memory.episodic.cancel_orphaned_talent_reminders`) cancels them — `ad_hoc`, no department, `pending` or `running`, matching the five generated reminder shapes (outreach, interview coordination, reference checks, onboarding check-in, offer expiry) — and clears the awaiting-reply flag on delivered ones so the nudge engine stops chasing them. The marker row in `app_migrations` is claimed first with `INSERT OR IGNORE` in the same transaction, so concurrent boots cannot double-run or crash. The nudge engine (`scheduler.nudge_engine`, default 15 min) scans stalled `awaiting_human` runs, stale commitments, and idle initiatives, then emits `proactive_nudge` rows routed via `people.channel.prefer_channel_for` — honouring each Person's preferred (last-used) channel and availability windows, deferring those outside their window and skipping those with no reachable channel. Emission is capped per `scope_key` (`NUDGE_MAX_PER_SCOPE`, default 3 delivered nudges) so a parked item is not chased forever.\n\nThe stale-commitment source also chases **open loops** (see Attunement): `scheduled_actions` rows with `kind='open_loop'`, recorded `done` on the `__internal__` channel so the runner never dispatches them, whose `awaiting_response_since` is the loop's *due time*. They are chased as soon as they are overdue — not after `NUDGE_COMMITMENT_STALE_DAYS` — with a check-in intent addressed to the loop's owner (which quotes only the owner's own verbatim words and tells the dispatching turn to treat them as data), through the same `prefer_channel_for` routing, availability windows and outbound guard. Until open loops existed nothing in production set `awaiting_response_since`, so this source had nothing to chase. Each scan first closes loops older than `ATTUNEMENT_LOOP_TTL_DAYS` (21) as `expired`, then marks proactive outreach nobody answered within `ATTUNEMENT_IGNORE_AFTER_HOURS` as `ignored` in the outcome ledger. Ranking uses that ledger: a candidate whose person left their last five resolved nudges of that kind unanswered ranks after all others and waits three times its cooldown; a single answer lifts it. Approving a stalled run (however it's approved) and updating an initiative count as acting on the nudges that chased them. The generic dispatch path tags each send with its source (`_outreach_source`) so the ledger can attribute it.\n\n### Alert lifecycle: expiry sweep and the review heartbeat\n\nTwo alert-maintenance jobs live here. The **expiry sweep** is loop-level, not a heartbeat row: `_maybe_sweep_alerts` runs `alerts.lifecycle.expire_stale_alerts` (and, on the same 15-minute throttle, `monitoring.research.watch_policy.sweep` — expiring unreviewed research watch suggestions, auto-disabling research-added watches that proved noisy or dead, and filing one `watchlist_suggestions` nudge when ≥3 suggestions have waited ≥7 days; see External monitoring) once at boot and every 15 minutes at the top of the tick — before the company-profile and rotation gates, so an old backlog expires even before onboarding completes, flipping `unread` alerts past their category TTL to `expired` and auditing `alert_sweep`. Pure DB hygiene, no model call, reversible via `POST /alerts/{id}/reopen`.\n\nThe **Executive alert review** is a real heartbeat — kind `alert_review_scan`, `__internal__` channel, bootstrapped idempotently at startup when `ALERT_REVIEW_ENABLED` and chained every `ALERT_REVIEW_INTERVAL_HOURS` (6) with the same crash-resilient run → mark-done → chain shape as `nudge_scan`. `_run_principal_brief` also runs a `pre_brief` pass right before the morning brief (a review failure never blocks the brief). Each pass re-examines open alerts with evidence and, within department authority and the privacy rule, routes, nudges, escalates, drafts, merges or resolves them — see the Today section for the policy. The moves go through the real handlers (`message_person`, `draft_artifact`), so the outbound anti-spam guard applies, and `ALERT_REVIEW_MAX_MOVES_PER_SCAN` bounds side effects per pass.\n\n## Client rotation claim pause\n\nThe `client_rotation` kind (multi-client practice mode, opt-in via `CLIENT_ROTATION_ENABLED`) adds one loop-level behavior: while a rotation's `.rotation_in_progress` marker exists, the scheduler **skips claiming entirely** for that tick. Rotation switches the live company context between parked clients; claiming during the window would fire the just-activated client's overdue outbound follow-ups from a context nobody is watching. Everything due fires on the first tick after the original client is restored. Stale markers (crash mid-rotation) are reconciled at scheduler startup, and the rotation row is idempotently re-seeded both at boot and after every slot activation (scheduled rows swap with the client). See the Client Companies section for the rotation's full design.\n\nAn optional `notion_sync_scan` heartbeat (`NOTION_SYNC_ENABLED`, off by default) incrementally re-indexes Notion pages the workspace integration can see into the isolated `notion_wiki` collection (not COMPANY), reconciles un-shared pages, then chains the next tick.",
+ "markdown": "The scheduler is an asyncio task started in the FastAPI lifespan (`openexecutive.scheduler.runner.run_scheduler`). It polls every 30s and reads due rows from `scheduled_actions` (in `episodic_memory.db`). The due query uses `claim_due_actions`, an UPDATE…RETURNING claim, so each row fires at most once per process — this assumes a single scheduler instance per database. Polls are gated on an active company profile via `_company_profile_active()`; before onboarding, due rows stay `pending`.\n\n### Cadence DSL\n\n`openexecutive.departments.cadence` supports, all in UTC:\n\n- `daily@HH:MM`\n- `weekly@DOW@HH:MM` or `weekly@DOW-HH:MM` (DOW is a 3-letter day, e.g. `weekly@thu@09:00`)\n- `quarterly@DD-HH:MM`\n\n`PATCH /departments/{slug}` rejects a spec that does not parse (bad format, unknown DOW, out-of-range time) with a 422 naming the valid formats, so a typo is caught at save time instead of silently never firing. An empty spec means no cadence.\n\nWhen a department cadence is due, the runner invokes the `department_check_in` workflow and chains the following occurrence via `cadence.enqueue_next()`. Deleting a department cancels its pending `dept_cadence` rows, and `cancel_orphaned_cadences()` sweeps orphans on boot.\n\nUser-created (dynamic) workflows can carry the same cadence DSL. A cadence-enabled definition enqueues a `dynamic_workflow` action (`workflows.dynamic_cadence`); when due, the runner runs the stored `DynamicWorkflow`, DMs the artifact to the definition's `cadence_person_id`, and re-chains the next occurrence. Saving/updating/deleting the definition reconciles its pending `dynamic_workflow` rows. A cadence definition may not contain an approval gate — a cron fire has no human to ask — with one exception, the **held-writes** pause: when an action step holds a write to a new target, the runner checkpoints the run (`checkpoint_gate`, the owner is DMed), still marks the row done and re-chains the cadence, and stamps `deliver_to_person_id` on the resume payload so the resumer DMs the artifact to the cadence recipient once the owner answers (or the 48 h timeout skips the held writes). Any other gate is still refused at execution: it calls `workflows.gate.ensure_workflow_event`, which raises on a gate so the run is recorded as failed. It previously ignored the gate and stored a completed run with `\"(no artifact)\"` as its body, which looked like a success every period.\n\n### Channel routing & nudges\n\nThe delivery channel lives on the `scheduled_actions` row (`channel` / `channel_ref`); the runner dispatches through whichever was set at enqueue time — `telegram`, `slack_dm`, `discord_dm`, `email`, or `__internal__` (workflow steps and heartbeats bypass outbound dispatch). Rows left pending by the removed staff-onboarding kinds drain through that same `__internal__` short-circuit (marked done, no dispatch); the removed talent workflows' *ad-hoc* reminders sat on the principal's real DM channel instead, so a one-shot startup sweep (`memory.episodic.cancel_orphaned_talent_reminders`) cancels them — `ad_hoc`, no department, `pending` or `running`, matching the five generated reminder shapes (outreach, interview coordination, reference checks, onboarding check-in, offer expiry) — and clears the awaiting-reply flag on delivered ones so the nudge engine stops chasing them. The marker row in `app_migrations` is claimed first with `INSERT OR IGNORE` in the same transaction, so concurrent boots cannot double-run or crash. The nudge engine (`scheduler.nudge_engine`, default 15 min) scans stalled `awaiting_human` runs, stale commitments, and idle initiatives, then emits `proactive_nudge` rows routed via `people.channel.prefer_channel_for` — honouring each Person's preferred (last-used) channel and availability windows, deferring those outside their window and skipping those with no reachable channel. Emission is capped per `scope_key` (`NUDGE_MAX_PER_SCOPE`, default 3 delivered nudges) so a parked item is not chased forever.\n\nThe stale-commitment source also chases **open loops** (see Attunement): `scheduled_actions` rows with `kind='open_loop'`, recorded `done` on the `__internal__` channel so the runner never dispatches them, whose `awaiting_response_since` is the loop's *due time*. They are chased as soon as they are overdue — not after `NUDGE_COMMITMENT_STALE_DAYS` — with a check-in intent addressed to the loop's owner (which quotes only the owner's own verbatim words and tells the dispatching turn to treat them as data), through the same `prefer_channel_for` routing, availability windows and outbound guard. Until open loops existed nothing in production set `awaiting_response_since`, so this source had nothing to chase. Each scan first closes loops older than `ATTUNEMENT_LOOP_TTL_DAYS` (21) as `expired`, then marks proactive outreach nobody answered within `ATTUNEMENT_IGNORE_AFTER_HOURS` as `ignored` in the outcome ledger. Ranking uses that ledger: a candidate whose person left their last five resolved nudges of that kind unanswered ranks after all others and waits three times its cooldown; a single answer lifts it. Approving a stalled run (however it's approved) and updating an initiative count as acting on the nudges that chased them. The generic dispatch path tags each send with its source (`_outreach_source`) so the ledger can attribute it.\n\n### Alert lifecycle: expiry sweep and the review heartbeat\n\nTwo alert-maintenance jobs live here. The **expiry sweep** is loop-level, not a heartbeat row: `_maybe_sweep_alerts` runs `alerts.lifecycle.expire_stale_alerts` (and, on the same 15-minute throttle, `monitoring.research.watch_policy.sweep` — expiring unreviewed research watch suggestions, auto-disabling research-added watches that proved noisy or dead, and filing one `watchlist_suggestions` nudge when ≥3 suggestions have waited ≥7 days; see External monitoring) once at boot and every 15 minutes at the top of the tick — before the company-profile and rotation gates, so an old backlog expires even before onboarding completes, flipping `unread` alerts past their category TTL to `expired` and auditing `alert_sweep`. Pure DB hygiene, no model call, reversible via `POST /alerts/{id}/reopen`.\n\nThe **Executive alert review** is a real heartbeat — kind `alert_review_scan`, `__internal__` channel, bootstrapped idempotently at startup when `ALERT_REVIEW_ENABLED` and chained every `ALERT_REVIEW_INTERVAL_HOURS` (6) with the same crash-resilient run → mark-done → chain shape as `nudge_scan`. `_run_principal_brief` also runs a `pre_brief` pass right before the morning brief (a review failure never blocks the brief). Each pass re-examines open alerts with evidence and, within department authority and the privacy rule, routes, nudges, escalates, drafts, merges or resolves them — see the Today section for the policy. The moves go through the real handlers (`message_person`, `draft_artifact`), so the outbound anti-spam guard applies, and `ALERT_REVIEW_MAX_MOVES_PER_SCAN` bounds side effects per pass.\n\n## Client rotation claim pause\n\nThe `client_rotation` kind (multi-client practice mode, opt-in via `CLIENT_ROTATION_ENABLED`) adds one loop-level behavior: while a rotation's `.rotation_in_progress` marker exists, the scheduler **skips claiming entirely** for that tick. Rotation switches the live company context between parked clients; claiming during the window would fire the just-activated client's overdue outbound follow-ups from a context nobody is watching. Everything due fires on the first tick after the original client is restored. Stale markers (crash mid-rotation) are reconciled at scheduler startup, and the rotation row is idempotently re-seeded both at boot and after every slot activation (scheduled rows swap with the client). See the Client Companies section for the rotation's full design.\n\nAn optional `notion_sync_scan` heartbeat (`NOTION_SYNC_ENABLED`, off by default) incrementally re-indexes Notion pages the workspace integration can see into the isolated `notion_wiki` collection (not COMPANY), reconciles un-shared pages, then chains the next tick.",
"mermaid": "flowchart TD\n Loop[\"run_scheduler<br/>poll every 30s\"]\n Claim[\"claim_due_actions<br/>(status=pending, by kind)\"]\n Table[(\"scheduled_actions\")]\n Dispatch[\"dispatch via row channel<br/>(ad_hoc / proactive_nudge)\"]\n Dept[\"dept_cadence →<br/>department_check_in\"]\n Nudge[\"nudge_scan →<br/>nudge_engine scan\"]\n Brief[\"principal_brief_morning / _eod →<br/>morning_brief / end_of_day_digest\"]\n Reflect[\"executive_reflection →<br/>reflection (artifact only)\"]\n ExtMon[\"external_monitor_scan →<br/>monitoring pipeline\"]\n Research[\"watchlist_research_scan →<br/>executive_research (skip-if-unchanged)\"]\n Notion[\"notion_sync_scan →<br/>isolated wiki ingest\"]\n Chain[\"enqueue_next<br/>(re-arm recurring tick)\"]\n Prefer[\"prefer_channel_for<br/>(availability + last-used)\"]\n Channels[\"Slack / Discord<br/>Telegram / Email\"]\n Principal[\"DM principal\"]\n Alerts[\"alerts pipeline → /today\"]\n Loop --> Claim\n Claim -- \"claim due rows\" --> Table\n Claim -- \"ad_hoc / proactive_nudge\" --> Dispatch\n Claim -- \"dept_cadence\" --> Dept\n Claim -- \"nudge_scan\" --> Nudge\n Claim -- \"principal_brief_*\" --> Brief\n Claim -- \"executive_reflection\" --> Reflect\n Claim -- \"external_monitor_scan\" --> ExtMon\n Claim -- \"watchlist_research_scan\" --> Research\n Claim -- \"notion_sync_scan\" --> Notion\n Nudge -- \"prefer_channel_for\" --> Prefer\n Prefer -- \"emits proactive_nudge\" --> Table\n Dispatch --> Channels\n Brief --> Principal\n ExtMon --> Alerts\n Dept --> Chain\n Nudge --> Chain\n Brief --> Chain\n Reflect --> Chain\n ExtMon --> Chain\n Research --> Chain\n Notion --> Chain\n Chain --> Table\n class Loop entry\n class Claim compute\n class Table storage\n class Dispatch compute\n class Dept compute\n class Nudge compute\n class Brief compute\n class Reflect compute\n class ExtMon compute\n class Research compute\n class Notion compute\n class Chain compute\n class Prefer compute\n class Channels external\n class Principal external\n class Alerts hot",
- "generated_at": "2026-09-23T22:46:10.736155+00:00"
+ "generated_at": "2026-09-24T00:00:00Z"
}
diff --git a/packages/core/openexecutive/architecture/prebuilt/schemas.json b/packages/core/openexecutive/architecture/prebuilt/schemas.json
index c42ee052..01ef6a88 100644
--- a/packages/core/openexecutive/architecture/prebuilt/schemas.json
+++ b/packages/core/openexecutive/architecture/prebuilt/schemas.json
@@ -1,7 +1,7 @@
{
"section_id": "schemas",
"title": "Data Schemas",
- "markdown": "The shapes below are the load-bearing data structures: episodic SQLite tables (in `episodic_memory.db`) and the Pydantic models for departments and people.\n\n### Episodic tables\n\n| Table | Key columns |\n|---|---|\n| `decisions` | `id`, `timestamp`, `domain`, `summary`, `rationale`, `outcome`, `tags`, `department`, `session_id` |\n| `initiatives` | `id`, `title`, `status`, `created_at`, `updated_at`, `summary`, `department` |\n| `advice_given` | `id`, `timestamp`, `domain`, `query_summary`, `advice_summary`, `department`, `session_id` |\n| `scheduled_actions` | `id`, `created_at`, `run_at`, `channel`, `channel_ref`, `intent_text`, `status`, `attempts`, `kind`, `department`, `assigned_to_person_id`, `awaiting_response_since`, `scope_key`, `required_scope` |\n| `outbound_context` | `id`, `created_at`, `channel`, `channel_ref`, `recipient_person_id`, `outbound_text`, `originating_session_id`, `outbound_message_id`, `consumed_at`, `status` |\n| `chat_messages` | `id`, `session_id`, `role`, `content`, `created_at`, `action_chips`, `stopped`, `sender_person_id`, `feedback`, `feedback_note`, `feedback_by_person_id` |\n| `attunement_usage` | `day` (PK, UTC date), `calls` — the per-day ceiling on open-loop extraction model calls |\n| `attunement_profiles` | `person_id` (PK), `rules` (JSON: up to 4 `{text, basis, evidence}`), `locked`, `updated_at`, `updated_by`, `last_pass_at`, `pass_day`, `passes_today`, `last_message_id` — per-person working style plus pass pacing |\n| `attunement_profile_history` | `id`, `person_id`, `created_at`, `rules`, `locked`, `updated_by` — every change to a working style |\n| `proactive_outcomes` | `id`, `created_at`, `person_id`, `source`, `ref`, `channel`, `channel_ref`, `outbound_context_id`, `outcome` (`replied` / `acted` / `ignored` / `void`, NULL while open), `resolved_at` — one row per proactive DM (Attunement outcome ledger) |\n\n| `dynamic_workflows` | `name` (PK), `definition` (JSON of `DynamicWorkflowDef`), `is_active`, `created_at`, `updated_at` |\n| `app_migrations` | `name` (PK), `applied_at` — one-shot data migrations (sweeps that must run exactly once per DB); schema DDL stays idempotent and is not recorded here |\n\n`department` and `session_id` are additive columns (default `''`); `session_id` scopes per-thread recall. `scheduled_actions.status` ∈ pending / running / done / failed / cancelled, and `scheduled_actions.kind` includes `dynamic_workflow` (a cadence-fired user-created workflow run) and `open_loop` (an Attunement open loop: `assigned_to_person_id` is the owner, `awaiting_response_since` the due time — cleared when the loop closes — and `scope_key` `loop:{owner}:{hash}`, unique among open loops via the partial index `idx_scheduled_open_loop_scope`). `chat_messages.sender_person_id` is the resolved rostered sender of a user message (never the session owner's principal fallback; NULL on legacy rows and for unrostered senders); `feedback` is `up` / `down` on an assistant reply. `dynamic_workflows` stores user-created (dynamic) workflow definitions interpreted by the generic `DynamicWorkflow` engine; the JSON `definition` holds free-text input fields and an ordered step list (specialist / approval_gate / synthesis) plus an optional cadence.\n\n### Legacy tables (talent / staff onboarding)\n\nThe talent (executive-search) and staff-onboarding features were removed. Their tables —\n`engagements`, `candidates`, `offers`, `onboarding_templates`, `onboarding_plans`,\n`onboarding_tasks` — are **not dropped**: no code creates, reads or writes them any more,\nbut rows survive on upgraded installs. `clients.slots` still wipes them when a blank client\nslot is activated (existence-guarded, a no-op on fresh installs) so a slot can never inherit\na previous client's candidate data.\n\n### Department / Goal / ChecklistItem\n\n| Model | Fields |\n|---|---|\n| `DepartmentConfig` | `slug`, `title`, `specialist_key`, `charter`, `authority_level`, `head_person_id`, `head_persona_slug`, `cadences`, `slack_channel_id`, `discord_channel_id`, `telegram_chat_id` |\n| `Goal` | `id`, `department_slug`, `period_type`, `period_value`, `key_result`, `target`, `current`, `status`, `created_at`, `updated_at`, `last_reviewed_at` |\n| `DepartmentState` | `config`, `goals`, `headcount`, `budget_usd`, `member_person_ids`, `updated_at` |\n\n`authority_level` ∈ `auto_execute` / `propose_only` / `escalate`; `Goal.status` ∈ `on_track` / `at_risk` / `off_track`.\n\n### Person\n\n| Field group | Fields |\n|---|---|\n| Identity | `id`, `full_name`, `role`, `is_principal`, `department_slugs` |\n| Contact | `email`, `slack_user_id`, `telegram_chat_id`, `discord_user_id`, `preferred_channel` |\n| Routing | `availability`, `authority_scope`, `response_sla_hours`, `on_leave_until`, `reports_to_person_id` |\n| Lifecycle | `archived`, `created_at`, `updated_at` |\n\nExactly one `Person` should have `is_principal=True` — the fallback approver when no delegated person matches.",
+ "markdown": "The shapes below are the load-bearing data structures: episodic SQLite tables (in `episodic_memory.db`) and the Pydantic models for departments and people.\n\n### Episodic tables\n\n| Table | Key columns |\n|---|---|\n| `decisions` | `id`, `timestamp`, `domain`, `summary`, `rationale`, `outcome`, `tags`, `department`, `session_id` |\n| `initiatives` | `id`, `title`, `status`, `created_at`, `updated_at`, `summary`, `department` |\n| `advice_given` | `id`, `timestamp`, `domain`, `query_summary`, `advice_summary`, `department`, `session_id` |\n| `scheduled_actions` | `id`, `created_at`, `run_at`, `channel`, `channel_ref`, `intent_text`, `status`, `attempts`, `kind`, `department`, `assigned_to_person_id`, `awaiting_response_since`, `scope_key`, `required_scope` |\n| `outbound_context` | `id`, `created_at`, `channel`, `channel_ref`, `recipient_person_id`, `outbound_text`, `originating_session_id`, `outbound_message_id`, `consumed_at`, `status` |\n| `chat_messages` | `id`, `session_id`, `role`, `content`, `created_at`, `action_chips`, `stopped`, `sender_person_id`, `feedback`, `feedback_note`, `feedback_by_person_id` |\n| `attunement_usage` | `day` (PK, UTC date), `calls` — the per-day ceiling on open-loop extraction model calls |\n| `attunement_profiles` | `person_id` (PK), `rules` (JSON: up to 4 `{text, basis, evidence}`), `locked`, `updated_at`, `updated_by`, `last_pass_at`, `pass_day`, `passes_today`, `last_message_id` — per-person working style plus pass pacing |\n| `attunement_profile_history` | `id`, `person_id`, `created_at`, `rules`, `locked`, `updated_by` — every change to a working style |\n| `proactive_outcomes` | `id`, `created_at`, `person_id`, `source`, `ref`, `channel`, `channel_ref`, `outbound_context_id`, `outcome` (`replied` / `acted` / `ignored` / `void`, NULL while open), `resolved_at` — one row per proactive DM (Attunement outcome ledger) |\n\n| `dynamic_workflows` | `name` (PK), `definition` (JSON of `DynamicWorkflowDef`), `is_active`, `created_at`, `updated_at`, `owner_person_id` (creator; set on insert only, kept out of the definition JSON) |\n| `workflow_approved_targets` | (`workflow_name`, `value`) PK, `key`, `approved_at`, `run_id` — targets a workflow's tool steps may write to without asking again; cleared when the workflow is deleted |\n| `app_migrations` | `name` (PK), `applied_at` — one-shot data migrations (sweeps that must run exactly once per DB); schema DDL stays idempotent and is not recorded here |\n\n`department` and `session_id` are additive columns (default `''`); `session_id` scopes per-thread recall. `scheduled_actions.status` ∈ pending / running / done / failed / cancelled, and `scheduled_actions.kind` includes `dynamic_workflow` (a cadence-fired user-created workflow run) and `open_loop` (an Attunement open loop: `assigned_to_person_id` is the owner, `awaiting_response_since` the due time — cleared when the loop closes — and `scope_key` `loop:{owner}:{hash}`, unique among open loops via the partial index `idx_scheduled_open_loop_scope`). `chat_messages.sender_person_id` is the resolved rostered sender of a user message (never the session owner's principal fallback; NULL on legacy rows and for unrostered senders); `feedback` is `up` / `down` on an assistant reply. `dynamic_workflows` stores user-created (dynamic) workflow definitions interpreted by the generic `DynamicWorkflow` engine; the JSON `definition` holds free-text input fields and an ordered step list (specialist / approval_gate / synthesis) plus an optional cadence.\n\n### Legacy tables (talent / staff onboarding)\n\nThe talent (executive-search) and staff-onboarding features were removed. Their tables —\n`engagements`, `candidates`, `offers`, `onboarding_templates`, `onboarding_plans`,\n`onboarding_tasks` — are **not dropped**: no code creates, reads or writes them any more,\nbut rows survive on upgraded installs. `clients.slots` still wipes them when a blank client\nslot is activated (existence-guarded, a no-op on fresh installs) so a slot can never inherit\na previous client's candidate data.\n\n### Department / Goal / ChecklistItem\n\n| Model | Fields |\n|---|---|\n| `DepartmentConfig` | `slug`, `title`, `specialist_key`, `charter`, `authority_level`, `head_person_id`, `head_persona_slug`, `cadences`, `slack_channel_id`, `discord_channel_id`, `telegram_chat_id` |\n| `Goal` | `id`, `department_slug`, `period_type`, `period_value`, `key_result`, `target`, `current`, `status`, `created_at`, `updated_at`, `last_reviewed_at` |\n| `DepartmentState` | `config`, `goals`, `headcount`, `budget_usd`, `member_person_ids`, `updated_at` |\n\n`authority_level` ∈ `auto_execute` / `propose_only` / `escalate`; `Goal.status` ∈ `on_track` / `at_risk` / `off_track`.\n\n### Person\n\n| Field group | Fields |\n|---|---|\n| Identity | `id`, `full_name`, `role`, `is_principal`, `department_slugs` |\n| Contact | `email`, `slack_user_id`, `telegram_chat_id`, `discord_user_id`, `preferred_channel` |\n| Routing | `availability`, `authority_scope`, `response_sla_hours`, `on_leave_until`, `reports_to_person_id` |\n| Lifecycle | `archived`, `created_at`, `updated_at` |\n\nExactly one `Person` should have `is_principal=True` — the fallback approver when no delegated person matches.",
"mermaid": null,
- "generated_at": "2026-09-22T23:17:20.508677+00:00"
+ "generated_at": "2026-09-24T00:00:00Z"
}
diff --git a/packages/core/openexecutive/architecture/prebuilt/workflows.json b/packages/core/openexecutive/architecture/prebuilt/workflows.json
index f4a5a97e..b52a5d06 100644
--- a/packages/core/openexecutive/architecture/prebuilt/workflows.json
+++ b/packages/core/openexecutive/architecture/prebuilt/workflows.json
@@ -1,7 +1,7 @@
{
"section_id": "workflows",
"title": "Workflows",
- "markdown": "Workflows are deterministic, multi-step orchestrations. The built-ins are registered in `openexecutive.workflows.WORKFLOW_REGISTRY`; user-created (dynamic) workflows are stored as data (see below). Each follows the same contract: structured input feeds an ordered list of named steps that render a Markdown artifact, persisted via `complete_run` into `workflow_runs.artifact`. Every step emits a `WorkflowEvent` (start/progress/complete) streamed over SSE at `/workflows/{name}/runs`.\n\nThe registry holds 24 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, 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`.\n\n### Change-aware principal briefs\n\n`morning_brief` and `end_of_day_digest` are the two recurring briefs the scheduler DMs to the principal. Both are now a *delta*, not a re-list: the window is \"since the last **delivered** brief\" (`briefing.brief_state.since_for`; 24 h on a cold store, clamped to 7 days), activity comes from `_build_activity(limit, since=…)`, proposals (action category only) split into *new since last brief* — enumerated, with each item's why-now and next move — versus a one-line carried-over count, a *rewritten* block lists carried items the review rewrote inside the window (`brief_state.rewritten_since`: verdict `changed`, still open — the brief reports them under \"what changed\", never as done), and a *handled overnight* block lists what the Executive's alert review **completed** on its own (`brief_state.handled_since`; the `changed` verdict is excluded because the alert is still open). Section order: top call → what changed → handled overnight → needs you (new only) → waiting on → at risk. A date-free fingerprint of the inputs is compared to the last delivered one; if unchanged the artifact is the one-liner \"Nothing new since yesterday's brief — N items still waiting on you.\" and no model call is made (`PRINCIPAL_BRIEF_SUPPRESS_UNCHANGED`; `force_full=true` on a manual run bypasses it). The workflow yields a `result` event with the fingerprint; only the scheduler records it, after a successful delivery, in `briefing_narrative` under scope `brief:<kind>` — so manual runs never advance the window.\n\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.\n\n### Wait-for-human pause\n\n`wait_for_human` (`openexecutive/workflows/wait_for_human.py`) is a first-class step primitive that pauses a run: the runner calls `save_checkpoint`, the `workflow_runs` row moves to `status='awaiting_human'`, and the serialized `WaitForHumanEvent` is stored in `state_json`. (Department authority is a *separate* mechanism — `propose_only` departments file a briefing alert via `departments.authority.propose_via_alert` and mark the scheduled action done; they do not route through this gate.)\n\n**Delivery.** Both checkpoint sites — the SSE route and the `run_workflow` chat tool — call `workflows.gate_delivery.deliver_gate_question` immediately *before* checkpointing, so `state_json` carries the routing fields a reply is matched against. Two modes. When the approver is the person already in the conversation (the chat session's `origin_channel` is set and its `caller_person_id` is the gate's `person_id`), nothing is sent — the question rides in the Executive's own reply — and the gate records `origin_session_id` plus the session's channel. Otherwise the question is delivered through `schedule_tools.handle_message_person`, which picks the person's preferred channel, falls through on a failed send, and falls back to a briefing alert; the gate then records the channel, address and provider message id that send returned, plus the id of the DM session it landed in — that send is always 1:1, so the answer belongs in that conversation and nowhere else. Without it the gate matched on person and channel alone, so an unrelated @mention in a public channel resolved it and had the acknowledgement, run title included, posted where everyone could read it. Delivery is not guaranteed: the outbound guard can suppress it (duplicate, rate cap, quiet hours) and an unreachable person gets the alert fallback. Both cases leave the routing fields empty and report `delivery` as `suppressed` / `alerted` rather than claiming someone was asked, and the chat tool's presentation hint changes accordingly.\n\n**Matching a reply.** Each inbound adapter passes the message to `inbound_resolver.resolve_inbound_message` with its `session_id`. Matching is three-tier: an explicit `in_reply_to` against a stored `outbound_message_id`; otherwise a single open run on that channel; otherwise one utility-fast disambiguation call gated at 0.85 confidence. An unmatched explicit reference rules out only the candidates that carry a stored outbound id — the ones it could have matched — and the rest continue; rejecting outright meant an adapter that passes a thread id on every message (Slack's `thread_ts`) short-circuited the later tiers forever, and a global test let one delivered gate's id block an unrelated self-approval gate. Channel names are normalized (`slack_dm` ≡ `slack`), the delivered address is compared when both sides know it, a row whose `state_json` will not parse is refused (a corrupt row otherwise presents as a legacy one), and an empty stored channel is treated as a wildcard only for rows checkpointed before gate delivery existed. Two guards keep an open gate from swallowing unrelated traffic: a gate carrying an `origin_session_id` matches replies only from the conversations the adapter names (a Slack or Discord thread offers its parent channel session too, mirroring the history double-write, since a gate raised on a mention recorded that session while the answer arrives under the thread's — on Slack only when that person rooted the thread, or the alias would reach into a colleague's), and the parser can return `unrelated`, which declines to resolve and lets the message reach the normal chat path. The parser is handed the gate's own question, so a bare \"yes\" is judged against something. Its fallback is flagged by a key the model cannot emit rather than by a magic note string it could, and a fallback declines to resolve on *every* reply shape — recording the empty string a `free_text` fallback fabricates would close a sign-off on a parser outage. Every shape can answer `unrelated`, not just `approve_reject`: without it an open `free_text` gate turned the person's next message into its answer verbatim, and a `numeric` one swallowed any message containing a number. `resumer.apply_resolution` then records the decision, marks the run `resolved`, and writes an audit row. A timeout applies the step's `on_timeout` policy (escalate / auto_proceed / fail). The outcome surfaces on the Today dashboard.\n\n**Resuming past the gate.** A paused run continues on its own. Re-entering it was long assumed to mean serializing a Python generator frame; it does not. The only state alive across a dynamic workflow's steps is its inputs (already persisted), a company-profile block that is recomputed, the completed steps' output strings, and the loop cursor — so the engine hands the checkpoint a small JSON `WorkflowResumeState` (workflow name, the gate's id and index, the next index, the outputs so far), stored in `workflow_runs.resume_state_json`, and `DynamicWorkflow.resume` replays its step loop from the recorded index. `run()` and `resume()` share that one loop, which is why a second gate needs no special handling — it is simply another pause raised from the same place. The payload rides on a `WaitForHumanEvent` field declared `exclude=True`, so it can never leak into `state_json`, whose exact key set the resolver branches on. A gate with no payload is *pause-only*: the decision is recorded and the run stops, which is what every caller got before resume existed.\n\n`resumer._process_resumable` claims a resolved run with one guarded UPDATE — `resolved` → `running`, stamping `resumed_at` and minting a claim token — and drives it to a terminal row. It runs two ways: immediately, via a task `apply_resolution` kicks off so a Slack approval starts moving in seconds, and every 60s from the poll loop as the durable backstop. Both share the claim, so a run executes exactly once even with two resumers against one database. The 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.\n\n**The claim is fenced, because it is not a lease.** The stale sweep decides a worker is dead from a wall-clock guess, so a slow but *alive* worker will eventually be declared dead and replaced. Every write the executor makes carries its claim token and is refused once superseded — otherwise the replaced worker's late completion lands on top of its replacement's result, or its checkpoint at a later gate resurrects an already-finished run and asks the approver a second time. The retry budget resets at each new gate (a gate is new work, not a retry), and a run that exhausts it is *ended* rather than dropped: an exhausted run sits in `running` with a payload, in neither queue, and would otherwise show as in-progress forever.\n\n**The gate fails closed.** Continuing is an allowlist — `approve` and the synthetic `auto_proceed` — not \"anything that is not a stop word\". `decision` is whatever a fast model extracted from free-form chat and it drifts; under a denylist, \"rejected\", \"Reject\", \"decline\" and \"no\" would all continue, so the approver declines and the deliverable is produced anyway. Reply shapes that ask a question rather than seek permission always continue, since the answer *is* the value. A stop ends the run at `error` with the human's note. Either way the decision becomes the gate step's own output, so it reads as a section *in* the artifact — capped and blockquoted, because that text reaches the synthesis specialist as prompt context.\n\n**A definition edited during the pause is refused.** Resume re-validates the payload's version, the recorded gate, *and* a fingerprint of the whole step list, and derives the index to continue at rather than reading it from the payload. Pinning only the gate would not be enough: definitions are overwritten by name and any rostered user can save one, so someone could keep the gate identical and replace every step after it — and the approver's sign-off would be recorded against work they never saw, which defeats the one thing an approval gate is for. No built-in workflow yields the gate; only user-created dynamic workflows do.\n\n### Launching from chat\n\nWorkflows are not only reachable from the `/jobs` UI — the Executive can list and run any of them mid-conversation. `openexecutive.orchestrator.workflow_run_tools` wires two tools into the main chat loop: `list_workflows` (the launchable catalog, with each workflow's input fields) and `run_workflow` (runs one to completion and returns its Markdown artifact, using the same engine as `POST /workflows/{name}/runs`). `run_workflow` resolves both built-ins and custom workflows via `get_workflow`, validates `inputs` against the workflow's input model, persists the run (`create_run` → `complete_run` / `fail_run`), and on an approval-gate step checkpoints the run as `awaiting_human` exactly as the HTTP route does — literally the same code, since both call `workflows.gate.checkpoint_gate`, which delivers the question and writes the checkpoint in one place. It never hangs waiting on a human, and it reports both whether the question reached them and whether the run will continue by itself once answered. The runners that *cannot* pause — the schedulers, evals, client rotation, onboarding, the research tools — call `gate.ensure_workflow_event`, which raises on a gate rather than letting one be swallowed; the scheduler's dynamic-workflow branch used to ignore it and record a successful run containing nothing. `executive_research` is excluded (it has the dedicated `run_executive_research` tool). Running a workflow from chat delivers nothing on its own — it renders the artifact into the conversation, and the recurring principal briefs (`morning_brief`, `end_of_day_digest`) reach anyone only via the scheduler's own `_deliver_to_principal`. The tool description used to claim those two DM the principal when run and to confirm before firing them, which had the model soliciting a confirmation on a false premise; it now names `executive_reflection` as the one workflow that really does execute tool calls of its own (DMs to heads, broadcasts, alerts). A successful run surfaces an `action_taken` chip linking to `/jobs/runs/{run_id}`.\n\n### Dynamic (user-created) workflows\n\nUsers create reusable workflows on the fly — from the executive chat, the conversational wizard at `/jobs/new`, or the step-by-step advanced editor — without shipping code. A dynamic workflow is a stored JSON definition (the `dynamic_workflows` table) interpreted at runtime by one generic `DynamicWorkflow` engine (`openexecutive/workflows/dynamic.py`) that implements the same `Workflow` ABC as the built-ins, so the run path, SSE streaming, run persistence, and `/jobs/[name]` form rendering are unchanged. `get_workflow` / `list_workflows` fall through to the dynamic store after the static registry (built-ins win on a name collision).\n\nA definition declares free-text input fields and an ordered step list of four kinds: **specialist** (consult a specialist with a goal prompt, optionally grounded by RAG), **action** (get something done with tools — see below), **approval_gate** (a `wait_for_human` pause), and a terminal **synthesis** step that assembles the artifact. At least one specialist or action step is required. `validate_definition` enforces the structural rules: exactly one terminal synthesis step, valid specialists, `{placeholder}` tokens that reference declared input fields, rostered approval/cadence people, 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 (cadences are UTC), and taken names — is rendered once per session into the first user turn, and while refining, the exact current draft is prepended to the latest user turn so the model edits it rather than re-deriving it. Roster names and roles are flattened to one line and capped at 80 characters before they enter that context, and the system prompt tells the model to treat the whole block as data, never instructions. Sessions live in memory (`/workflows/designer/*`, 2 h TTL, 50-session cap), run one model turn at a time (a second concurrent `/message` or `/draft` gets 409, and a failed turn is rolled back by identity), and never write: the review card saves through the same `POST /workflows/custom`, which re-validates, and *Edit details* opens the draft in the advanced editor (`/jobs/new?designer=<id>`) before saving.\n\n**Action steps (workflows that act).** An `action` step (`ActionStepSpec`: `goal`, `tools`, `max_tool_calls` 1–50, default 20) is run by the `workflow_actor` Council agent (`openexecutive/workflows/action_step.py`) as a bounded tool-use loop. Its `tools` list is an allowlist of exact tool names — MCP gateway tools (`server__tool`, e.g. `google_workspace__append_table_rows`) and a small set of built-ins (`oe__read_file`, `oe__message_person`, `oe__create_alert`) — and **clicking Create is the user's approval** of that list: the review card shows every tool, flags the ones that may change things (anything whose name doesn't say it reads, and any tool with a URL/URI/endpoint/webhook parameter anywhere in its schema, or whose schema couldn't be read, since a URL can carry data out), and names them in a \"this workflow can use these without asking again\" notice. Because that card is the approval, a workflow with action steps saved from chat (`draft_workflow`/`save_workflow`, whose confirmation is a token the model holds itself) is stored **switched off** (`is_active=false`) and `save_workflow` returns `status: saved_pending_review` with a `/jobs/{name}` link. An inactive workflow can't run or schedule (`get_workflow` and the scheduler skip it); `/jobs/{name}` shows it on the same review card, where **Turn on workflow** (`POST /workflows/custom/{name}/activate`, which re-validates the tools) is the approval — the click sends the definition the card showed, and the server refuses (409) if the stored one has changed since, so chat overwriting it while the card is open can't get new tools switched on. Chat may revise a switched-off workflow but refuses to replace a switched-on one that has action steps (an inbound email steering the Executive could otherwise switch off an approved job and stage new tools under its name); those edits happen in the advanced editor. The Workflows catalog (`/jobs`) lists switched-off workflows in a compact *Waiting for your approval* strip, and saving edits in the advanced editor keeps one off. `tool_catalog.py` resolves names to schemas through the gateway's `search_tools` (extensible-mcp's Markdown output is parsed; resolving is also the per-session discovery its `call_tool` requires) and validates availability at save time (`POST`/`PUT /workflows/custom`, chat `draft_workflow`/`save_workflow`, designer drafts) — an unknown, misspelled or deny-listed tool is a 422. The gateway meta-tools (`search_tools`, `call_tool`, `load_mcp_server`) can never be step tools. `run()` resolves every action step's tools before any step runs, so a vanished tool stops the run before an earlier step acts; `resume()` checks only the steps still to run, after the gate and decision are validated. The last turn of an action step always switches tools off so the agent can report. At run time only the allowlisted tools are offered (sorted; constant cached system block, per-run goal/inputs/earlier results in the user turn), every `tool_use` is re-checked against the allowlist, MCP calls go through `MCPGateway.call_tool` so the config deny-list and the Gmail/Calendar/Drive recipient gates still apply, the call budget is enforced (then a final tools-off turn asks for the report; running out of turns fails the step and lists what was already done), tool errors (the gateway's `Error:` / `Error calling tool` / `Tool error:` prefixes, or a truthy `error` field) return to the model as `is_error` results, each call emits a `progress` event and an audit row (`workflow_tool_call`: tool and outcome; for tools that may change things also a short digest of target arguments — ids, recipients, URLs, paths — so a redirected write is visible; content arguments are never logged), and the step's output is the agent's report plus an \"Actions taken\" list. Tool output is framed as data, never instructions. `oe__read_file` extracts text (PDF, Word, Excel, CSV, Markdown, text) only from files under `WORKFLOW_FILE_DIRS` (default: workspace-mcp's attachment folder), resolving symlinks and `..` before the check. Action steps are allowed in scheduled workflows. Because they have external side effects, a resumed run heartbeats its claim (`touch_resume_claim`, at most once a minute as events flow — each tool call emits one; a busy database is retried on the next heartbeat, never treated as a lost claim; the sweep's requeue re-checks the claim's age in the same UPDATE, so a heartbeat landing between the sweep's read and its write wins), so the stale-claim sweep never requeues and replays a slow but live run, and a worker that finds its claim superseded stops at its next event. A worker that actually crashes mid-resume is still requeued; its action steps then run again, so goals should say how to avoid duplicates (the actor reads current state before writing). `GET /workflows/tools/search?q=` and `GET /workflows/tools/describe?names=` back the advanced editor's tool picker and the review card's labels.\n\nAn optional cadence (`daily@` / `weekly@` / `quarterly@`) re-uses the scheduler via the `dynamic_workflow` action kind, which runs the workflow on schedule and DMs the artifact to a rostered recipient. A gate followed by further steps pauses at `awaiting_human` and then resumes once answered, so gates no longer have to sit immediately before synthesis. They remain forbidden in cadence-enabled definitions: a scheduled fire has no interactive human to ask.\n\nBuilt-ins the system runs on its own (`morning_brief`, `end_of_day_digest`, `executive_reflection`, `executive_research`) set `background = True`, surfaced as `WorkflowMeta.background`; the `/jobs` catalog files them under a **System** chip instead of the default view. They stay runnable by hand.\n\nCompleted artifacts are discoverable in the unified Artifacts section (`/artifacts`) alongside their run-detail page at `/jobs/runs/{run_id}`.\n\n## Data-driven retrospectives\n\n`engagement_value_report` introduces a new workflow pattern: instead of the user typing the substance into a form (the `investor_update` / `mbr` shape), the workflow **reads its substance from the database**. A deterministic gatherer (`clients/engagement_activity.py`) pulls the period's decisions, initiatives, advisory consultations, delivered workflow artifacts (excluding prior value reports), follow-through counts, and alerts handled — from the live DB for the active client, or a parked client slot's `state.db` opened read-only. A single board-comms call narrates those facts (the prompt forbids inventing anything not in them; an empty period skips the LLM entirely), and the artifact's lists are assembled deterministically. Built for renewal conversations — the engagement record is the evidence.",
+ "markdown": "Workflows are deterministic, multi-step orchestrations. The built-ins are registered in `openexecutive.workflows.WORKFLOW_REGISTRY`; user-created (dynamic) workflows are stored as data (see below). Each follows the same contract: structured input feeds an ordered list of named steps that render a Markdown artifact, persisted via `complete_run` into `workflow_runs.artifact`. Every step emits a `WorkflowEvent` (start/progress/complete) streamed over SSE at `/workflows/{name}/runs`.\n\nThe registry holds 24 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, 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`.\n\n### Change-aware principal briefs\n\n`morning_brief` and `end_of_day_digest` are the two recurring briefs the scheduler DMs to the principal. Both are now a *delta*, not a re-list: the window is \"since the last **delivered** brief\" (`briefing.brief_state.since_for`; 24 h on a cold store, clamped to 7 days), activity comes from `_build_activity(limit, since=…)`, proposals (action category only) split into *new since last brief* — enumerated, with each item's why-now and next move — versus a one-line carried-over count, a *rewritten* block lists carried items the review rewrote inside the window (`brief_state.rewritten_since`: verdict `changed`, still open — the brief reports them under \"what changed\", never as done), and a *handled overnight* block lists what the Executive's alert review **completed** on its own (`brief_state.handled_since`; the `changed` verdict is excluded because the alert is still open). Section order: top call → what changed → handled overnight → needs you (new only) → waiting on → at risk. A date-free fingerprint of the inputs is compared to the last delivered one; if unchanged the artifact is the one-liner \"Nothing new since yesterday's brief — N items still waiting on you.\" and no model call is made (`PRINCIPAL_BRIEF_SUPPRESS_UNCHANGED`; `force_full=true` on a manual run bypasses it). The workflow yields a `result` event with the fingerprint; only the scheduler records it, after a successful delivery, in `briefing_narrative` under scope `brief:<kind>` — so manual runs never advance the window.\n\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.\n\n### Wait-for-human pause\n\n`wait_for_human` (`openexecutive/workflows/wait_for_human.py`) is a first-class step primitive that pauses a run: the runner calls `save_checkpoint`, the `workflow_runs` row moves to `status='awaiting_human'`, and the serialized `WaitForHumanEvent` is stored in `state_json`. (Department authority is a *separate* mechanism — `propose_only` departments file a briefing alert via `departments.authority.propose_via_alert` and mark the scheduled action done; they do not route through this gate.)\n\n**Delivery.** Both checkpoint sites — the SSE route and the `run_workflow` chat tool — call `workflows.gate_delivery.deliver_gate_question` immediately *before* checkpointing, so `state_json` carries the routing fields a reply is matched against. Two modes. When the approver is the person already in the conversation (the chat session's `origin_channel` is set and its `caller_person_id` is the gate's `person_id`), nothing is sent — the question rides in the Executive's own reply — and the gate records `origin_session_id` plus the session's channel. Otherwise the question is delivered through `schedule_tools.handle_message_person`, which picks the person's preferred channel, falls through on a failed send, and falls back to a briefing alert; the gate then records the channel, address and provider message id that send returned, plus the id of the DM session it landed in — that send is always 1:1, so the answer belongs in that conversation and nowhere else. Without it the gate matched on person and channel alone, so an unrelated @mention in a public channel resolved it and had the acknowledgement, run title included, posted where everyone could read it. Delivery is not guaranteed: the outbound guard can suppress it (duplicate, rate cap, quiet hours) and an unreachable person gets the alert fallback. Both cases leave the routing fields empty and report `delivery` as `suppressed` / `alerted` rather than claiming someone was asked, and the chat tool's presentation hint changes accordingly.\n\n**Matching a reply.** Each inbound adapter passes the message to `inbound_resolver.resolve_inbound_message` with its `session_id`. Matching is three-tier: an explicit `in_reply_to` against a stored `outbound_message_id`; otherwise a single open run on that channel; otherwise one utility-fast disambiguation call gated at 0.85 confidence. An unmatched explicit reference rules out only the candidates that carry a stored outbound id — the ones it could have matched — and the rest continue; rejecting outright meant an adapter that passes a thread id on every message (Slack's `thread_ts`) short-circuited the later tiers forever, and a global test let one delivered gate's id block an unrelated self-approval gate. Channel names are normalized (`slack_dm` ≡ `slack`), the delivered address is compared when both sides know it, a row whose `state_json` will not parse is refused (a corrupt row otherwise presents as a legacy one), and an empty stored channel is treated as a wildcard only for rows checkpointed before gate delivery existed. Two guards keep an open gate from swallowing unrelated traffic: a gate carrying an `origin_session_id` matches replies only from the conversations the adapter names (a Slack or Discord thread offers its parent channel session too, mirroring the history double-write, since a gate raised on a mention recorded that session while the answer arrives under the thread's — on Slack only when that person rooted the thread, or the alias would reach into a colleague's), and the parser can return `unrelated`, which declines to resolve and lets the message reach the normal chat path. The parser is handed the gate's own question, so a bare \"yes\" is judged against something. Its fallback is flagged by a key the model cannot emit rather than by a magic note string it could, and a fallback declines to resolve on *every* reply shape — recording the empty string a `free_text` fallback fabricates would close a sign-off on a parser outage. Every shape can answer `unrelated`, not just `approve_reject`: without it an open `free_text` gate turned the person's next message into its answer verbatim, and a `numeric` one swallowed any message containing a number. `resumer.apply_resolution` then records the decision, marks the run `resolved`, and writes an audit row. A timeout applies the step's `on_timeout` policy (escalate / auto_proceed / fail). The outcome surfaces on the Today dashboard.\n\n**Resuming past the gate.** A paused run continues on its own. Re-entering it was long assumed to mean serializing a Python generator frame; it does not. The only state alive across a dynamic workflow's steps is its inputs (already persisted), a company-profile block that is recomputed, the completed steps' output strings, and the loop cursor — so the engine hands the checkpoint a small JSON `WorkflowResumeState` (workflow name, the gate's id and index, the next index, the outputs so far), stored in `workflow_runs.resume_state_json`, and `DynamicWorkflow.resume` replays its step loop from the recorded index. `run()` and `resume()` share that one loop, which is why a second gate needs no special handling — it is simply another pause raised from the same place. The payload rides on a `WaitForHumanEvent` field declared `exclude=True`, so it can never leak into `state_json`, whose exact key set the resolver branches on. A gate with no payload is *pause-only*: the decision is recorded and the run stops, which is what every caller got before resume existed.\n\n`resumer._process_resumable` claims a resolved run with one guarded UPDATE — `resolved` → `running`, stamping `resumed_at` and minting a claim token — and drives it to a terminal row. It runs two ways: immediately, via a task `apply_resolution` kicks off so a Slack approval starts moving in seconds, and every 60s from the poll loop as the durable backstop. Both share the claim, so a run executes exactly once even with two resumers against one database. The 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.\n\n**The claim is fenced, because it is not a lease.** The stale sweep decides a worker is dead from a wall-clock guess, so a slow but *alive* worker will eventually be declared dead and replaced. Every write the executor makes carries its claim token and is refused once superseded — otherwise the replaced worker's late completion lands on top of its replacement's result, or its checkpoint at a later gate resurrects an already-finished run and asks the approver a second time. The retry budget resets at each new gate (a gate is new work, not a retry), and a run that exhausts it is *ended* rather than dropped: an exhausted run sits in `running` with a payload, in neither queue, and would otherwise show as in-progress forever.\n\n**The gate fails closed.** Continuing is an allowlist — `approve` and the synthetic `auto_proceed` — not \"anything that is not a stop word\". `decision` is whatever a fast model extracted from free-form chat and it drifts; under a denylist, \"rejected\", \"Reject\", \"decline\" and \"no\" would all continue, so the approver declines and the deliverable is produced anyway. Reply shapes that ask a question rather than seek permission always continue, since the answer *is* the value. A stop ends the run at `error` with the human's note. Either way the decision becomes the gate step's own output, so it reads as a section *in* the artifact — capped and blockquoted, because that text reaches the synthesis specialist as prompt context.\n\n**A definition edited during the pause is refused.** Resume re-validates the payload's version, the recorded gate, *and* a fingerprint of the whole step list, and derives the index to continue at rather than reading it from the payload. Pinning only the gate would not be enough: definitions are overwritten by name and any rostered user can save one, so someone could keep the gate identical and replace every step after it — and the approver's sign-off would be recorded against work they never saw, which defeats the one thing an approval gate is for. No built-in workflow yields the gate; only user-created dynamic workflows do.\n\n### Launching from chat\n\nWorkflows are not only reachable from the `/jobs` UI — the Executive can list and run any of them mid-conversation. `openexecutive.orchestrator.workflow_run_tools` wires two tools into the main chat loop: `list_workflows` (the launchable catalog, with each workflow's input fields) and `run_workflow` (runs one to completion and returns its Markdown artifact, using the same engine as `POST /workflows/{name}/runs`). `run_workflow` resolves both built-ins and custom workflows via `get_workflow`, validates `inputs` against the workflow's input model, persists the run (`create_run` → `complete_run` / `fail_run`), and on an approval-gate step checkpoints the run as `awaiting_human` exactly as the HTTP route does — literally the same code, since both call `workflows.gate.checkpoint_gate`, which delivers the question and writes the checkpoint in one place. It never hangs waiting on a human, and it reports both whether the question reached them and whether the run will continue by itself once answered. The runners that *cannot* pause — the schedulers, evals, client rotation, onboarding, the research tools — call `gate.ensure_workflow_event`, which raises on a gate rather than letting one be swallowed; the scheduler's dynamic-workflow branch used to ignore it and record a successful run containing nothing. `executive_research` is excluded (it has the dedicated `run_executive_research` tool). Running a workflow from chat delivers nothing on its own — it renders the artifact into the conversation, and the recurring principal briefs (`morning_brief`, `end_of_day_digest`) reach anyone only via the scheduler's own `_deliver_to_principal`. The tool description used to claim those two DM the principal when run and to confirm before firing them, which had the model soliciting a confirmation on a false premise; it now names `executive_reflection` as the one workflow that really does execute tool calls of its own (DMs to heads, broadcasts, alerts). A successful run surfaces an `action_taken` chip linking to `/jobs/runs/{run_id}`.\n\n### Dynamic (user-created) workflows\n\nUsers create reusable workflows on the fly — from the executive chat, the conversational wizard at `/jobs/new`, or the step-by-step advanced editor — without shipping code. A dynamic workflow is a stored JSON definition (the `dynamic_workflows` table) interpreted at runtime by one generic `DynamicWorkflow` engine (`openexecutive/workflows/dynamic.py`) that implements the same `Workflow` ABC as the built-ins, so the run path, SSE streaming, run persistence, and `/jobs/[name]` form rendering are unchanged. `get_workflow` / `list_workflows` fall through to the dynamic store after the static registry (built-ins win on a name collision).\n\nA definition declares free-text input fields and an ordered step list of four kinds: **specialist** (consult a specialist with a goal prompt, optionally grounded by RAG), **action** (get something done with tools — see below), **approval_gate** (a `wait_for_human` pause), and a terminal **synthesis** step that assembles the artifact. At least one specialist or action step is required. `validate_definition` enforces the structural rules: exactly one terminal synthesis step, valid specialists, `{placeholder}` tokens that reference declared input fields, rostered approval/cadence people, 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 (cadences are UTC), and taken names — is rendered once per session into the first user turn, and while refining, the exact current draft is prepended to the latest user turn so the model edits it rather than re-deriving it. Roster names and roles are flattened to one line and capped at 80 characters before they enter that context, and the system prompt tells the model to treat the whole block as data, never instructions. Sessions live in memory (`/workflows/designer/*`, 2 h TTL, 50-session cap), run one model turn at a time (a second concurrent `/message` or `/draft` gets 409, and a failed turn is rolled back by identity), and never write: the review card saves through the same `POST /workflows/custom`, which re-validates, and *Edit details* opens the draft in the advanced editor (`/jobs/new?designer=<id>`) before saving.\n\n**Action steps (workflows that act).** An `action` step (`ActionStepSpec`: `goal`, `tools`, `max_tool_calls` 1–50, default 20) is run by the `workflow_actor` Council agent (`openexecutive/workflows/action_step.py`) as a bounded tool-use loop. Its `tools` list is an allowlist of exact tool names — MCP gateway tools (`server__tool`, e.g. `google_workspace__append_table_rows`) and a small set of built-ins (`oe__read_file`, `oe__message_person`, `oe__create_alert`) — and **clicking Create is the user's approval** of that list: the review card shows every tool, flags the ones that may change things (anything whose name doesn't say it reads, and any tool with a URL/URI/endpoint/webhook parameter anywhere in its schema, or whose schema couldn't be read, since a URL can carry data out), and names them in a \"this workflow can use these without asking again\" notice. Because that card is the approval, a workflow with action steps saved from chat (`draft_workflow`/`save_workflow`, whose confirmation is a token the model holds itself) is stored **switched off** (`is_active=false`) and `save_workflow` returns `status: saved_pending_review` with a `/jobs/{name}` link. An inactive workflow can't run or schedule (`get_workflow` and the scheduler skip it); `/jobs/{name}` shows it on the same review card, where **Turn on workflow** (`POST /workflows/custom/{name}/activate`, which re-validates the tools) is the approval — the click sends the definition the card showed, and the server refuses (409) if the stored one has changed since, so chat overwriting it while the card is open can't get new tools switched on. Chat may revise a switched-off workflow but refuses to replace a switched-on one that has action steps (an inbound email steering the Executive could otherwise switch off an approved job and stage new tools under its name); those edits happen in the advanced editor. The Workflows catalog (`/jobs`) lists switched-off workflows in a compact *Waiting for your approval* strip, and saving edits in the advanced editor keeps one off. `tool_catalog.py` resolves names to schemas through the gateway's `search_tools` (extensible-mcp's Markdown output is parsed; resolving is also the per-session discovery its `call_tool` requires) and validates availability at save time (`POST`/`PUT /workflows/custom`, chat `draft_workflow`/`save_workflow`, designer drafts) — an unknown, misspelled or deny-listed tool is a 422. The gateway meta-tools (`search_tools`, `call_tool`, `load_mcp_server`) can never be step tools. `run()` resolves every action step's tools before any step runs, so a vanished tool stops the run before an earlier step acts; `resume()` checks only the steps still to run, after the gate and decision are validated. The last turn of an action step always switches tools off so the agent can report. At run time only the allowlisted tools are offered (sorted; constant cached system block, per-run goal/inputs/earlier results in the user turn), every `tool_use` is re-checked against the allowlist, MCP calls go through `MCPGateway.call_tool` so the config deny-list and the Gmail/Calendar/Drive recipient gates still apply, the call budget is enforced (then a final tools-off turn asks for the report; running out of turns fails the step and lists what was already done), tool errors (the gateway's `Error:` / `Error calling tool` / `Tool error:` prefixes, or a truthy `error` field) return to the model as `is_error` results, each call emits a `progress` event and an audit row (`workflow_tool_call`: tool and outcome; for tools that may change things also a short digest of target arguments — ids, recipients, URLs, paths — so a redirected write is visible; content arguments are never logged), and the step's output is the agent's report plus an \"Actions taken\" list. Tool output is framed as data, never instructions.\n\n**Targets are chosen at run time — and a new one is confirmed once.** Approving a workflow approves its *tools*; which sheet, doc, recipient or URL each call hits is chosen by the model at run time, by design (a tab per month, a reply to whoever sent the invoice, a doc per client). What bounds that is the allowlist, the gateway's recipient gates, the audit digest, and **first-write confirmation**: a `TargetPolicy` (one per run) checks every call to a tool that may change things. `resource_targets` walks its arguments recursively for resource keys (snake- or camel-case ids, `to`/`cc`/`bcc`, recipients, addresses, attendees, members, users, owners, parents, URLs/links/hrefs, paths, channels, spaces, rooms, phones, hosts, buckets, tables, spreadsheet/document/folder/calendar/file); a matching key marks everything beneath it, even a `name`. Outside a resource, only a new item's own `name`/`title`/`subject`, message/thread/draft/label ids, `range`/`sheet` and workspace-mcp's acting `user_google_email` are skipped — and whatever the key, a bare value shaped like an email address, a URL or an international phone number is a target, except inside what the call writes (`rows`, `values`, `body`, `text` …). Key names are a heuristic, so this is a best-effort guard layered on the allowlist, the gateway gates and the audit. Float ids are compared as integers. Arguments too deep, naming too many targets, or holding an over-long value **fail closed** (the call is refused). A target is trusted only when it was approved for this workflow before (`workflow_approved_targets`, by value) or is an id a write in this run created — a top-level id/link field (`id`, `spreadsheetId`, `webViewLink` …) of the **structured JSON object** result of a tool whose name says it creates (create / insert / upload …) and that takes no URL — a tool whose schema couldn't be read is assumed to (free text, nested records and readers' or updaters' results are never read, so a fetched page, an echoed title, a shared page's links or a stranger in `ccRecipients` can't plant one); those survive a pause in the resume payload (`run_created`). Values written in the workflow's own text are *not* trusted, since anyone who can edit the workflow could change them without review: they are asked once, then remembered. Approvals are by value, for any of the workflow's tools, and are **cleared when the workflow's tool set changes** (a newly added tool must earn them again). Any other target makes the call **held**: it is not run and costs no budget, the model is told it is waiting for approval and carries on, and it is audited `held for approval` (at most 10 held per step, 16 KB each; an identical repeat is held once). Whether a call is checked at all follows the read-only label, which now never marks a tool whose name carries a write verb anywhere (`find_and_replace_doc`). After the step finishes, the run pauses with a `WaitForHumanEvent` to the workflow's **owner** (`owner_person_id`, the person who created it on the Workflows page or in chat; falling back to the principal if unknown or archived), `on_timeout=auto_proceed`, 48 h, and a `WorkflowResumeState` of `kind=\"held_writes\"` carrying the exact held calls. On resume (`_resume_held_writes`, fingerprint-checked like a gate, with the remaining steps' tools checked first), only `approve` runs them — each still has to be in the live step's allowlist and resolve; its targets are remembered first — and anything else (decline, timeout, unreadable) skips them; either way a *Held for approval* section is added to the step's output and the run continues at the next step. With no one to ask, held writes are skipped and noted; a step that fails or crashes after holding, or a resume that stops early (definition changed, a later tool missing), audits its held writes as dropped and says they did not run. The question quotes each target JSON-escaped (a value can't add its own lines) and always shows a URL's full scheme and host, saying how much of the rest is hidden. The owner answers by chat reply or with **Approve / Decline** on the run page (`POST /workflows/runs/{id}/decision`, which the principal may also use); remembered targets are listed and removable on the workflow page.\n\n`oe__read_file` extracts text (PDF, Word, Excel, CSV, Markdown, text) only from files under `WORKFLOW_FILE_DIRS` (default: workspace-mcp's attachment folder), resolving symlinks and `..` before the check. Action steps are allowed in scheduled workflows. Because they have external side effects, a resumed run heartbeats its claim (`touch_resume_claim`, at most once a minute as events flow — each tool call emits one; a busy database is retried on the next heartbeat, never treated as a lost claim; the sweep's requeue re-checks the claim's age in the same UPDATE, so a heartbeat landing between the sweep's read and its write wins), so the stale-claim sweep never requeues and replays a slow but live run, and a worker that finds its claim superseded stops at its next event. A worker that actually crashes mid-resume is still requeued; its action steps then run again, so goals should say how to avoid duplicates (the actor reads current state before writing). `GET /workflows/tools/search?q=` and `GET /workflows/tools/describe?names=` back the advanced editor's tool picker and the review card's labels.\n\nAn optional cadence (`daily@` / `weekly@` / `quarterly@`) re-uses the scheduler via the `dynamic_workflow` action kind, which runs the workflow on schedule and DMs the artifact to a rostered recipient. A gate followed by further steps pauses at `awaiting_human` and then resumes once answered, so gates no longer have to sit immediately before synthesis. They remain forbidden in cadence-enabled definitions: a scheduled fire has no interactive human to ask.\n\nBuilt-ins the system runs on its own (`morning_brief`, `end_of_day_digest`, `executive_reflection`, `executive_research`) set `background = True`, surfaced as `WorkflowMeta.background`; the `/jobs` catalog files them under a **System** chip instead of the default view. They stay runnable by hand.\n\nCompleted artifacts are discoverable in the unified Artifacts section (`/artifacts`) alongside their run-detail page at `/jobs/runs/{run_id}`.\n\n## Data-driven retrospectives\n\n`engagement_value_report` introduces a new workflow pattern: instead of the user typing the substance into a form (the `investor_update` / `mbr` shape), the workflow **reads its substance from the database**. A deterministic gatherer (`clients/engagement_activity.py`) pulls the period's decisions, initiatives, advisory consultations, delivered workflow artifacts (excluding prior value reports), follow-through counts, and alerts handled — from the live DB for the active client, or a parked client slot's `state.db` opened read-only. A single board-comms call narrates those facts (the prompt forbids inventing anything not in them; an empty period skips the LLM entirely), and the artifact's lists are assembled deterministically. Built for renewal conversations — the engagement record is the evidence.",
"mermaid": "flowchart TD\n Input[\"Structured input\"]\n Steps[\"Ordered named steps\"]\n Wait[\"wait_for_human pause\"]\n Sched[\"workflow_runs<br/>(awaiting_human)\"]\n Resolver[\"inbound_resolver<br/>+ resumer\"]\n Artifact[\"Markdown artifact<br/>(workflow_runs.artifact)\"]\n Today[\"Today / Artifacts\"]\n Input --> Steps\n Steps --> Wait\n Wait --> Sched\n Sched -- \"human reply\" --> Resolver\n Resolver -- \"resolved → claim\" --> Steps\n Steps -- \"complete_run\" --> Artifact\n Artifact --> Today\n class Input entry\n class Steps compute\n class Wait compute\n class Sched storage\n class Resolver compute\n class Artifact storage\n class Today external",
"generated_at": "2026-09-24T00:00:00Z"
}
diff --git a/packages/core/openexecutive/guide/prebuilt/jobs.json b/packages/core/openexecutive/guide/prebuilt/jobs.json
index df4bfe05..a56c81e2 100644
--- a/packages/core/openexecutive/guide/prebuilt/jobs.json
+++ b/packages/core/openexecutive/guide/prebuilt/jobs.json
@@ -1,7 +1,7 @@
{
"section_id": "jobs",
"title": "Workflows",
- "markdown": "**What it is:** Structured, multi-step workflows that produce a *deliverable* — a board deck, a go-to-market plan, a performance review — or *get something done* with your connected tools, like filing emailed bills into a spreadsheet, rather than just a chat reply.\n\n**What it does:**\n\n- Browse the workflow catalog as compact cards; filter by area with the chips at the top (**Custom** holds yours, **System** holds the workflows Open Executive runs on its own, like the morning brief).\n- Start a run and watch it stream its progress step by step.\n- See your runs split into **Active**, **Awaiting sign-off**, **Done**, and **Error**, and search them by name.\n- Create your own **custom workflow** by describing it: the assistant asks a few clarifying questions, then drafts it for you to review.\n- Let a workflow **use tools** — Gmail, Google Sheets, Drive and anything else connected — to actually do the work, not just write about it.\n- Put a custom workflow on a **schedule** (e.g. every Monday at 09:00) so it runs without being asked.\n- Each finished run produces a document you can read and keep.\n\n**How to use:**\n\n*Run a workflow*\n\n1. Open **Workflows** and click a workflow in the **Catalog** — narrow the list with the chips or the search box.\n2. Fill in the fields (required ones have a red \\*). **Insert example** or **Load sample run** fills in realistic values if you just want to try it.\n3. Click **Continue**, then **Run workflow**. Progress streams step by step; when it finishes you land on the run page, with **Copy** and **Download .md**.\n\n*Build your own*\n\n1. Click **+ New workflow** and describe the job in plain words — what it should produce, who it's for, and how often — or pick one of the starter suggestions.\n2. Answer the clarifying questions (usually two or three) by typing or by clicking a suggested answer. **Draft it now** skips the rest.\n3. Review the draft: its steps, schedule, what you fill in each run, the assumptions it made, and the **tools** each action step will use (ones that can change things are marked).\n4. Click **Create workflow** — this approves those tools, and runs use them without asking again — or **Keep refining** and type what to change, or **Edit details** to fine-tune it field by field. It appears under **Custom** in the Catalog, with **Edit** and **Delete**.\n\n*Advanced editor* — reached from **Edit** on a custom workflow, **Edit details** on a draft, or **Use the advanced editor**:\n\n1. **Details:** a unique **Name** in snake_case (e.g. `weekly_competitor_watch`; 3–49 characters, starting with a letter), a title, description, section and estimated minutes.\n2. **Input fields:** click **+ Add field** for anything the person running it must supply. Use a field in a step's goal as `{field_name}`.\n3. **Steps:** add **+ Specialist** steps (pick a specialist, write its goal), **+ Action** steps (write what to get done and where, then **Search tools** and **+ Add** the ones it may use), and, if someone must sign off, an **+ Approval gate** (who to ask, the question, a timeout, and what happens on timeout). New steps are added at the bottom — use **↑** to move them above the synthesis step, which pulls everything together and must stay last; put an approval gate just before it. Up to 12 steps and 16 input fields.\n4. **Schedule (optional):** tick **Run on a schedule**, enter a cadence, and choose who the result is delivered to. Scheduled workflows can't have required inputs or approval gates.\n5. Click **Create workflow** (**Save changes** when editing).\n\nCadences are written like this (times are UTC): `daily@09:00`, `weekly@mon@09:00`, or `quarterly@01-09:00` (the 1st of January, April, July and October).\n\n*Workflows that use tools* — describe the job and where things live, e.g. *\"Every morning, find the bills I email you, read each PDF and add a row (vendor, amount, due date) to my Bill tracker sheet.\"* The assistant finds the right tools (here Gmail search and attachments, reading PDFs, and appending rows to Google Sheets) and asks about anything it needs, like which sheet. While a run works, the run page shows each tool as it's used, and the result lists every action taken. A workflow can only use the tools you approved, and every tool call is recorded in the audit log. You can also ask for one in chat: a workflow that uses tools is saved **switched off**, and the Executive gives you a link. It shows under *Waiting for your approval* at the top of the catalog; open it, check the steps and tools, and click **Turn on workflow** — until then it can't run or follow a schedule.\n\n*Signing off a paused run* — when a run reaches an approval gate it moves to **Awaiting sign-off** and the approver is messaged directly. They answer by replying on Slack, Discord or Telegram — \"yes\", \"LGTM\", \"no\", \"not now\". There's no approve button in the web app. \"No\" or \"not now\" ends the run.\n\n**From chat:**\n\n- *\"What workflows can you run?\"* or *\"Run a competitive teardown of Acme.\"* — the Executive runs it and brings the result back into the conversation.\n- *\"Build me a workflow called weekly_competitor_watch: the CMO checks our top three competitors for pricing and product changes, then summarise. Run it every Monday at 09:00 UTC and send it to me.\"* — the Executive drafts it, shows you a summary, and saves it once you say yes.\n\n*Note: outputs are listed in Artifacts. Ask OE can also fill in the advanced editor form for you.*",
+ "markdown": "**What it is:** Structured, multi-step workflows that produce a *deliverable* — a board deck, a go-to-market plan, a performance review — or *get something done* with your connected tools, like filing emailed bills into a spreadsheet, rather than just a chat reply.\n\n**What it does:**\n\n- Browse the workflow catalog as compact cards; filter by area with the chips at the top (**Custom** holds yours, **System** holds the workflows Open Executive runs on its own, like the morning brief).\n- Start a run and watch it stream its progress step by step.\n- See your runs split into **Active**, **Awaiting sign-off**, **Done**, and **Error**, and search them by name.\n- Create your own **custom workflow** by describing it: the assistant asks a few clarifying questions, then drafts it for you to review.\n- Let a workflow **use tools** — Gmail, Google Sheets, Drive and anything else connected — to actually do the work, not just write about it.\n- Put a custom workflow on a **schedule** (e.g. every Monday at 09:00) so it runs without being asked.\n- Each finished run produces a document you can read and keep.\n\n**How to use:**\n\n*Run a workflow*\n\n1. Open **Workflows** and click a workflow in the **Catalog** — narrow the list with the chips or the search box.\n2. Fill in the fields (required ones have a red \\*). **Insert example** or **Load sample run** fills in realistic values if you just want to try it.\n3. Click **Continue**, then **Run workflow**. Progress streams step by step; when it finishes you land on the run page, with **Copy** and **Download .md**.\n\n*Build your own*\n\n1. Click **+ New workflow** and describe the job in plain words — what it should produce, who it's for, and how often — or pick one of the starter suggestions.\n2. Answer the clarifying questions (usually two or three) by typing or by clicking a suggested answer. **Draft it now** skips the rest.\n3. Review the draft: its steps, schedule, what you fill in each run, the assumptions it made, and the **tools** each action step will use (ones that can change things are marked).\n4. Click **Create workflow** — this approves those tools, and runs use them without asking again — or **Keep refining** and type what to change, or **Edit details** to fine-tune it field by field. It appears under **Custom** in the Catalog, with **Edit** and **Delete**.\n\n*Advanced editor* — reached from **Edit** on a custom workflow, **Edit details** on a draft, or **Use the advanced editor**:\n\n1. **Details:** a unique **Name** in snake_case (e.g. `weekly_competitor_watch`; 3–49 characters, starting with a letter), a title, description, section and estimated minutes.\n2. **Input fields:** click **+ Add field** for anything the person running it must supply. Use a field in a step's goal as `{field_name}`.\n3. **Steps:** add **+ Specialist** steps (pick a specialist, write its goal), **+ Action** steps (write what to get done and where, then **Search tools** and **+ Add** the ones it may use), and, if someone must sign off, an **+ Approval gate** (who to ask, the question, a timeout, and what happens on timeout). New steps are added at the bottom — use **↑** to move them above the synthesis step, which pulls everything together and must stay last; put an approval gate just before it. Up to 12 steps and 16 input fields.\n4. **Schedule (optional):** tick **Run on a schedule**, enter a cadence, and choose who the result is delivered to. Scheduled workflows can't have required inputs or approval gates.\n5. Click **Create workflow** (**Save changes** when editing).\n\nCadences are written like this (times are UTC): `daily@09:00`, `weekly@mon@09:00`, or `quarterly@01-09:00` (the 1st of January, April, July and October).\n\n*Workflows that use tools* — describe the job and where things live, e.g. *\"Every morning, find the bills I email you, read each PDF and add a row (vendor, amount, due date) to my Bill tracker sheet.\"* The assistant finds the right tools (here Gmail search and attachments, reading PDFs, and appending rows to Google Sheets) and asks about anything it needs, like which sheet. While a run works, the run page shows each tool as it's used, and the result lists every action taken. A workflow can only use the tools you approved, and every tool call is recorded in the audit log. You can also ask for one in chat: a workflow that uses tools is saved **switched off**, and the Executive gives you a link. It shows under *Waiting for your approval* at the top of the catalog; open it, check the steps and tools, and click **Turn on workflow** — until then it can't run or follow a schedule.\n\n*Signing off a paused run* — when a run reaches an approval gate it moves to **Awaiting sign-off** and the approver is messaged directly. They answer by replying on Slack, Discord or Telegram — \"yes\", \"LGTM\", \"no\", \"not now\" — or with **Approve** / **Decline** on the run page (the principal can answer any sign-off there too). \"No\" or \"not now\" ends the run.\n\n*The first write somewhere new* — a workflow that uses tools picks where to write each time it runs (this month's tab, the sender of an invoice, a new doc per client). The first time it wants to write somewhere it hasn't written before — a different spreadsheet, a new recipient — that one write waits, the rest of the run carries on, and whoever created the workflow is asked: yes lets it write there now and in future runs, no skips it. The places a workflow may write without asking are listed under **Approved targets** on its page; remove one and it asks again.\n\n**From chat:**\n\n- *\"What workflows can you run?\"* or *\"Run a competitive teardown of Acme.\"* — the Executive runs it and brings the result back into the conversation.\n- *\"Build me a workflow called weekly_competitor_watch: the CMO checks our top three competitors for pricing and product changes, then summarise. Run it every Monday at 09:00 UTC and send it to me.\"* — the Executive drafts it, shows you a summary, and saves it once you say yes.\n\n*Note: outputs are listed in Artifacts. Ask OE can also fill in the advanced editor form for you.*",
"mermaid": null,
"generated_at": "2026-09-24T00:00:00Z"
}
diff --git a/packages/core/openexecutive/orchestrator/workflow_authoring_tools.py b/packages/core/openexecutive/orchestrator/workflow_authoring_tools.py
index 5f475523..ba647623 100644
--- a/packages/core/openexecutive/orchestrator/workflow_authoring_tools.py
+++ b/packages/core/openexecutive/orchestrator/workflow_authoring_tools.py
@@ -181,6 +181,14 @@ def _approved_tool_workflow_error(name: str, existing: Any) -> str | None:
)
+def _session_caller_id() -> int | None:
+ """The person chatting — recorded as a new workflow's owner."""
+ from openexecutive.workflows.gate_delivery import session_caller_id
+
+ session = current_session.get()
+ return session_caller_id(session) if session is not None else None
+
+
def _needs_review(defn: Any) -> bool:
"""True when the workflow has tool-using steps, which a person must approve.
@@ -317,7 +325,7 @@ async def handle_save_workflow(tool_input: dict[str, Any]) -> str:
# Conditional on the row read above, so an activation (from any
# process) landing after the approved-workflow check can't be
# overwritten by this save.
- saved = save_if_unchanged(defn, existing)
+ saved = save_if_unchanged(defn, existing, owner_person_id=_session_caller_id())
except Exception as exc:
logger.exception("save_workflow: persist failed")
return json.dumps({"error": f"failed to save: {exc}"})
diff --git a/packages/core/openexecutive/scheduler/runner.py b/packages/core/openexecutive/scheduler/runner.py
index 92a0e0e2..19984985 100644
--- a/packages/core/openexecutive/scheduler/runner.py
+++ b/packages/core/openexecutive/scheduler/runner.py
@@ -1116,7 +1116,9 @@ async def _run_dynamic_workflow(action: ScheduledAction, now: datetime) -> None:
schedule_dynamic_workflow_cadence,
)
from openexecutive.workflows.dynamic_store import get_definition
+ from openexecutive.workflows.gate import checkpoint_gate
from openexecutive.workflows.persistence import complete_run, create_run, fail_run
+ from openexecutive.workflows.wait_for_human import WaitForHumanEvent
assert action.id is not None
name = action.channel_ref
@@ -1137,7 +1139,21 @@ async def _run_dynamic_workflow(action: ScheduledAction, now: datetime) -> None:
)
store = ChromaDBStore(persist_directory=get_settings().vector_store_path)
artifact = ""
+ paused = False
async for event in workflow.run(inputs=wf_inputs, store=store):
+ # The one pause a scheduled run CAN take: an action step held
+ # writes to new targets. Nothing waits in-process — the run is
+ # checkpointed, its owner is asked, and the resumer finishes it
+ # (and DMs the artifact to this cadence's recipient) later.
+ if (
+ isinstance(event, WaitForHumanEvent)
+ and event.resume_state is not None
+ and event.resume_state.kind == "held_writes"
+ ):
+ event.resume_state.deliver_to_person_id = action.assigned_to_person_id
+ await checkpoint_gate(run_id=run_id, event=event, workflow_title=workflow.title)
+ paused = True
+ break
# The only scheduler branch that can receive a DYNAMIC workflow, so
# the only one that can be handed an approval gate. A cadence fire
# has no human in the loop, and `validate_definition` forbids gates
@@ -1152,7 +1168,10 @@ async def _run_dynamic_workflow(action: ScheduledAction, now: datetime) -> None:
artifact = event.content
elif event.type == "error" and event.message:
raise RuntimeError(event.message)
- complete_run(run_id, artifact or "(no artifact)")
+ if paused:
+ artifact = "" # the resumer delivers it once the owner answers
+ else:
+ complete_run(run_id, artifact or "(no artifact)")
except Exception as exc:
logger.exception("scheduler: dynamic_workflow %r (action %d) failed", name, action.id)
with contextlib.suppress(Exception):
diff --git a/packages/core/openexecutive/workflows/action_step.py b/packages/core/openexecutive/workflows/action_step.py
index ff0f88ab..e0c4ec94 100644
--- a/packages/core/openexecutive/workflows/action_step.py
+++ b/packages/core/openexecutive/workflows/action_step.py
@@ -20,9 +20,16 @@ Prompt caching: the system block is a constant with ``cache_control``; the
per-run goal, inputs, and earlier results go in the user turn. The tool array
varies per step but not within one, so the prefix is reused across the loop.
+Targets: approving a workflow approves its tools, not which sheet, doc,
+recipient or URL each call hits — that is chosen at run time, by design. With
+a ``TargetPolicy``, a write whose resource arguments name a target this
+workflow has never been approved for is **held** instead of run: the model is
+told it is waiting for the owner, the rest of the step carries on, and the
+engine pauses the run after the step to ask (see ``dynamic``).
+
Yields ``(kind, payload)`` tuples the engine turns into workflow events:
-``("progress", text)``, then exactly one of ``("output", report)`` or
-``("error", fixed_message)``.
+``("progress", text)`` and ``("held", HeldCall)`` as they happen, then
+exactly one of ``("output", report)`` or ``("error", fixed_message)``.
"""
from __future__ import annotations
@@ -30,14 +37,16 @@ import asyncio
import json
import logging
import re
-from collections.abc import AsyncIterator
+from collections.abc import AsyncIterator, Iterable
from datetime import UTC, datetime
from typing import Any
from openexecutive.agents.workflow_actor import WORKFLOW_ACTOR_AGENT_ID, WorkflowActorAgent
from openexecutive.config import get_settings
from openexecutive.workflows import tool_catalog
-from openexecutive.workflows.dynamic_models import ActionStepSpec
+from openexecutive.workflows.approved_targets import approved_values, normalize_value
+from openexecutive.workflows.dynamic_models import ActionStepSpec, DynamicWorkflowDef
+from openexecutive.workflows.wait_for_human import HeldCall
logger = logging.getLogger(__name__)
@@ -50,7 +59,21 @@ _MAX_INPUT_CHARS = 2_000
_MAX_PRIOR_OUTPUT_CHARS = 6_000
_MAX_COMPANY_CHARS = 6_000
-StepYield = tuple[str, str]
+StepYield = tuple[str, Any]
+
+# Held writes per step, and the size of one held call's arguments (they are
+# stored in the run's resume payload until the owner answers).
+MAX_HELD_PER_STEP = 10
+_MAX_HELD_ARGS_CHARS = 16_000
+HELD_TOOL_RESULT = json.dumps({
+ "status": "held",
+ "message": (
+ "This call writes somewhere this workflow has not written before, so "
+ "it is held for the workflow owner's approval and will run exactly as "
+ "given if they approve. Do not retry it. Carry on with anything that "
+ "does not depend on it, and mention it in your report."
+ ),
+})
def _truncate(text: str, limit: int) -> str:
@@ -151,6 +174,199 @@ def _target_digest(arguments: dict[str, Any]) -> dict[str, str]:
return digest
+# Argument keys that name where a write lands: ids (snake or camel case),
+# recipients, addresses, members, URLs, paths, channels, hosts, buckets,
+# tables, and the Google resource kinds. Deliberately not `range` or `sheet`
+# (a new tab or range in an approved spreadsheet is the same spreadsheet),
+# nor a new item's own name/title, nor message/thread/draft/label ids (a
+# reply's real target is its recipients, which the gateway's recipient gates
+# check), nor `user_google_email` (workspace-mcp's acting account, on every
+# call). A key that matches marks everything beneath it too, so a target
+# can't hide one level down (`recipients: [{address: …}]`); a composite key
+# like `channel_name` or `bucket_name` still counts.
+_RESOURCE_KEY_RE = re.compile(
+ r"(^id$|_id$|^ids$|_ids$|^to$|^cc$|^bcc$|recipient|email|address|attendee|"
+ r"reply_?to|^from$|sender|assignee|reviewer|issue_?key|project_?key|"
+ r"member|user|group|owner|parent|destination|target|url|uri|path|channel|host|"
+ r"bucket|table|database|repo|spreadsheet|document|folder|calendar|webhook|"
+ r"endpoint|phone|space|room|href|link|org|team|tenant|account|topic|queue|"
+ r"collection|dataset|^file$)",
+ re.IGNORECASE,
+)
+# fileId, parentIds, docID, idList (Trello)
+_CAMEL_ID_RE = re.compile(r"([a-z0-9](Ids?|IDs?)$|^id[A-Z])")
+_NOT_RESOURCE_KEY_RE = re.compile(
+ r"^(name|title|subject|file_?name|display_?name|user_google_email|"
+ r"(message|thread|draft|label|request)_?ids?)$",
+ re.IGNORECASE,
+)
+# Whatever its key is called, a bare value shaped like an address, a URL or
+# an international phone number is a target: key names are only a heuristic,
+# and these are the shapes an exfiltrating write needs. Except inside what a
+# call writes (rows, body, text …), where an address is data, not a target.
+_TARGET_VALUE_RE = re.compile(
+ r"^(?:[^\s@]+@[^\s@]+\.[^\s@]+|[a-z][a-z0-9+.\-]*://\S+|\+[0-9][0-9 ()\-]{6,}[0-9])$",
+ re.IGNORECASE,
+)
+_CONTENT_KEY_RE = re.compile(
+ r"^(rows|values|data|body|content|text|html|markdown|description|notes?|"
+ r"comment|summary|headline)$",
+ re.IGNORECASE,
+)
+# Past these, a call's targets can't all be checked, so it is refused rather
+# than partly checked (fail closed).
+_MAX_TARGET_DEPTH = 8
+_MAX_TARGETS = 100
+_MAX_TARGET_CHARS = 2_000
+
+
+def _is_resource_key(key: str) -> bool:
+ if _NOT_RESOURCE_KEY_RE.search(key):
+ return False
+ return bool(_RESOURCE_KEY_RE.search(key) or _CAMEL_ID_RE.search(key))
+
+
+def resource_targets(arguments: Any) -> tuple[list[tuple[str, str]], bool]:
+ """Every ``(key, value)`` in ``arguments`` that names where a call acts.
+
+ Walks nested objects and lists; a resource key marks everything beneath
+ it. Returns ``(targets, complete)``: ``complete`` is False when the
+ arguments are too deep, name too many targets, or hold an over-long
+ value — the caller must then refuse the call, since what it didn't check
+ is exactly where an injected target would hide.
+ """
+ found: list[tuple[str, str]] = []
+ seen: set[str] = set()
+ complete = True
+
+ def add(key: str, value: Any) -> None:
+ nonlocal complete
+ if isinstance(value, bool) or not isinstance(value, str | int | float):
+ return
+ if isinstance(value, float) and value.is_integer():
+ value = int(value) # 987654321.0 is the same chat as 987654321
+ text = str(value).strip()
+ if not text or text in seen:
+ return
+ if len(text) > _MAX_TARGET_CHARS or len(found) >= _MAX_TARGETS:
+ complete = False
+ return
+ seen.add(text)
+ found.append((key, text))
+
+ def walk(node: Any, key: str, depth: int, is_resource: bool, in_content: bool) -> None:
+ nonlocal complete
+ if depth > _MAX_TARGET_DEPTH:
+ complete = False
+ return
+ if isinstance(node, dict):
+ for k, v in node.items():
+ k = str(k)
+ # A target can be a key: `members: {"[email protected]": "writer"}`.
+ if _TARGET_VALUE_RE.match(k.strip()):
+ add(key, k)
+ # Inside a resource (`channel: {name: …}`, `repository:
+ # {owner, name}`) even a name is part of the target.
+ walk(v, k, depth + 1, is_resource or _is_resource_key(k),
+ in_content or _CONTENT_KEY_RE.match(k) is not None)
+ elif isinstance(node, list):
+ for item in node:
+ walk(item, key, depth + 1, is_resource, in_content)
+ elif is_resource or (
+ not in_content
+ and not _NOT_RESOURCE_KEY_RE.search(key) # e.g. the acting user_google_email
+ and isinstance(node, str)
+ and _TARGET_VALUE_RE.match(node.strip())
+ ):
+ add(key, node)
+
+ walk(arguments, "", 0, False, False)
+ return found, complete
+
+
+_MAX_CREATED_VALUES = 2_000
+_MAX_CREATED_RESULT_CHARS = 200_000
+# Keys of a write's result that name the thing it created.
+_CREATED_KEY_RE = re.compile(r"(^id$|_id$|[a-z0-9]Id$|link$|Link$|url$|Url$)")
+# A created id must be at least this long to be trusted (so "1" never is).
+_MIN_CREATED_VALUE = 6
+
+
+class TargetPolicy:
+ """Which targets a run may write to without asking. One per run.
+
+ Trusted without asking:
+ - values approved for this workflow before (``approved_targets``) — by the
+ owner answering a held write, never by anything the model or a page can
+ write;
+ - ids a write in this run created: the top-level id / link fields
+ (``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 reader's or updater's result
+ describes things someone else may have written. Free text is
+ never parsed — a page, an echoed title or a document body could
+ otherwise plant an id — and a URL-taking tool's result is whatever the
+ URL served. These survive a pause through the resume payload
+ (``created``).
+ Everything else, including values written in the workflow's own text
+ (which anyone who can edit the workflow could change without a review),
+ is asked once and then remembered.
+ """
+
+ def __init__(self, *, approved: set[str], created: Iterable[str] = ()) -> None:
+ self._approved = {normalize_value(v) for v in approved}
+ self._created = {normalize_value(v) for v in created}
+
+ @classmethod
+ def for_workflow(
+ cls, defn: DynamicWorkflowDef, created: Iterable[str] = ()
+ ) -> TargetPolicy:
+ return cls(approved=approved_values(defn.name), created=created)
+
+ def _trusted(self, value: str) -> bool:
+ norm = normalize_value(value)
+ return norm in self._approved or norm in self._created
+
+ def unapproved(self, targets: list[tuple[str, str]]) -> list[tuple[str, str]]:
+ return [(k, v) for k, v in targets if not self._trusted(v)]
+
+ def note_written(self, result_text: str, info: tool_catalog.ToolInfo) -> None:
+ """Trust the id a successful write returned for what it created.
+
+ Only the TOP-LEVEL id / link fields of a structured (JSON object)
+ result count — e.g. ``{"spreadsheetId": …, "spreadsheetUrl": …}``.
+ Nested records (``user``, ``ccRecipients``, ``owners``) describe
+ other things, often chosen by someone else, so they never do.
+ """
+ text = str(result_text)
+ if (
+ not tool_catalog.creates(info)
+ or tool_catalog.takes_url(info)
+ or len(text) > _MAX_CREATED_RESULT_CHARS
+ ):
+ return
+ try:
+ parsed = json.loads(text)
+ except (ValueError, RecursionError):
+ return
+ if not isinstance(parsed, dict):
+ return
+ for key, value in parsed.items():
+ if len(self._created) >= _MAX_CREATED_VALUES:
+ break
+ if not isinstance(value, str | int) or isinstance(value, bool):
+ continue
+ if _CREATED_KEY_RE.search(str(key)) and len(str(value)) >= _MIN_CREATED_VALUE:
+ self._created.add(normalize_value(str(value)))
+
+ def created(self) -> list[str]:
+ """Run-created values, for the resume payload of a pause."""
+ return sorted(self._created)
+
+ def approve(self, targets: list[tuple[str, str]]) -> None:
+ self._approved.update(normalize_value(v) for _, v in targets)
+
+
def _audit(
workflow_name: str,
step_id: str,
@@ -247,6 +463,7 @@ async def run_action_step(
values: dict[str, Any],
company_block: str,
prior_outputs: dict[str, tuple[str, str]],
+ policy: TargetPolicy | None,
model: str | None = None,
) -> AsyncIterator[StepYield]:
from openexecutive.providers.registry import get_provider
@@ -289,6 +506,7 @@ async def run_action_step(
allowed = set(step.tools)
budget = _Budget(step.max_tool_calls)
actions: list[tuple[str, str]] = []
+ holds = _Holds()
max_turns = step.max_tool_calls + _EXTRA_TURNS
for turn in range(max_turns):
@@ -332,12 +550,26 @@ async def run_action_step(
"this step's tool-call budget is used up"
), "refused: budget"
else:
- budget.used += 1
- if resolved[name].read_only is not True:
+ writes = resolved[name].read_only is not True
+ if writes:
targets = _target_digest(arguments)
- yield ("progress", f"Using {name}…")
- content, is_error = await _call_tool(name, arguments, resolved[name])
- outcome = "error" if is_error else "ok"
+ decision = holds.decide(name, arguments, policy if writes else None)
+ if isinstance(decision, str):
+ (content, is_error), outcome = _refusal(decision), "refused: target check"
+ elif decision is not None:
+ # Not run and not counted against the budget: it runs later,
+ # exactly as given, only if the owner approves. A repeat of
+ # a call already held is answered the same way, not held twice.
+ if decision is not _ALREADY_HELD:
+ yield ("held", decision)
+ content, is_error, outcome = HELD_TOOL_RESULT, False, "held for approval"
+ else:
+ budget.used += 1
+ yield ("progress", f"Using {name}…")
+ content, is_error = await _call_tool(name, arguments, resolved[name])
+ outcome = "error" if is_error else "ok"
+ if writes and not is_error and policy is not None:
+ policy.note_written(content, resolved[name])
_audit(workflow_name, step.id, name, outcome, targets)
actions.append((name, outcome))
results.append(
@@ -360,6 +592,157 @@ async def run_action_step(
)
+# Returned for a repeat of a call already held: answered as held, not held twice.
+_ALREADY_HELD = HeldCall(tool="(already held)")
+
+
+class _Holds:
+ """Per-step bookkeeping for calls held for approval."""
+
+ def __init__(self) -> None:
+ self.count = 0
+ self._seen: set[str] = set()
+
+ def decide(
+ self, name: str, arguments: dict[str, Any], policy: TargetPolicy | None
+ ) -> HeldCall | str | None:
+ """None: run the call. A HeldCall: hold it (``_ALREADY_HELD`` for a
+ repeat of one already held). A string: refuse it, with that reason."""
+ if policy is None:
+ return None
+ targets, complete = resource_targets(arguments)
+ if not complete:
+ return (
+ "this call names more targets than can be checked (too many, too "
+ "deeply nested, or too long), so it was not run"
+ )
+ new_targets = policy.unapproved(targets)
+ if not new_targets:
+ return None
+ key = json.dumps({"tool": name, "arguments": arguments}, sort_keys=True, default=str)
+ if key in self._seen:
+ return _ALREADY_HELD
+ if self.count >= MAX_HELD_PER_STEP or len(key) > _MAX_HELD_ARGS_CHARS:
+ return (
+ "this call writes to a new target and can't be held for approval "
+ "(too many held already, or it is too large); it was not run"
+ )
+ self._seen.add(key)
+ self.count += 1
+ return HeldCall(tool=name, arguments=arguments, targets=new_targets)
+
+
+# How much of a held target the owner is shown. Longer values show their
+# start and end — the part an injected URL varies is usually the tail.
+_SHOWN_TARGET_CHARS = 400
+
+
+def _escape_invisible(text: str) -> str:
+ """Escape line/paragraph separators, bidi and other format/control
+ characters, so a quoted target renders as one faithful line."""
+ import unicodedata
+
+ return "".join(
+ f"\\u{ord(ch):04x}" if unicodedata.category(ch) in {"Zl", "Zp", "Cf", "Cc"} else ch
+ for ch in text
+ )
+
+
+def describe_target(key: str, value: str) -> str:
+ """One held target as shown to the owner, e.g. ``spreadsheet_id "1AbC…"``.
+
+ Quoted with JSON escaping, so a value can't break the line and add its
+ own text to the question. A URL always shows its full scheme and host —
+ that is where it goes — and anything shortened says how much is hidden.
+ """
+ from urllib.parse import urlsplit
+
+ head = ""
+ rest = value
+ try:
+ parts = urlsplit(value)
+ except ValueError:
+ parts = None
+ if parts is not None and parts.scheme and parts.netloc:
+ head = f"{parts.scheme}://{parts.netloc}"
+ rest = value[len(head):]
+ if len(rest) > _SHOWN_TARGET_CHARS:
+ half = _SHOWN_TARGET_CHARS // 2
+ hidden = len(rest) - 2 * half
+ rest = f"{rest[:half]}…({hidden} characters not shown)…{rest[-half:]}"
+ shown = _escape_invisible(json.dumps(head + rest, ensure_ascii=False))
+ safe_key = re.sub(r"[^A-Za-z0-9_.\-]", "_", key)
+ return f"{safe_key} {shown}" if safe_key else shown
+
+
+async def run_held_calls(
+ step: ActionStepSpec,
+ held: list[HeldCall],
+ *,
+ workflow_name: str,
+ run_id: str,
+ approved: bool,
+ skip_reason: str,
+ policy: TargetPolicy | None,
+) -> str:
+ """Settle the calls ``step`` held for approval; return a report section.
+
+ Approved: each call's targets are remembered for this workflow, then the
+ call runs exactly as the model gave it — but only if its tool is still in
+ the (live) step's allowlist and still resolves. Not approved: nothing runs.
+ Every call is audited either way.
+ """
+ from openexecutive.workflows.approved_targets import remember
+
+ resolved = await tool_catalog.resolve(list(step.tools)) if approved else {}
+ lines = ["**Held for approval**", ""]
+ for call in held:
+ where = ", ".join(describe_target(k, v) for k, v in call.targets) or "a new target"
+ if not approved:
+ outcome = f"skipped ({skip_reason})"
+ elif call.tool not in step.tools or call.tool not in resolved:
+ outcome = "skipped (the tool is no longer available to this step)"
+ else:
+ remember(workflow_name, call.targets, run_id=run_id)
+ content, is_error = await _call_tool(call.tool, call.arguments, resolved[call.tool])
+ outcome = "error" if is_error else "done"
+ if policy is not None:
+ policy.approve(call.targets)
+ if not is_error:
+ policy.note_written(content, resolved[call.tool])
+ _audit(
+ workflow_name, step.id, call.tool, f"held → {outcome}", _target_digest(call.arguments)
+ )
+ lines.append(f"- `{call.tool}` → {where} — {outcome}")
+ return "\n".join(lines)
+
+
+def drop_held_calls(workflow_name: str, step_id: str, held: list[HeldCall], reason: str) -> str:
+ """Audit held calls that will never be asked about or run; return a note
+ for the run's error ("N held write(s) were not run")."""
+ for call in held:
+ _audit(workflow_name, step_id, call.tool, f"held → dropped ({reason})",
+ _target_digest(call.arguments))
+ return f"{len(held)} held write(s) were not run"
+
+
+def held_question(workflow_title: str, held: list[HeldCall]) -> str:
+ """What the owner is asked about the writes a step held."""
+ lines = [
+ f"The workflow \u201c{workflow_title}\u201d wants to write somewhere it "
+ "hasn't written before:",
+ ]
+ for call in held:
+ where = ", ".join(describe_target(k, v) for k, v in call.targets) or "a new target"
+ lines.append(f"- {where} (via {call.tool})")
+ lines.append(
+ "Reply yes to allow all of the above — they run now, and future runs "
+ "can write to these with any of this workflow's tools without asking — "
+ "or no to skip them."
+ )
+ return "\n".join(lines)
+
+
def _format_output(report: str, actions: list[tuple[str, str]]) -> str:
lines = [report.strip() or "(The step finished without a report.)", "", "**Actions taken**", ""]
if actions:
diff --git a/packages/core/openexecutive/workflows/approved_targets.py b/packages/core/openexecutive/workflows/approved_targets.py
new file mode 100644
index 00000000..c8fc0558
--- /dev/null
+++ b/packages/core/openexecutive/workflows/approved_targets.py
@@ -0,0 +1,166 @@
+"""Targets a workflow's tool steps have been approved to write to.
+
+Approving a workflow approves its *tools*; which sheet, doc, recipient or URL
+each call hits is chosen at run time. The first time a workflow writes to a
+target it has never used, that write is held and its owner is asked (see
+``action_step`` / ``dynamic``). A yes lands here, so later runs write to the
+same target without asking again.
+
+Approval is by **value** — a spreadsheet id, an address, a URL — not by tool:
+the tools themselves were approved when the workflow was switched on.
+
+Same DB file and conventions as ``dynamic_store``: lazy idempotent table
+creation, and a ``db_path`` override on every function for tests.
+"""
+from __future__ import annotations
+
+from collections.abc import Iterable
+from datetime import UTC, datetime
+from pathlib import Path
+from typing import Any
+
+from openexecutive.memory.episodic import DB_PATH, _get_conn
+
+
+def _resolve(db_path: Path | None) -> Path:
+ """Dynamic DB_PATH resolution — lets tests monkeypatch the module DB_PATH."""
+ return db_path if db_path is not None else DB_PATH
+
+
+def normalize_value(value: str) -> str:
+ """Canonical form a target is stored and compared in.
+
+ Addresses are case-insensitive in practice, so an approved
+ ``[email protected]`` also covers ``[email protected]``; everything else
+ (ids, paths, URLs) is compared exactly.
+ """
+ text = str(value).strip()
+ if "@" in text and " " not in text and "/" not in text:
+ return text.lower()
+ return text
+
+
+def initialize_approved_targets_db(db_path: Path | None = None) -> None:
+ with _get_conn(_resolve(db_path)) as conn:
+ conn.execute(
+ """
+ CREATE TABLE IF NOT EXISTS workflow_approved_targets (
+ workflow_name TEXT NOT NULL,
+ value TEXT NOT NULL,
+ key TEXT NOT NULL,
+ approved_at TEXT NOT NULL,
+ run_id TEXT NOT NULL DEFAULT '',
+ PRIMARY KEY (workflow_name, value)
+ )
+ """
+ )
+
+
+def _table_exists(conn: Any) -> bool:
+ return (
+ conn.execute(
+ "SELECT 1 FROM sqlite_master WHERE type='table' AND name='workflow_approved_targets'"
+ ).fetchone()
+ is not None
+ )
+
+
+def approved_values(workflow_name: str, db_path: Path | None = None) -> set[str]:
+ if not _resolve(db_path).exists():
+ return set()
+ with _get_conn(_resolve(db_path)) as conn:
+ if not _table_exists(conn):
+ return set()
+ rows = conn.execute(
+ "SELECT value FROM workflow_approved_targets WHERE workflow_name = ?",
+ (workflow_name,),
+ ).fetchall()
+ return {str(r[0]) for r in rows}
+
+
+def remember(
+ workflow_name: str,
+ targets: Iterable[tuple[str, str]],
+ *,
+ run_id: str = "",
+ db_path: Path | None = None,
+) -> None:
+ """Record ``(key, value)`` targets as approved. Re-approving is a no-op."""
+ rows = [
+ (workflow_name, normalize_value(value), str(key), run_id)
+ for key, value in targets
+ if normalize_value(value)
+ ]
+ if not rows:
+ return
+ initialize_approved_targets_db(db_path)
+ now = datetime.now(UTC).isoformat()
+ with _get_conn(_resolve(db_path)) as conn:
+ conn.executemany(
+ """
+ INSERT INTO workflow_approved_targets (workflow_name, value, key, approved_at, run_id)
+ VALUES (?, ?, ?, ?, ?)
+ ON CONFLICT(workflow_name, value) DO NOTHING
+ """,
+ [(name, value, key, now, run) for name, value, key, run in rows],
+ )
+
+
+def list_targets(workflow_name: str, db_path: Path | None = None) -> list[dict[str, str]]:
+ if not _resolve(db_path).exists():
+ return []
+ with _get_conn(_resolve(db_path)) as conn:
+ if not _table_exists(conn):
+ return []
+ rows = conn.execute(
+ "SELECT value, key, approved_at, run_id FROM workflow_approved_targets "
+ "WHERE workflow_name = ? ORDER BY approved_at, value",
+ (workflow_name,),
+ ).fetchall()
+ return [
+ {"value": r[0], "key": r[1], "approved_at": r[2], "run_id": r[3]} for r in rows
+ ]
+
+
+def forget(workflow_name: str, value: str, db_path: Path | None = None) -> bool:
+ if not _resolve(db_path).exists():
+ return False
+ with _get_conn(_resolve(db_path)) as conn:
+ if not _table_exists(conn):
+ return False
+ cur = conn.execute(
+ "DELETE FROM workflow_approved_targets WHERE workflow_name = ? AND value = ?",
+ (workflow_name, normalize_value(value)),
+ )
+ return cur.rowcount > 0
+
+
+def forget_all(workflow_name: str, db_path: Path | None = None) -> None:
+ """Drop every approval for ``workflow_name`` — a deleted workflow's approvals
+ must not carry over to a new one saved under the same name."""
+ if not _resolve(db_path).exists():
+ return
+ with _get_conn(_resolve(db_path)) as conn:
+ if _table_exists(conn):
+ conn.execute(
+ "DELETE FROM workflow_approved_targets WHERE workflow_name = ?", (workflow_name,)
+ )
+
+
+def approver_for(workflow_name: str) -> int | None:
+ """Who is asked to approve a new target: the workflow's creator.
+
+ Falls back to the principal when the creator is unknown (workflows saved
+ before owners were recorded, or created without a resolvable caller) or
+ no longer an active roster member. None only when neither exists.
+ """
+ from openexecutive.people.store import find_principal_person, get_person
+ from openexecutive.workflows.dynamic_store import get_owner
+
+ owner_id = get_owner(workflow_name)
+ if owner_id is not None:
+ owner = get_person(owner_id)
+ if owner is not None and not getattr(owner, "archived", False):
+ return owner_id
+ principal = find_principal_person()
+ return principal.id if principal is not None and principal.id is not None else None
diff --git a/packages/core/openexecutive/workflows/dynamic.py b/packages/core/openexecutive/workflows/dynamic.py
index 13f527ab..061530fd 100644
--- a/packages/core/openexecutive/workflows/dynamic.py
+++ b/packages/core/openexecutive/workflows/dynamic.py
@@ -38,7 +38,7 @@ from __future__ import annotations
import hashlib
import string
from collections.abc import AsyncIterator
-from typing import Any
+from typing import TYPE_CHECKING, Any, TypeVar
from pydantic import BaseModel, Field, create_model
@@ -65,15 +65,56 @@ from openexecutive.workflows.wait_for_human import (
CONTINUE_DECISIONS,
DECISION_VERBS,
NON_APPROVAL_SHAPES,
+ HeldCall,
WaitForHumanEvent,
WaitForHumanResolution,
WorkflowResumeState,
)
+if TYPE_CHECKING: # imported lazily at runtime (workflows -> orchestrator cycle)
+ from openexecutive.workflows.action_step import TargetPolicy
+
+# How long the owner has to answer about new write targets. No answer means
+# the held writes are skipped and the run finishes without them.
+HELD_WRITES_TIMEOUT_HOURS = 48
+
# Synthetic first step every dynamic workflow runs — loads the company profile
# and surfaces a "Load context" row in the UI, mirroring the built-ins.
_CONTEXT_STEP_ID = "context"
+
+def _context_start() -> WorkflowEvent:
+ return WorkflowEvent(type="step_start", step_id=_CONTEXT_STEP_ID, step_title="Load context")
+
+_StepT = TypeVar("_StepT", ApprovalGateStepSpec, ActionStepSpec)
+
+
+def _with_dropped(
+ error: WorkflowEvent, workflow_name: str, state: WorkflowResumeState, reason: str
+) -> WorkflowEvent:
+ """A resume that stops before settling its held writes: audit them as
+ dropped and say so in the error."""
+ if state.kind != "held_writes" or not state.held:
+ return error
+ from openexecutive.workflows.action_step import drop_held_calls
+
+ note = drop_held_calls(workflow_name, state.gate_step_id, state.held, reason)
+ return error.model_copy(update={"message": f"{error.message} ({note})"})
+
+
+def _load_context(verb: str) -> tuple[str, WorkflowEvent]:
+ """The company block, plus the event closing the "Load context" row.
+
+ Re-derived on resume rather than persisted: it is a pure function of the
+ profile, and a profile edited during a pause is the one later steps see.
+ """
+ profile = load_or_create_profile()
+ return _company_context_block(profile), WorkflowEvent(
+ type="step_done",
+ step_id=_CONTEXT_STEP_ID,
+ summary=f"{verb} profile for {profile.name or 'company'}.",
+ )
+
# Cap on the approver's own text carried into the artifact — and therefore
# into the synthesis specialist's prompt. A decision needs a sentence or two
# of reasoning; anything longer is not a sign-off note.
@@ -195,16 +236,9 @@ class DynamicWorkflow(Workflow):
return
# --- context ---
- yield WorkflowEvent(
- type="step_start", step_id=_CONTEXT_STEP_ID, step_title="Load context"
- )
- profile = load_or_create_profile()
- company_block = _company_context_block(profile)
- yield WorkflowEvent(
- type="step_done",
- step_id=_CONTEXT_STEP_ID,
- summary=f"Loaded profile for {profile.name or 'company'}.",
- )
+ yield _context_start()
+ company_block, loaded = _load_context("Loaded")
+ yield loaded
async for event in self._run_steps(
start_index=0,
@@ -212,6 +246,7 @@ class DynamicWorkflow(Workflow):
company_block=company_block,
outputs={},
store=store,
+ policy=self._target_policy(),
):
yield event
@@ -238,7 +273,14 @@ class DynamicWorkflow(Workflow):
# it with "Unknown specialist: …" as a section is worse than failing.
stale = _stale_specialist_steps(self._defn)
if stale:
- yield _stale_error(stale)
+ yield _with_dropped(_stale_error(stale), self.name, state, "the run could not resume")
+ return
+
+ if state.kind == "held_writes":
+ async for event in self._resume_held_writes(
+ values=values, state=state, resolution=resolution, store=store
+ ):
+ yield event
return
gate = self._gate_for_resume(state)
@@ -259,19 +301,9 @@ class DynamicWorkflow(Workflow):
)
return
- # Re-derive the company block rather than persisting it: it is a pure
- # function of the profile, and a profile edited during the pause should
- # be the one the remaining steps see.
- yield WorkflowEvent(
- type="step_start", step_id=_CONTEXT_STEP_ID, step_title="Load context"
- )
- profile = load_or_create_profile()
- company_block = _company_context_block(profile)
- yield WorkflowEvent(
- type="step_done",
- step_id=_CONTEXT_STEP_ID,
- summary=f"Reloaded profile for {profile.name or 'company'}.",
- )
+ yield _context_start()
+ company_block, loaded = _load_context("Reloaded")
+ yield loaded
decision = str(resolution.parsed_decision.get("decision") or "")
if not _may_continue(gate, decision):
@@ -327,15 +359,161 @@ class DynamicWorkflow(Workflow):
company_block=company_block,
outputs=outputs,
store=store,
+ policy=self._target_policy(state.run_created),
):
yield event
+ async def _resume_held_writes(
+ self,
+ *,
+ values: dict[str, Any],
+ state: WorkflowResumeState,
+ resolution: WaitForHumanResolution,
+ store: ChromaDBStore,
+ ) -> AsyncIterator[WorkflowEvent]:
+ """Continue a run that paused because an action step held new-target writes.
+
+ The step itself already ran. Only an explicit "approve" runs the held
+ calls (exactly as stored); a "no", a timeout, or anything unreadable
+ skips them. Either way the run then carries on at the next step.
+ """
+ from openexecutive.workflows.action_step import run_held_calls
+
+ step = self._step_for_resume(state, ActionStepSpec)
+ if step is None:
+ yield _with_dropped(
+ WorkflowEvent(
+ type="error",
+ message=(
+ "the workflow definition changed while this run was waiting "
+ "for approval of new write targets, so it can no longer be "
+ f"resumed safely (expected action step {state.gate_step_id!r}) "
+ "— re-run the workflow"
+ ),
+ ),
+ self.name, state, "the definition changed",
+ )
+ return
+
+ yield _context_start()
+ company_block, loaded = _load_context("Reloaded")
+ yield loaded
+
+ # Same order as a gate: the remaining steps' tools are checked before
+ # anything acts — including the held writes about to be approved.
+ missing_tools = await unavailable_step_tools(
+ self._defn, start_index=state.gate_step_index + 1
+ )
+ if missing_tools:
+ yield _with_dropped(
+ _missing_tools_error(missing_tools, resuming=True),
+ self.name, state, "a later step's tools are unavailable",
+ )
+ return
+
+ decision = str(resolution.parsed_decision.get("decision") or "")
+ approved = decision == "approve"
+ skip_reason = {
+ "reject": "declined",
+ "auto_proceed": "no answer in time",
+ }.get(decision, "not approved")
+ policy = self._target_policy(state.run_created)
+ section = await run_held_calls(
+ step,
+ state.held,
+ workflow_name=self.name,
+ run_id=resolution.run_id,
+ approved=approved,
+ skip_reason=skip_reason,
+ policy=policy,
+ )
+ outputs: dict[str, tuple[str, str]] = dict(state.outputs)
+ title, text = outputs.get(step.id, (step.title, ""))
+ outputs[step.id] = (title, f"{text}\n\n{section}".strip())
+ yield WorkflowEvent(
+ type="step_done", step_id=step.id, summary=_first_line(section)
+ )
+
+ async for event in self._run_steps(
+ start_index=state.gate_step_index + 1,
+ values=values,
+ company_block=company_block,
+ outputs=outputs,
+ store=store,
+ policy=policy,
+ ):
+ yield event
+
+ async def _held_writes_pause(
+ self,
+ step: ActionStepSpec,
+ index: int,
+ held: list[HeldCall],
+ outputs: dict[str, tuple[str, str]],
+ policy: TargetPolicy | None,
+ ) -> WaitForHumanEvent | None:
+ """The pause that asks the owner about ``step``'s held writes.
+
+ Asks the workflow's creator (falling back to the principal). With no
+ one to ask, the held writes are skipped, noted in the step's output,
+ and None is returned so the run carries on.
+ """
+ from openexecutive.workflows.action_step import held_question, run_held_calls
+ from openexecutive.workflows.approved_targets import approver_for
+
+ approver = approver_for(self.name)
+ if approver is None:
+ section = await run_held_calls(
+ step,
+ held,
+ workflow_name=self.name,
+ run_id="",
+ approved=False,
+ skip_reason="no one to approve it",
+ policy=policy,
+ )
+ title, text = outputs[step.id]
+ outputs[step.id] = (title, f"{text}\n\n{section}")
+ return None
+ return WaitForHumanEvent(
+ person_id=approver,
+ question=held_question(self.title, held),
+ timeout_hours=HELD_WRITES_TIMEOUT_HOURS,
+ # No answer skips the held writes (only "approve" runs them) and
+ # lets the rest of the run finish.
+ on_timeout="auto_proceed",
+ expected_reply_shape="approve_reject",
+ context_summary=f"New write targets in workflow {self.title!r}",
+ resume_state=WorkflowResumeState(
+ workflow_name=self.name,
+ gate_step_id=step.id,
+ gate_step_index=index,
+ steps_fingerprint=_steps_fingerprint(self._defn),
+ outputs=dict(outputs),
+ kind="held_writes",
+ held=list(held),
+ run_created=policy.created() if policy is not None else [],
+ ),
+ )
+
+ def _target_policy(self, created: list[str] | None = None) -> TargetPolicy:
+ from openexecutive.workflows.action_step import TargetPolicy
+
+ return TargetPolicy.for_workflow(self._defn, created=created or ())
+
# -- step loop ---------------------------------------------------------
def _gate_for_resume(
self, state: WorkflowResumeState
) -> ApprovalGateStepSpec | None:
- """The gate this payload paused at, or None if it no longer matches.
+ """The approval gate this payload paused at, or None if it no longer matches."""
+ return self._step_for_resume(state, ApprovalGateStepSpec)
+
+ def _step_for_resume(
+ self, state: WorkflowResumeState, step_type: type[_StepT]
+ ) -> _StepT | None:
+ """The step a payload paused at (a gate, or the action step that held
+ writes), or None if it no longer matches.
Every field is checked against the LIVE definition because all of them
can go stale during a pause: the payload may predate this build
@@ -350,7 +528,7 @@ class DynamicWorkflow(Workflow):
if not 0 <= state.gate_step_index < len(self._defn.steps):
return None
step = self._defn.steps[state.gate_step_index]
- if not isinstance(step, ApprovalGateStepSpec) or step.id != state.gate_step_id:
+ if not isinstance(step, step_type) or step.id != state.gate_step_id:
return None
# The gate being where we left it is NOT enough. Someone can keep the
# gate identical and replace every step after it while the run is
@@ -370,6 +548,7 @@ class DynamicWorkflow(Workflow):
company_block: str,
outputs: dict[str, tuple[str, str]],
store: ChromaDBStore,
+ policy: TargetPolicy | None,
) -> AsyncIterator[WorkflowEvent]:
"""Interpret steps from ``start_index`` on.
@@ -446,13 +625,17 @@ class DynamicWorkflow(Workflow):
# a live reference would keep mutating under it if the
# loop ever continued.
outputs=dict(outputs),
+ run_created=policy.created() if policy is not None else [],
),
)
yield gate # type: ignore[misc]
return
elif isinstance(step, ActionStepSpec):
- from openexecutive.workflows.action_step import run_action_step
+ from openexecutive.workflows.action_step import (
+ drop_held_calls,
+ run_action_step,
+ )
yield WorkflowEvent(
type="step_start", step_id=step.id, step_title=step.title
@@ -465,27 +648,44 @@ class DynamicWorkflow(Workflow):
message=f"step {step.id!r} placeholder error: {exc}",
)
return
- async for kind, payload in run_action_step(
- step,
- workflow_name=self.name,
- workflow_title=self.title,
- goal=goal,
- values=values,
- company_block=company_block,
- prior_outputs=dict(outputs),
- ):
- if kind == "progress":
- yield WorkflowEvent(
- type="progress", step_id=step.id, summary=payload
- )
- elif kind == "error":
- yield WorkflowEvent(type="error", message=payload)
+ held: list[HeldCall] = []
+ try:
+ async for kind, payload in run_action_step(
+ step,
+ workflow_name=self.name,
+ workflow_title=self.title,
+ goal=goal,
+ values=values,
+ company_block=company_block,
+ prior_outputs=dict(outputs),
+ policy=policy,
+ ):
+ if kind == "progress":
+ yield WorkflowEvent(
+ type="progress", step_id=step.id, summary=payload
+ )
+ elif kind == "held":
+ held.append(payload)
+ elif kind == "error":
+ if held:
+ note = drop_held_calls(self.name, step.id, held, "the step failed")
+ payload = f"{payload} ({note})"
+ yield WorkflowEvent(type="error", message=payload)
+ return
+ else:
+ outputs[step.id] = (step.title, payload)
+ yield WorkflowEvent(
+ type="step_done", step_id=step.id, summary=_first_line(payload)
+ )
+ except BaseException: # cancellation too: they will never run
+ if held:
+ drop_held_calls(self.name, step.id, held, "the step stopped")
+ raise
+ if held:
+ pause = await self._held_writes_pause(step, index, held, outputs, policy)
+ if pause is not None:
+ yield pause # type: ignore[misc]
return
- else:
- outputs[step.id] = (step.title, payload)
- yield WorkflowEvent(
- type="step_done", step_id=step.id, summary=_first_line(payload)
- )
elif isinstance(step, SynthesisStepSpec):
yield WorkflowEvent(
diff --git a/packages/core/openexecutive/workflows/dynamic_store.py b/packages/core/openexecutive/workflows/dynamic_store.py
index 88f83b8c..afb25fde 100644
--- a/packages/core/openexecutive/workflows/dynamic_store.py
+++ b/packages/core/openexecutive/workflows/dynamic_store.py
@@ -12,6 +12,7 @@ deserialising every row's body.
"""
from __future__ import annotations
+import sqlite3
from datetime import UTC, datetime
from pathlib import Path
@@ -38,26 +39,44 @@ def initialize_dynamic_workflows_db(db_path: Path | None = None) -> None:
)
"""
)
+ # Who created the workflow — asked to approve its first write to a
+ # new target. A column, not a definition field, so neither a client
+ # body nor a chat-drafted definition can set it; written on insert
+ # only, so edits, overwrites and activation keep the original.
+ columns = {r[1] for r in conn.execute("PRAGMA table_info(dynamic_workflows)")}
+ if "owner_person_id" not in columns:
+ try:
+ conn.execute("ALTER TABLE dynamic_workflows ADD COLUMN owner_person_id INTEGER")
+ except sqlite3.OperationalError as exc:
+ # Another process (API, scheduler, a bot) added it first.
+ if "duplicate column" not in str(exc).lower():
+ raise
def upsert_definition(
- defn: DynamicWorkflowDef, db_path: Path | None = None
+ defn: DynamicWorkflowDef,
+ db_path: Path | None = None,
+ *,
+ owner_person_id: int | None = None,
) -> DynamicWorkflowDef:
"""Insert or replace a definition by name. Stamps created_at/updated_at.
Returns the stored definition (with timestamps applied). On update, the
- original created_at is preserved.
+ original created_at and owner are preserved; ``owner_person_id`` only
+ applies when the row is new.
"""
initialize_dynamic_workflows_db(db_path)
now = datetime.now(UTC).isoformat()
existing = get_definition(defn.name, db_path=db_path)
+ _reset_approvals_if_tools_changed(existing, defn, db_path)
created_at = existing.created_at if existing and existing.created_at else now
defn = defn.model_copy(update={"created_at": created_at, "updated_at": now})
with _get_conn(_resolve(db_path)) as conn:
conn.execute(
"""
- INSERT INTO dynamic_workflows (name, definition, is_active, created_at, updated_at)
- VALUES (?, ?, ?, ?, ?)
+ INSERT INTO dynamic_workflows
+ (name, definition, is_active, created_at, updated_at, owner_person_id)
+ VALUES (?, ?, ?, ?, ?, ?)
ON CONFLICT(name) DO UPDATE SET
definition = excluded.definition,
is_active = excluded.is_active,
@@ -69,6 +88,7 @@ def upsert_definition(
1 if defn.is_active else 0,
created_at,
now,
+ owner_person_id,
),
)
return defn
@@ -116,7 +136,13 @@ def delete_definition(name: str, db_path: Path | None = None) -> bool:
if not _table_exists(conn):
return False
cur = conn.execute("DELETE FROM dynamic_workflows WHERE name = ?", (name,))
- return cur.rowcount > 0
+ deleted = cur.rowcount > 0
+ if deleted:
+ # A new workflow saved under this name must earn its own approvals.
+ from openexecutive.workflows.approved_targets import forget_all
+
+ forget_all(name, db_path=db_path)
+ return deleted
def set_active(name: str, active: bool, db_path: Path | None = None) -> bool:
@@ -173,15 +199,21 @@ def save_if_unchanged(
defn: DynamicWorkflowDef,
expected: DynamicWorkflowDef | None,
db_path: Path | None = None,
+ *,
+ owner_person_id: int | None = None,
) -> DynamicWorkflowDef | None:
"""Write ``defn`` only if the row is still ``expected`` (None: still absent).
For callers that decide from a read whether a write is allowed (chat's
save refuses to replace an approved tool workflow): a write from any
process landing after that read makes this a no-op. Returns the stored
- definition, or None when the row changed.
+ definition, or None when the row changed. ``owner_person_id`` only
+ applies to a new row.
"""
+ from openexecutive.workflows.approved_targets import initialize_approved_targets_db
+
initialize_dynamic_workflows_db(db_path)
+ initialize_approved_targets_db(db_path)
now = datetime.now(UTC).isoformat()
created_at = expected.created_at if expected and expected.created_at else now
stored = defn.model_copy(update={"created_at": created_at, "updated_at": now})
@@ -191,11 +223,12 @@ def save_if_unchanged(
if expected is None:
cur = conn.execute(
"""
- INSERT INTO dynamic_workflows (name, definition, is_active, created_at, updated_at)
- VALUES (?, ?, ?, ?, ?)
+ INSERT INTO dynamic_workflows
+ (name, definition, is_active, created_at, updated_at, owner_person_id)
+ VALUES (?, ?, ?, ?, ?, ?)
ON CONFLICT(name) DO NOTHING
""",
- (stored.name, body, active, created_at, now),
+ (stored.name, body, active, created_at, now, owner_person_id),
)
else:
cur = conn.execute(
@@ -207,4 +240,46 @@ def save_if_unchanged(
(body, active, now, stored.name, expected.updated_at),
)
changed = cur.rowcount == 1
+ if changed and expected is not None and _tools_of(expected) != _tools_of(stored):
+ # Same connection and commit as the write: a crash can't leave the
+ # old approvals standing under the new tool set.
+ conn.execute(
+ "DELETE FROM workflow_approved_targets WHERE workflow_name = ?", (stored.name,)
+ )
return stored if changed else None
+
+
+def _tools_of(defn: DynamicWorkflowDef | None) -> set[str]:
+ from openexecutive.workflows.dynamic_models import ActionStepSpec
+
+ if defn is None:
+ return set()
+ return {t for s in defn.steps if isinstance(s, ActionStepSpec) for t in s.tools}
+
+
+def _reset_approvals_if_tools_changed(
+ old: DynamicWorkflowDef | None, new: DynamicWorkflowDef, db_path: Path | None
+) -> None:
+ """Approved targets were approved for the tools the workflow had. A tool
+ set that changes (e.g. a send tool added to a sheet workflow) must earn
+ its approvals again, rather than inherit them unseen."""
+ if old is not None and _tools_of(old) != _tools_of(new):
+ from openexecutive.workflows.approved_targets import forget_all
+
+ forget_all(new.name, db_path=db_path)
+
+
+def get_owner(name: str, db_path: Path | None = None) -> int | None:
+ """The person who created ``name``, or None (unknown, or saved before owners)."""
+ if not _resolve(db_path).exists():
+ return None
+ with _get_conn(_resolve(db_path)) as conn:
+ if not _table_exists(conn):
+ return None
+ columns = {r[1] for r in conn.execute("PRAGMA table_info(dynamic_workflows)")}
+ if "owner_person_id" not in columns:
+ return None
+ row = conn.execute(
+ "SELECT owner_person_id FROM dynamic_workflows WHERE name = ?", (name,)
+ ).fetchone()
+ return int(row[0]) if row is not None and row[0] is not None else None
diff --git a/packages/core/openexecutive/workflows/gate_delivery.py b/packages/core/openexecutive/workflows/gate_delivery.py
index 545086e1..aeb47be3 100644
--- a/packages/core/openexecutive/workflows/gate_delivery.py
+++ b/packages/core/openexecutive/workflows/gate_delivery.py
@@ -76,7 +76,7 @@ async def deliver_gate_question(
if (
session is not None
and origin_channel
- and _session_caller_id(session) == event.person_id
+ and session_caller_id(session) == event.person_id
):
return (
event.model_copy(
@@ -193,7 +193,7 @@ def _dm_session_id(channel: str, channel_ref: str) -> str:
return pattern.format(ref=channel_ref)
-def _session_caller_id(session: object) -> int | None:
+def session_caller_id(session: object) -> int | None:
"""The person id behind the current chat session, if it is known."""
for attr in ("caller_person_id", "person_id"):
value = getattr(session, attr, None)
@@ -212,7 +212,7 @@ async def _launcher_name(session: object) -> str:
is the difference between a sign-off request and an anonymous one that
merely looks official.
"""
- person_id = _session_caller_id(session)
+ person_id = session_caller_id(session)
if person_id is None:
return ""
try:
diff --git a/packages/core/openexecutive/workflows/resumer.py b/packages/core/openexecutive/workflows/resumer.py
index 389bd95f..978a2f15 100644
--- a/packages/core/openexecutive/workflows/resumer.py
+++ b/packages/core/openexecutive/workflows/resumer.py
@@ -426,6 +426,9 @@ async def _execute_resume(
# other runners use: that flips running -> awaiting_human,
# stores the fresh payload, and clears gate 1's resolution so
# this run is not immediately re-claimed on its old answer.
+ # A scheduled run still owes its artifact to its recipient.
+ if event.resume_state is not None and state.deliver_to_person_id is not None:
+ event.resume_state.deliver_to_person_id = state.deliver_to_person_id
try:
await checkpoint_gate(
run_id=run_id,
@@ -514,9 +517,23 @@ async def _execute_resume(
},
)
logger.info("resumer: run %s resumed -> %s", run_id, outcome)
+ if artifact and state.deliver_to_person_id is not None:
+ await _deliver_artifact(run_id, state.deliver_to_person_id, artifact)
return True
+async def _deliver_artifact(run_id: str, person_id: int, artifact: str) -> None:
+ """DM a resumed scheduled run's artifact — the delivery the scheduler
+ would have made had the run not paused. Best effort: the run is already
+ stored as done, and a failed send must not change that."""
+ try:
+ from openexecutive.orchestrator.schedule_tools import handle_message_person
+
+ await handle_message_person({"person_id": person_id, "text": artifact})
+ except Exception:
+ logger.exception("resumer: run %s artifact delivery failed (run still done)", run_id)
+
+
def _resolution_from_row(row: dict, run_id: str) -> WaitForHumanResolution:
"""The stored resolution, or a neutral stand-in if it cannot be read.
diff --git a/packages/core/openexecutive/workflows/tool_catalog.py b/packages/core/openexecutive/workflows/tool_catalog.py
index 3f17337a..1b9dfa00 100644
--- a/packages/core/openexecutive/workflows/tool_catalog.py
+++ b/packages/core/openexecutive/workflows/tool_catalog.py
@@ -46,17 +46,64 @@ _SEARCH_TOP_K = 8
_MAX_READ_FILE_BYTES = 25 * 1024 * 1024
_READABLE_SUFFIXES = frozenset({".pdf", ".docx", ".doc", ".xlsx", ".xlsm", ".csv", ".md", ".txt"})
-# Verbs that mark a tool as read-only for the review card's "writes" badge.
-# The gateway reports no read-only hints, so this is a LABEL for the human,
-# never a security control — the allowlist and the gateway's own gates are.
+# Verbs that mark a tool as read-only. The gateway reports no read-only
+# hints, so this is a name heuristic. It drives the review card's "may change
+# things" badge AND which calls the first-write target check skips, so it
+# errs toward "may change": a name that also carries a write verb anywhere
+# (`find_and_replace_doc`, `get_or_create_folder`) is never read-only.
_READ_VERBS = (
"get_", "list_", "search_", "read_", "query_", "find_",
"check_", "describe_", "inspect_", "debug_",
)
+_WRITE_WORDS = frozenset({
+ "add", "append", "apply", "approve", "archive", "assign", "book", "cancel",
+ "clear", "close", "comment", "commit", "copy", "create", "delete", "deploy",
+ "draft", "edit", "execute", "forward", "grant", "import", "insert", "invite",
+ "join", "label", "leave", "mark", "merge", "modify", "move", "notify",
+ "patch", "pay", "post", "publish", "push", "put", "remove", "rename",
+ "reopen", "replace", "reply", "restore", "revoke", "run", "save", "schedule",
+ "send", "set", "share", "submit", "subscribe", "sync", "transfer", "trash",
+ "update", "upload", "upsert", "write",
+})
+_NAME_WORD_RE = re.compile(r"[A-Z]?[a-z0-9]+|[A-Z]+(?![a-z])")
+# Tools whose result can name something the run itself made. Only their
+# structured results can vouch for a new target (see action_step.TargetPolicy).
+_CREATE_WORDS = frozenset({"create", "insert", "upload", "add", "copy", "new", "make", "duplicate"})
+
+
+def _name_words(name: str) -> set[str]:
+ bare = name.split("__", 1)[-1]
+ return {w.lower() for part in re.split(r"[_\-\s]+", bare) for w in _NAME_WORD_RE.findall(part)}
+
+
+def _has_word(words: set[str], vocabulary: frozenset[str]) -> bool:
+ """A word from ``vocabulary``, alone or glued to the front of a longer
+ token (`createfolder`). Short words only match alone, so `settings` is not
+ `set`. For write words a false match only means a stricter check."""
+ return any(
+ w in vocabulary or any(len(v) >= 4 and w.startswith(v) for v in vocabulary)
+ for w in words
+ )
+
+
+def creates(info: ToolInfo) -> bool:
+ """Whether a tool's name says it creates something (create/insert/upload…).
+
+ Stricter than the write check, since here a false match would TRUST a
+ result: whole words only (`list_uploads` is not `upload`), and never a
+ name that starts with a read verb (`get_copyright_info`).
+ """
+ bare = info.name.split("__", 1)[-1].lower()
+ if bare.startswith(_READ_VERBS):
+ return False
+ return bool(_name_words(info.name) & _CREATE_WORDS)
# A tool that takes a URL can carry data OUT (the URL itself, or a request
# body), whatever its name says — e.g. `fetch__fetch`. Never label one as
# reads-only: the review card must show the user it can reach the outside.
-_EGRESS_PARAM_HINTS = ("url", "uri", "endpoint", "webhook")
+_EGRESS_PARAM_HINTS = (
+ "url", "uri", "endpoint", "webhook", "host", "link", "href", "domain", "site",
+ "server", "remote",
+)
@dataclass(frozen=True)
@@ -115,6 +162,19 @@ def _schema_property_names(schema: Any, depth: int = 0) -> set[str]:
return names
+def takes_url(info: ToolInfo) -> bool:
+ """Whether a tool has a URL-shaped parameter anywhere (it can reach out,
+ and what comes back is whatever that URL served). An unknown schema is
+ assumed to — the same fail-safe as the read-only label."""
+ if not info.input_schema:
+ return True
+ return any(
+ hint in key
+ for key in _schema_property_names(info.input_schema or {})
+ for hint in _EGRESS_PARAM_HINTS
+ )
+
+
def _read_only_label(name: str, input_schema: dict[str, Any] | None = None) -> bool | None:
if input_schema is None:
return None # schema unknown: can't rule out egress, so never "reads only"
@@ -122,8 +182,9 @@ def _read_only_label(name: str, input_schema: dict[str, Any] | None = None) -> b
hint in key for key in _schema_property_names(input_schema) for hint in _EGRESS_PARAM_HINTS
):
return None
- bare = name.split("__", 1)[-1].lower()
- return True if bare.startswith(_READ_VERBS) else None
+ if _has_word(_name_words(name), _WRITE_WORDS):
+ return None
+ return True if name.split("__", 1)[-1].lower().startswith(_READ_VERBS) else None
# ── MCP: parse the gateway's search_tools output ────────────────────────────
diff --git a/packages/core/openexecutive/workflows/wait_for_human.py b/packages/core/openexecutive/workflows/wait_for_human.py
index fffb3f9c..13895d6d 100644
--- a/packages/core/openexecutive/workflows/wait_for_human.py
+++ b/packages/core/openexecutive/workflows/wait_for_human.py
@@ -33,6 +33,20 @@ logger = logging.getLogger(__name__)
_CONFIDENCE_THRESHOLD = 0.85
+class HeldCall(BaseModel):
+ """A tool call an action step held because it writes to a new target.
+
+ Stored in the resume payload so that, if the owner approves, exactly this
+ call — the tool and arguments the model chose — runs, rather than a fresh
+ model turn that might choose differently.
+ """
+
+ tool: str
+ arguments: dict[str, Any] = Field(default_factory=dict)
+ # (argument key, value) pairs that were not yet approved.
+ targets: list[tuple[str, str]] = Field(default_factory=list)
+
+
class WorkflowResumeState(BaseModel):
"""Everything needed to restart a paused workflow at the step after its gate.
@@ -69,6 +83,19 @@ class WorkflowResumeState(BaseModel):
# step_id -> (step title, output text) for every step completed before the
# gate. Round-trips through JSON as a 2-array and back to a tuple.
outputs: dict[str, tuple[str, str]] = Field(default_factory=dict)
+ # What paused the run. "gate": an approval-gate step at gate_step_index.
+ # "held_writes": the action step at gate_step_index held writes to new
+ # targets (``held``); the step itself has run, and the owner's answer
+ # decides whether those exact calls run before the next step. Payloads
+ # written before this field existed parse as "gate".
+ kind: Literal["gate", "held_writes"] = "gate"
+ held: list[HeldCall] = Field(default_factory=list)
+ # Scheduled runs DM their artifact on completion; a run that paused
+ # completes in the resumer instead, which delivers it to this person.
+ deliver_to_person_id: int | None = None
+ # Values the run itself created before pausing (ids a write returned), so
+ # its target check still trusts them after resuming.
+ run_created: list[str] = Field(default_factory=list)
class WaitForHumanEvent(BaseModel):
diff --git a/packages/core/tests/unit/test_action_step.py b/packages/core/tests/unit/test_action_step.py
index de948f75..bf7f66a2 100644
--- a/packages/core/tests/unit/test_action_step.py
+++ b/packages/core/tests/unit/test_action_step.py
@@ -122,6 +122,7 @@ async def _run(step: ActionStepSpec, **kw: Any) -> list[tuple[str, str]]:
values=kw.get("values", {"sheet": "Bill tracker"}),
company_block=kw.get("company_block", "Company: Northwind"),
prior_outputs=kw.get("prior_outputs", {}),
+ policy=kw.get("policy"),
):
out.append(item)
return out
diff --git a/packages/core/tests/unit/test_held_writes.py b/packages/core/tests/unit/test_held_writes.py
new file mode 100644
index 00000000..2eb4e1d9
--- /dev/null
+++ b/packages/core/tests/unit/test_held_writes.py
@@ -0,0 +1,896 @@
+"""First write to a new target: held, asked, then run exactly as given (or skipped).
+
+Covers the target policy in action steps, the held-writes pause and resume in
+the engine, remembered targets, workflow owners (who gets asked), the web
+decision endpoint, and scheduled runs pausing for held writes.
+"""
+from __future__ import annotations
+
+import asyncio
+import json
+from pathlib import Path
+from types import SimpleNamespace
+from typing import Any
+
+import pytest
+from fastapi.testclient import TestClient
+
+from openexecutive.memory import episodic
+from openexecutive.people import store as people_store
+from openexecutive.workflows import action_step as act
+from openexecutive.workflows import approved_targets as at
+from openexecutive.workflows import dynamic_store
+from openexecutive.workflows import persistence as wf_persistence
+from openexecutive.workflows.dynamic import DynamicWorkflow
+from openexecutive.workflows.dynamic_models import DynamicWorkflowDef
+from openexecutive.workflows.wait_for_human import (
+ HeldCall,
+ WaitForHumanEvent,
+ WaitForHumanResolution,
+ WorkflowResumeState,
+)
+
+from . import test_action_step as _action_step_tests
+from .test_action_step import (
+ APPEND,
+ READ,
+ _FakeGateway,
+ _install,
+ _resp,
+ _run,
+ _ScriptedProvider,
+ _step,
+ _text,
+ _use,
+)
+
+# Reuse the action-step tests' fixtures (a fake gateway + resolver, and a
+# captured audit log) under the same names.
+gateway = _action_step_tests.gateway
+audit = _action_step_tests.audit
+
+SHEET = "1AbCdEfGhIjK_tracker"
+OTHER = "9ZyXwVuTsRqP_payroll"
+
+
[email protected](autouse=True)
+def _isolated(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
+ db = tmp_path / "test.db"
+ for module in (episodic, wf_persistence, people_store, dynamic_store, at):
+ monkeypatch.setattr(module, "DB_PATH", db)
+ episodic.initialize_db(db)
+ wf_persistence.initialize_runs_db(db)
+ people_store.initialize_db(db)
+ dynamic_store.initialize_dynamic_workflows_db(db)
+ monkeypatch.setattr(
+ "openexecutive.workflows.dynamic.load_or_create_profile",
+ lambda: SimpleNamespace(name="Northwind", is_empty=lambda: True),
+ )
+ monkeypatch.delenv("BACKEND_SHARED_SECRET", raising=False)
+ return db
+
+
+def _defn(**overrides: Any) -> DynamicWorkflowDef:
+ base: dict[str, Any] = {
+ "name": "file_bills_wf",
+ "title": "File bills",
+ "steps": [
+ {"kind": "action", "id": "file_bills", "title": "File bills",
+ "goal": "File them.", "tools": [APPEND, READ]},
+ {"kind": "synthesis", "id": "assemble", "title": "Assemble"},
+ ],
+ }
+ base.update(overrides)
+ return DynamicWorkflowDef.model_validate(base)
+
+
+def _policy(approved: set[str] | None = None) -> act.TargetPolicy:
+ return act.TargetPolicy(approved=approved or set())
+
+
+_WRITE_TOOL = act.tool_catalog.ToolInfo(APPEND, "Append rows.", {"type": "object", "properties": {}})
+CREATE = "docs__create_document"
+_CREATE_TOOL = act.tool_catalog.ToolInfo(CREATE, "Create a doc.", {"type": "object", "properties": {}})
+_FETCH_TOOL = act.tool_catalog.ToolInfo(
+ "fetch__fetch", "Fetch a URL.", {"type": "object", "properties": {"url": {"type": "string"}}}
+)
+
+
+# --- resource_targets --------------------------------------------------------
+
+
+def test_resource_targets_walk_nested_objects_and_lists() -> None:
+ args = {
+ "spreadsheet_id": SHEET,
+ "range": "Sheet1!A1",
+ "sheet": "March",
+ "rows": [["Acme", "10"]],
+ "message": {"to": ["[email protected]", "[email protected]"], "subject": "hi"},
+ "file_name": "bills.csv",
+ "thread_id": "t-123456789",
+ }
+ targets, complete = act.resource_targets(args)
+ assert complete
+ assert ("spreadsheet_id", SHEET) in targets
+ assert ("to", "[email protected]") in targets and ("to", "[email protected]") in targets
+ keys = {k for k, _ in targets}
+ # A new tab/range, a file's name, and a reply's thread are not targets.
+ assert not keys & {"range", "sheet", "file_name", "thread_id", "rows", "subject"}
+
+
+def test_resource_keys_carry_down_and_camel_case_ids_count() -> None:
+ graph = {"message": {"toRecipients": [{"emailAddress": {"name": "Eve", "address": "[email protected]"}}]}}
+ # Inside a resource even the display name counts (asked once, then remembered).
+ assert act.resource_targets(graph) == ([("name", "Eve"), ("address", "[email protected]")], True)
+ assert act.resource_targets({"recipients": [{"address": "[email protected]"}]})[0] == [
+ ("address", "[email protected]")
+ ]
+ ids = act.resource_targets({"fileId": "f-123456", "parentIds": ["p-123456"], "threadId": "t-1"})[0]
+ assert ids == [("fileId", "f-123456"), ("parentIds", "p-123456")]
+
+
+def test_targets_that_cannot_all_be_checked_fail_closed() -> None:
+ deep: dict = {"to": "[email protected]"}
+ for _ in range(10):
+ deep = {"a": deep}
+ assert act.resource_targets(deep)[1] is False
+ many = {"to": [f"user{i}@example.com" for i in range(act._MAX_TARGETS + 1)]}
+ assert act.resource_targets(many)[1] is False
+ assert act.resource_targets({"url": "https://x.example/" + "a" * 3000})[1] is False
+
+
+def test_policy_trusts_only_approvals_and_structured_ids_a_write_created() -> None:
+ policy = _policy(approved={"[email protected]"})
+ assert policy.unapproved([("to", "[email protected]")]) == [] # approved, case-insensitive
+ assert policy.unapproved([("spreadsheet_id", OTHER)]) == [("spreadsheet_id", OTHER)]
+ # A write's structured result: its ids are trusted, its echoed title isn't.
+ # A non-creating write's result vouches for nothing.
+ policy.note_written(json.dumps({"spreadsheetId": OTHER}), _WRITE_TOOL)
+ assert policy.unapproved([("spreadsheet_id", OTHER)]) != []
+ policy.note_written(
+ json.dumps({"spreadsheetId": OTHER, "title": "1AttackerSheetXXXX"}), _CREATE_TOOL
+ )
+ assert policy.unapproved([("spreadsheet_id", OTHER)]) == []
+ assert policy.unapproved([("spreadsheet_id", "1AttackerSheetXXXX")]) != []
+ # Free text is never parsed, and a URL tool's result is what the URL served.
+ policy.note_written("Created doc 'x' (ID: 1FreeTextIdXXXX)", _CREATE_TOOL)
+ policy.note_written(json.dumps({"id": "1PlantedByPageXXXX"}), _FETCH_TOOL)
+ assert policy.unapproved([("id", "1FreeTextIdXXXX"), ("id", "1PlantedByPageXXXX")]) == [
+ ("id", "1FreeTextIdXXXX"), ("id", "1PlantedByPageXXXX"),
+ ]
+ # Ids are compared exactly (only addresses are case-insensitive), and whole.
+ assert policy.unapproved([("spreadsheet_id", OTHER.upper())]) != []
+ good = "https://example.com/" + "a" * 470 + "/good"
+ policy.approve([("url", good)])
+ assert policy.unapproved([("url", good[:-4] + "evil")]) != []
+ # Run-created values survive a pause through the payload.
+ again = act.TargetPolicy(approved=set(), created=policy.created())
+ assert again.unapproved([("spreadsheet_id", OTHER)]) == []
+
+
+def test_name_keys_only_skip_their_own_value() -> None:
+ targets, _ = act.resource_targets({
+ "channel_name": "#payroll", "bucket_name": "exfil-bucket", "name": "Q3 notes",
+ "user_google_email": "[email protected]", "attendees": ["[email protected]"],
+ })
+ assert targets == [
+ ("channel_name", "#payroll"), ("bucket_name", "exfil-bucket"), ("attendees", "[email protected]"),
+ ]
+
+
+# --- holding in the action step ------------------------------------------------
+
+
+async def test_new_target_is_held_not_run(
+ monkeypatch: pytest.MonkeyPatch, gateway: _FakeGateway, audit: list[dict[str, Any]]
+) -> None:
+ provider = _ScriptedProvider(
+ [
+ _resp(_use(APPEND, {"spreadsheet_id": OTHER, "rows": [["x"]]}, "tu_1")),
+ _resp(_use(APPEND, {"spreadsheet_id": SHEET, "rows": [["y"]]}, "tu_2")),
+ _resp(_text("Filed one; one is waiting.")),
+ ]
+ )
+ _install(monkeypatch, provider)
+ out = []
+ async for item in act.run_action_step(
+ _step(max_tool_calls=1),
+ workflow_name="file_bills_wf", workflow_title="File bills", goal="File them.",
+ values={}, company_block="", prior_outputs={},
+ policy=_policy(approved={SHEET}),
+ ):
+ out.append(item)
+ held = [p for k, p in out if k == "held"]
+ assert len(held) == 1 and held[0].targets == [("spreadsheet_id", OTHER)]
+ assert held[0].arguments == {"spreadsheet_id": OTHER, "rows": [["x"]]}
+ # Only the approved write reached the gateway — and the held one didn't
+ # spend the budget of 1, or the second call would have been refused.
+ assert [c["arguments"]["spreadsheet_id"] for c in gateway.calls] == [SHEET]
+ tool_result = provider.calls[1]["messages"][-1]["content"][0]
+ assert json.loads(tool_result["content"])["status"] == "held"
+ assert tool_result["is_error"] is False
+ assert any(r["details"]["outcome"] == "held for approval" for r in audit
+ if r["type"] == "workflow_tool_call")
+ assert out[-1][0] == "output" and "held for approval" in out[-1][1]
+
+
+async def test_read_only_calls_and_no_policy_never_hold(
+ monkeypatch: pytest.MonkeyPatch, gateway: _FakeGateway, audit: list[dict[str, Any]]
+) -> None:
+ provider = _ScriptedProvider(
+ [
+ _resp(_use(READ, {"spreadsheet_id": OTHER}, "tu_1")),
+ _resp(_text("Read it.")),
+ ]
+ )
+ _install(monkeypatch, provider)
+ out = []
+ async for item in act.run_action_step(
+ _step(), workflow_name="w", workflow_title="W", goal="g", values={},
+ company_block="", prior_outputs={}, policy=_policy(),
+ ):
+ out.append(item)
+ assert not [k for k, _ in out if k == "held"] and len(gateway.calls) == 1
+
+ _install(monkeypatch, _ScriptedProvider(
+ [_resp(_use(APPEND, {"spreadsheet_id": OTHER}, "tu_1")), _resp(_text("ok"))]
+ ))
+ out = await _run(_step()) # no policy: nothing is held
+ assert not [k for k, _ in out if k == "held"] and len(gateway.calls) == 2
+
+
+async def test_hold_limit_refuses_further_new_targets(
+ monkeypatch: pytest.MonkeyPatch, gateway: _FakeGateway, audit: list[dict[str, Any]]
+) -> None:
+ n = act.MAX_HELD_PER_STEP + 1
+ provider = _ScriptedProvider(
+ [_resp(*[_use(APPEND, {"spreadsheet_id": f"sheet-{i:08d}"}, f"tu_{i}") for i in range(n)]),
+ _resp(_text("done"))]
+ )
+ _install(monkeypatch, provider)
+ out = []
+ async for item in act.run_action_step(
+ _step(max_tool_calls=20), workflow_name="w", workflow_title="W", goal="g",
+ values={}, company_block="", prior_outputs={}, policy=_policy(),
+ ):
+ out.append(item)
+ assert len([k for k, _ in out if k == "held"]) == act.MAX_HELD_PER_STEP
+ assert "refused: target check" in out[-1][1] and gateway.calls == []
+
+
+async def test_a_repeated_held_call_is_held_once(
+ monkeypatch: pytest.MonkeyPatch, gateway: _FakeGateway, audit: list[dict[str, Any]]
+) -> None:
+ call = {"spreadsheet_id": OTHER, "rows": [["x"]]}
+ _install(monkeypatch, _ScriptedProvider(
+ [_resp(_use(APPEND, call, "tu_1"), _use(APPEND, dict(call), "tu_2")), _resp(_text("ok"))]
+ ))
+ out = []
+ async for item in act.run_action_step(
+ _step(), workflow_name="w", workflow_title="W", goal="g", values={},
+ company_block="", prior_outputs={}, policy=_policy(),
+ ):
+ out.append(item)
+ assert len([k for k, _ in out if k == "held"]) == 1
+
+
+async def test_oversized_or_uncheckable_calls_are_refused_not_run(
+ monkeypatch: pytest.MonkeyPatch, gateway: _FakeGateway, audit: list[dict[str, Any]]
+) -> None:
+ big = {"spreadsheet_id": OTHER, "rows": [["x" * (act._MAX_HELD_ARGS_CHARS + 1)]]}
+ deep: dict = {"to": "[email protected]"}
+ for _ in range(10):
+ deep = {"a": deep}
+ _install(monkeypatch, _ScriptedProvider(
+ [_resp(_use(APPEND, big, "tu_1"), _use(APPEND, deep, "tu_2")), _resp(_text("ok"))]
+ ))
+ out = []
+ async for item in act.run_action_step(
+ _step(), workflow_name="w", workflow_title="W", goal="g", values={},
+ company_block="", prior_outputs={}, policy=_policy(),
+ ):
+ out.append(item)
+ assert not [k for k, _ in out if k == "held"] and gateway.calls == []
+ assert out[-1][1].count("refused: target check") == 2
+
+
+# --- engine: pause and resume --------------------------------------------------
+
+
+def _held_run(monkeypatch: pytest.MonkeyPatch, approver: int | None = 7) -> list[Any]:
+ monkeypatch.setattr(at, "approver_for", lambda name: approver)
+ _install(monkeypatch, _ScriptedProvider(
+ [_resp(_use(APPEND, {"spreadsheet_id": OTHER, "rows": [["x"]]}, "tu_1")),
+ _resp(_text("One write is waiting."))]
+ ))
+ wf = DynamicWorkflow(_defn())
+
+ async def collect() -> list[Any]:
+ return [e async for e in wf.run(wf.input_model()(), store=None)] # type: ignore[arg-type]
+
+ return asyncio.run(collect())
+
+
+def test_run_pauses_after_the_step_and_asks_the_owner(
+ monkeypatch: pytest.MonkeyPatch, gateway: _FakeGateway, audit: list[dict[str, Any]]
+) -> None:
+ events = _held_run(monkeypatch, approver=7)
+ pause = events[-1]
+ assert isinstance(pause, WaitForHumanEvent)
+ assert pause.person_id == 7 and pause.on_timeout == "auto_proceed"
+ assert OTHER in pause.question and APPEND in pause.question
+ state = pause.resume_state
+ assert state is not None and state.kind == "held_writes"
+ assert state.gate_step_id == "file_bills" and state.gate_step_index == 0
+ assert state.held[0].arguments["spreadsheet_id"] == OTHER
+ assert "file_bills" in state.outputs # the step itself finished
+ assert gateway.calls == []
+
+
+def test_a_step_that_fails_after_holding_says_the_writes_did_not_run(
+ monkeypatch: pytest.MonkeyPatch, gateway: _FakeGateway, audit: list[dict[str, Any]]
+) -> None:
+ monkeypatch.setattr(at, "approver_for", lambda name: 7)
+ _install(monkeypatch, _ScriptedProvider(
+ [_resp(_use(APPEND, {"spreadsheet_id": OTHER}, "tu_1")), RuntimeError("provider down")]
+ ))
+ wf = DynamicWorkflow(_defn())
+ events = asyncio.run(_collect(wf))
+ assert not any(isinstance(e, WaitForHumanEvent) for e in events)
+ assert events[-1].type == "error" and "1 held write(s) were not run" in (events[-1].message or "")
+ assert any("the step failed" in r["details"]["outcome"] for r in audit
+ if r["type"] == "workflow_tool_call")
+
+
+def test_no_one_to_ask_skips_the_held_writes_and_finishes(
+ monkeypatch: pytest.MonkeyPatch, gateway: _FakeGateway, audit: list[dict[str, Any]]
+) -> None:
+ events = _held_run(monkeypatch, approver=None)
+ assert not any(isinstance(e, WaitForHumanEvent) for e in events)
+ artifact = next(e for e in events if getattr(e, "type", "") == "artifact").content or ""
+ assert "skipped (no one to approve it)" in artifact and gateway.calls == []
+
+
+def _resume(wf: DynamicWorkflow, state: WorkflowResumeState, decision: str) -> list[Any]:
+ resolution = WaitForHumanResolution(
+ run_id="run-1", reply_text=decision, source_channel="web",
+ parsed_decision={"decision": decision}, person_id=7,
+ )
+
+ async def collect() -> list[Any]:
+ return [
+ e async for e in wf.resume(
+ inputs=wf.input_model()(), state=state, resolution=resolution,
+ store=None, # type: ignore[arg-type]
+ )
+ ]
+
+ return asyncio.run(collect())
+
+
+def test_approve_runs_exactly_the_held_call_and_remembers_it(
+ monkeypatch: pytest.MonkeyPatch, gateway: _FakeGateway, audit: list[dict[str, Any]]
+) -> None:
+ state = _held_run(monkeypatch)[-1].resume_state
+ events = _resume(DynamicWorkflow(_defn()), state, "approve")
+ assert gateway.calls == [
+ {"name": APPEND, "arguments": {"spreadsheet_id": OTHER, "rows": [["x"]]}}
+ ]
+ artifact = next(e for e in events if e.type == "artifact").content or ""
+ assert f'`{APPEND}` → spreadsheet_id "{OTHER}" — done' in artifact
+ assert OTHER in at.approved_values("file_bills_wf")
+ # The next run writes there without asking.
+ _install(monkeypatch, _ScriptedProvider(
+ [_resp(_use(APPEND, {"spreadsheet_id": OTHER}, "tu_1")), _resp(_text("Filed."))]
+ ))
+ wf = DynamicWorkflow(_defn())
+ again = asyncio.run(_collect(wf))
+ assert not any(isinstance(e, WaitForHumanEvent) for e in again)
+ assert len(gateway.calls) == 2
+
+
+async def _collect(wf: DynamicWorkflow) -> list[Any]:
+ return [e async for e in wf.run(wf.input_model()(), store=None)] # type: ignore[arg-type]
+
+
[email protected](("decision", "reason"), [
+ ("reject", "declined"), ("auto_proceed", "no answer in time"), ("defer", "not approved"),
+])
+def test_anything_but_approve_skips_the_held_call_and_continues(
+ monkeypatch: pytest.MonkeyPatch, gateway: _FakeGateway, audit: list[dict[str, Any]],
+ decision: str, reason: str,
+) -> None:
+ state = _held_run(monkeypatch)[-1].resume_state
+ events = _resume(DynamicWorkflow(_defn()), state, decision)
+ artifact = next(e for e in events if e.type == "artifact").content or ""
+ assert f"skipped ({reason})" in artifact
+ assert gateway.calls == [] and at.approved_values("file_bills_wf") == set()
+
+
+def test_resume_refuses_when_the_steps_changed(
+ monkeypatch: pytest.MonkeyPatch, gateway: _FakeGateway, audit: list[dict[str, Any]]
+) -> None:
+ state = _held_run(monkeypatch)[-1].resume_state
+ edited = _defn(steps=[
+ {"kind": "action", "id": "file_bills", "title": "File bills",
+ "goal": "File them somewhere else.", "tools": [APPEND, READ]},
+ {"kind": "synthesis", "id": "assemble", "title": "Assemble"},
+ ])
+ events = _resume(DynamicWorkflow(edited), state, "approve")
+ assert events[-1].type == "error" and "changed" in (events[-1].message or "")
+ assert gateway.calls == []
+
+
+def test_approved_call_is_skipped_if_its_tool_no_longer_resolves(
+ monkeypatch: pytest.MonkeyPatch, gateway: _FakeGateway, audit: list[dict[str, Any]]
+) -> None:
+ state = _held_run(monkeypatch)[-1].resume_state
+
+ async def _nothing(names: list[str]) -> dict[str, Any]:
+ return {}
+
+ monkeypatch.setattr(act.tool_catalog, "resolve", _nothing)
+ monkeypatch.setattr(
+ "openexecutive.workflows.dynamic.unavailable_step_tools", _async_empty
+ )
+ events = _resume(DynamicWorkflow(_defn()), state, "approve")
+ artifact = next(e for e in events if e.type == "artifact").content or ""
+ assert "skipped (the tool is no longer available to this step)" in artifact
+ assert gateway.calls == []
+
+
+async def _async_empty(*_a: Any, **_k: Any) -> list[str]:
+ return []
+
+
+def test_old_gate_payloads_still_parse_as_gates() -> None:
+ state = WorkflowResumeState.model_validate_json(json.dumps({
+ "workflow_name": "w", "gate_step_id": "g", "gate_step_index": 1,
+ "steps_fingerprint": "x", "outputs": {},
+ }))
+ assert state.kind == "gate" and state.held == [] and state.deliver_to_person_id is None
+
+
+# --- remembered targets and owners -------------------------------------------
+
+
+def test_approved_targets_store_round_trip() -> None:
+ at.remember("wf", [("to", " [email protected] "), ("spreadsheet_id", SHEET)], run_id="r1")
+ at.remember("wf", [("to", "[email protected]")]) # re-approval is a no-op
+ assert at.approved_values("wf") == {"[email protected]", SHEET}
+ assert {t["value"] for t in at.list_targets("wf")} == {"[email protected]", SHEET}
+ assert at.forget("wf", "[email protected]") is True
+ assert at.approved_values("wf") == {SHEET}
+ assert at.approved_values("other") == set()
+
+
+def test_deleting_a_workflow_forgets_its_targets() -> None:
+ dynamic_store.upsert_definition(_defn())
+ at.remember("file_bills_wf", [("spreadsheet_id", SHEET)])
+ assert dynamic_store.delete_definition("file_bills_wf")
+ assert at.approved_values("file_bills_wf") == set()
+
+
+def test_owner_is_set_on_insert_only_and_approver_falls_back() -> None:
+ owner = people_store.upsert_person(full_name="Dana Ops")
+ principal = people_store.upsert_person(full_name="Pat Principal", is_principal=True)
+ dynamic_store.upsert_definition(_defn(), owner_person_id=owner)
+ # Later writes (edit, overwrite, activate) never change it.
+ dynamic_store.upsert_definition(_defn(title="Renamed"), owner_person_id=principal)
+ dynamic_store.set_active("file_bills_wf", False)
+ assert dynamic_store.get_owner("file_bills_wf") == owner
+ assert at.approver_for("file_bills_wf") == owner
+ people_store.archive_person(owner)
+ assert at.approver_for("file_bills_wf") == principal
+ dynamic_store.upsert_definition(_defn(name="unowned_wf"))
+ assert at.approver_for("unowned_wf") == principal
+
+
+# --- HTTP: owner on create, decisions, targets --------------------------------
+
+
+def client(monkeypatch: pytest.MonkeyPatch) -> TestClient:
+ from openexecutive.api.main import create_app
+
+ with TestClient(create_app()) as c:
+ yield c
+
+
+def _caller(monkeypatch: pytest.MonkeyPatch, person_id: int | None) -> None:
+ monkeypatch.setattr(
+ "openexecutive.api.routes.chat._resolve_caller_person_id", lambda _r: person_id
+ )
+
+
+def test_create_records_the_caller_and_ignores_a_client_owner(
+ monkeypatch: pytest.MonkeyPatch, client: TestClient
+) -> None:
+ _caller(monkeypatch, 42)
+ body = {**_defn().model_dump(), "owner_person_id": 99, "steps": [
+ {"kind": "action", "id": "file_bills", "title": "File bills",
+ "goal": "File them.", "tools": ["oe__read_file"]},
+ {"kind": "synthesis", "id": "assemble", "title": "Assemble"},
+ ]}
+ r = client.post("/workflows/custom", json=body)
+ assert r.status_code == 201, r.text
+ assert r.json()["owner_person_id"] == 42
+ _caller(monkeypatch, 7)
+ assert client.put("/workflows/custom/file_bills_wf", json=body).status_code == 200
+ assert client.get("/workflows/custom/file_bills_wf").json()["owner_person_id"] == 42
+
+
+def _awaiting(run_id: str, person_id: int, shape: str = "approve_reject") -> None:
+ wf_persistence.create_run(run_id, "file_bills_wf", "Run", {})
+ state = json.dumps({"question": "OK?", "expected_reply_shape": shape})
+ from datetime import UTC, datetime, timedelta
+
+ wf_persistence.save_checkpoint(run_id, state, person_id, datetime.now(UTC) + timedelta(hours=1))
+
+
+def test_decision_endpoint_authorisation_and_states(
+ monkeypatch: pytest.MonkeyPatch, client: TestClient
+) -> None:
+ asker = people_store.upsert_person(full_name="Dana Ops")
+ other = people_store.upsert_person(full_name="Sam Else")
+ principal = people_store.upsert_person(full_name="Pat Principal", is_principal=True)
+
+ _awaiting("run-a", asker)
+ _caller(monkeypatch, other)
+ assert client.post("/workflows/runs/run-a/decision", json={"decision": "approve"}).status_code == 403
+ _caller(monkeypatch, None)
+ assert client.post("/workflows/runs/run-a/decision", json={"decision": "approve"}).status_code == 403
+ _caller(monkeypatch, asker)
+ assert client.post("/workflows/runs/run-a/decision", json={"decision": "maybe"}).status_code == 422
+ r = client.post("/workflows/runs/run-a/decision", json={"decision": "approve"})
+ assert r.status_code == 200, r.text
+ run = wf_persistence.get_run("run-a")
+ assert run is not None and run["status"] == "resolved"
+ assert json.loads(run["resolution_json"])["parsed_decision"]["decision"] == "approve"
+ # Answered already.
+ assert client.post("/workflows/runs/run-a/decision", json={"decision": "reject"}).status_code == 409
+
+ _awaiting("run-b", asker)
+ _caller(monkeypatch, principal) # the principal can always answer
+ assert client.post("/workflows/runs/run-b/decision", json={"decision": "reject"}).status_code == 200
+
+ _awaiting("run-c", asker, shape="free_text")
+ _caller(monkeypatch, asker)
+ assert client.post("/workflows/runs/run-c/decision", json={"decision": "approve"}).status_code == 409
+ assert client.post("/workflows/runs/nope/decision", json={"decision": "approve"}).status_code == 404
+
+
+def test_targets_routes_list_and_forget(client: TestClient) -> None:
+ dynamic_store.upsert_definition(_defn())
+ at.remember("file_bills_wf", [("spreadsheet_id", SHEET)])
+ listed = client.get("/workflows/custom/file_bills_wf/targets").json()["targets"]
+ assert [t["value"] for t in listed] == [SHEET]
+ assert client.delete(f"/workflows/custom/file_bills_wf/targets?value={SHEET}").status_code == 200
+ assert client.delete(f"/workflows/custom/file_bills_wf/targets?value={SHEET}").status_code == 404
+ assert client.get("/workflows/custom/nope/targets").status_code == 404
+
+
+# --- chat save records the chat caller ------------------------------------------
+
+
+def test_chat_save_records_the_session_caller(monkeypatch: pytest.MonkeyPatch) -> None:
+ from openexecutive.orchestrator import workflow_authoring_tools as wat
+ from openexecutive.orchestrator.schedule_tools import current_session
+
+ definition = {
+ "name": "weekly_watch", "title": "Weekly Watch",
+ "steps": [
+ {"kind": "specialist", "id": "research", "title": "R", "specialist": "cso",
+ "goal": "Analyze."},
+ {"kind": "synthesis", "id": "assemble", "title": "A"},
+ ],
+ }
+ token = current_session.set(SimpleNamespace(caller_person_id=5))
+ try:
+ out = json.loads(asyncio.run(wat.handle_save_workflow(
+ {"definition": definition, "confirm_token": wat._canonical_token(definition)}
+ )))
+ finally:
+ current_session.reset(token)
+ assert out.get("status") == "saved", out
+ assert dynamic_store.get_owner("weekly_watch") == 5
+
+
+# --- scheduled runs -------------------------------------------------------------
+
+
+def test_scheduled_run_pauses_for_held_writes_and_rechains(
+ monkeypatch: pytest.MonkeyPatch, gateway: _FakeGateway, audit: list[dict[str, Any]]
+) -> None:
+ from openexecutive.scheduler import runner
+
+ defn = dynamic_store.upsert_definition(_defn())
+ monkeypatch.setattr(at, "approver_for", lambda name: 7)
+ _install(monkeypatch, _ScriptedProvider(
+ [_resp(_use(APPEND, {"spreadsheet_id": OTHER}, "tu_1")), _resp(_text("Waiting."))]
+ ))
+ checkpoints: list[WaitForHumanEvent] = []
+
+ async def _checkpoint(*, run_id: str, event: WaitForHumanEvent, workflow_title: str = "") -> None:
+ checkpoints.append(event)
+
+ done: list[int] = []
+ chained: list[str] = []
+ completed: list[str] = []
+ dms: list[Any] = []
+
+ async def _dm(payload: dict[str, Any]) -> str:
+ dms.append(payload)
+ return "{}"
+
+ monkeypatch.setattr("openexecutive.orchestrator.schedule_tools.handle_message_person", _dm)
+ monkeypatch.setattr("openexecutive.workflows.gate.checkpoint_gate", _checkpoint)
+ monkeypatch.setattr(runner, "mark_action_done", lambda aid: done.append(aid))
+ monkeypatch.setattr(
+ "openexecutive.workflows.dynamic_cadence.schedule_dynamic_workflow_cadence",
+ lambda d, after=None: chained.append(d.name),
+ )
+ monkeypatch.setattr(
+ "openexecutive.workflows.persistence.complete_run", lambda rid, art: completed.append(rid)
+ )
+ monkeypatch.setattr("openexecutive.knowledge.store.ChromaDBStore", lambda **k: None)
+ action = SimpleNamespace(id=3, channel_ref=defn.name, assigned_to_person_id=11)
+ asyncio.run(runner._run_dynamic_workflow(action, now=__import__("datetime").datetime.now())) # type: ignore[arg-type]
+ assert len(checkpoints) == 1
+ state = checkpoints[0].resume_state
+ assert state is not None and state.kind == "held_writes" and state.deliver_to_person_id == 11
+ assert completed == [] and done == [3] and chained == [defn.name]
+ assert dms == [] # the resumer delivers once the owner answers
+
+
+def test_resumer_delivers_a_scheduled_runs_artifact(monkeypatch: pytest.MonkeyPatch) -> None:
+ from openexecutive.workflows import resumer
+
+ sent: list[dict[str, Any]] = []
+
+ async def _send(payload: dict[str, Any]) -> str:
+ sent.append(payload)
+ return "{}"
+
+ monkeypatch.setattr("openexecutive.orchestrator.schedule_tools.handle_message_person", _send)
+ asyncio.run(resumer._deliver_artifact("run-1", 11, "# Report"))
+ assert sent == [{"person_id": 11, "text": "# Report"}]
+
+
+def test_held_call_model_round_trips_through_resume_json() -> None:
+ state = WorkflowResumeState(
+ workflow_name="w", gate_step_id="s", gate_step_index=0, steps_fingerprint="f",
+ kind="held_writes", deliver_to_person_id=3,
+ held=[HeldCall(tool=APPEND, arguments={"spreadsheet_id": OTHER}, targets=[("spreadsheet_id", OTHER)])],
+ )
+ back = WorkflowResumeState.model_validate_json(state.model_dump_json())
+ assert back == state
+
+
+def test_owner_column_is_added_to_an_existing_table(tmp_path: Path) -> None:
+ import sqlite3
+
+ db = tmp_path / "old.db"
+ with sqlite3.connect(db) as conn:
+ conn.execute(
+ "CREATE TABLE dynamic_workflows (name TEXT PRIMARY KEY, definition TEXT NOT NULL, "
+ "is_active INTEGER NOT NULL DEFAULT 1, created_at TEXT NOT NULL, updated_at TEXT NOT NULL)"
+ )
+ assert dynamic_store.get_owner("x", db_path=db) is None # old DB, no column yet
+ dynamic_store.initialize_dynamic_workflows_db(db)
+ dynamic_store.initialize_dynamic_workflows_db(db) # idempotent
+ dynamic_store.upsert_definition(_defn(), db_path=db, owner_person_id=4)
+ assert dynamic_store.get_owner("file_bills_wf", db_path=db) == 4
+
+
+def test_a_write_verb_anywhere_in_the_name_is_never_read_only() -> None:
+ label = act.tool_catalog._read_only_label
+ assert label("gw__find_and_replace_doc", {}) is None
+ assert label("gw__get_or_create_folder", {}) is None
+ assert label("gw__read_sheet_values", {}) is True
+
+
+
+# --- round 2: target detection edge cases --------------------------------------
+
+
+def test_names_inside_a_resource_and_float_ids_are_targets() -> None:
+ assert act.resource_targets({"repository": {"owner": "acme", "name": "secret-repo"}})[0] == [
+ ("owner", "acme"), ("name", "secret-repo"),
+ ]
+ assert act.resource_targets({"channel": {"name": "exfil"}})[0] == [("name", "exfil")]
+ assert act.resource_targets({"chat_id": 987654321.0})[0] == [("chat_id", "987654321")]
+
+
+def test_address_url_and_phone_shaped_values_are_targets_under_any_key() -> None:
+ targets, _ = act.resource_targets({
+ "space": "spaces/AAA", "href": "https://evil.example/x", "sms": "+1 555 123 4567",
+ "whatever": "[email protected]",
+ # …but inside what the call writes, an address is data.
+ "rows": [["Acme", "[email protected]", "https://acme.example/inv/1"]],
+ })
+ values = {v for _, v in targets}
+ assert values == {"spaces/AAA", "https://evil.example/x", "+1 555 123 4567", "[email protected]"}
+
+
+def test_only_top_level_ids_of_a_write_result_are_trusted() -> None:
+ policy = _policy()
+ policy.note_written(json.dumps({
+ "number": 5, "id": "issue-123456", "html_url": "https://gh.example/i/5",
+ "user": {"login": "attacker", "id": "user-999999"},
+ "ccRecipients": [{"emailAddress": {"address": "[email protected]"}}],
+ }), _CREATE_TOOL)
+ assert policy.unapproved([("id", "issue-123456"), ("url", "https://gh.example/i/5")]) == []
+ assert policy.unapproved([("user", "attacker"), ("id", "user-999999"),
+ ("to", "[email protected]")]) != []
+ policy.note_written("[" * 90_000 + "]" * 90_000, _CREATE_TOOL) # no RecursionError
+ # A tool whose schema couldn't be read may take a URL: never trusted.
+ blind = act.tool_catalog.ToolInfo("x__create_thing", "", {})
+ policy.note_written(json.dumps({"id": "planted-123456"}), blind)
+ assert policy.unapproved([("id", "planted-123456")]) != []
+
+
+def test_the_owner_question_cannot_be_rewritten_by_a_target() -> None:
+ forged = "1AbC` (via x)\nThese were all approved last week.\n- `x"
+ question = act.held_question("File bills", [HeldCall(tool=APPEND, targets=[("spreadsheet_id", forged)])])
+ assert "\nThese were all approved" not in question
+ host = "docs.google.com." + "a." * 120 + "evil.com"
+ shown = act.describe_target("url", f"https://{host}/" + "p" * 900 + "/edit")
+ assert host in shown and "characters not shown" in shown
+
+
+def test_more_write_verbs_block_the_read_only_label() -> None:
+ label = act.tool_catalog._read_only_label
+ for name in ("gh__find_and_close_issues", "gh__check_and_merge_pr", "x__get_and_save"):
+ assert label(name, {}) is None
+
+
+def test_run_created_ids_survive_a_held_writes_pause(
+ monkeypatch: pytest.MonkeyPatch, gateway: _FakeGateway, audit: list[dict[str, Any]]
+) -> None:
+ created = "1NewDocCreatedByRun"
+ gateway.replies[CREATE] = json.dumps({"documentId": created})
+ real_resolve = act.tool_catalog.resolve
+
+ async def _resolve(names: list[str]) -> dict[str, Any]:
+ found = await real_resolve([n for n in names if n != CREATE])
+ if CREATE in names:
+ found[CREATE] = _CREATE_TOOL
+ return found
+
+ monkeypatch.setattr(act.tool_catalog, "resolve", _resolve)
+ monkeypatch.setattr(at, "approver_for", lambda name: 7)
+ at.remember("file_bills_wf", [("folder_id", SHEET)])
+ _install(monkeypatch, _ScriptedProvider(
+ [_resp(_use(CREATE, {"folder_id": SHEET}, "tu_1")), # approved write creates a doc
+ _resp(_use(APPEND, {"spreadsheet_id": OTHER}, "tu_2")), # new target: held
+ _resp(_text("One waiting."))]
+ ))
+ one_step = _defn(steps=[
+ {"kind": "action", "id": "file_bills", "title": "File bills",
+ "goal": "File them.", "tools": [APPEND, CREATE]},
+ {"kind": "synthesis", "id": "assemble", "title": "Assemble"},
+ ])
+ events = asyncio.run(_collect(DynamicWorkflow(one_step)))
+ state = events[-1].resume_state
+ assert created in state.run_created
+ two_steps = _defn(steps=[
+ {"kind": "action", "id": "file_bills", "title": "File bills",
+ "goal": "File them.", "tools": [APPEND, CREATE]},
+ {"kind": "action", "id": "link_doc", "title": "Link doc",
+ "goal": "Write to the new doc.", "tools": [APPEND]},
+ {"kind": "synthesis", "id": "assemble", "title": "Assemble"},
+ ])
+ state = state.model_copy(update={
+ "steps_fingerprint": __import__(
+ "openexecutive.workflows.dynamic", fromlist=["_steps_fingerprint"]
+ )._steps_fingerprint(two_steps)
+ })
+ _install(monkeypatch, _ScriptedProvider(
+ [_resp(_use(APPEND, {"spreadsheet_id": created}, "tu_3")), _resp(_text("Linked."))]
+ ))
+ resumed = _resume(DynamicWorkflow(two_steps), state, "reject")
+ assert not any(isinstance(e, WaitForHumanEvent) for e in resumed)
+ assert gateway.calls[-1]["arguments"] == {"spreadsheet_id": created}
+
+
+def test_a_resume_that_stops_early_audits_its_held_writes(
+ monkeypatch: pytest.MonkeyPatch, gateway: _FakeGateway, audit: list[dict[str, Any]]
+) -> None:
+ state = _held_run(monkeypatch)[-1].resume_state
+ edited = _defn(steps=[
+ {"kind": "action", "id": "file_bills", "title": "File bills",
+ "goal": "Changed.", "tools": [APPEND, READ]},
+ {"kind": "synthesis", "id": "assemble", "title": "Assemble"},
+ ])
+ events = _resume(DynamicWorkflow(edited), state, "approve")
+ assert "1 held write(s) were not run" in (events[-1].message or "")
+ assert any("dropped (the definition changed)" in r["details"]["outcome"] for r in audit
+ if r["type"] == "workflow_tool_call")
+
+
+def test_owner_column_add_tolerates_a_concurrent_add(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ import sqlite3
+ from contextlib import contextmanager
+
+ db = tmp_path / "race.db"
+ dynamic_store.initialize_dynamic_workflows_db(db) # column exists already
+ real = dynamic_store._get_conn
+
+ class _StalePragma:
+ def __init__(self, conn: sqlite3.Connection) -> None:
+ self._conn = conn
+
+ def execute(self, sql: str, *a: Any) -> Any:
+ if sql.startswith("PRAGMA table_info"):
+ return iter([]) # as if read before the other process added it
+ return self._conn.execute(sql, *a)
+
+ @contextmanager
+ def _conn(path: Path): # noqa: ANN202
+ with real(path) as c:
+ yield _StalePragma(c)
+
+ monkeypatch.setattr(dynamic_store, "_get_conn", _conn)
+ dynamic_store.initialize_dynamic_workflows_db(db) # duplicate column -> tolerated
+
+
+def test_key_gaps_and_compound_write_verbs() -> None:
+ targets, _ = act.resource_targets({
+ "reply_to": "[email protected]", "fileID": "f-123456", "idList": "l-123456",
+ "issueKey": "PROJ-12", "members": {"[email protected]": "writer"},
+ })
+ assert {"[email protected]", "f-123456", "l-123456", "PROJ-12", "[email protected]"} <= {
+ v for _, v in targets
+ }
+ label = act.tool_catalog._read_only_label
+ schema = {"type": "object", "properties": {}}
+ assert label("gw__get_or_createfolder", schema) is None
+ assert label("db__query_execute", schema) is None
+ assert label("gw__get_settings", schema) is True
+
+
+def test_changing_the_tool_set_resets_approved_targets() -> None:
+ dynamic_store.upsert_definition(_defn())
+ at.remember("file_bills_wf", [("spreadsheet_id", SHEET)])
+ dynamic_store.upsert_definition(_defn(title="Renamed")) # same tools: kept
+ assert at.approved_values("file_bills_wf") == {SHEET}
+ dynamic_store.upsert_definition(_defn(steps=[
+ {"kind": "action", "id": "file_bills", "title": "File bills",
+ "goal": "File them.", "tools": [APPEND, READ, "oe__message_person"]},
+ {"kind": "synthesis", "id": "assemble", "title": "Assemble"},
+ ]))
+ assert at.approved_values("file_bills_wf") == set()
+
+
+def test_creates_needs_a_whole_create_word_and_no_read_verb() -> None:
+ creates = act.tool_catalog.creates
+ schema = {"type": "object", "properties": {}}
+ for name in ("x__get_copyright_info", "x__list_uploads", "x__get_add_ons", "x__get_makefile"):
+ assert not creates(act.tool_catalog.ToolInfo(name, "", schema)), name
+ for name in ("docs__create_document", "drive__upload_file", "x__copy_file"):
+ assert creates(act.tool_catalog.ToolInfo(name, "", schema)), name
+
+
+def test_invisible_characters_in_a_target_are_escaped() -> None:
+ shown = act.describe_target("to", "a
b‮[email protected]")
+ assert "
" not in shown and "‮" not in shown and "\\u2028" in shown
+
+
+def test_a_conditional_save_that_changes_tools_clears_approvals_in_the_same_write() -> None:
+ first = dynamic_store.save_if_unchanged(_defn(), None)
+ assert first is not None
+ at.remember("file_bills_wf", [("spreadsheet_id", SHEET)])
+ retooled = _defn(steps=[
+ {"kind": "action", "id": "file_bills", "title": "File bills",
+ "goal": "File them.", "tools": [APPEND]},
+ {"kind": "synthesis", "id": "assemble", "title": "Assemble"},
+ ])
+ current = dynamic_store.get_definition("file_bills_wf")
+ assert dynamic_store.save_if_unchanged(retooled, current) is not None
+ assert at.approved_values("file_bills_wf") == set()
diff --git a/packages/core/tests/unit/test_resumer.py b/packages/core/tests/unit/test_resumer.py
index d373a74f..128d9dd7 100644
--- a/packages/core/tests/unit/test_resumer.py
+++ b/packages/core/tests/unit/test_resumer.py
@@ -953,3 +953,65 @@ def test_requeue_with_cutoff_spares_a_freshly_heartbeated_run() -> None:
assert wf_persistence.requeue_run_for_resume(
"res-1", stale_before=datetime.now(UTC) + timedelta(minutes=1)
) is True
+
+
+def _scheduled_resume_state() -> str:
+ state = json.loads(_RESUME_STATE)
+ state["deliver_to_person_id"] = 11
+ return json.dumps(state)
+
+
+def _capture_dms(monkeypatch: pytest.MonkeyPatch) -> list[dict]:
+ sent: list[dict] = []
+
+ async def _send(payload: dict) -> str:
+ sent.append(payload)
+ return "{}"
+
+ monkeypatch.setattr("openexecutive.orchestrator.schedule_tools.handle_message_person", _send)
+ return sent
+
+
+def test_resumed_scheduled_run_dms_its_artifact(monkeypatch: pytest.MonkeyPatch) -> None:
+ """A scheduled run that paused (held writes) completes in the resumer, which
+ makes the delivery the scheduler would have made."""
+ from openexecutive.workflows.resumer import _process_resumable
+
+ sent = _capture_dms(monkeypatch)
+ _resolved(resume_state=_scheduled_resume_state())
+ _install_stub(monkeypatch, _real_workflow())
+ assert asyncio.run(_process_resumable(datetime.now(UTC))) == 1
+ assert sent == [{"person_id": 11, "text": "# Final artifact"}]
+
+ # A run with no scheduled recipient delivers nothing.
+ sent.clear()
+ _resolved(run_id="res-2")
+ _install_stub(monkeypatch, _real_workflow())
+ asyncio.run(_process_resumable(datetime.now(UTC)))
+ assert sent == []
+
+
+def test_a_later_pause_keeps_the_scheduled_recipient(monkeypatch: pytest.MonkeyPatch) -> None:
+ from openexecutive.workflows.resumer import _process_resumable
+ from openexecutive.workflows.wait_for_human import WaitForHumanEvent, WorkflowResumeState
+
+ sent = _capture_dms(monkeypatch)
+ later = WaitForHumanEvent(
+ person_id=7, question="Again?",
+ resume_state=WorkflowResumeState(
+ workflow_name="weekly_watch", gate_step_id="gate", gate_step_index=1,
+ steps_fingerprint="x",
+ ),
+ )
+ checkpointed: list[WaitForHumanEvent] = []
+
+ async def _checkpoint(*, event: WaitForHumanEvent, **_kw: object) -> None:
+ checkpointed.append(event)
+
+ monkeypatch.setattr("openexecutive.workflows.gate.checkpoint_gate", _checkpoint)
+ _resolved(resume_state=_scheduled_resume_state())
+ _install_stub(monkeypatch, _real_workflow([later]))
+ asyncio.run(_process_resumable(datetime.now(UTC)))
+ assert checkpointed[0].resume_state is not None
+ assert checkpointed[0].resume_state.deliver_to_person_id == 11
+ assert sent == []
diff --git a/packages/ui/src/app/jobs/[name]/page.tsx b/packages/ui/src/app/jobs/[name]/page.tsx
index b70df984..50c0cc0d 100644
--- a/packages/ui/src/app/jobs/[name]/page.tsx
+++ b/packages/ui/src/app/jobs/[name]/page.tsx
@@ -4,6 +4,7 @@ import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { useParams, useSearchParams } from "next/navigation";
import Link from "next/link";
import WorkflowRunner from "@/components/WorkflowRunner";
+import ApprovedTargets from "@/components/jobs/ApprovedTargets";
import PendingWorkflowReview from "@/components/jobs/PendingWorkflowReview";
import {
DynamicWorkflowDef,
@@ -365,6 +366,8 @@ export default function JobDetailPage() {
</form>
)}
+ {!running && workflow.is_custom && <ApprovedTargets name={workflow.name} />}
+
{running && (
<WorkflowRunner
workflow={workflow}
diff --git a/packages/ui/src/app/jobs/runs/[id]/page.tsx b/packages/ui/src/app/jobs/runs/[id]/page.tsx
index b6963010..6b0abad0 100644
--- a/packages/ui/src/app/jobs/runs/[id]/page.tsx
+++ b/packages/ui/src/app/jobs/runs/[id]/page.tsx
@@ -9,6 +9,7 @@ import {
GateState,
TERMINAL_RUN_STATUSES,
WorkflowRunDetail,
+ decideWorkflowRun,
getWorkflowRun,
} from "@/lib/api";
import { runStatusLabel, runStatusTextColor } from "@/lib/runStatus";
@@ -182,7 +183,9 @@ export default function RunDetailPage() {
)}
{run.status === "awaiting_human" && (
- <AwaitingPanel run={run} />
+ // Keyed on the question, so a later sign-off in the same run starts
+ // with fresh buttons rather than the previous answer.
+ <AwaitingPanel key={`${run.awaiting_until ?? ""}:${run.state_json ?? ""}`} run={run} />
)}
{run.status === "resolved" && (
@@ -272,6 +275,24 @@ const DELIVERY_NOTES: Record<string, string> = {
function AwaitingPanel({ run }: { run: WorkflowRunDetail }) {
const gate = parseGateState(run.state_json);
+ const [answer, setAnswer] = useState<"approve" | "reject" | null>(null);
+ const [sending, setSending] = useState(false);
+ const [answerError, setAnswerError] = useState<string | null>(null);
+ // Yes/no requests can be answered here; written replies still go via chat.
+ const canAnswer = (gate?.expected_reply_shape ?? "approve_reject") === "approve_reject";
+
+ async function decide(decision: "approve" | "reject") {
+ setSending(true);
+ setAnswerError(null);
+ try {
+ await decideWorkflowRun(run.run_id, decision);
+ setAnswer(decision);
+ } catch (e) {
+ setAnswerError(e instanceof Error ? e.message : String(e));
+ } finally {
+ setSending(false);
+ }
+ }
const delivery = gate?.delivery;
const undelivered = delivery !== undefined && delivery !== "sent" && delivery !== "self";
const deadline = run.awaiting_until
@@ -286,8 +307,37 @@ function AwaitingPanel({ run }: { run: WorkflowRunDetail }) {
{run.awaiting_person_id ? ` from person ${run.awaiting_person_id}` : ""}
</div>
{gate?.question && (
- <div className="text-fg text-sm">&ldquo;{gate.question}&rdquo;</div>
+ <div className="text-fg text-sm whitespace-pre-wrap break-words">
+ &ldquo;{gate.question}&rdquo;
+ </div>
+ )}
+ {canAnswer && !answer && (
+ <div className="flex flex-wrap items-center gap-2 pt-1">
+ <button
+ type="button"
+ onClick={() => void decide("approve")}
+ disabled={sending}
+ className="rounded-md bg-indigo-600 px-3 py-1.5 text-xs font-medium text-white hover:bg-indigo-500 disabled:opacity-50 transition"
+ >
+ Approve
+ </button>
+ <button
+ type="button"
+ onClick={() => void decide("reject")}
+ disabled={sending}
+ className="rounded-md border border-line px-3 py-1.5 text-xs text-fg hover:bg-surface-overlay disabled:opacity-50 transition"
+ >
+ Decline
+ </button>
+ <span className="text-xs text-fg-muted">or reply in chat</span>
+ </div>
+ )}
+ {answer && (
+ <div className="text-xs text-fg">
+ {answer === "approve" ? "Approved" : "Declined"} — the run picks up again in a moment.
+ </div>
)}
+ {answerError && <div className="text-xs text-red-300">{answerError}</div>}
<div className="text-xs space-y-1">
{deadline && <div>Deadline {deadline}.</div>}
{delivery && (
diff --git a/packages/ui/src/components/jobs/ApprovedTargets.tsx b/packages/ui/src/components/jobs/ApprovedTargets.tsx
new file mode 100644
index 00000000..7b656a95
--- /dev/null
+++ b/packages/ui/src/components/jobs/ApprovedTargets.tsx
@@ -0,0 +1,70 @@
+"use client";
+
+import { useEffect, useState } from "react";
+import { ApprovedTarget, forgetApprovedTarget, listApprovedTargets } from "@/lib/api";
+
+/**
+ * Where a custom workflow's tool steps may write without asking again. Each
+ * entry was approved the first time the workflow wrote there; removing one
+ * means the next write there asks again.
+ */
+export default function ApprovedTargets({ name }: { name: string }) {
+ const [targets, setTargets] = useState<ApprovedTarget[] | null>(null);
+ const [error, setError] = useState<string | null>(null);
+
+ useEffect(() => {
+ let cancelled = false;
+ listApprovedTargets(name)
+ .then((t) => {
+ if (!cancelled) setTargets(t);
+ })
+ .catch(() => {
+ if (!cancelled) setTargets([]);
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, [name]);
+
+ async function remove(value: string) {
+ setError(null);
+ try {
+ await forgetApprovedTarget(name, value);
+ setTargets((t) => (t ?? []).filter((x) => x.value !== value));
+ } catch (e) {
+ setError(e instanceof Error ? e.message : String(e));
+ }
+ }
+
+ if (!targets || targets.length === 0) return null;
+
+ return (
+ <details className="rounded-md border border-line bg-surface/40 px-3 py-2 text-sm">
+ <summary className="cursor-pointer text-fg">
+ Approved targets <span className="text-fg-muted">({targets.length})</span>
+ </summary>
+ <p className="mt-2 text-xs text-fg-muted">
+ This workflow can write to these without asking. Remove one and the next
+ write there asks again.
+ </p>
+ <ul className="mt-2 divide-y divide-line/60">
+ {targets.map((t) => (
+ <li key={t.value} className="flex items-center gap-3 py-1.5 min-w-0">
+ <span className="shrink-0 text-[11px] text-fg-subtle">{t.key}</span>
+ <code className="min-w-0 flex-1 truncate text-xs text-fg" title={t.value}>
+ {t.value}
+ </code>
+ <button
+ type="button"
+ onClick={() => void remove(t.value)}
+ className="shrink-0 text-[11px] text-fg-muted hover:text-red-400 transition"
+ >
+ Remove
+ </button>
+ </li>
+ ))}
+ </ul>
+ {error && <p className="mt-1 text-xs text-red-300">{error}</p>}
+ </details>
+ );
+}
diff --git a/packages/ui/src/components/jobs/WorkflowDraftReview.tsx b/packages/ui/src/components/jobs/WorkflowDraftReview.tsx
index be0d6240..9b270b1a 100644
--- a/packages/ui/src/components/jobs/WorkflowDraftReview.tsx
+++ b/packages/ui/src/components/jobs/WorkflowDraftReview.tsx
@@ -145,6 +145,11 @@ export default function WorkflowDraftReview({
{pending ? "Waiting for your approval · off" : "Draft workflow"}
</p>
<h3 className="text-base font-semibold text-fg">{def.title}</h3>
+ {def.owner_person_id != null && (
+ <p className="text-xs text-fg-subtle mt-0.5">
+ Created by {personName(people, def.owner_person_id)}
+ </p>
+ )}
{def.description && (
<p className="text-sm text-fg-muted mt-0.5">{def.description}</p>
)}
diff --git a/packages/ui/src/lib/api.ts b/packages/ui/src/lib/api.ts
index e3d6c64d..4adce212 100644
--- a/packages/ui/src/lib/api.ts
+++ b/packages/ui/src/lib/api.ts
@@ -1188,6 +1188,9 @@ export interface DynamicWorkflowDef {
is_active?: boolean;
created_at?: string;
updated_at?: string;
+ // Who created it (server-managed; echoing it back in a body has no effect).
+ // Asked to approve the workflow's first write to a new target.
+ owner_person_id?: number | null;
}
// The 8 specialists a dynamic step may consult (matches SPECIALIST_REGISTRY,
@@ -1281,6 +1284,28 @@ export async function activateCustomWorkflow(
return res.json();
}
+/** A target a workflow's tool steps may write to without asking again. */
+export interface ApprovedTarget {
+ value: string;
+ key: string;
+ approved_at: string;
+ run_id: string;
+}
+
+export async function listApprovedTargets(name: string): Promise<ApprovedTarget[]> {
+ const res = await fetch(`${API_BASE}/workflows/custom/${encodeURIComponent(name)}/targets`);
+ if (!res.ok) throw await _customError(res);
+ return (await res.json()).targets;
+}
+
+export async function forgetApprovedTarget(name: string, value: string): Promise<void> {
+ const res = await fetch(
+ `${API_BASE}/workflows/custom/${encodeURIComponent(name)}/targets?value=${encodeURIComponent(value)}`,
+ { method: "DELETE" }
+ );
+ if (!res.ok) throw await _customError(res);
+}
+
export async function deleteCustomWorkflow(name: string): Promise<void> {
const res = await fetch(`${API_BASE}/workflows/custom/${encodeURIComponent(name)}`, {
method: "DELETE",
@@ -1517,6 +1542,19 @@ export async function listWorkflowRuns(
return data.runs;
}
+/** Answer a run waiting on a yes/no sign-off (the person asked, or the principal). */
+export async function decideWorkflowRun(
+ runId: string,
+ decision: "approve" | "reject"
+): Promise<void> {
+ const res = await fetch(`${API_BASE}/workflows/runs/${encodeURIComponent(runId)}/decision`, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ decision }),
+ });
+ if (!res.ok) throw await _customError(res);
+}
+
export async function getWorkflowRun(runId: string): Promise<WorkflowRunDetail> {
const res = await fetch(`${API_BASE}/workflows/runs/${encodeURIComponent(runId)}`);
if (!res.ok) throw new Error("Failed to load workflow run");