Skip to content

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

fix: hold escalations, allow cancel, and keep roster edits owner-only (#216)

Rufus4975dfffc9be
diff --git a/packages/core/openexecutive/api/routes/scheduled.py b/packages/core/openexecutive/api/routes/scheduled.py
index 1b47e8a7..cdb95b99 100644
--- a/packages/core/openexecutive/api/routes/scheduled.py
+++ b/packages/core/openexecutive/api/routes/scheduled.py
@@ -1,8 +1,9 @@
-"""Admin endpoints for inspecting and cancelling proactive scheduled actions."""
+"""Endpoints for inspecting and cancelling proactive scheduled actions."""
from __future__ import annotations
import hmac
import logging
+import os
from fastapi import APIRouter, Depends, Header, HTTPException, Request, status
@@ -20,46 +21,74 @@ logger = logging.getLogger(__name__)
_VALID_STATUS_FILTERS = {"pending", "running", "done", "failed", "cancelled"}
_LOOPBACK_HOSTS = {"127.0.0.1", "::1", "localhost"}
+_MAX_ACTOR_LEN = 200
-def require_admin_token(
+def _signed_in_caller(request: Request) -> str | None:
+ """The signed-in user's email when the request came through the UI proxy.
+
+ The proxy (packages/ui/src/app/api/backend/[...path]/route.ts) strips any
+ client-sent ``x-caller-*`` header and stamps ``x-caller-email`` from the
+ verified sign-in, next to the ``x-api-key`` shared secret. The email is only
+ trusted when that secret is configured AND this request carries it: with
+ ``BACKEND_SHARED_SECRET`` unset, anyone who can reach the API could write
+ the header themselves.
+ """
+ secret = os.environ.get("BACKEND_SHARED_SECRET", "").strip()
+ if not secret:
+ return None
+ provided = request.headers.get("x-api-key", "")
+ if not hmac.compare_digest(provided.encode(), secret.encode()):
+ return None
+ email = (request.headers.get("x-caller-email") or "").strip().lower()
+ return email[:_MAX_ACTOR_LEN] or None
+
+
+def require_cancel_permission(
request: Request,
x_admin_token: str | None = Header(default=None, alias="X-Admin-Token"),
-) -> None:
- """Gate destructive scheduled-action endpoints. Fails closed by default.
-
- Three cases:
- - SCHEDULED_ADMIN_TOKEN is set → must match the header (constant-time compare).
- - SCHEDULED_ADMIN_TOKEN is unset and request comes from loopback → allowed
- (convenient for `make dev`).
- - SCHEDULED_ADMIN_TOKEN is unset and request comes from a remote host → 503,
- forcing operators to set the token before exposing the endpoint.
-
- Applied only to DELETE (cancel) — GETs are unauthenticated to match the
- /memories/* routes the Memories UI already consumes.
+) -> str:
+ """Gate cancelling a scheduled action; returns who is cancelling, for the audit row.
+
+ Cancelling only stops something from happening — the same "safe
+ direction" that lets any signed-in user pause the Executive
+ (routes/executive.py) — so it is allowed for:
+ - a matching ``X-Admin-Token`` when SCHEDULED_ADMIN_TOKEN is set (scripts);
+ - a signed-in user coming through the UI proxy (``_signed_in_caller``), so
+ the Pulse page's Cancel button works on a deployed server, not only
+ under `make dev`;
+ - a loopback caller when no admin token is configured (`make dev`, curl).
+
+ Anything else fails closed: 401 when an admin token is configured, 503
+ otherwise. GETs stay unauthenticated to match the /memories/* routes the
+ Pulse page already reads.
"""
expected = get_settings().scheduled_admin_token
+ if (
+ expected
+ and x_admin_token is not None
+ and hmac.compare_digest(x_admin_token.encode(), expected.encode())
+ ):
+ return "admin-token"
+ caller = _signed_in_caller(request)
+ if caller:
+ return caller
client_host = request.client.host if request.client else ""
- is_loopback = client_host in _LOOPBACK_HOSTS
-
+ if not expected and client_host in _LOOPBACK_HOSTS:
+ return "local"
if expected:
- if x_admin_token is None or not hmac.compare_digest(
- x_admin_token, expected
- ):
- raise HTTPException(
- status_code=status.HTTP_401_UNAUTHORIZED,
- detail="Invalid or missing X-Admin-Token",
- )
- return
-
- if not is_loopback:
raise HTTPException(
- status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
- detail=(
- "Scheduled-action admin endpoints are disabled. Set "
- "SCHEDULED_ADMIN_TOKEN to enable them for non-loopback access."
- ),
+ status_code=status.HTTP_401_UNAUTHORIZED,
+ detail="Invalid or missing X-Admin-Token",
)
+ raise HTTPException(
+ status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
+ detail=(
+ "Cancelling scheduled actions is disabled for this caller. Set the "
+ "same BACKEND_SHARED_SECRET on the API and the UI so signed-in users "
+ "can cancel, or SCHEDULED_ADMIN_TOKEN for scripts."
+ ),
+ )
@router.get(
@@ -101,9 +130,10 @@ def get_scheduled(action_id: int) -> ScheduledAction:
@router.delete(
"/scheduled/{action_id}",
response_model=ScheduledAction,
- dependencies=[Depends(require_admin_token)],
)
-def cancel_scheduled(action_id: int) -> ScheduledAction:
+def cancel_scheduled(
+ action_id: int, actor: str = Depends(require_cancel_permission)
+) -> ScheduledAction:
result = cancel_scheduled_action(action_id)
if result == "not_found":
raise HTTPException(status_code=404, detail="scheduled action not found")
@@ -115,4 +145,17 @@ def cancel_scheduled(action_id: int) -> ScheduledAction:
row = get_scheduled_action(action_id)
if row is None: # pragma: no cover — defensive
raise HTTPException(status_code=404, detail="scheduled action not found")
+ from openexecutive.audit import log_event as audit_log
+
+ audit_log(
+ "scheduled_action_cancelled",
+ f"Cancelled scheduled {row.kind} #{action_id}: {row.intent_text[:120]}",
+ actor=actor,
+ details={
+ "action_id": action_id,
+ "kind": row.kind,
+ "channel": row.channel,
+ "department": row.department or None,
+ },
+ )
return row
diff --git a/packages/core/openexecutive/architecture/architecture-facts.yaml b/packages/core/openexecutive/architecture/architecture-facts.yaml
index c327929f..924266e7 100644
--- a/packages/core/openexecutive/architecture/architecture-facts.yaml
+++ b/packages/core/openexecutive/architecture/architecture-facts.yaml
@@ -621,6 +621,32 @@ routing:
`ensure_head_persona_override` so the head-voice plumbing fires.
Every invocation emits a `tool_invocation` audit event with
actor="executive".
+
+ The three WRITE tools are the principal's alone, and only on a surface
+ that verified the speaker (`_refuse_unless_owner`): the web chat
+ (`Session.from_web_chat`, the signed-in Google account) or the
+ principal's own Slack / Discord (`origin_channel`, the platform's user
+ id over an authenticated connection), or a PRIVATE Telegram chat only
+ when TELEGRAM_WEBHOOK_SECRET is set — Telegram identifies the chat, not
+ the sender (a group is all its members), and /webhook/telegram is
+ exempt from the shared secret, so without the webhook secret anyone
+ can post an update naming the principal's chat id
+ (`_is_verified_speaker_surface`). `is_principal_or_self(caller, None)`
+ decides, so an archived principal is refused too. Everything else gets
+ `{"status": "refused", "detail": ...}` — a rostered teammate on any
+ surface, a signed-in web user whose email is on no People row (told to
+ link their email on the People page), and every unverified surface:
+ email (the poller resolves the From header, which proves nothing —
+ even the principal's address), Google Chat (no sender identity), the
+ CLI, the MCP server, and unattended runs (no `current_session`). Why:
+ these tools are offered on every turn, and a People row is the web
+ sign-in allow-list, the outbound-email allow-list and approval routing
+ at once — a crafted inbound email or a teammate could otherwise add an
+ address that can then sign in and receive mail, or grant themselves
+ WILDCARD. Refusals are audited (`tool_invocation`, ok=false,
+ refused=true, with caller / origin_channel / from_web_chat) and render
+ no action chip. `list_people` stays open. The People page (behind the
+ web sign-in) is unaffected.
department_tools: |
`list_department_goals` and `update_department_goal`
(openexecutive.orchestrator.department_tools) let the Executive
@@ -2059,7 +2085,10 @@ people:
executive_write_access: |
The Executive can mutate the roster directly without going through the
UI via the `list_people` / `upsert_person` / `archive_person` /
- `set_department_head` tools (openexecutive.orchestrator.people_tools).
+ `set_department_head` tools (openexecutive.orchestrator.people_tools) —
+ but only when the principal asks from the web chat, their own Slack or
+ Discord, or a private Telegram chat with TELEGRAM_WEBHOOK_SECRET set;
+ anyone and anything else is refused.
See `routing.people_tools` for details.
brief_insights: |
openexecutive.people.insights generates a one-line per-person note for the
@@ -2155,11 +2184,42 @@ scheduler:
init, bounded by an `app_migrations` marker row (runs once per DB).
Department-scoped
actions pass through the authority gate first
- (`departments.authority.gate_action`), which can `propose` (route to
- an approver via alert, not dispatched), `escalate` (alert + dispatch),
- `allow`, or defer to the approver's next available window. Nudge
- engine emissions set `department=""` to bypass the gate — they are
- about reaching the approver, not a dept-scoped operation.
+ (`departments.authority.gate_action`), which can `execute`
+ (auto_execute: dispatch), `propose` (route to an approver via alert,
+ not dispatched; deferred to the approver's next available window when
+ they are outside it) or `escalate` (an urgent "[ESCALATION]" alert to
+ the approver right away, never deferred, and NOT dispatched — the row
+ is marked done and the card's "If you approve: … right away" line is
+ what sends it). Because that card is the action's only trace, it is
+ never silently lost: severity high, filed unrouted when nobody holds
+ the scope and no principal is set (the Briefing lists every unread
+ card), and deduped on the whole action — kind, channel, recipient and
+ intent (`escalate_via_alert` → `propose_via_alert(dedup_on=...)`) — rather than the summary's
+ first 60 characters, so another escalation that shares an opening, or
+ the same text for someone else, cannot swallow it. An identical
+ escalation folds into a still-open card and gets a fresh one once that
+ card was handled (the action id is the external-id suffix), and a card
+ that cannot be written (`raise_errors=True`) retries the row with
+ backoff and, once the retries are spent, marks it `failed` (logged as
+ an error) — never `done`. `escalate` used to raise the alert AND dispatch, which
+ contradicted the UI's "the specialist will not act" and sent the
+ action twice once the card was approved. A gated `dept_cadence` row
+ becomes a card and does not chain its next occurrence (re-bootstrapped
+ at startup) — true of propose_only departments before this change too.
+ Nudge engine emissions set `department=""` to bypass the gate — they
+ are about reaching the approver, not a dept-scoped operation.
+ Cancelling: DELETE /scheduled/{id} (the Pulse page's Cancel) soft-
+ cancels a `pending` row (409 otherwise; the UPDATE is itself guarded
+ on status='pending', so a row the scheduler claimed in between is
+ never overwritten). Like pause it only stops
+ work, so any signed-in user may: `require_cancel_permission` accepts
+ a matching X-Admin-Token (SCHEDULED_ADMIN_TOKEN, scripts), a signed-in
+ user through the UI proxy — `x-caller-email` trusted only when the
+ request also carries the BACKEND_SHARED_SECRET `x-api-key` — or a
+ loopback caller when no admin token is set; else 401 (token set) /
+ 503. Each cancel is audited `scheduled_action_cancelled` with the
+ caller's email, "admin-token" or "local" as actor. Before this the UI
+ could never send the admin token, so Cancel failed on every deploy.
nudge_engine: |
openexecutive.scheduler.nudge_engine — periodic heartbeat (kind=
`nudge_scan`, default every 15 min via NUDGE_SCAN_INTERVAL_MINUTES)
@@ -2493,6 +2553,7 @@ audit:
- watchlist_auto_disabled — the sweep disabled a research-origin watch (`reason`: dismissed N of M alerts with low trust; no signals in 30 days; 3 consecutive poll failures). Renders in the HANDLED block as `stopped_watching`; re-enable from /watchlist.
- auth_login / auth_logout — admin auth events
- executive_paused / executive_resumed — the operator pause switch flipped (scheduler.pause). actor is the caller's email (else "api"); details carry the reason on pause, and paused_at / paused_by / held_actions on resume. Re-pausing or re-resuming writes nothing.
+ - scheduled_action_cancelled — a pending scheduled action cancelled via DELETE /scheduled/{id} (the Pulse page's Cancel, or a script). actor is the signed-in caller's email, "admin-token" or "local"; details carry action_id, kind, channel and department. A refused or 409 cancel writes nothing.
turn_id: Set per Executive turn (`f"t-{uuid12}"`) and propagated automatically to retriever / specialist / tool / cache / committee emits via `openexecutive.audit.context` ContextVars. Groups every row in one user-assistant exchange under the same `turn_id`; the session view derives causal edges from this.
writer: openexecutive.audit.AuditLogger — synchronous SQLite writer; uses WAL + 5s busy_timeout so concurrent webhook/scheduler/poller threads don't see "database is locked".
failure_mode: All writes swallow exceptions and log a warning — an audit failure must never break a chat turn or tool call. The post-response cache_event emit also `getattr`-guards every usage field so a provider that omits one still produces a row.
@@ -5154,17 +5215,20 @@ for_executives:
tools), routes it to whoever holds the "approve money under
$10k" tag, and waits. No payment moves until they say yes.
escalate:
- label: Escalate to the principal (escalate)
+ label: Escalate to a human (escalate)
meaning: |
- For live, time-sensitive signal — an interested customer
- replying, a competitor moving, a board-level event — Open
- Executive both alerts the principal AND ships the immediate
- response in the same beat. You hear about it now; you don't
- wait for the morning brief.
+ For work too sensitive or time-critical for the routine queue —
+ legal, a board-level event, a key customer upset — Open Executive
+ drafts the response and puts it in front of the right person
+ straight away, flagged urgent, even outside their working hours.
+ Nothing is sent until they approve; approving sends it right away.
+ (It used to send first and alert at the same time, which is not
+ what "escalate to a human" promises.)
example: |
- A prospect replies on LinkedIn. Open Executive drafts the
- acknowledgement, holds 30 minutes on the calendar, and pings
- the principal so they're in the loop before the day ends.
+ A customer's lawyer emails about a contract dispute. Legal is set
+ to escalate, so Open Executive drafts the holding reply and the
+ general counsel sees an urgent card within minutes — but the reply
+ only goes out when they approve it.
proactive_examples: |
What Open Executive does when you're not in a chat with it:
- Sends a morning brief (state of departments, what needs your
diff --git a/packages/core/openexecutive/architecture/prebuilt/agents.json b/packages/core/openexecutive/architecture/prebuilt/agents.json
index b16e252f..73cb9a38 100644
--- a/packages/core/openexecutive/architecture/prebuilt/agents.json
+++ b/packages/core/openexecutive/architecture/prebuilt/agents.json
@@ -1,7 +1,7 @@
{
"section_id": "agents",
"title": "Agent Council",
- "markdown": "The Executive (`openexecutive.orchestrator.executive.Executive`) is a single coherent persona that fans out to specialist sub-agents via Anthropic tool use. Each specialist subclasses `openexecutive.agents.base.BaseAgent`, carrying a `name`, `domain`, and `model`, and exposes `analyze(...)`, which wraps the question in user-turn context and calls Claude through the per-call provider.\n\nRouting uses one `consult_specialist` tool. Beside it the Executive carries its skill tools (`search_skills`, `load_skill`, `create_skill`, `update_skill`, `delete_skill` — shown to users as **playbooks**; `create_skill` / `update_skill` / `delete_skill` never change the library — they save a draft (`knowledge/skill_drafts.py`) that a person approves on the Playbooks tab, and the reply links to it; `update_skill` / `delete_skill` (and `create_skill`, for a name a workflow still follows) refuse any built-in name (including a company's customized copy) and any company playbook a workflow (even a switched-off custom one) follows — workflows read playbooks at run time, approved scheduled ones included, and this loop also runs on inbound email and chat, so only a person on the Playbooks tab can change what a workflow follows; a hidden built-in is invisible to search and load; each `search_skills` hit lists the `workflows` that follow it, and the persona routes \"the finished deliverable\" to that workflow and quick or partial asks to the playbook inline); Tool calls made while proactive work is tagged (scheduler dispatch, reflection, research, alert review) feed the Attunement outcome ledger. Attunement adds `list_open_loops` (what a person owes — everyone's for the principal only in a private conversation, otherwise the caller's own) and `close_open_loop`, which only closes a loop when the turn's resolved speaker is the principal or the loop's owner — an unrostered sender, a signed-in web user not on the roster, and unattended sessions are refused. Multiple parallel `tool_use` blocks in a single assistant turn fan out concurrently through `router.route_parallel`, each running its own domain-filtered ChromaDB query before the specialist sees the question. The Executive then synthesizes the returned analyses into one reply.\n\nThe nine entries in `SPECIALIST_REGISTRY` (`openexecutive.orchestrator.router`):\n\n| Key | Agent | Domain |\n| --- | --- | --- |\n| `cso` | `StrategyAgent` | strategy |\n| `cfo` | `FinanceAgent` | finance |\n| `chro` | `HRAgent` | hr |\n| `gc` | `LegalAgent` | legal |\n| `coo` | `OperationsAgent` | operations |\n| `cmo` | `MarketingAgent` | marketing |\n| `cpo` | `ProductAgent` | product |\n| `board_comms` | `BoardCommsAgent` | board |\n| `triage` | `TriageAgent` | triage |\n\nModels: specialists default to `claude-sonnet-5`; a deep-reasoning tier uses `claude-opus-5` (adaptive thinking); routing/fast classification uses `claude-haiku-4-5`. The Council's **Deep reasoning** toggle is honoured on Claude Opus/Sonnet (direct or via OpenRouter) and on any OpenRouter model whose live catalog entry supports `reasoning` (today all OpenAI, Gemini, DeepSeek and Grok entries; not Llama) — the request translator turns Anthropic adaptive thinking + effort into OpenRouter's `reasoning` parameter. It is a silent no-op on models that can't reason, and disabled for Haiku, which rejects adaptive thinking. The Council picks a model in two steps: a **Provider** dropdown (Anthropic, OpenAI, Google, Meta, DeepSeek, xAI, Local, …), then a **Model** dropdown limited to that provider, with readable names (\"Claude Opus 5.5\") and the raw id and serving route shown underneath. The Anthropic group combines the direct Claude models (`claude-fable-5-1`, `claude-opus-5-5`, `claude-opus-5`, `claude-sonnet-5`, `claude-haiku-4-5`) with any Claude generation that exists only on OpenRouter, and never lists a model twice. With `OPENROUTER_ENABLED`, the non-Anthropic entries come from OpenRouter's live `/models` catalog (fetched at startup, refreshed in the background, filtered to tool-capable paid text models from an allowlisted vendor set), falling back to a built-in snapshot if the fetch fails. Eight Council-only agents are model/prompt-overridable in the UI but NOT callable via `consult_specialist`, because they are deliberately kept out of `SPECIALIST_REGISTRY`: `quality_judge` (committee review), `utility_fast` (gates, titles, decision parsing), `research` (the `executive_research` fan-out), `fixture_generator` (invents demo companies), `engagement_intake` (models a real client from intake material), `onboarding_interviewer` (interviews a new user about their own company and drafts its profile, people and departments), `workflow_designer` (runs the conversational New workflow wizard on `/jobs/new`: searches the available tools, asks clarifying questions, then drafts a validated dynamic-workflow definition for the user to review), and `workflow_actor` (runs a workflow's `action` steps: a bounded tool-use loop limited to the tools the user approved for that step). `fixture_generator`, `engagement_intake` and `onboarding_interviewer` share one shape — a forced tool call producing a whole company, validated for referential integrity, with a single repair retry — but opposite epistemics: the fixture author invents, the other two extract and leave unstated facts empty rather than guessing.\n\nOne more structured-output utility agent sits beside `triage`: `openexecutive.agents.alert_review.AlertReviewAgent` (routing model, one forced `emit_alert_reviews` tool call, never raises). The alert review job hands it a batch of open alerts with evidence and gets back, per alert, a verdict (relevant / changed / resolved / stale), a confidence, the evidence it relied on, a one-line note, why-now, an optional deadline, and a recommended move (none / route / nudge / escalate / draft / suggest_workflow / merge / close) with its parameters. Like `triage`, it never mutates state — `alerts.review.apply_verdict` executes the verdicts deterministically within authority, so the model's job is judgment, not action.\n\nEvery specialist *advises* — each returns domain analysis the Executive synthesizes into one voice. None of them act on the company's behalf; the side-effecting tools in the main loop (schedule, people, departments, broadcast, watchlist, workflows) belong to the Executive, not to a specialist.\n\nThe Executive can also launch *any* workflow conversationally: `orchestrator.workflow_run_tools` adds `list_workflows` (the launchable catalog with each workflow's inputs) and `run_workflow` (runs a built-in or custom workflow to completion and returns its artifact, checkpointing approval gates as `awaiting_human`). This makes the `/jobs` catalog reachable from chat — see the Workflows section.\n\nDeliverables are first-class too. `orchestrator.artifact_tools` gives the Executive three tools: `draft_artifact` publishes a memo, web page (`html`), Word document (`docx`), spreadsheet (`xlsx`, from structured `sheets`) or a `link` to something it created in one of the principal's connected apps through the generic MCP gateway (`search_tools` → `call_tool`, any server — no vendor is named), and returns the artifact's id and link; `list_artifacts` and `get_artifact` let it find and reread its own past work (drafts and workflow outputs alike, through the same `artifact_records` read model the API uses). Revising is `draft_artifact(supersedes=<id>)`, which archives the earlier version. When the principal asks for a deliverable the tool is always used; the \"quiet is the right default\" bar applies only to unprompted drafts. The format enum is a hard-coded sorted tuple so the cached tool schema stays byte-stable. Delivery: `message_person(person_id, text, artifact_id?)` appends the artifact's title and a `UI_BASE_URL/artifacts/<id>` link (through the same outbound guard as any DM; the link needs Open Executive access), and a Gmail send/draft can attach the file itself by `artifact_id` — see Integrations.\n\nThe Executive also backs the **Ask OE** panel's form-fill tier via `orchestrator.form_tools.propose_form_values`: when a chat turn arrives with a `<page_context>` block describing a form on the user's screen, the Executive can propose values for it. The proposal is delivered to the UI as a `form_patch` SSE event and placed into the form as highlighted suggestions — the tool never saves or submits anything; the user reviews and saves manually. The tool is **always** in the tool list (tool definitions sit at the top of the cached prompt prefix, so a conditionally-present tool would invalidate the prompt cache whenever panel and non-panel turns alternate); its description restricts usage to turns that carry a form descriptor.",
+ "markdown": "The Executive (`openexecutive.orchestrator.executive.Executive`) is a single coherent persona that fans out to specialist sub-agents via Anthropic tool use. Each specialist subclasses `openexecutive.agents.base.BaseAgent`, carrying a `name`, `domain`, and `model`, and exposes `analyze(...)`, which wraps the question in user-turn context and calls Claude through the per-call provider.\n\nRouting uses one `consult_specialist` tool. Beside it the Executive carries its skill tools (`search_skills`, `load_skill`, `create_skill`, `update_skill`, `delete_skill` — shown to users as **playbooks**; `create_skill` / `update_skill` / `delete_skill` never change the library — they save a draft (`knowledge/skill_drafts.py`) that a person approves on the Playbooks tab, and the reply links to it; `update_skill` / `delete_skill` (and `create_skill`, for a name a workflow still follows) refuse any built-in name (including a company's customized copy) and any company playbook a workflow (even a switched-off custom one) follows — workflows read playbooks at run time, approved scheduled ones included, and this loop also runs on inbound email and chat, so only a person on the Playbooks tab can change what a workflow follows; a hidden built-in is invisible to search and load; each `search_skills` hit lists the `workflows` that follow it, and the persona routes \"the finished deliverable\" to that workflow and quick or partial asks to the playbook inline); Tool calls made while proactive work is tagged (scheduler dispatch, reflection, research, alert review) feed the Attunement outcome ledger. Attunement adds `list_open_loops` (what a person owes — everyone's for the principal only in a private conversation, otherwise the caller's own) and `close_open_loop`, which only closes a loop when the turn's resolved speaker is the principal or the loop's owner — an unrostered sender, a signed-in web user not on the roster, and unattended sessions are refused. The roster write tools (`upsert_person`, `archive_person`, `set_department_head`) are the principal's alone, and only on a surface that verified the speaker — the web chat, the principal's own Slack or Discord, or a private Telegram chat when `TELEGRAM_WEBHOOK_SECRET` is set (Telegram identifies the chat rather than the sender, and without that secret its webhook accepts anyone's update). A teammate, an email (even from the principal's address), Google Chat, the CLI, the MCP server and unattended runs get `status: refused` (audited, and no action chip), because a People row is also the web sign-in and outbound-email allow-list. Multiple parallel `tool_use` blocks in a single assistant turn fan out concurrently through `router.route_parallel`, each running its own domain-filtered ChromaDB query before the specialist sees the question. The Executive then synthesizes the returned analyses into one reply.\n\nThe nine entries in `SPECIALIST_REGISTRY` (`openexecutive.orchestrator.router`):\n\n| Key | Agent | Domain |\n| --- | --- | --- |\n| `cso` | `StrategyAgent` | strategy |\n| `cfo` | `FinanceAgent` | finance |\n| `chro` | `HRAgent` | hr |\n| `gc` | `LegalAgent` | legal |\n| `coo` | `OperationsAgent` | operations |\n| `cmo` | `MarketingAgent` | marketing |\n| `cpo` | `ProductAgent` | product |\n| `board_comms` | `BoardCommsAgent` | board |\n| `triage` | `TriageAgent` | triage |\n\nModels: specialists default to `claude-sonnet-5`; a deep-reasoning tier uses `claude-opus-5` (adaptive thinking); routing/fast classification uses `claude-haiku-4-5`. The Council's **Deep reasoning** toggle is honoured on Claude Opus/Sonnet (direct or via OpenRouter) and on any OpenRouter model whose live catalog entry supports `reasoning` (today all OpenAI, Gemini, DeepSeek and Grok entries; not Llama) — the request translator turns Anthropic adaptive thinking + effort into OpenRouter's `reasoning` parameter. It is a silent no-op on models that can't reason, and disabled for Haiku, which rejects adaptive thinking. The Council picks a model in two steps: a **Provider** dropdown (Anthropic, OpenAI, Google, Meta, DeepSeek, xAI, Local, …), then a **Model** dropdown limited to that provider, with readable names (\"Claude Opus 5.5\") and the raw id and serving route shown underneath. The Anthropic group combines the direct Claude models (`claude-fable-5-1`, `claude-opus-5-5`, `claude-opus-5`, `claude-sonnet-5`, `claude-haiku-4-5`) with any Claude generation that exists only on OpenRouter, and never lists a model twice. With `OPENROUTER_ENABLED`, the non-Anthropic entries come from OpenRouter's live `/models` catalog (fetched at startup, refreshed in the background, filtered to tool-capable paid text models from an allowlisted vendor set), falling back to a built-in snapshot if the fetch fails. Eight Council-only agents are model/prompt-overridable in the UI but NOT callable via `consult_specialist`, because they are deliberately kept out of `SPECIALIST_REGISTRY`: `quality_judge` (committee review), `utility_fast` (gates, titles, decision parsing), `research` (the `executive_research` fan-out), `fixture_generator` (invents demo companies), `engagement_intake` (models a real client from intake material), `onboarding_interviewer` (interviews a new user about their own company and drafts its profile, people and departments), `workflow_designer` (runs the conversational New workflow wizard on `/jobs/new`: searches the available tools, asks clarifying questions, then drafts a validated dynamic-workflow definition for the user to review), and `workflow_actor` (runs a workflow's `action` steps: a bounded tool-use loop limited to the tools the user approved for that step). `fixture_generator`, `engagement_intake` and `onboarding_interviewer` share one shape — a forced tool call producing a whole company, validated for referential integrity, with a single repair retry — but opposite epistemics: the fixture author invents, the other two extract and leave unstated facts empty rather than guessing.\n\nOne more structured-output utility agent sits beside `triage`: `openexecutive.agents.alert_review.AlertReviewAgent` (routing model, one forced `emit_alert_reviews` tool call, never raises). The alert review job hands it a batch of open alerts with evidence and gets back, per alert, a verdict (relevant / changed / resolved / stale), a confidence, the evidence it relied on, a one-line note, why-now, an optional deadline, and a recommended move (none / route / nudge / escalate / draft / suggest_workflow / merge / close) with its parameters. Like `triage`, it never mutates state — `alerts.review.apply_verdict` executes the verdicts deterministically within authority, so the model's job is judgment, not action.\n\nEvery specialist *advises* — each returns domain analysis the Executive synthesizes into one voice. None of them act on the company's behalf; the side-effecting tools in the main loop (schedule, people, departments, broadcast, watchlist, workflows) belong to the Executive, not to a specialist.\n\nThe Executive can also launch *any* workflow conversationally: `orchestrator.workflow_run_tools` adds `list_workflows` (the launchable catalog with each workflow's inputs) and `run_workflow` (runs a built-in or custom workflow to completion and returns its artifact, checkpointing approval gates as `awaiting_human`). This makes the `/jobs` catalog reachable from chat — see the Workflows section.\n\nDeliverables are first-class too. `orchestrator.artifact_tools` gives the Executive three tools: `draft_artifact` publishes a memo, web page (`html`), Word document (`docx`), spreadsheet (`xlsx`, from structured `sheets`) or a `link` to something it created in one of the principal's connected apps through the generic MCP gateway (`search_tools` → `call_tool`, any server — no vendor is named), and returns the artifact's id and link; `list_artifacts` and `get_artifact` let it find and reread its own past work (drafts and workflow outputs alike, through the same `artifact_records` read model the API uses). Revising is `draft_artifact(supersedes=<id>)`, which archives the earlier version. When the principal asks for a deliverable the tool is always used; the \"quiet is the right default\" bar applies only to unprompted drafts. The format enum is a hard-coded sorted tuple so the cached tool schema stays byte-stable. Delivery: `message_person(person_id, text, artifact_id?)` appends the artifact's title and a `UI_BASE_URL/artifacts/<id>` link (through the same outbound guard as any DM; the link needs Open Executive access), and a Gmail send/draft can attach the file itself by `artifact_id` — see Integrations.\n\nThe Executive also backs the **Ask OE** panel's form-fill tier via `orchestrator.form_tools.propose_form_values`: when a chat turn arrives with a `<page_context>` block describing a form on the user's screen, the Executive can propose values for it. The proposal is delivered to the UI as a `form_patch` SSE event and placed into the form as highlighted suggestions — the tool never saves or submits anything; the user reviews and saves manually. The tool is **always** in the tool list (tool definitions sit at the top of the cached prompt prefix, so a conditionally-present tool would invalidate the prompt cache whenever panel and non-panel turns alternate); its description restricts usage to turns that carry a form descriptor.",
"mermaid": "flowchart TD\n User([User message]) --> Exec[\"Executive<br/>orchestrator\"]\n Exec -->|consult_specialist| Cso[\"cso: StrategyAgent\"]\n Exec -->|consult_specialist| Cfo[\"cfo: FinanceAgent\"]\n Exec -->|consult_specialist| Gc[\"gc: LegalAgent\"]\n Exec -->|consult_specialist| More[\"chro / coo / cmo / cpo<br/>board_comms / triage\"]\n Cso --> Claude[\"Claude (Anthropic)\"]\n Cfo --> Claude\n Gc --> Claude\n More --> Claude\n Claude --> Exec\n class User entry\n class Exec compute\n class Cso compute\n class Cfo compute\n class Gc compute\n class More compute\n class Claude external",
- "generated_at": "2026-09-24T17:52:47.993540+00:00"
+ "generated_at": "2026-09-25T01:36:05.539643+00:00"
}
diff --git a/packages/core/openexecutive/architecture/prebuilt/api.json b/packages/core/openexecutive/architecture/prebuilt/api.json
index f4bc97cc..6f6b1163 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. A `session_id` in the body must be a chat the caller may use (the same ownership rule as `sessions`). If it isn't, the turn runs in a fresh chat instead, so nothing is written into someone else's session and the reply looks the same as for an unknown id. An unknown namespaced id (`slack:…`, `telegram:…` and so on) is ignored and a fresh chat is started, because those ids belong to the channel adapters and claiming one first would make the caller its owner. 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}`, `GET /sessions/{id}/messages`, `DELETE /sessions/{id}`, `POST /sessions/{id}/messages/{message_id}/feedback`, `GET /sessions/{id}/followup` | List, read and delete saved chat sessions (assistant messages carry their row `id` and any `feedback`). The list is scoped to the caller. Every per-session route checks ownership, because session ids are guessable (`slack:dm:<user id>`, `telegram:<chat id>`): only the session's owner or the principal gets through, and a legacy row with no owner is the principal's alone. Anyone else gets the same 404 as for an unknown id, so the routes can't be used to find out which chats exist. The one other way in is having started the chat in this process (matched by Person id or verified email, so it survives the caller being added to the roster), which is how a caller the roster can't resolve keeps using their own chat. That record is in memory, so after a restart such an ownerless chat is refused for reads. The principal can continue someone else's ownerless chat without becoming its owner. Deleting a session also drops its in-memory copy, so a later turn naming that id starts fresh. The feedback route records 👍/👎 (`{\"feedback\": \"up\"|\"down\"|null}`) on one assistant reply; only the session's own caller or the principal may rate it. 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 ownership check 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`, `GET /artifacts/{id}`, `GET /artifacts/{id}/download?as=`, `POST /artifacts/{id}/archive`, `POST /artifacts/{id}/restore`, `DELETE /artifacts/{id}` | Browsable deliverables in any format — Markdown, HTML, Word, Excel, or a link into a connected app — with `format`, `downloads`, `external_url` and `supersedes_id` on every summary. `download` renders the file (Word/Excel built at request time from the stored text; any Markdown artifact, workflow output included, can export `?as=docx`) and is always an attachment with `nosniff` and a sandbox CSP. |\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| `executive` | `GET /executive/status`, `POST /executive/pause`, `POST /executive/resume` | Operator pause switch for all autonomous work (scheduler, Gmail poller, workflow resumer); inbound chat and DMs stay live. Status returns `{paused, paused_at, paused_by, reason, held_actions, can_resume}` — `held_actions` counts due `pending` rows that fire on resume. `pause` takes an optional `reason` (≤200 chars) and is idempotent (re-pausing keeps the original start and reason); `paused_by` is the UI proxy's `x-caller-email`, else `api`. Behind the shared-secret middleware — not `SCHEDULED_ADMIN_TOKEN`, which the UI cannot send. Any caller may pause; `resume` is principal-only (`is_principal_or_self`, 403 otherwise; open while no principal is rostered; a header-less caller resolves to the principal as in `chat`), and status carries `can_resume` for the viewer so the UI hides Resume from everyone else. |\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`, `/skills/{name}/restore` | Skill registry (the UI's **Playbooks**) CRUD and search. `PUT` on a built-in saves a company customization that shadows it; `DELETE` returns `{name, outcome}` — `deleted`, `reverted` (customization removed, built-in back) or `hidden` (built-in hidden for this company); `restore` un-hides; `GET /skills?include_hidden=true` lists hidden built-ins. List and detail carry `used_by` — `[{name, title, is_custom}]` of the workflows that follow the playbook (switched-off custom ones included) (`WorkflowMeta.playbooks` is the other direction). |\n| `skill_drafts` | `/skill-drafts`, `/skill-drafts/{name}`, `/skill-drafts/{name}/approve` | Review queue for playbook changes the Executive proposed from chat. `GET` lists drafts (`action` create / update / delete, the proposed fields, an `id` version token, `current` — the playbook in effect now — and `followers`, the workflows that follow the name); `approve` (body `{id}`) applies exactly the reviewed version through the ordinary skills operations — 409 and the draft is kept if it was replaced since, on a conflict, or if its playbook vanished; `DELETE ?id=` discards that version only. |\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. A `session_id` in the body must be a chat the caller may use (the same ownership rule as `sessions`). If it isn't, the turn runs in a fresh chat instead, so nothing is written into someone else's session and the reply looks the same as for an unknown id. An unknown namespaced id (`slack:…`, `telegram:…` and so on) is ignored and a fresh chat is started, because those ids belong to the channel adapters and claiming one first would make the caller its owner. 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}`, `GET /sessions/{id}/messages`, `DELETE /sessions/{id}`, `POST /sessions/{id}/messages/{message_id}/feedback`, `GET /sessions/{id}/followup` | List, read and delete saved chat sessions (assistant messages carry their row `id` and any `feedback`). The list is scoped to the caller. Every per-session route checks ownership, because session ids are guessable (`slack:dm:<user id>`, `telegram:<chat id>`): only the session's owner or the principal gets through, and a legacy row with no owner is the principal's alone. Anyone else gets the same 404 as for an unknown id, so the routes can't be used to find out which chats exist. The one other way in is having started the chat in this process (matched by Person id or verified email, so it survives the caller being added to the roster), which is how a caller the roster can't resolve keeps using their own chat. That record is in memory, so after a restart such an ownerless chat is refused for reads. The principal can continue someone else's ownerless chat without becoming its owner. Deleting a session also drops its in-memory copy, so a later turn naming that id starts fresh. The feedback route records 👍/👎 (`{\"feedback\": \"up\"|\"down\"|null}`) on one assistant reply; only the session's own caller or the principal may rate it. 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 ownership check 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`, `GET /artifacts/{id}`, `GET /artifacts/{id}/download?as=`, `POST /artifacts/{id}/archive`, `POST /artifacts/{id}/restore`, `DELETE /artifacts/{id}` | Browsable deliverables in any format — Markdown, HTML, Word, Excel, or a link into a connected app — with `format`, `downloads`, `external_url` and `supersedes_id` on every summary. `download` renders the file (Word/Excel built at request time from the stored text; any Markdown artifact, workflow output included, can export `?as=docx`) and is always an attachment with `nosniff` and a sandbox CSP. |\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| `executive` | `GET /executive/status`, `POST /executive/pause`, `POST /executive/resume` | Operator pause switch for all autonomous work (scheduler, Gmail poller, workflow resumer); inbound chat and DMs stay live. Status returns `{paused, paused_at, paused_by, reason, held_actions, can_resume}` — `held_actions` counts due `pending` rows that fire on resume. `pause` takes an optional `reason` (≤200 chars) and is idempotent (re-pausing keeps the original start and reason); `paused_by` is the UI proxy's `x-caller-email`, else `api`. Behind the shared-secret middleware — not `SCHEDULED_ADMIN_TOKEN`, which the UI cannot send. Any caller may pause; `resume` is principal-only (`is_principal_or_self`, 403 otherwise; open while no principal is rostered; a header-less caller resolves to the principal as in `chat`), and status carries `can_resume` for the viewer so the UI hides Resume from everyone else. |\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). `DELETE /scheduled/{id}` cancels a `pending` row (409 otherwise). Like pause it only stops work, so any signed-in user may — the UI proxy's `x-caller-email` is trusted when the request also carries the `BACKEND_SHARED_SECRET` `x-api-key` — as may a matching `X-Admin-Token` (`SCHEDULED_ADMIN_TOKEN`) or a loopback caller with no token set; otherwise 401 (token set) or 503. Audited as `scheduled_action_cancelled`. |\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`, `/skills/{name}/restore` | Skill registry (the UI's **Playbooks**) CRUD and search. `PUT` on a built-in saves a company customization that shadows it; `DELETE` returns `{name, outcome}` — `deleted`, `reverted` (customization removed, built-in back) or `hidden` (built-in hidden for this company); `restore` un-hides; `GET /skills?include_hidden=true` lists hidden built-ins. List and detail carry `used_by` — `[{name, title, is_custom}]` of the workflows that follow the playbook (switched-off custom ones included) (`WorkflowMeta.playbooks` is the other direction). |\n| `skill_drafts` | `/skill-drafts`, `/skill-drafts/{name}`, `/skill-drafts/{name}/approve` | Review queue for playbook changes the Executive proposed from chat. `GET` lists drafts (`action` create / update / delete, the proposed fields, an `id` version token, `current` — the playbook in effect now — and `followers`, the workflows that follow the name); `approve` (body `{id}`) applies exactly the reviewed version through the ordinary skills operations — 409 and the draft is kept if it was replaced since, on a conflict, or if its playbook vanished; `DELETE ?id=` discards that version only. |\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-24T17:10:12.035035+00:00"
+ "generated_at": "2026-09-25T01:22:23.080573+00:00"
}
diff --git a/packages/core/openexecutive/architecture/prebuilt/audit.json b/packages/core/openexecutive/architecture/prebuilt/audit.json
index 6c4a27ca..000925c4 100644
--- a/packages/core/openexecutive/architecture/prebuilt/audit.json
+++ b/packages/core/openexecutive/architecture/prebuilt/audit.json
@@ -1,7 +1,7 @@
{
"section_id": "audit",
"title": "Audit Log",
- "markdown": "The audit log is a persistent, searchable, append-only record of what the system did — distinct from episodic memory (which biases future LLM behavior). Every event flows through `audit/logger.log_event`, a synchronous SQLite writer (WAL + 5s busy_timeout) that appends one row to the `audit_log` table in `episodic_memory.db`.\n\n### Event types\nRows are tagged by `event_type`, including `chat_turn`, `specialist_consult`, `tool_invocation`, `scheduled_action`, `alert`, `integration_inbound` (Slack / Discord / email / Telegram / Google Chat), plus `knowledge_retrieval`, `memory_extraction` (one row per episodic-extraction pass, written in a `finally` so a crashed pass is recorded too: how many items the model proposed, how many were stored, a `{kind, reason}` record per drop, a `malformed` count for payload shapes that were never usable items, and a `failure` naming the exception type when the pass raised — including `CancelledError`, which is a `BaseException` and so would otherwise be logged as a clean empty pass — a `proposed>0, stored=0` streak means the quote validator is rejecting everything, which is otherwise invisible), `cache_event` (one row per model call from every call site — Executive turns, specialist consults (chat turns and workflow steps), research specialists, the research routing and watchlist passes, triage, memory extraction — carrying tokens, cache hits, cost, server-side search count and, inside a research run, its `run_id`), `memory_snapshot`, `committee_review`, `peer_memory`, `attunement` (one row per open-loop extraction pass — opened / closed / dropped with a reason per drop and a `failure` type — plus a row per loop opened or closed and per 👍/👎 on a reply; see Attunement), `executive_paused` / `executive_resumed` (the operator pause switch; actor is the caller's email, details carry the reason, or on resume the held-action count), and the external-signal/monitor events.\n\n### Session & turn context\nEach row carries `session_id`, `turn_id`, `actor`, `summary`, `details_json`, `full_json`, and `department`. A `turn_id` (`f\"t-{uuid12}\"`) is set per Executive turn and propagated automatically via ContextVars to retriever / specialist / tool / cache emits, grouping one user-assistant exchange. `summary` is the searchable column (LIKE, ~300 char cap); `details_json` is structured and not searched.\n\n### Views\n- `GET /audit` — filterable list with a \"Group by session\" toggle and session pills.\n- `GET /audit/session/{id}` — full ordered timeline plus a server-derived node/edge graph rendered as a three-pane React Flow chart.\n\n### Invariant\nAudit writes never break a chat turn: all writes swallow exceptions and log a warning, and instrumentation observes only — it never touches request building or the cached prompt blocks. Audit is append-only: no UPDATE or DELETE paths exist in product code.",
+ "markdown": "The audit log is a persistent, searchable, append-only record of what the system did — distinct from episodic memory (which biases future LLM behavior). Every event flows through `audit/logger.log_event`, a synchronous SQLite writer (WAL + 5s busy_timeout) that appends one row to the `audit_log` table in `episodic_memory.db`.\n\n### Event types\nRows are tagged by `event_type`, including `chat_turn`, `specialist_consult`, `tool_invocation`, `scheduled_action`, `alert`, `integration_inbound` (Slack / Discord / email / Telegram / Google Chat), plus `knowledge_retrieval`, `memory_extraction` (one row per episodic-extraction pass, written in a `finally` so a crashed pass is recorded too: how many items the model proposed, how many were stored, a `{kind, reason}` record per drop, a `malformed` count for payload shapes that were never usable items, and a `failure` naming the exception type when the pass raised — including `CancelledError`, which is a `BaseException` and so would otherwise be logged as a clean empty pass — a `proposed>0, stored=0` streak means the quote validator is rejecting everything, which is otherwise invisible), `cache_event` (one row per model call from every call site — Executive turns, specialist consults (chat turns and workflow steps), research specialists, the research routing and watchlist passes, triage, memory extraction — carrying tokens, cache hits, cost, server-side search count and, inside a research run, its `run_id`), `memory_snapshot`, `committee_review`, `peer_memory`, `attunement` (one row per open-loop extraction pass — opened / closed / dropped with a reason per drop and a `failure` type — plus a row per loop opened or closed and per 👍/👎 on a reply; see Attunement), `executive_paused` / `executive_resumed` (the operator pause switch; actor is the caller's email, details carry the reason, or on resume the held-action count), `scheduled_action_cancelled` (a pending scheduled action cancelled from the Pulse page or a script; actor is the signed-in email, `admin-token` or `local`), and the external-signal/monitor events.\n\n### Session & turn context\nEach row carries `session_id`, `turn_id`, `actor`, `summary`, `details_json`, `full_json`, and `department`. A `turn_id` (`f\"t-{uuid12}\"`) is set per Executive turn and propagated automatically via ContextVars to retriever / specialist / tool / cache emits, grouping one user-assistant exchange. `summary` is the searchable column (LIKE, ~300 char cap); `details_json` is structured and not searched.\n\n### Views\n- `GET /audit` — filterable list with a \"Group by session\" toggle and session pills.\n- `GET /audit/session/{id}` — full ordered timeline plus a server-derived node/edge graph rendered as a three-pane React Flow chart.\n\n### Invariant\nAudit writes never break a chat turn: all writes swallow exceptions and log a warning, and instrumentation observes only — it never touches request building or the cached prompt blocks. Audit is append-only: no UPDATE or DELETE paths exist in product code.",
"mermaid": "flowchart TD\n Chat[\"Chat turn / consult / tool call\"]\n Sched[\"Scheduled action\"]\n Inbound[\"Inbound integration\"]\n Log[\"audit/logger.log_event\"]\n DB[\"audit_log table (append-only)\"]\n ListView[\"/audit list view\"]\n SessView[\"/audit/session/{id} flow chart\"]\n Chat -->|event + turn_id| Log\n Sched --> Log\n Inbound --> Log\n Log -->|swallow errors, never block| DB\n DB --> ListView\n DB --> SessView\n class Chat entry\n class Sched entry\n class Inbound entry\n class Log compute\n class DB storage\n class ListView hot\n class SessView hot",
- "generated_at": "2026-09-24T14:41:02.752633+00:00"
+ "generated_at": "2026-09-25T01:22:23.080573+00:00"
}
diff --git a/packages/core/openexecutive/architecture/prebuilt/memory.json b/packages/core/openexecutive/architecture/prebuilt/memory.json
index ca9e4110..56d62950 100644
--- a/packages/core/openexecutive/architecture/prebuilt/memory.json
+++ b/packages/core/openexecutive/architecture/prebuilt/memory.json
@@ -1,7 +1,7 @@
{
"section_id": "memory",
"title": "Memory System",
- "markdown": "The Executive's durable memory is an episodic SQLite store at `./episodic_memory.db`, managed by `openexecutive.memory.episodic`. It holds four tables:\n\n- `decisions` — choices made, with `domain`, `summary`, `rationale`, `outcome`, and `tags`.\n- `initiatives` — tracked efforts with a `status` and `summary` (idempotent upserts).\n- `advice_given` — query/advice pairs per domain.\n- `scheduled_actions` — a dispatch queue, treated separately from recall memory.\n\n### What gets extracted, and when\n\n`episodic.extract_and_store` runs after a turn and asks a utility-fast model for decisions, initiatives and advice. Every candidate must carry a `user_commitment_quote` that appears verbatim in the principal's own message (`_is_valid_user_commitment`) — the turn's speaker text (`memory_text` when the entry point supplies one, else the prompt), so a quoted Executive email or a briefing card's body inside the prompt cannot satisfy it — the model has repeatedly tried to log the Executive's *recommendations* as the user's commitments, and that quote is the hard gate against it.\n\nA turn reaches the extractor if `should_extract(user_message)` is true, which means only that the principal said something — there is deliberately **no length floor**. There used to be one, on the combined user+assistant length, and on a live tenant it selected almost exactly the wrong turns: 9 of 16 exchanges were blocked, and the 9 held every instruction the principal gave, while the 7 admitted were long analytical exchanges with no commitment in them. The extractor ran 13 times and stored nothing.\n\nMoving that floor to the user's side would relocate the bug, not fix it. The canonical executive decision is a long analysis answered with \"Approve option B.\" (17 chars) or \"Do B.\" (5), and any floor high enough to skip \"Done\" (4) also skips those — \"Do B.\" and \"Done\" differ by one character and mean opposite things. Length cannot separate a decision from an acknowledgement; the verbatim-quote check can, so `_is_valid_user_commitment` is the gate that decides. The price is one utility-fast call on turns that propose nothing.\n\nThat quote check is only meaningful when `user_message` holds the **principal's** words, and on a chat channel it does not — `Executive.chat()` is reached from Slack, Discord, Telegram, Google Chat and the email poller. A teammate's line would be written to `decisions` with no speaker attached, indistinguishable from the principal's own; an inbound email body is text the sender chose, so a self-quote is free. Removing the length floor is what makes this bite — short channel traffic used to fall under it incidentally — so `should_extract` also takes the turn's `origin_channel` and `person_id`. No channel means the web app, the CLI or the API, all of them the principal's own authenticated surfaces, where `person_id` is legitimately null in a single-user install. A turn that names a channel must resolve to a person marked `is_principal`, and an unresolvable speaker fails closed.\n\nEach pass writes a `memory_extraction` audit row — in a `finally`, so a pass that crashed is recorded too, with the exception type as its `failure` reason: how many items the model proposed, how many were stored, a `malformed` count so a pass where the model returned only garbage does not read as one that found nothing, and a `{kind, reason}` record per drop — `bad_quote` and `missing_field` for an item the model proposed, `not_a_list`, `item_not_a_dict` and `payload_not_a_dict` for a shape that was never a usable item. Every proposed item is either stored or dropped, so `proposed == stored + item drops` is the arithmetic that says whether anything was lost silently. The tool payload is not schema-checked anywhere, so a malformed shape is counted as a drop rather than raised — it used to abort the whole pass, discarding the other two kinds with it and suppressing the row, which read exactly like \"extraction never ran\". Without it, \"the model found nothing\" and \"the model found things and every one was rejected\" are indistinguishable from outside the database — which is why the failure above survived undetected and took a SQLite session on the tenant to find. A `proposed>0, stored=0` streak is the signal to watch.\n\nThe validator rejects a paraphrase, and the model paraphrases: on one install two of three real commitments were lost that way, the quote beginning \"SVN's engagement covers only …\" where the person had typed something else. So a `bad_quote` drop earns exactly one corrective call. The model is shown the rejected items and the quotes it gave, told to copy the span character-for-character (typos and casing included) or return empty arrays, and the tool is forced where the provider supports tool choice. Every retry item is validated first; a still-invalid one adds no second drop and is counted `still_invalid`. A valid item is then classified in order: its label matches a pending drop record → a recovery, stored and the record released; else its quote (terminal punctuation ignored) already supports a stored item of that kind → a re-send, ignored and counted `repeated`, so a model that re-sends everything cannot double-count `stored`; else a new proposal, stored and counted — a reworded label cannot be told from a different item, and crediting it would erase the very `bad_quote` census the row exists to show, so its original drop stands. Recovery is checked before re-send because two commitments can rest on one sentence. Malformed shapes at any level — a kind that is not a list, an item or payload that is not a dict, a response with no tool call — are counted `malformed`, so a retry that returned garbage does not read like one that obediently returned nothing. The row's `retry` block (`rejected`, `recovered`, `repeated`, `still_invalid`, `malformed`, `failure`) is always present, zeros when nothing was rejected; `rejected` is set from the complete drop list when the row is written, so neither a store failure before the retry nor a cancellation during it can zero it. The arithmetic above still holds after the retry. An exception on the retry is recorded as the retry's own `failure` and leaves the first pass's results untouched; the cost is one utility-model call, only on turns that dropped something. `memory_extraction` is a declared event type, so the audit page's filter can select it.\n\n### Session scoping\n\n`decisions` and `advice_given` rows carry a `session_id`, so per-thread channels (Discord, Telegram) can pull just-this-thread history without leaking cross-conversation context. A null `session_id` falls back to a global view.\n\n### Surfacing\n\n`openexecutive.memory.episodic.format_for_prompt` renders recent decisions and initiatives into a compact `<past_decisions>` block injected into the user turn — alongside `<retrieved_context>` and peer memory — never into a cached system block.\n\nThe chat route also injects a `<briefing>` block into the same user turn: a compact digest of the current open (unread) alerts, built by `openexecutive.briefing.context.format_open_alerts_for_prompt` (company-wide, `status=\"unread\"`, mirroring `/today`). This is what lets the Executive discuss a briefing item the principal clicked or named on `/today` (e.g. \"Gulf Coast Port Cyberattack\"). It is resolved in parallel with the other context fetches, omitted when there are no open alerts, and never placed in a cached system block.\n\nOn the Pulse page the Memory section shows the three lists as Decisions, Initiatives and Advice tabs, with a fourth **People** tab for peer memory (what Honcho has derived about each person, read-only, see the peer memory section). The header's Memories tile counts the three lists plus the peer notes, and says how many of the number are peer notes in its hint, since the People tab's badge counts people rather than notes.\n\n### System of record\n\nSQL is the system of record; the peer-memory service is a recall layer mirrored from it, not a replacement. When `store_decision` / `store_initiative` / `store_advice` insert a row whose `department` is non-empty and not `\"general\"`, the row is mirrored as a kind-tagged note into that department's peer via `append_department_note`. The mirror fires only after a successful INSERT, is fire-and-forget, and never rolls back the SQL row on peer-memory failure. `scheduled_actions` is never mirrored — it is a queue, not memory.\n\nThe episodic extractor still learns only from the principal's own words. Commitments and asks from everyone else on the roster are tracked as **open loops** (see Attunement) — `scheduled_actions` rows with `kind='open_loop'`, opened and closed by a separate quote-gated pass after each attributed turn. That pass depends on `chat_messages.sender_person_id`, which records who actually wrote each persisted user message. An open loop counts toward `list_awaiting_replies_by_person` only once it is due, and `list_scheduled_actions(exclude_internal=True)` filters `__internal__` rows in SQL so readers that want real sends are not starved by them. `mark_outbound_context_consumed` also resolves the Attunement outcome row for that DM as `replied` — a matched reply is the clearest sign proactive outreach landed — and a real change to an existing initiative (`store_initiative` / `update_initiative`, new status or summary) marks the updater's own check-in nudges `acted` — an update with no known updater, such as `PATCH /memories/initiatives/{id}`, credits nobody.",
+ "markdown": "The Executive's durable memory is an episodic SQLite store at `./episodic_memory.db`, managed by `openexecutive.memory.episodic`. It holds four tables:\n\n- `decisions` — choices made, with `domain`, `summary`, `rationale`, `outcome`, and `tags`.\n- `initiatives` — tracked efforts with a `status` and `summary` (idempotent upserts).\n- `advice_given` — query/advice pairs per domain.\n- `scheduled_actions` — a dispatch queue, treated separately from recall memory. `cancel_scheduled_action` guards its UPDATE on `status = 'pending'`, so a cancel never overwrites a row the scheduler claimed a moment earlier.\n\n### What gets extracted, and when\n\n`episodic.extract_and_store` runs after a turn and asks a utility-fast model for decisions, initiatives and advice. Every candidate must carry a `user_commitment_quote` that appears verbatim in the principal's own message (`_is_valid_user_commitment`) — the turn's speaker text (`memory_text` when the entry point supplies one, else the prompt), so a quoted Executive email or a briefing card's body inside the prompt cannot satisfy it — the model has repeatedly tried to log the Executive's *recommendations* as the user's commitments, and that quote is the hard gate against it.\n\nA turn reaches the extractor if `should_extract(user_message)` is true, which means only that the principal said something — there is deliberately **no length floor**. There used to be one, on the combined user+assistant length, and on a live tenant it selected almost exactly the wrong turns: 9 of 16 exchanges were blocked, and the 9 held every instruction the principal gave, while the 7 admitted were long analytical exchanges with no commitment in them. The extractor ran 13 times and stored nothing.\n\nMoving that floor to the user's side would relocate the bug, not fix it. The canonical executive decision is a long analysis answered with \"Approve option B.\" (17 chars) or \"Do B.\" (5), and any floor high enough to skip \"Done\" (4) also skips those — \"Do B.\" and \"Done\" differ by one character and mean opposite things. Length cannot separate a decision from an acknowledgement; the verbatim-quote check can, so `_is_valid_user_commitment` is the gate that decides. The price is one utility-fast call on turns that propose nothing.\n\nThat quote check is only meaningful when `user_message` holds the **principal's** words, and on a chat channel it does not — `Executive.chat()` is reached from Slack, Discord, Telegram, Google Chat and the email poller. A teammate's line would be written to `decisions` with no speaker attached, indistinguishable from the principal's own; an inbound email body is text the sender chose, so a self-quote is free. Removing the length floor is what makes this bite — short channel traffic used to fall under it incidentally — so `should_extract` also takes the turn's `origin_channel` and `person_id`. No channel means the web app, the CLI or the API, all of them the principal's own authenticated surfaces, where `person_id` is legitimately null in a single-user install. A turn that names a channel must resolve to a person marked `is_principal`, and an unresolvable speaker fails closed.\n\nEach pass writes a `memory_extraction` audit row — in a `finally`, so a pass that crashed is recorded too, with the exception type as its `failure` reason: how many items the model proposed, how many were stored, a `malformed` count so a pass where the model returned only garbage does not read as one that found nothing, and a `{kind, reason}` record per drop — `bad_quote` and `missing_field` for an item the model proposed, `not_a_list`, `item_not_a_dict` and `payload_not_a_dict` for a shape that was never a usable item. Every proposed item is either stored or dropped, so `proposed == stored + item drops` is the arithmetic that says whether anything was lost silently. The tool payload is not schema-checked anywhere, so a malformed shape is counted as a drop rather than raised — it used to abort the whole pass, discarding the other two kinds with it and suppressing the row, which read exactly like \"extraction never ran\". Without it, \"the model found nothing\" and \"the model found things and every one was rejected\" are indistinguishable from outside the database — which is why the failure above survived undetected and took a SQLite session on the tenant to find. A `proposed>0, stored=0` streak is the signal to watch.\n\nThe validator rejects a paraphrase, and the model paraphrases: on one install two of three real commitments were lost that way, the quote beginning \"SVN's engagement covers only …\" where the person had typed something else. So a `bad_quote` drop earns exactly one corrective call. The model is shown the rejected items and the quotes it gave, told to copy the span character-for-character (typos and casing included) or return empty arrays, and the tool is forced where the provider supports tool choice. Every retry item is validated first; a still-invalid one adds no second drop and is counted `still_invalid`. A valid item is then classified in order: its label matches a pending drop record → a recovery, stored and the record released; else its quote (terminal punctuation ignored) already supports a stored item of that kind → a re-send, ignored and counted `repeated`, so a model that re-sends everything cannot double-count `stored`; else a new proposal, stored and counted — a reworded label cannot be told from a different item, and crediting it would erase the very `bad_quote` census the row exists to show, so its original drop stands. Recovery is checked before re-send because two commitments can rest on one sentence. Malformed shapes at any level — a kind that is not a list, an item or payload that is not a dict, a response with no tool call — are counted `malformed`, so a retry that returned garbage does not read like one that obediently returned nothing. The row's `retry` block (`rejected`, `recovered`, `repeated`, `still_invalid`, `malformed`, `failure`) is always present, zeros when nothing was rejected; `rejected` is set from the complete drop list when the row is written, so neither a store failure before the retry nor a cancellation during it can zero it. The arithmetic above still holds after the retry. An exception on the retry is recorded as the retry's own `failure` and leaves the first pass's results untouched; the cost is one utility-model call, only on turns that dropped something. `memory_extraction` is a declared event type, so the audit page's filter can select it.\n\n### Session scoping\n\n`decisions` and `advice_given` rows carry a `session_id`, so per-thread channels (Discord, Telegram) can pull just-this-thread history without leaking cross-conversation context. A null `session_id` falls back to a global view.\n\n### Surfacing\n\n`openexecutive.memory.episodic.format_for_prompt` renders recent decisions and initiatives into a compact `<past_decisions>` block injected into the user turn — alongside `<retrieved_context>` and peer memory — never into a cached system block.\n\nThe chat route also injects a `<briefing>` block into the same user turn: a compact digest of the current open (unread) alerts, built by `openexecutive.briefing.context.format_open_alerts_for_prompt` (company-wide, `status=\"unread\"`, mirroring `/today`). This is what lets the Executive discuss a briefing item the principal clicked or named on `/today` (e.g. \"Gulf Coast Port Cyberattack\"). It is resolved in parallel with the other context fetches, omitted when there are no open alerts, and never placed in a cached system block.\n\nOn the Pulse page the Memory section shows the three lists as Decisions, Initiatives and Advice tabs, with a fourth **People** tab for peer memory (what Honcho has derived about each person, read-only, see the peer memory section). The header's Memories tile counts the three lists plus the peer notes, and says how many of the number are peer notes in its hint, since the People tab's badge counts people rather than notes.\n\n### System of record\n\nSQL is the system of record; the peer-memory service is a recall layer mirrored from it, not a replacement. When `store_decision` / `store_initiative` / `store_advice` insert a row whose `department` is non-empty and not `\"general\"`, the row is mirrored as a kind-tagged note into that department's peer via `append_department_note`. The mirror fires only after a successful INSERT, is fire-and-forget, and never rolls back the SQL row on peer-memory failure. `scheduled_actions` is never mirrored — it is a queue, not memory.\n\nThe episodic extractor still learns only from the principal's own words. Commitments and asks from everyone else on the roster are tracked as **open loops** (see Attunement) — `scheduled_actions` rows with `kind='open_loop'`, opened and closed by a separate quote-gated pass after each attributed turn. That pass depends on `chat_messages.sender_person_id`, which records who actually wrote each persisted user message. An open loop counts toward `list_awaiting_replies_by_person` only once it is due, and `list_scheduled_actions(exclude_internal=True)` filters `__internal__` rows in SQL so readers that want real sends are not starved by them. `mark_outbound_context_consumed` also resolves the Attunement outcome row for that DM as `replied` — a matched reply is the clearest sign proactive outreach landed — and a real change to an existing initiative (`store_initiative` / `update_initiative`, new status or summary) marks the updater's own check-in nudges `acted` — an update with no known updater, such as `PATCH /memories/initiatives/{id}`, credits nobody.",
"mermaid": "flowchart TD\n Store[\"store_decision / store_initiative / store_advice\"]\n DB[\"episodic_memory.db<br/>decisions / initiatives<br/>advice_given / scheduled_actions\"]\n Fmt[\"format_for_prompt\"]\n Turn[\"User turn<br/>past_decisions block\"]\n Mirror[\"append_department_note\"]\n Peer[\"Department peer<br/>(Honcho)\"]\n Store --> DB\n DB --> Fmt\n Fmt --> Turn\n Store -->|\"dept set & not general\"| Mirror\n Mirror -->|\"fire-and-forget\"| Peer\n class Store entry\n class DB storage\n class Fmt compute\n class Turn hot\n class Peer external\n",
- "generated_at": "2026-09-23T18:53:18Z"
+ "generated_at": "2026-09-25T01:36:05.539643+00:00"
}
diff --git a/packages/core/openexecutive/architecture/prebuilt/nojargon_authority.json b/packages/core/openexecutive/architecture/prebuilt/nojargon_authority.json
index d6319b4d..babfab65 100644
--- a/packages/core/openexecutive/architecture/prebuilt/nojargon_authority.json
+++ b/packages/core/openexecutive/architecture/prebuilt/nojargon_authority.json
@@ -1,7 +1,7 @@
{
"section_id": "nojargon_authority",
"title": "Without the Jargon: How It Decides To Act",
- "markdown": "Every time Open Executive could take an action, it picks one of three modes. The mode depends on how routine and reversible the work is — not on guesswork.\n\n| Mode | When | What happens |\n|---|---|---|\n| **Act on its own** | Routine, recoverable work — morning hygiene, meeting nudges, doc sweeps | It just does it and shows you what it did. No approval. |\n| **Propose for approval** | Decisions that need a human signature — a new vendor, a hire, a customer-facing release | It drafts the work, parks it in the right person's queue, and sends nothing until they approve. |\n| **Escalate to you** | Live signal — an interested customer replies, a competitor moves, a board-level event | It alerts you now *and* ships the immediate response in the same beat. You don't wait for the morning brief. |\n\nWho approves a proposal is decided by **what someone is cleared to approve, not their job title.** Each person carries tags — \"approve money under $10k,\" \"sign off on hires,\" \"onboard a new vendor.\" When a proposal needs sign-off, Open Executive routes it to whoever holds the matching tag. If nobody matches, it falls back to you. You are always the final stop.\n\n*See also: Authority & Org for the implementation.*",
- "mermaid": "flowchart TD\n Action[\"A possible action\"] --> Q{\"What kind<br/>of work?\"}\n Q -->|\"routine & recoverable\"| Act[\"Act on its own\"]\n Q -->|\"needs a signature\"| Propose[\"Propose for approval\"]\n Q -->|\"live, time-sensitive\"| Escalate[\"Escalate to you\"]\n Act --> Done[\"Done — shown to you\"]\n Propose --> Approver[\"Routed to the<br/>matching tag-holder\"]\n Approver -->|\"no match\"| You([\"You (final stop)\"])\n Approver -->|\"approved\"| Done\n Escalate --> You\n Escalate --> Done\n class Action entry\n class Q compute\n class Act compute\n class Propose compute\n class Escalate compute\n class Approver compute\n class You entry\n class Done hot",
- "generated_at": "2026-06-01T00:00:00+00:00"
+ "markdown": "Every time Open Executive could take an action, it picks one of three modes. The mode depends on how routine and reversible the work is — not on guesswork.\n\n| Mode | When | What happens |\n|---|---|---|\n| **Act on its own** | Routine, recoverable work — morning hygiene, meeting nudges, doc sweeps | It just does it and shows you what it did. No approval. |\n| **Propose for approval** | Decisions that need a human signature — a new vendor, a hire, a customer-facing release | It drafts the work, parks it in the right person's queue, and sends nothing until they approve. |\n| **Escalate to a human** | Sensitive or time-critical work — legal, a board-level event, an upset key customer | It puts the drafted response in front of the right person straight away, flagged urgent, even outside their working hours — and sends nothing until they approve. |\n\nWho approves a proposal is decided by **what someone is cleared to approve, not their job title.** Each person carries tags — \"approve money under $10k,\" \"sign off on hires,\" \"onboard a new vendor.\" When a proposal needs sign-off, Open Executive routes it to whoever holds the matching tag. If nobody matches, it falls back to you. You are always the final stop.\n\n*See also: Authority & Org for the implementation.*",
+ "mermaid": "flowchart TD\n Action[\"A possible action\"] --> Q{\"What kind<br/>of work?\"}\n Q -->|\"routine & recoverable\"| Act[\"Act on its own\"]\n Q -->|\"needs a signature\"| Propose[\"Propose for approval\"]\n Q -->|\"sensitive or urgent\"| Escalate[\"Escalate to a human\"]\n Act --> Done[\"Done — shown to you\"]\n Propose --> Approver[\"Routed to the<br/>matching tag-holder\"]\n Approver -->|\"no match\"| You([\"You (final stop)\"])\n Approver -->|\"approved\"| Done\n Escalate -->|\"urgent, right away\"| Approver\n class Action entry\n class Q compute\n class Act compute\n class Propose compute\n class Escalate compute\n class Approver compute\n class You entry\n class Done hot",
+ "generated_at": "2026-09-25T01:22:23.080573+00:00"
}
diff --git a/packages/core/openexecutive/architecture/prebuilt/org.json b/packages/core/openexecutive/architecture/prebuilt/org.json
index 66f4d67d..227c012f 100644
--- a/packages/core/openexecutive/architecture/prebuilt/org.json
+++ b/packages/core/openexecutive/architecture/prebuilt/org.json
@@ -1,7 +1,7 @@
{
"section_id": "org",
"title": "Org Structure (Departments & People)",
- "markdown": "The org model has two persistent registries backed by SQLite (both share `episodic_memory.db`): **departments** and **people**. Eight default departments are seeded exactly once per database on first boot, tracked by a `default_departments_seeded` sentinel in `departments_meta`; after that the user owns the list and deleted departments stay deleted across restarts.\n\n### Company setup (onboarding)\nBoth registries are first populated by **conversational onboarding** at\n`/onboard`. The user describes their business in their own words (optionally\nattaching a deck or one-pager); the `onboarding_interviewer` agent — Council-\nvisible but outside `SPECIALIST_REGISTRY`, so the Executive cannot reach it via\n`consult_specialist` — asks up to 8 clarifying questions, then emits a draft\ncompany profile, a leadership roster, and a department list. The user reviews\nand edits that draft inline (the same section editors `/company-profile` uses)\nbefore anything is written.\n\nTwo properties matter here. First, **the interview never writes**: the whole\nexchange lives in an in-memory, TTL'd session, and the single write happens at\n`POST /onboard/interview/commit`, so a rejected save leaves the draft editable\nand retryable. Second, **the department step is additive** — drafted\ndepartments are matched onto existing ones by slug or title and updated in\nplace, unmatched ones are created, and nothing is ever deleted. That is\ndeliberately unlike the fixture loader's `_seed_departments`, which DELETEs\nevery row first: doing that here would drop the eight defaults along with their\n`specialist_key` wiring, which `create_department` (always `specialist_key =\nNULL`) cannot restore. `profile.org_structure` is derived from the reviewed\npeople and department tables at commit time, so it cannot drift from them.\n\nExactly one person is marked `is_principal` and receives `WILDCARD` authority;\nno contact details are imported, even if the user volunteers them, because\nchannels and handles are a deliberate action on the People page. The original\n12-step form wizard remains available at `/onboard?mode=form` and backs the\n`openexecutive onboard` CLI.\n\n### Departments\nEach department carries a charter, `Goal` rows, `ChecklistItem`s, and named cadences. Cadence specs (`daily@HH:MM`, `weekly@DOW@HH:MM`, `quarterly@DD-HH:MM`, UTC) enqueue a `department_check_in` workflow when due, then chain the next occurrence; `PATCH /departments/{slug}` rejects a spec that does not parse with a 422. A department may map to one of the 8 specialist agents via `specialist_key`, or stay informational. An assigned head gets a generated department-head voice persona.\n\nA department can also list **watched entities** (`watched_entities`, edited one per line on its page): vendors it is evaluating, competitors in its lane, tickers it tracks. The research watch policy treats them as strong grounding — a proposal about one can be added to the watch list on its own — and routes the resulting watch, its alerts and any suggestion cards to the department and its head rather than the principal (see External monitoring).\n\n### Authority gate\nEach department declares an `AuthorityLevel`: `propose_only` routes scheduled actions through an approval workflow (`wait_for_human`); `auto_execute` (autonomous) fires directly. The approver is chosen by `AuthorityScope` — a scheduled action's `required_scope` (e.g. `vendor_onboarding`, `spend_lt_10k`) feeds `find_approvers(scope)`, which ranks non-principal scope-holders ahead of `WILDCARD` holders. A null/unknown scope falls back to `WILDCARD` (the principal).\n\n### People & channels\nThe people registry resolves each `Person` to a `(channel, channel_ref)` pair via `prefer_channel_for()`, honoring `preferred_channel` (falling back email → slack → discord → telegram) and availability windows. Departments can also set `slack_channel_id` / `discord_channel_id` / `telegram_chat_id` to broadcast to a team room instead of DMing the head.\n\nEach person's page also lists their **open loops** (see Attunement) — what they committed to or were asked for in conversation — with a *Mark done* action; archiving a person closes their open loops, since an archived person can no longer be chased. The list is the principal's or that person's only; `people.store.is_principal_or_self` is the one check behind it, the close action and reply feedback.",
+ "markdown": "The org model has two persistent registries backed by SQLite (both share `episodic_memory.db`): **departments** and **people**. Eight default departments are seeded exactly once per database on first boot, tracked by a `default_departments_seeded` sentinel in `departments_meta`; after that the user owns the list and deleted departments stay deleted across restarts.\n\n### Company setup (onboarding)\nBoth registries are first populated by **conversational onboarding** at\n`/onboard`. The user describes their business in their own words (optionally\nattaching a deck or one-pager); the `onboarding_interviewer` agent — Council-\nvisible but outside `SPECIALIST_REGISTRY`, so the Executive cannot reach it via\n`consult_specialist` — asks up to 8 clarifying questions, then emits a draft\ncompany profile, a leadership roster, and a department list. The user reviews\nand edits that draft inline (the same section editors `/company-profile` uses)\nbefore anything is written.\n\nTwo properties matter here. First, **the interview never writes**: the whole\nexchange lives in an in-memory, TTL'd session, and the single write happens at\n`POST /onboard/interview/commit`, so a rejected save leaves the draft editable\nand retryable. Second, **the department step is additive** — drafted\ndepartments are matched onto existing ones by slug or title and updated in\nplace, unmatched ones are created, and nothing is ever deleted. That is\ndeliberately unlike the fixture loader's `_seed_departments`, which DELETEs\nevery row first: doing that here would drop the eight defaults along with their\n`specialist_key` wiring, which `create_department` (always `specialist_key =\nNULL`) cannot restore. `profile.org_structure` is derived from the reviewed\npeople and department tables at commit time, so it cannot drift from them.\n\nExactly one person is marked `is_principal` and receives `WILDCARD` authority;\nno contact details are imported, even if the user volunteers them, because\nchannels and handles are a deliberate action on the People page. The original\n12-step form wizard remains available at `/onboard?mode=form` and backs the\n`openexecutive onboard` CLI.\n\n### Departments\nEach department carries a charter, `Goal` rows, `ChecklistItem`s, and named cadences. Cadence specs (`daily@HH:MM`, `weekly@DOW@HH:MM`, `quarterly@DD-HH:MM`, UTC) enqueue a `department_check_in` workflow when due, then chain the next occurrence; `PATCH /departments/{slug}` rejects a spec that does not parse with a 422. A department may map to one of the 8 specialist agents via `specialist_key`, or stay informational. An assigned head gets a generated department-head voice persona.\n\nA department can also list **watched entities** (`watched_entities`, edited one per line on its page): vendors it is evaluating, competitors in its lane, tickers it tracks. The research watch policy treats them as strong grounding — a proposal about one can be added to the watch list on its own — and routes the resulting watch, its alerts and any suggestion cards to the department and its head rather than the principal (see External monitoring).\n\n### Authority gate\nEach department declares an `AuthorityLevel`, which `departments.authority.gate_action` checks whenever a department-scoped scheduled action comes due. `auto_execute` (autonomous) fires directly. `propose_only` turns the action into an approval card for an approver (`propose_via_alert`) and sends nothing, deferring the card to the approver's next availability window when they are outside it. `escalate` also sends nothing until someone approves: it raises an urgent `[ESCALATION]` card (severity high) right away, never deferred — filed unrouted when nobody holds the scope and no principal is set, since the Briefing lists every unread card — what the Departments page promises (\"the specialist will not act — it forwards everything to a human\"). It used to raise the card *and* dispatch, so approving the card sent the action a second time. Calendar bookings follow the same rule. The approver is chosen by `AuthorityScope` — a scheduled action's `required_scope` (e.g. `vendor_onboarding`, `spend_lt_10k`) feeds `find_approvers(scope)`, which ranks non-principal scope-holders ahead of `WILDCARD` holders. A null/unknown scope falls back to `WILDCARD` (the principal).\n\n### People & channels\nThe people registry resolves each `Person` to a `(channel, channel_ref)` pair via `prefer_channel_for()`, honoring `preferred_channel` (falling back email → slack → discord → telegram) and availability windows. Departments can also set `slack_channel_id` / `discord_channel_id` / `telegram_chat_id` to broadcast to a team room instead of DMing the head.\n\nEach person's page also lists their **open loops** (see Attunement) — what they committed to or were asked for in conversation — with a *Mark done* action; archiving a person closes their open loops, since an archived person can no longer be chased. The list is the principal's or that person's only; `people.store.is_principal_or_self` is the one check behind it, the close action and reply feedback.\n\nThe Executive can change the roster from a chat turn (`upsert_person`, `archive_person`, `set_department_head`) only when the principal asks, from the web chat, their own Slack or Discord, or a private Telegram chat when `TELEGRAM_WEBHOOK_SECRET` is set. A teammate, an email (even one from the principal's address), Google Chat, the CLI, the MCP server and unattended runs are refused, because a People row is also the web sign-in allow-list, the outbound-email allow-list and approval routing. The People page itself is unaffected.",
"mermaid": "flowchart TD\n People[\"People registry (Person, is_principal)\"]\n Dept[\"Departments (8 seeded once)\"]\n GC[\"Goals / checklists / cadences\"]\n Head[\"Head + voice persona\"]\n Gate[\"Authority gate (propose_only vs autonomous)\"]\n Scope[\"AuthorityScope to find_approvers\"]\n Chan[\"Channel resolution (Discord / Telegram / email)\"]\n Dept --> GC\n Dept --> Head\n Dept -->|proposes action| Gate\n Gate -->|required_scope| Scope\n Scope -->|ranks approvers| People\n People --> Chan\n Dept -->|team room| Chan\n class People storage\n class Dept storage\n class GC storage\n class Gate compute\n class Scope compute\n class Chan compute\n class Head compute",
- "generated_at": "2026-09-23T22:46:22.244621+00:00"
+ "generated_at": "2026-09-25T01:36:05.539643+00:00"
}
diff --git a/packages/core/openexecutive/architecture/prebuilt/scheduler.json b/packages/core/openexecutive/architecture/prebuilt/scheduler.json
index e164045b..06992b8a 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### Operator pause\n\nA global pause switch (`openexecutive.scheduler.pause`, one row in the `executive_control` table) stops everything the Executive starts on its own. It is the first check of every scheduler tick: while paused the tick does nothing — no alert/watchlist sweep, no claim — so due rows stay `pending` and fire on the first tick after resume. Actions already claimed when the pause lands run to completion; pausing holds work, it never cancels it. The same check gates the Gmail poller (the inbox is left unread) and the workflow resumer (no `wait_for_human` timeouts or resumes, and `apply_resolution` records a reply without kicking the run). Inbound conversations — web chat, Slack, Discord, Telegram, Google Chat — are deliberately not gated. The switch is set from the sidebar, the paused banner or Settings in the UI, or via `POST /executive/pause` / `POST /executive/resume`; each flip writes an `executive_paused` / `executive_resumed` audit row. Any signed-in caller may pause (it only holds work); resuming releases every held action at once, so it is the principal's alone (open only while no principal is on the roster). The state persists across restarts (boot logs a warning while paused) and across client-slot switches. `is_paused()` is read-only: a DB file or table that does not exist yet reads as \"running\", but a read error on an existing DB reads as \"paused\" — the brake fails closed, so a storage fault holds work rather than silently releasing it while the UI still shows \"paused\" (the UI shows \"status unknown\" when it cannot read the state).\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.",
+ "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### Operator pause\n\nA global pause switch (`openexecutive.scheduler.pause`, one row in the `executive_control` table) stops everything the Executive starts on its own. It is the first check of every scheduler tick: while paused the tick does nothing — no alert/watchlist sweep, no claim — so due rows stay `pending` and fire on the first tick after resume. Actions already claimed when the pause lands run to completion; pausing holds work, it never cancels it. The same check gates the Gmail poller (the inbox is left unread) and the workflow resumer (no `wait_for_human` timeouts or resumes, and `apply_resolution` records a reply without kicking the run). Inbound conversations — web chat, Slack, Discord, Telegram, Google Chat — are deliberately not gated. The switch is set from the sidebar, the paused banner or Settings in the UI, or via `POST /executive/pause` / `POST /executive/resume`; each flip writes an `executive_paused` / `executive_resumed` audit row. Any signed-in caller may pause (it only holds work); resuming releases every held action at once, so it is the principal's alone (open only while no principal is on the roster). The state persists across restarts (boot logs a warning while paused) and across client-slot switches. `is_paused()` is read-only: a DB file or table that does not exist yet reads as \"running\", but a read error on an existing DB reads as \"paused\" — the brake fails closed, so a storage fault holds work rather than silently releasing it while the UI still shows \"paused\" (the UI shows \"status unknown\" when it cannot read the state).\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### Department authority & cancelling\n\nA department-scoped row passes the authority gate (`departments.authority.gate_action`, see Org) before it is dispatched: `auto_execute` dispatches; `propose_only` raises an approval card and marks the row done without dispatching (deferred to the approver's next availability window when they are outside it); `escalate` raises an urgent `[ESCALATION]` card (severity high) straight away — never deferred — and likewise does not dispatch, because approving the card is what sends it. As that card is the action's only trace it always lands: unrouted when there is no approver and no principal, and deduped on the whole action (kind, channel, recipient and intent) rather than the summary's first 60 characters, so another escalation sharing an opening — or the same text for someone else — cannot swallow it. An identical escalation folds into a still-open card and gets a fresh one once that card was handled, and a card that cannot be written retries the row with backoff and, once the retries are spent, marks it `failed` — never `done`. (It used to raise the card *and* dispatch.) A gated `dept_cadence` row becomes a card and does not chain its next occurrence until the next startup bootstrap. Nudge-engine rows carry no department and bypass the gate.\n\nA `pending` row can be cancelled with `DELETE /scheduled/{id}` — the Pulse page's Cancel; the update only moves a row that is still `pending`, so one the scheduler has just claimed is never overwritten. Cancelling only stops work, so, like pause, any signed-in user may: the route accepts a signed-in caller through the UI proxy (its `x-caller-email`, trusted only alongside the `BACKEND_SHARED_SECRET` `x-api-key`), a matching `X-Admin-Token` (`SCHEDULED_ADMIN_TOKEN`, for scripts), or a loopback caller when no token is set — otherwise 401 (token set) or 503. Each cancel is audited as `scheduled_action_cancelled` with who did it.\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 Pause{\"is_paused()?<br/>(executive_control)\"}\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 --> Pause\n Pause -- \"paused: hold, sleep\" --> Loop\n Pause -- \"running\" --> 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-24T14:59:39.568371+00:00"
+ "generated_at": "2026-09-25T01:40:36.243753+00:00"
}
diff --git a/packages/core/openexecutive/audit/logger.py b/packages/core/openexecutive/audit/logger.py
index 1b369138..06f8870e 100644
--- a/packages/core/openexecutive/audit/logger.py
+++ b/packages/core/openexecutive/audit/logger.py
@@ -63,6 +63,7 @@ EVENT_TYPES: tuple[str, ...] = (
"attunement", # open loops opened / closed / expired, 👍/👎 on replies
"executive_paused", # operator paused autonomous work (scheduler/pause.py)
"executive_resumed", # operator resumed it; held work released
+ "scheduled_action_cancelled", # a person cancelled a pending action (DELETE /scheduled/{id})
)
diff --git a/packages/core/openexecutive/departments/authority.py b/packages/core/openexecutive/departments/authority.py
index 3725d676..b96ffd03 100644
--- a/packages/core/openexecutive/departments/authority.py
+++ b/packages/core/openexecutive/departments/authority.py
@@ -3,19 +3,22 @@
The gate is consulted whenever a proactive action (scheduled or cadence)
has a department slug — it reads the department's authority_level and
decides whether the action should execute immediately, be proposed to an
-approver, or be escalated to the principal.
+approver, or be escalated to an approver as urgent. Only `execute` runs the
+action; `propose` and `escalate` both wait for a person to approve it.
All callers are expected to pass `now` explicitly so the gate is
deterministic and easy to test without time mocking.
"""
from __future__ import annotations
+import hashlib
import logging
from datetime import UTC, datetime
from typing import Literal
from pydantic import BaseModel
+from openexecutive.alerts.models import AlertSeverity
from openexecutive.departments import registry as dept_registry
from openexecutive.departments.models import AuthorityLevel
from openexecutive.people.models import AuthorityScope
@@ -46,11 +49,12 @@ def gate_action(
Returns a GateDecision describing:
- execute — run the action immediately (auto_execute level or has consent)
- propose — surface to an approver; do not execute now
- - escalate — surface to principal AND execute (high-urgency escalation)
+ - escalate — surface to an approver as urgent, now; do not execute until
+ they approve (the level promises "the specialist will not act")
`deliver_at` is set when the best matching approver is outside their
- availability window — the caller should reschedule for that time instead
- of dispatching immediately.
+ availability window — a `propose` caller should reschedule for that time
+ instead of surfacing it immediately; an escalation does not wait.
"""
if now.tzinfo is None:
now = now.replace(tzinfo=UTC)
@@ -94,7 +98,7 @@ def gate_action(
reason=f"department {department_slug!r} has authority_level=propose_only",
)
- # ESCALATE: route to approver AND escalate (execute with notification).
+ # ESCALATE: route to an approver as urgent; nothing executes until they approve.
return _route_proposal(
department_slug=department_slug,
action="escalate",
@@ -129,7 +133,7 @@ def _route_proposal(
department_slug, scope,
)
return GateDecision(
- allowed=action == "escalate",
+ allowed=False,
action=action,
assignee_person_id=None,
deliver_at=None,
@@ -152,7 +156,7 @@ def _route_proposal(
deliver_at = None if in_window_now else next_available_window(assignee.id, after=now)
return GateDecision(
- allowed=action == "escalate",
+ allowed=False,
action=action,
assignee_person_id=assignee.id,
deliver_at=deliver_at,
@@ -166,50 +170,68 @@ def _route_proposal(
def propose_via_alert(
department_slug: str,
- person_id: int,
+ person_id: int | None,
summary: str,
body: str,
suggested_action: str = "",
extra_tags: list[str] | None = None,
*,
external_id_suffix: str = "",
+ severity: AlertSeverity = AlertSeverity.MEDIUM,
+ dedup_on: str | None = None,
+ raise_errors: bool = False,
) -> int | None:
"""Persist a proposal as an alert routed to a specific Person.
- Returns the alert id, or None if a duplicate was suppressed.
+ Returns the alert id, or None if a duplicate was suppressed. A store
+ failure is logged and also returns None, unless ``raise_errors``.
topic_tags carries both department and person identifiers so the UI
and future resolvers can filter/match without parsing the body;
``extra_tags`` lets a caller carry the originating alert's tags (e.g.
a ``comp`` / ``legal`` marker) onto the proposal.
- ``external_id_suffix`` turns the card into a recurring one: an open
- (unread) card with the same dedup key is refreshed in place with the new
- body — whatever its suffix, so one situation never has two open cards —
- and once the person has acted on it a fresh card is minted only when
- the suffix changes (callers pass e.g. the ISO week). Without a suffix
- the proposal is one-shot and a repeat with the same summary is
- suppressed for good. Coalescing keeps the open card's routing: a head
- change re-routes it only once the current card has been handled.
+ ``external_id_suffix`` makes the card recurring. An open (unread) card
+ with the same dedup key is refreshed in place with the new body —
+ whatever its suffix, so one situation never has two open cards.
+ Otherwise a new card is inserted under ``{dedup_key}:{suffix}``: after
+ the person has acted on a card, the next one lands only if its suffix
+ differs from the handled card's (a period such as the ISO week gives
+ one per period; a per-occurrence id gives one per occurrence). Without
+ a suffix the proposal is one-shot and a repeat is suppressed for good.
+ Coalescing keeps the open card's routing: a head change re-routes it
+ only once the current card has been handled.
+
+ ``person_id=None`` files the card unrouted: the Briefing lists every
+ unread card, so work with nobody to route to still reaches a person.
+ ``dedup_on`` keys the dedup on that text (hashed) instead of the
+ summary's first 60 characters.
"""
from openexecutive.alerts.store import coalesce_alert, insert_alert
- topic_tags = [f"department:{department_slug}", f"person:{person_id}"]
+ topic_tags = [f"department:{department_slug}"]
+ if person_id is not None:
+ topic_tags.append(f"person:{person_id}")
for tag in extra_tags or []:
if tag not in topic_tags:
topic_tags.append(tag)
- dedup_key = f"proposal:{department_slug}:{person_id}:{summary[:60]}"
+ route_key = "unrouted" if person_id is None else str(person_id)
+ subject = (
+ summary[:60] if dedup_on is None
+ else hashlib.sha256(dedup_on.encode()).hexdigest()[:16]
+ )
+ dedup_key = f"proposal:{department_slug}:{route_key}:{subject}"
external_id = f"{dedup_key}:{external_id_suffix}" if external_id_suffix else dedup_key
try:
if external_id_suffix and coalesce_alert(
- source="authority_gate", dedup_key=dedup_key, severity="medium", body=body,
+ source="authority_gate", dedup_key=dedup_key, severity=severity, body=body,
):
return None
return insert_alert(
source="authority_gate",
external_id=external_id,
- severity="medium",
+ severity=severity,
headline=summary,
body=body,
suggested_action=suggested_action,
@@ -218,13 +240,56 @@ def propose_via_alert(
routed_to_person_id=person_id,
)
except Exception:
+ if raise_errors:
+ raise
logger.exception(
- "authority_gate: propose_via_alert failed for dept=%r person=%d",
+ "authority_gate: propose_via_alert failed for dept=%r person=%s",
department_slug, person_id,
)
return None
+def escalate_via_alert(
+ department_slug: str,
+ person_id: int | None,
+ summary: str,
+ body: str,
+ suggested_action: str,
+ *,
+ action_key: str,
+ occurrence_id: str,
+) -> int | None:
+ """File the urgent card that holds an escalated action until a person
+ approves it.
+
+ Nothing is sent before approval, so this card is the action's only
+ trace and must never be silently lost:
+
+ - severity HIGH, so it ranks above routine proposals;
+ - keyed on ``action_key`` — the whole action (what, how, to whom) — so
+ another escalation that shares an opening, or the same text for someone
+ else, is a card of its own;
+ - an identical action whose card is still unread folds into that card;
+ once that card has been handled, ``occurrence_id`` (unique per
+ scheduled row) lets the next one land instead of colliding with the
+ handled card's external id;
+ - ``person_id=None`` files it unrouted rather than dropping it;
+ - a store failure raises, so the caller can retry rather than mark the
+ action done.
+ """
+ return propose_via_alert(
+ department_slug,
+ person_id,
+ summary,
+ body,
+ suggested_action,
+ severity=AlertSeverity.HIGH,
+ dedup_on=action_key,
+ external_id_suffix=occurrence_id,
+ raise_errors=True,
+ )
+
+
def cast_action(a: str) -> Literal["propose", "escalate"]:
"""Narrow an untyped string to the propose/escalate literal."""
if a == "escalate":
diff --git a/packages/core/openexecutive/memory/episodic.py b/packages/core/openexecutive/memory/episodic.py
index 63134254..19cc7d89 100644
--- a/packages/core/openexecutive/memory/episodic.py
+++ b/packages/core/openexecutive/memory/episodic.py
@@ -1470,10 +1470,16 @@ def cancel_scheduled_action(action_id: int, db_path: Path | None = None) -> str:
current = row["status"]
if current != "pending":
return "not_cancellable"
- conn.execute(
- "UPDATE scheduled_actions SET status = 'cancelled' WHERE id = ?",
+ # Guard the write too: the scheduler's claim can flip the row to
+ # 'running' between the SELECT and here, and a cancel must never
+ # overwrite a claimed row (the dispatch would go ahead regardless).
+ cursor = conn.execute(
+ "UPDATE scheduled_actions SET status = 'cancelled' "
+ "WHERE id = ? AND status = 'pending'",
(action_id,),
)
+ if cursor.rowcount == 0:
+ return "not_cancellable"
return "cancelled"
diff --git a/packages/core/openexecutive/orchestrator/action_chips.py b/packages/core/openexecutive/orchestrator/action_chips.py
index fadf7167..f4583295 100644
--- a/packages/core/openexecutive/orchestrator/action_chips.py
+++ b/packages/core/openexecutive/orchestrator/action_chips.py
@@ -152,9 +152,10 @@ def summarize_action(
# The Executive's prose will explain what went wrong; we just don't
# paint a green ✓ chip over a red outcome.
return None
- if parsed is not None and parsed.get("status") == "not_found":
- # The target row didn't exist, so nothing changed (e.g. archive_person
- # for an unknown person). No state change → no ✓ chip.
+ if parsed is not None and parsed.get("status") in ("not_found", "refused"):
+ # The target row didn't exist (e.g. archive_person for an unknown
+ # person), or the tool refused the caller (e.g. a roster change asked
+ # for by someone other than the principal). Nothing changed → no ✓ chip.
return None
if parsed is not None and parsed.get("noop") is True:
# Idempotent re-call (e.g. `ack_alert` after the briefing UI already
diff --git a/packages/core/openexecutive/orchestrator/people_tools.py b/packages/core/openexecutive/orchestrator/people_tools.py
index 6dcc702e..e9e29f42 100644
--- a/packages/core/openexecutive/orchestrator/people_tools.py
+++ b/packages/core/openexecutive/orchestrator/people_tools.py
@@ -238,6 +238,94 @@ def _audit(tool: str, kind: str, ok: bool, summary: str, details: dict[str, Any]
)
+# Surfaces that verify who sent every message: the web chat (the signed-in
+# Google account, stamped by the UI proxy), and Slack / Discord (the platform's
+# own user id, over an authenticated connection). Email (an unauthenticated
+# From header), Google Chat (no sender identity), the CLI, the MCP server and
+# unattended runs (scheduler, workflows, alert review) don't. Telegram only
+# sometimes — see `_is_verified_speaker_surface`.
+_VERIFIED_SPEAKER_CHANNELS = frozenset({"slack", "discord"})
+
+
+def _is_verified_speaker_surface(session: Any) -> bool:
+ if bool(getattr(session, "from_web_chat", False)):
+ return True
+ channel = str(getattr(session, "origin_channel", "") or "")
+ if channel in _VERIFIED_SPEAKER_CHANNELS:
+ return True
+ if channel != "telegram":
+ return False
+ # Telegram identifies the chat, not the sender, and its webhook is exempt
+ # from the shared secret: an update is only proven to come from Telegram
+ # when TELEGRAM_WEBHOOK_SECRET is set (otherwise anyone can post one naming
+ # the principal's chat id). A group (negative id) is everyone in it.
+ from openexecutive.config import get_settings
+
+ chat_ref = str(getattr(session, "origin_channel_ref", "") or "")
+ return bool(get_settings().telegram_webhook_secret) and chat_ref.isdigit()
+
+
+def _roster_refusal_reason(session: Any) -> str | None:
+ """None when this turn may change the roster, else what to tell the asker."""
+ from openexecutive.people.store import is_principal_or_self
+
+ from_web = bool(getattr(session, "from_web_chat", False))
+ if session is None or not _is_verified_speaker_surface(session):
+ return (
+ "Only the company's owner can change the People list, and this request "
+ "did not come from somewhere I can confirm it is them. Tell whoever "
+ "asked that the owner needs to make this change, from the web app or "
+ "their own Slack or Discord."
+ )
+ caller = getattr(session, "caller_person_id", None)
+ try:
+ if is_principal_or_self(caller, None):
+ return None
+ except Exception:
+ logger.exception("people_tools: principal lookup failed — refusing roster write")
+ if from_web and caller is None:
+ return (
+ "Only the company's owner can change the People list, and this signed-in "
+ "email is not on anyone's People entry, so I cannot confirm it is the "
+ "owner. If it is, they should add their sign-in email to their own "
+ "entry on the People page and ask again, or make the change there."
+ )
+ return (
+ "Only the company's owner can add, change or remove people or set "
+ "department heads, and this request came from someone else. Tell them "
+ "the owner needs to make this change."
+ )
+
+
+def _refuse_unless_owner(tool: str) -> str | None:
+ """The refusal tool result when this turn may not change the roster, else None.
+
+ A People row decides who may sign in to the web app, who the Executive may
+ email, and who approves what — and these tools are offered on every turn,
+ including one an inbound email, a Google Chat message or a teammate
+ started. So only the principal may change the roster from chat, and only on
+ a surface that verified it is them. The People page (behind the web
+ sign-in) is unaffected.
+ """
+ from openexecutive.orchestrator.schedule_tools import current_session
+
+ session = current_session.get()
+ reason = _roster_refusal_reason(session)
+ if reason is None:
+ return None
+ _audit(
+ tool, "write", False,
+ f"{tool} refused: not the principal on a verified surface",
+ {
+ "refused": True,
+ "caller_person_id": getattr(session, "caller_person_id", None),
+ "origin_channel": getattr(session, "origin_channel", "") or None,
+ "from_web_chat": bool(getattr(session, "from_web_chat", False)),
+ },
+ )
+ return json.dumps({"status": "refused", "detail": reason})
+
+
async def handle_list_people(tool_input: dict[str, Any]) -> str:
from openexecutive.people import store as people_store
@@ -280,6 +368,10 @@ async def handle_upsert_person(tool_input: dict[str, Any]) -> str:
_audit("upsert_person", "write", False, f"upsert_person bad input: {err}", {"error": err[:300]})
return json.dumps({"error": err})
+ refused = _refuse_unless_owner("upsert_person")
+ if refused is not None:
+ return refused
+
try:
full_name = str(tool_input["full_name"]).strip()
if not full_name:
@@ -405,6 +497,10 @@ async def handle_archive_person(tool_input: dict[str, Any]) -> str:
from openexecutive.people import registry as people_registry
from openexecutive.people import store as people_store
+ refused = _refuse_unless_owner("archive_person")
+ if refused is not None:
+ return refused
+
try:
person_id = int(tool_input["person_id"])
except (KeyError, TypeError, ValueError) as exc:
@@ -445,6 +541,10 @@ async def handle_set_department_head(tool_input: dict[str, Any]) -> str:
from openexecutive.departments.head_persona import ensure_head_persona_override
from openexecutive.people import store as people_store
+ refused = _refuse_unless_owner("set_department_head")
+ if refused is not None:
+ return refused
+
try:
department_slug = str(tool_input["department_slug"]).strip()
if not department_slug:
diff --git a/packages/core/openexecutive/scheduler/runner.py b/packages/core/openexecutive/scheduler/runner.py
index b9dd3a63..bd923270 100644
--- a/packages/core/openexecutive/scheduler/runner.py
+++ b/packages/core/openexecutive/scheduler/runner.py
@@ -231,7 +231,11 @@ async def _execute_action(
# Authority gate — only applies to department-scoped actions.
# ------------------------------------------------------------------
if action.department:
- from openexecutive.departments.authority import gate_action, propose_via_alert
+ from openexecutive.departments.authority import (
+ escalate_via_alert,
+ gate_action,
+ propose_via_alert,
+ )
from openexecutive.people.models import AuthorityScope
from openexecutive.people.registry import get_person
from openexecutive.scheduler.action_phrasing import describe_executive_action
@@ -303,22 +307,54 @@ async def _execute_action(
return
if decision.action == "escalate":
- # Create alert AND fall through to dispatch.
- if decision.assignee_person_id is not None:
- propose_via_alert(
- department_slug=action.department,
- person_id=decision.assignee_person_id,
+ # Hold for a human, flagged urgent; do NOT dispatch. The setting
+ # promises "the specialist will not act — it forwards everything
+ # to a human", and the card's "If you approve: … right away" line
+ # is what sends it — dispatching here as well acted before anyone
+ # agreed, then acted again on approval. Unlike `propose`, an
+ # escalation is never deferred to the approver's window. The card
+ # is the action's only trace (see `escalate_via_alert` for how it
+ # is kept from being lost); if it cannot be written the row is
+ # retried with backoff and finally marked failed — never done.
+ try:
+ escalate_via_alert(
+ action.department,
+ decision.assignee_person_id,
summary=f"[ESCALATION] {action.intent_text[:140]}",
body=action.intent_text,
suggested_action=_proposed_action_phrase(urgent=True),
+ action_key="|".join((
+ action.kind, action.channel, action.channel_ref,
+ str(action.assigned_to_person_id), action.intent_text,
+ )),
+ occurrence_id=str(action.id),
)
- else:
+ except Exception as exc:
+ logger.exception(
+ "scheduler: escalation card for action %d could not be filed",
+ action.id,
+ )
+ if mark_action_failed_or_retry(
+ action.id, f"escalation card could not be filed: {exc}"
+ ) == "failed":
+ logger.error(
+ "scheduler: escalated action %d dept=%r gave up — no "
+ "card was filed and nothing was sent",
+ action.id, action.department,
+ )
+ return
+ if decision.assignee_person_id is None:
logger.warning(
- "scheduler: escalate for dept=%r has no assignee — "
- "alert skipped, dispatch continues",
- action.department,
+ "scheduler: escalate for dept=%r has no approver — "
+ "action %d filed as an unrouted card",
+ action.department, action.id,
)
- # fall through → dispatch proceeds below
+ mark_action_done(action.id)
+ logger.info(
+ "scheduler: action %d escalated to person %s — not dispatched",
+ action.id, decision.assignee_person_id,
+ )
+ return
# ------------------------------------------------------------------
# Department cadence — run the check-in workflow, then chain the next
diff --git a/packages/core/tests/integration/test_scheduled_api.py b/packages/core/tests/integration/test_scheduled_api.py
index b5a7642f..43276f86 100644
--- a/packages/core/tests/integration/test_scheduled_api.py
+++ b/packages/core/tests/integration/test_scheduled_api.py
@@ -16,6 +16,16 @@ from openexecutive.memory.episodic import (
)
[email protected](autouse=True)
+def _isolate_audit_and_secret(monkeypatch: pytest.MonkeyPatch) -> None:
+ # A cancel writes an audit row; keep it out of ./episodic_memory.db. And a
+ # BACKEND_SHARED_SECRET leaking in from the shell must not change the
+ # admin-token / loopback cases these tests pin (signed-in cancels are
+ # covered in tests/unit/test_scheduled_cancel_permission.py).
+ monkeypatch.setattr("openexecutive.audit.log_event", lambda *a, **k: None)
+ monkeypatch.delenv("BACKEND_SHARED_SECRET", raising=False)
+
+
@pytest.fixture()
def client(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> TestClient:
db_path = tmp_path / "episodic.db"
diff --git a/packages/core/tests/unit/test_action_chips.py b/packages/core/tests/unit/test_action_chips.py
index d3790074..6ded4372 100644
--- a/packages/core/tests/unit/test_action_chips.py
+++ b/packages/core/tests/unit/test_action_chips.py
@@ -147,6 +147,27 @@ def test_chip_suppressed_on_not_found() -> None:
assert chip is None
+ ("tool_name", "tool_input"),
+ [
+ ("upsert_person", {"full_name": "Mallory"}),
+ ("archive_person", {"person_id": 3}),
+ ("set_department_head", {"department_slug": "legal", "person_id": 3}),
+ ],
+)
+def test_chip_suppressed_when_roster_change_is_refused(
+ tool_name: str, tool_input: dict
+) -> None:
+ # A roster change asked for by someone other than the principal is refused
+ # (people_tools returns `status: refused`), so no "Updated …" ✓ chip.
+ chip = summarize_action(
+ tool_name=tool_name,
+ tool_input=tool_input,
+ tool_result=json.dumps({"status": "refused", "detail": "owner only"}),
+ )
+ assert chip is None
+
+
def test_run_workflow_chip_with_link() -> None:
chip = summarize_action(
tool_name="run_workflow",
diff --git a/packages/core/tests/unit/test_authority_gate.py b/packages/core/tests/unit/test_authority_gate.py
index c6eed3b5..febd7a3a 100644
--- a/packages/core/tests/unit/test_authority_gate.py
+++ b/packages/core/tests/unit/test_authority_gate.py
@@ -151,8 +151,9 @@ def test_propose_only_approver_outside_window_sets_deliver_at() -> None:
# ESCALATE
# ---------------------------------------------------------------------------
-def test_escalate_routes_and_is_allowed() -> None:
- """ESCALATE should set action='escalate' and allowed=True (dispatch continues)."""
+def test_escalate_routes_and_is_not_allowed() -> None:
+ """ESCALATE routes to an approver and is NOT allowed to execute: the level
+ promises "the specialist will not act" until a person approves."""
_set_dept_level("legal", AuthorityLevel.ESCALATE)
principal_id = people_store.upsert_person(
full_name="Founder", is_principal=True
@@ -161,10 +162,20 @@ def test_escalate_routes_and_is_allowed() -> None:
decision = gate_action("legal", "ad_hoc", now=_NOW)
assert decision.action == "escalate"
- assert decision.allowed is True
+ assert decision.allowed is False
assert decision.assignee_person_id == principal_id
+def test_escalate_with_no_approver_is_not_allowed() -> None:
+ """With nobody to ask, an escalation still must not execute."""
+ _set_dept_level("legal", AuthorityLevel.ESCALATE)
+
+ decision = gate_action("legal", "ad_hoc", now=_NOW)
+ assert decision.action == "escalate"
+ assert decision.allowed is False
+ assert decision.assignee_person_id is None
+
+
# ---------------------------------------------------------------------------
# Missing department
# ---------------------------------------------------------------------------
diff --git a/packages/core/tests/unit/test_people_tools.py b/packages/core/tests/unit/test_people_tools.py
index 10d11c29..925845a3 100644
--- a/packages/core/tests/unit/test_people_tools.py
+++ b/packages/core/tests/unit/test_people_tools.py
@@ -1,13 +1,17 @@
"""Unit tests for openexecutive.orchestrator.people_tools.
These tools let the Executive add/update/archive people and assign
-department heads from inside a chat turn (no UI round-trip).
+department heads from inside a chat turn (no UI round-trip) — for the
+principal only, on a surface that verified it is them.
"""
from __future__ import annotations
import asyncio
import json
+from collections.abc import Iterator
+from contextlib import contextmanager
from pathlib import Path
+from typing import Any
import pytest
@@ -21,6 +25,8 @@ from openexecutive.orchestrator.people_tools import (
handle_set_department_head,
handle_upsert_person,
)
+from openexecutive.orchestrator.schedule_tools import current_session
+from openexecutive.orchestrator.session import Session
from openexecutive.people import registry as people_registry
from openexecutive.people import store as people_store
@@ -43,6 +49,38 @@ def shared_db(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
return db_path
[email protected](autouse=True)
+def audit_calls(monkeypatch: pytest.MonkeyPatch) -> list[dict[str, Any]]:
+ """Capture the tools' audit rows instead of writing ./episodic_memory.db."""
+ calls: list[dict[str, Any]] = []
+
+ def _fake_log_event(event_type: str, summary: str, **kwargs: Any) -> None:
+ calls.append({"event_type": event_type, "summary": summary, **kwargs})
+
+ monkeypatch.setattr("openexecutive.audit.log_event", _fake_log_event)
+ return calls
+
+
[email protected](autouse=True)
+def owner_id(shared_db: Path) -> Iterator[int]:
+ """Run every call as the principal in the signed-in web chat — a turn
+ that may change the roster. Tests of refusals rebind with `_turn`."""
+ pid = people_store.upsert_person(full_name="Owner Olivia", is_principal=True)
+ people_registry.invalidate()
+ token = current_session.set(Session(from_web_chat=True, caller_person_id=pid))
+ yield pid
+ current_session.reset(token)
+
+
+@contextmanager
+def _turn(session: Session | None) -> Iterator[None]:
+ token = current_session.set(session)
+ try:
+ yield
+ finally:
+ current_session.reset(token)
+
+
def _call(coro_fn, payload: dict) -> dict:
return json.loads(asyncio.run(coro_fn(payload)))
@@ -276,6 +314,156 @@ def test_upsert_preserves_is_principal_on_update() -> None:
assert refreshed.role == "Founder"
+# --------------------------------------------------------------------------- #
+# Only the principal, on a surface that verified it is them, may change the
+# roster. A roster row decides web sign-in, who the Executive may email and who
+# approves what — and these tools are offered on every turn.
+# --------------------------------------------------------------------------- #
+
+
+def _names() -> set[str]:
+ return {p.full_name for p in people_store.list_people()}
+
+
+def test_owner_on_their_own_slack_can_change_the_roster(owner_id: int) -> None:
+ with _turn(Session(origin_channel="slack", caller_person_id=owner_id)):
+ result = _call(handle_upsert_person, {"full_name": "Cindy Lee"})
+ assert result["status"] == "ok"
+ assert "Cindy Lee" in _names()
+
+
[email protected]("surface", [
+ {"origin_channel": "slack"},
+ {"origin_channel": "discord"},
+ {"origin_channel": "telegram"},
+ {"from_web_chat": True},
+])
+def test_teammate_cannot_change_the_roster(surface: dict[str, Any]) -> None:
+ teammate = people_store.upsert_person(full_name="Ben Teammate")
+ with _turn(Session(caller_person_id=teammate, **surface)):
+ added = _call(handle_upsert_person, {
+ "full_name": "Mallory", "email": "[email protected]",
+ "authority_scopes": ["wildcard"],
+ })
+ promoted = _call(handle_upsert_person, {
+ "person_id": teammate, "full_name": "Ben Teammate",
+ "authority_scopes": ["wildcard"],
+ })
+ assert added["status"] == "refused"
+ assert promoted["status"] == "refused"
+ assert "owner" in added["detail"]
+ assert "Mallory" not in _names()
+ ben = people_store.get_person(teammate)
+ assert ben is not None and ben.authority_scope == []
+
+
[email protected]("surface", [
+ # An inbound email: the poller resolves the From header to a person, but a
+ # From header proves nothing — even when it names the principal.
+ {"session_id": "email:thread-1"},
+ {"origin_channel": "google_chat"},
+ # The CLI, the MCP server and unattended runs set no surface either.
+ {},
+], ids=["email", "google_chat", "no_surface"])
+def test_unverified_surfaces_cannot_change_the_roster(
+ owner_id: int, surface: dict[str, Any]
+) -> None:
+ with _turn(Session(caller_person_id=owner_id, **surface)):
+ result = _call(handle_upsert_person, {"full_name": "Mallory"})
+ assert result["status"] == "refused"
+ assert "web app" in result["detail"]
+ assert "Mallory" not in _names()
+
+
+def test_owner_in_a_private_telegram_chat_can_change_the_roster(
+ owner_id: int, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ monkeypatch.setenv("TELEGRAM_WEBHOOK_SECRET", "hook-secret")
+ session = Session(origin_channel="telegram", origin_channel_ref="424242",
+ caller_person_id=owner_id)
+ with _turn(session):
+ result = _call(handle_upsert_person, {"full_name": "Cindy Lee"})
+ assert result["status"] == "ok"
+
+
[email protected](("secret", "chat_ref"), [
+ # No webhook secret: /webhook/telegram accepts anyone's POST naming any
+ # chat id, so a Telegram "principal" proves nothing.
+ (None, "424242"),
+ # A group chat (negative id) is every member of the group.
+ ("hook-secret", "-100424242"),
+], ids=["no_webhook_secret", "group_chat"])
+def test_unverifiable_telegram_cannot_change_the_roster(
+ owner_id: int, monkeypatch: pytest.MonkeyPatch, secret: str | None, chat_ref: str
+) -> None:
+ # An empty value, not delenv: Settings also reads the repo .env, which a
+ # developer may have filled in; the process env wins over it.
+ monkeypatch.setenv("TELEGRAM_WEBHOOK_SECRET", secret or "")
+ session = Session(origin_channel="telegram", origin_channel_ref=chat_ref,
+ caller_person_id=owner_id)
+ with _turn(session):
+ result = _call(handle_upsert_person, {"full_name": "Mallory"})
+ assert result["status"] == "refused"
+ assert "Mallory" not in _names()
+
+
+def test_background_run_with_no_conversation_cannot_change_the_roster() -> None:
+ with _turn(None):
+ result = _call(handle_upsert_person, {"full_name": "Mallory"})
+ assert result["status"] == "refused"
+ assert "Mallory" not in _names()
+
+
+def test_unlinked_web_user_is_told_how_to_prove_they_are_the_owner() -> None:
+ # Signed in, but their email is on no People entry — e.g. a new owner who
+ # has not added it to their own row yet.
+ with _turn(Session(from_web_chat=True, caller_person_id=None)):
+ result = _call(handle_upsert_person, {"full_name": "Cindy Lee"})
+ assert result["status"] == "refused"
+ assert "People page" in result["detail"]
+ assert "Cindy Lee" not in _names()
+
+
+def test_archived_owner_cannot_change_the_roster(owner_id: int) -> None:
+ people_store.archive_person(owner_id)
+ result = _call(handle_upsert_person, {"full_name": "Cindy Lee"})
+ assert result["status"] == "refused"
+
+
+def test_archive_and_department_head_are_owner_only_too() -> None:
+ dept = dept_store.create_department("Legal")
+ teammate = people_store.upsert_person(full_name="Ben Teammate")
+ with _turn(Session(origin_channel="slack", caller_person_id=teammate)):
+ archived = _call(handle_archive_person, {"person_id": teammate})
+ head = _call(handle_set_department_head, {
+ "department_slug": dept.config.slug, "person_id": teammate,
+ })
+ assert archived["status"] == "refused"
+ assert head["status"] == "refused"
+ assert teammate in {p.id for p in people_store.list_people()}
+ refreshed = dept_store.get_department(dept.config.slug)
+ assert refreshed is not None and refreshed.config.head_person_id is None
+
+
+def test_refusal_is_audited(audit_calls: list[dict[str, Any]]) -> None:
+ teammate = people_store.upsert_person(full_name="Ben Teammate")
+ with _turn(Session(origin_channel="discord", caller_person_id=teammate)):
+ _call(handle_upsert_person, {"full_name": "Mallory"})
+ refused = [c for c in audit_calls if c["details"].get("refused")]
+ assert len(refused) == 1
+ assert refused[0]["details"]["tool"] == "upsert_person"
+ assert refused[0]["details"]["ok"] is False
+ assert refused[0]["details"]["caller_person_id"] == teammate
+ assert refused[0]["details"]["origin_channel"] == "discord"
+
+
+def test_reading_the_roster_stays_open_to_everyone() -> None:
+ teammate = people_store.upsert_person(full_name="Ben Teammate")
+ with _turn(Session(origin_channel="slack", caller_person_id=teammate)):
+ result = _call(handle_list_people, {})
+ assert "Ben Teammate" in {p["full_name"] for p in result["people"]}
+
+
# --------------------------------------------------------------------------- #
# ask_about_person — Honcho-backed directional peer-memory query
# --------------------------------------------------------------------------- #
diff --git a/packages/core/tests/unit/test_scheduled_actions_store.py b/packages/core/tests/unit/test_scheduled_actions_store.py
index cd761fc1..208776dd 100644
--- a/packages/core/tests/unit/test_scheduled_actions_store.py
+++ b/packages/core/tests/unit/test_scheduled_actions_store.py
@@ -1,8 +1,12 @@
"""Unit tests for the scheduled_actions table CRUD helpers in episodic memory."""
from __future__ import annotations
+import sqlite3
+from collections.abc import Iterator
+from contextlib import contextmanager
from datetime import UTC, datetime, timedelta
from pathlib import Path
+from typing import Any
import pytest
@@ -226,6 +230,55 @@ def test_cancel_missing_returns_not_found(db: Path) -> None:
assert cancel_scheduled_action(9999, db_path=db) == "not_found"
+def test_cancel_never_overwrites_a_row_claimed_mid_cancel(
+ db: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """The scheduler's claim can land between the status check and the write;
+ the write must then match nothing rather than cancel a running action."""
+ from openexecutive.memory import episodic
+
+ action_id = insert_scheduled_action(
+ run_at=_future(), channel="telegram", channel_ref="1", intent_text="t", db_path=db,
+ )
+ real_get_conn = episodic._get_conn
+
+ class _Fetched:
+ def __init__(self, row: Any) -> None:
+ self._row = row
+
+ def fetchone(self) -> Any:
+ return self._row
+
+ class _ClaimAfterStatusCheck:
+ """Connection proxy: the claim happens right after the status SELECT."""
+
+ def __init__(self, conn: sqlite3.Connection) -> None:
+ self._conn = conn
+
+ def execute(self, sql: str, params: tuple[Any, ...] = ()) -> Any:
+ cursor = self._conn.execute(sql, params)
+ if sql.startswith("SELECT status FROM scheduled_actions"):
+ row = cursor.fetchone()
+ self._conn.execute(
+ "UPDATE scheduled_actions SET status = 'running' WHERE id = ?", params
+ )
+ return _Fetched(row)
+ return cursor
+
+ @contextmanager
+ def _racing_conn(db_path: Path) -> Iterator[_ClaimAfterStatusCheck]:
+ with real_get_conn(db_path) as conn:
+ yield _ClaimAfterStatusCheck(conn)
+
+ monkeypatch.setattr(episodic, "_get_conn", _racing_conn)
+ assert cancel_scheduled_action(action_id, db_path=db) == "not_cancellable"
+ monkeypatch.undo()
+
+ row = get_scheduled_action(action_id, db_path=db)
+ assert row is not None
+ assert row.status == "running"
+
+
def test_count_pending_for_channel_ref(db: Path) -> None:
insert_scheduled_action(
run_at=_future(),
diff --git a/packages/core/tests/unit/test_scheduled_cancel_permission.py b/packages/core/tests/unit/test_scheduled_cancel_permission.py
new file mode 100644
index 00000000..177395d8
--- /dev/null
+++ b/packages/core/tests/unit/test_scheduled_cancel_permission.py
@@ -0,0 +1,202 @@
+"""Who may cancel a pending scheduled action (DELETE /scheduled/{id}).
+
+The Pulse page's Cancel button reaches the API through the UI proxy, which
+cannot send SCHEDULED_ADMIN_TOKEN, so on a deployed server (non-loopback) the
+button used to fail. A signed-in user coming through the proxy — proven by the
+shared secret plus the caller email the proxy stamps — may now cancel, the same
+"stopping is safe" rule the pause switch uses. A caller email on its own proves
+nothing, and every successful cancel is audited with who did it.
+"""
+from __future__ import annotations
+
+from datetime import UTC, datetime, timedelta
+from pathlib import Path
+from typing import Any
+
+import pytest
+from fastapi import FastAPI
+from fastapi.testclient import TestClient
+
+from openexecutive.api.routes.scheduled import router as scheduled_router
+from openexecutive.memory.episodic import (
+ get_scheduled_action,
+ initialize_db,
+ insert_scheduled_action,
+)
+
+_REMOTE = ("203.0.113.5", 50000)
+_LOOPBACK = ("127.0.0.1", 50000)
+_SECRET = "shared-s3cret"
+
+
[email protected](autouse=True)
+def _db(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ db_path = tmp_path / "episodic.db"
+ initialize_db(db_path)
+ monkeypatch.setattr("openexecutive.memory.episodic.DB_PATH", db_path)
+ # Empty rather than deleted: Settings also reads the repo .env (a
+ # developer's may set the token) and the process env wins over it.
+ monkeypatch.setenv("SCHEDULED_ADMIN_TOKEN", "")
+ monkeypatch.delenv("BACKEND_SHARED_SECRET", raising=False)
+
+
[email protected](autouse=True)
+def audit_calls(monkeypatch: pytest.MonkeyPatch) -> list[dict[str, Any]]:
+ """Capture audit rows instead of writing them to ./episodic_memory.db."""
+ calls: list[dict[str, Any]] = []
+
+ def _fake_log_event(event_type: str, summary: str, **kwargs: Any) -> None:
+ calls.append({"event_type": event_type, "summary": summary, **kwargs})
+
+ monkeypatch.setattr("openexecutive.audit.log_event", _fake_log_event)
+ return calls
+
+
+def _client(host: tuple[str, int]) -> TestClient:
+ app = FastAPI()
+ app.include_router(scheduled_router)
+ return TestClient(app, client=host)
+
+
+def _pending_action() -> int:
+ return insert_scheduled_action(
+ run_at=(datetime.now(UTC) + timedelta(hours=1)).isoformat(),
+ channel="slack_dm",
+ channel_ref="U123",
+ intent_text="Chase Dana about the vendor quote",
+ )
+
+
+def _status(action_id: int) -> str:
+ row = get_scheduled_action(action_id)
+ assert row is not None
+ return row.status
+
+
+def test_signed_in_user_can_cancel_on_a_deployed_server(
+ monkeypatch: pytest.MonkeyPatch, audit_calls: list[dict[str, Any]]
+) -> None:
+ monkeypatch.setenv("BACKEND_SHARED_SECRET", _SECRET)
+ action_id = _pending_action()
+
+ resp = _client(_REMOTE).delete(
+ f"/scheduled/{action_id}",
+ headers={"x-api-key": _SECRET, "x-caller-email": "[email protected]"},
+ )
+
+ assert resp.status_code == 200
+ assert resp.json()["status"] == "cancelled"
+ assert _status(action_id) == "cancelled"
+ assert len(audit_calls) == 1
+ assert audit_calls[0]["event_type"] == "scheduled_action_cancelled"
+ assert audit_calls[0]["actor"] == "[email protected]"
+ assert audit_calls[0]["details"]["action_id"] == action_id
+
+
+def test_caller_email_with_a_wrong_secret_is_refused(
+ monkeypatch: pytest.MonkeyPatch, audit_calls: list[dict[str, Any]]
+) -> None:
+ monkeypatch.setenv("BACKEND_SHARED_SECRET", _SECRET)
+ action_id = _pending_action()
+
+ resp = _client(_REMOTE).delete(
+ f"/scheduled/{action_id}",
+ headers={"x-api-key": "guess", "x-caller-email": "[email protected]"},
+ )
+
+ assert resp.status_code == 503
+ assert _status(action_id) == "pending"
+ assert audit_calls == []
+
+
+def test_caller_email_is_not_trusted_without_a_configured_secret(
+ audit_calls: list[dict[str, Any]],
+) -> None:
+ # With no shared secret anyone who can reach the API could write the header.
+ action_id = _pending_action()
+
+ resp = _client(_REMOTE).delete(
+ f"/scheduled/{action_id}", headers={"x-caller-email": "[email protected]"}
+ )
+
+ assert resp.status_code == 503
+ assert _status(action_id) == "pending"
+ assert audit_calls == []
+
+
+def test_secret_without_a_signed_in_email_is_refused(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setenv("BACKEND_SHARED_SECRET", _SECRET)
+ action_id = _pending_action()
+
+ resp = _client(_REMOTE).delete(
+ f"/scheduled/{action_id}", headers={"x-api-key": _SECRET}
+ )
+
+ assert resp.status_code == 503
+ assert _status(action_id) == "pending"
+
+
+def test_signed_in_user_can_cancel_even_when_an_admin_token_is_set(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setenv("BACKEND_SHARED_SECRET", _SECRET)
+ monkeypatch.setenv("SCHEDULED_ADMIN_TOKEN", "admin-123")
+ action_id = _pending_action()
+
+ resp = _client(_REMOTE).delete(
+ f"/scheduled/{action_id}",
+ headers={"x-api-key": _SECRET, "x-caller-email": "[email protected]"},
+ )
+
+ assert resp.status_code == 200
+ assert _status(action_id) == "cancelled"
+
+
+def test_admin_token_still_cancels_and_is_audited(
+ monkeypatch: pytest.MonkeyPatch, audit_calls: list[dict[str, Any]]
+) -> None:
+ monkeypatch.setenv("SCHEDULED_ADMIN_TOKEN", "admin-123")
+ action_id = _pending_action()
+ client = _client(_REMOTE)
+
+ assert client.delete(f"/scheduled/{action_id}").status_code == 401
+ assert (
+ client.delete(
+ f"/scheduled/{action_id}", headers={"X-Admin-Token": "nope"}
+ ).status_code
+ == 401
+ )
+ resp = client.delete(
+ f"/scheduled/{action_id}", headers={"X-Admin-Token": "admin-123"}
+ )
+
+ assert resp.status_code == 200
+ assert _status(action_id) == "cancelled"
+ assert [c["actor"] for c in audit_calls] == ["admin-token"]
+
+
+def test_loopback_without_an_admin_token_still_cancels(
+ audit_calls: list[dict[str, Any]],
+) -> None:
+ action_id = _pending_action()
+
+ resp = _client(_LOOPBACK).delete(f"/scheduled/{action_id}")
+
+ assert resp.status_code == 200
+ assert _status(action_id) == "cancelled"
+ assert [c["actor"] for c in audit_calls] == ["local"]
+
+
+def test_already_finished_action_is_not_audited_as_cancelled(
+ monkeypatch: pytest.MonkeyPatch, audit_calls: list[dict[str, Any]]
+) -> None:
+ monkeypatch.setenv("BACKEND_SHARED_SECRET", _SECRET)
+ action_id = _pending_action()
+ headers = {"x-api-key": _SECRET, "x-caller-email": "[email protected]"}
+ client = _client(_REMOTE)
+
+ assert client.delete(f"/scheduled/{action_id}", headers=headers).status_code == 200
+ assert client.delete(f"/scheduled/{action_id}", headers=headers).status_code == 409
+ assert len(audit_calls) == 1
diff --git a/packages/core/tests/unit/test_scheduler_routes_to_person.py b/packages/core/tests/unit/test_scheduler_routes_to_person.py
index 8806b86d..3e19884d 100644
--- a/packages/core/tests/unit/test_scheduler_routes_to_person.py
+++ b/packages/core/tests/unit/test_scheduler_routes_to_person.py
@@ -26,6 +26,9 @@ def _isolated(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(people_store, "DB_PATH", db)
monkeypatch.setattr(episodic, "DB_PATH", db)
monkeypatch.setattr(alert_store, "DB_PATH", db)
+ # Dispatch writes a "delivered" audit row; keep it out of the default
+ # ./episodic_memory.db, where it leaks into other modules' assertions.
+ monkeypatch.setattr("openexecutive.audit.log_event", lambda *a, **k: None)
dept_registry.invalidate()
people_registry.invalidate()
@@ -195,10 +198,10 @@ def test_auto_execute_dispatches() -> None:
# ---------------------------------------------------------------------------
-# escalate → alert created AND dispatch proceeds
+# escalate → urgent alert created, nothing dispatched until someone approves
# ---------------------------------------------------------------------------
-def test_escalate_creates_alert_and_dispatches() -> None:
+def test_escalate_creates_urgent_alert_and_holds() -> None:
dept_store.seed_default_departments()
dept_store.update_department("legal", authority_level=AuthorityLevel.ESCALATE)
principal_id = people_store.upsert_person(
@@ -213,29 +216,187 @@ def test_escalate_creates_alert_and_dispatches() -> None:
with patch(
"openexecutive.orchestrator.executive.Executive.chat",
new_callable=AsyncMock,
- ) as mock_chat, patch(
- "openexecutive.onboarding.profile_builder.load_or_create_profile",
- return_value=MagicMock(is_empty=lambda: True),
- ), patch(
- "openexecutive.knowledge.retriever.retrieve",
- return_value="",
- ), patch(
- "openexecutive.memory.episodic.format_for_prompt",
- return_value="",
- ):
+ ) as mock_chat:
asyncio.run(_execute_action(action, gateway=None))
- # Alert should have been created (escalate creates a proposal alert).
+ # Nothing is sent: "Escalates to a human" promises the specialist will not act.
+ mock_chat.assert_not_called()
+
+ # An urgent card went to the approver instead.
alerts = alert_store.list_alerts()
assert len(alerts) == 1
+ assert alerts[0].headline.startswith("[ESCALATION]")
+ assert alerts[0].severity == "high" # ranks above routine proposals
+ assert alerts[0].routed_to_person_id == principal_id
assert "department:legal" in alerts[0].topic_tags
- # Escalation phrasing is the concrete action with an urgency tail, not the
- # old "Escalated ... action — review immediately." meta-instruction.
+ # Escalation phrasing is the concrete action with an urgency tail — what
+ # approving the card will do, not something already done.
assert alerts[0].suggested_action.startswith("Send this")
assert alerts[0].suggested_action.endswith("right away.")
- # Dispatch should also have happened.
- mock_chat.assert_called_once()
+ updated = episodic.get_scheduled_action(action.id)
+ assert updated is not None
+ assert updated.status == "done"
+
+
+def test_escalate_is_not_deferred_to_approver_window() -> None:
+ """Unlike propose, an escalation reaches the approver now, even off-hours."""
+ dept_store.seed_default_departments()
+ dept_store.update_department("legal", authority_level=AuthorityLevel.ESCALATE)
+ approver_id = people_store.upsert_person(full_name="Sarah", slack_user_id="U_GC")
+ people_store.set_authority_scope(approver_id, [AuthorityScope.WILDCARD])
+ # Available only on Sundays 09-10 UTC. Whether or not that is now, an
+ # escalation must not be rescheduled to the approver's next window.
+ people_store.set_availability(approver_id, [
+ AvailabilityWindow(weekdays=[6], start_local="09:00", end_local="10:00", timezone="UTC")
+ ])
+ dept_registry.invalidate()
+ people_registry.invalidate()
+
+ action = _make_action(department="legal")
+
+ with patch(
+ "openexecutive.orchestrator.executive.Executive.chat",
+ new_callable=AsyncMock,
+ ) as mock_chat:
+ asyncio.run(_execute_action(action, gateway=None))
+
+ mock_chat.assert_not_called()
+ alerts = alert_store.list_alerts()
+ assert len(alerts) == 1
+ assert alerts[0].routed_to_person_id == approver_id
+ updated = episodic.get_scheduled_action(action.id)
+ assert updated is not None
+ assert updated.status == "done" # not rescheduled back to pending
+
+
+def test_escalate_with_nobody_to_ask_files_an_unrouted_card() -> None:
+ """No approver and no principal: the held action must still reach the
+ Briefing (which lists unrouted cards), never vanish with a log line."""
+ dept_store.seed_default_departments()
+ dept_store.update_department("legal", authority_level=AuthorityLevel.ESCALATE)
+ dept_registry.invalidate()
+ people_registry.invalidate()
+
+ action = _make_action(department="legal")
+
+ with patch(
+ "openexecutive.orchestrator.executive.Executive.chat",
+ new_callable=AsyncMock,
+ ) as mock_chat:
+ asyncio.run(_execute_action(action, gateway=None))
+
+ mock_chat.assert_not_called()
+ alerts = alert_store.list_alerts()
+ assert len(alerts) == 1
+ assert alerts[0].headline.startswith("[ESCALATION]")
+ assert alerts[0].routed_to_person_id is None
+ assert not any(t.startswith("person:") for t in alerts[0].topic_tags)
+ updated = episodic.get_scheduled_action(action.id)
+ assert updated is not None
+ assert updated.status == "done"
+
+
+def _escalate(intent_text: str, channel_ref: str = "U123") -> None:
+ episodic.insert_scheduled_action(
+ run_at=(_now() - timedelta(seconds=10)).isoformat(),
+ channel="slack_dm",
+ channel_ref=channel_ref,
+ intent_text=intent_text,
+ department="legal",
+ )
+ (action,) = episodic.claim_due_actions(_now())
+ with patch(
+ "openexecutive.orchestrator.executive.Executive.chat",
+ new_callable=AsyncMock,
+ ) as mock_chat:
+ asyncio.run(_execute_action(action, gateway=None))
+ mock_chat.assert_not_called()
+
+
+def test_escalations_sharing_an_opening_are_separate_cards() -> None:
+ """With nothing sent before approval, the card is the action's only trace:
+ two escalations whose first 60 characters match must not dedup."""
+ dept_store.seed_default_departments()
+ dept_store.update_department("legal", authority_level=AuthorityLevel.ESCALATE)
+ principal_id = people_store.upsert_person(full_name="Founder", is_principal=True)
+ people_store.set_authority_scope(principal_id, [AuthorityScope.WILDCARD])
+ dept_registry.invalidate()
+ people_registry.invalidate()
+ opening = "Send the NDA redline follow-up to Acme's counsel regarding section "
+
+ _escalate(opening + "4")
+ _escalate(opening + "7")
+ _escalate(opening + "7") # an identical repeat folds into the open card
+
+ bodies = sorted(a.body for a in alert_store.list_alerts())
+ assert bodies == [opening + "4", opening + "7"]
+
+
+def test_same_text_for_different_recipients_is_two_cards() -> None:
+ """Who an action goes to lives outside its intent text, so it must be part
+ of the dedup — else the second recipient's action merges into the first
+ card and is marked done with no trace."""
+ dept_store.seed_default_departments()
+ dept_store.update_department("legal", authority_level=AuthorityLevel.ESCALATE)
+ principal_id = people_store.upsert_person(full_name="Founder", is_principal=True)
+ people_store.set_authority_scope(principal_id, [AuthorityScope.WILDCARD])
+ dept_registry.invalidate()
+ people_registry.invalidate()
+
+ _escalate("Send the weekly status reminder", channel_ref="U1")
+ _escalate("Send the weekly status reminder", channel_ref="U2")
+
+ assert len(alert_store.list_alerts()) == 2
+
+
+def test_repeat_escalation_after_its_card_was_handled_gets_a_new_card() -> None:
+ dept_store.seed_default_departments()
+ dept_store.update_department("legal", authority_level=AuthorityLevel.ESCALATE)
+ principal_id = people_store.upsert_person(full_name="Founder", is_principal=True)
+ people_store.set_authority_scope(principal_id, [AuthorityScope.WILDCARD])
+ dept_registry.invalidate()
+ people_registry.invalidate()
+
+ _escalate("Department check-in: Legal")
+ (first,) = alert_store.list_alerts()
+ alert_store.set_status(first.id, "ack") # the principal approved it
+
+ _escalate("Department check-in: Legal") # next time: must not be swallowed
+
+ cards = alert_store.list_alerts()
+ assert len(cards) == 2
+ assert sorted(c.status for c in cards) == ["ack", "unread"]
+
+
+def test_escalation_is_retried_not_marked_done_when_its_card_cannot_be_filed(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ dept_store.seed_default_departments()
+ dept_store.update_department("legal", authority_level=AuthorityLevel.ESCALATE)
+ principal_id = people_store.upsert_person(full_name="Founder", is_principal=True)
+ people_store.set_authority_scope(principal_id, [AuthorityScope.WILDCARD])
+ dept_registry.invalidate()
+ people_registry.invalidate()
+
+ def _store_down(**_kwargs: object) -> int:
+ raise RuntimeError("database is locked")
+
+ monkeypatch.setattr(alert_store, "insert_alert", _store_down)
+ action = _make_action(department="legal")
+
+ with patch(
+ "openexecutive.orchestrator.executive.Executive.chat",
+ new_callable=AsyncMock,
+ ) as mock_chat:
+ asyncio.run(_execute_action(action, gateway=None))
+
+ mock_chat.assert_not_called()
+ updated = episodic.get_scheduled_action(action.id)
+ assert updated is not None
+ assert updated.status == "pending" # rescheduled with backoff, not lost
+ assert updated.attempts == 1
+ assert "escalation card could not be filed" in updated.last_error
# ---------------------------------------------------------------------------
diff --git a/packages/ui/src/lib/api.ts b/packages/ui/src/lib/api.ts
index 70b1e4f4..0ab9a9d0 100644
--- a/packages/ui/src/lib/api.ts
+++ b/packages/ui/src/lib/api.ts
@@ -1189,8 +1189,10 @@ export async function cancelScheduledAction(id: number): Promise<ScheduledAction
throw new Error("Action is no longer pending — can't cancel.");
}
if (res.status === 401 || res.status === 503) {
+ // Signed-in users can cancel once the API and the UI share
+ // BACKEND_SHARED_SECRET (every internet-reachable deploy sets it).
throw new Error(
- "Cancel is gated by SCHEDULED_ADMIN_TOKEN. The UI doesn't forward this header yet — cancel from a loopback client or unset the token.",
+ "Cancel isn't enabled on this server yet. Ask your administrator to set the same BACKEND_SHARED_SECRET on the API and the UI.",
);
}
if (!res.ok) throw new Error("Failed to cancel scheduled action");