Skip to content

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

feat(departments): let goals stand on their own with an owner (#594)

Rufus3efcb0938b61
diff --git a/packages/core/openexecutive/api/models.py b/packages/core/openexecutive/api/models.py
index 3b286b5d..99349cfc 100644
--- a/packages/core/openexecutive/api/models.py
+++ b/packages/core/openexecutive/api/models.py
@@ -390,6 +390,9 @@ class WorkspaceResponse(BaseModel):
# only to the principal, like the role; empty for anyone else.
company_domains: list[str] = Field(default_factory=list)
company_domains_custom: bool = False
+ # Whether any department exists. The UI shows the Departments tab only
+ # then: goals stand on their own, so a workspace may never need one.
+ has_departments: bool = False
class WorkspaceUpdateRequest(BaseModel):
diff --git a/packages/core/openexecutive/api/routes/departments.py b/packages/core/openexecutive/api/routes/departments.py
index 850235bb..774644c8 100644
--- a/packages/core/openexecutive/api/routes/departments.py
+++ b/packages/core/openexecutive/api/routes/departments.py
@@ -134,19 +134,17 @@ class GoalCreate(BaseModel):
target: str = Field(default="", max_length=512)
current: str = Field(default="", max_length=512)
status: GoalStatus = "on_track"
+ # Who the goal is on. Unset = the department's lead, else the principal.
+ owner_person_id: int | None = None
class GoalCreateInArea(GoalCreate):
- """A goal for an area named in words: an existing one by slug or title,
- else a new area of that name, else (blank) ``DEFAULT_GOAL_AREA``."""
+ """A goal that may name its department in words: an existing one by slug
+ or title, else a new one of that name. Blank = no department."""
area: str = Field(default="", max_length=80)
-# Where a goal goes when no area is named.
-DEFAULT_GOAL_AREA = "General"
-
-
class GoalPatch(BaseModel):
# Stripped first, so a whitespace-only goal or period is rejected like "".
model_config = ConfigDict(str_strip_whitespace=True)
@@ -157,6 +155,18 @@ class GoalPatch(BaseModel):
target: str | None = Field(default=None, max_length=512)
current: str | None = Field(default=None, max_length=512)
status: GoalStatus | None = None
+ # Sent as null to clear: no owner of its own / no department.
+ owner_person_id: int | None = None
+ department_slug: str | None = None
+
+
+class GoalView(Goal):
+ """A goal as the Goals page reads it: who it is on (its own owner, else
+ its department's lead, else the principal) and its department's title."""
+
+ owner_id: int | None = None
+ owner_name: str = ""
+ department_title: str | None = None
def _translate_legacy_body(body: dict) -> dict:
@@ -310,12 +320,25 @@ def _current_period_value(period_type: str) -> str:
return default_period_value(period_type, today)
-def _create_goal(slug: str, body: GoalCreate) -> Goal:
- if store.get_department(slug) is None:
+def _check_owner(person_id: int | None) -> None:
+ if person_id is None:
+ return
+ from openexecutive.people import store as people_store
+
+ person = people_store.get_person(person_id)
+ # A goal is owned by someone on the team, never an outside contact.
+ if person is None or person.archived or person.kind != "team":
+ raise HTTPException(status_code=422, detail="Unknown owner")
+
+
+def _create_goal(slug: str | None, body: GoalCreate) -> Goal:
+ if slug is not None and store.get_department(slug) is None:
raise HTTPException(status_code=404, detail="Unknown department")
+ _check_owner(body.owner_person_id)
period_value = (body.period_value or "").strip() or _current_period_value(body.period_type)
goal_id = store.insert_goal(
slug,
+ owner_person_id=body.owner_person_id,
period_type=body.period_type,
period_value=period_value,
key_result=body.key_result,
@@ -332,10 +355,21 @@ def _create_goal(slug: str, body: GoalCreate) -> Goal:
return goal
-def _patch_goal(slug: str, goal_id: int, body: GoalPatch) -> Goal:
+def _patch_goal(slug: str | None, goal_id: int, body: GoalPatch) -> Goal:
+ """``slug`` None = the department-free ``/goals/{id}`` route, which may
+ reach any goal; a department route reaches only that department's."""
existing = store.get_goal(goal_id)
- if existing is None or existing.department_slug != slug:
+ if existing is None or (slug is not None and existing.department_slug != slug):
raise HTTPException(status_code=404, detail="Unknown Goal for department")
+ sent = body.model_fields_set
+ moves: dict[str, object] = {}
+ if "owner_person_id" in sent:
+ _check_owner(body.owner_person_id)
+ moves["owner_person_id"] = body.owner_person_id
+ if "department_slug" in sent:
+ if body.department_slug and store.get_department(body.department_slug) is None:
+ raise HTTPException(status_code=422, detail="Unknown department")
+ moves["department_slug"] = body.department_slug or None
store.update_goal(
goal_id,
period_type=body.period_type,
@@ -344,6 +378,7 @@ def _patch_goal(slug: str, goal_id: int, body: GoalPatch) -> Goal:
target=body.target,
current=body.current,
status=body.status,
+ **moves, # type: ignore[arg-type]
)
updated = store.get_goal(goal_id)
if updated is None:
@@ -352,9 +387,9 @@ def _patch_goal(slug: str, goal_id: int, body: GoalPatch) -> Goal:
return updated
-def _delete_goal_impl(slug: str, goal_id: int) -> None:
+def _delete_goal_impl(slug: str | None, goal_id: int) -> None:
existing = store.get_goal(goal_id)
- if existing is None or existing.department_slug != slug:
+ if existing is None or (slug is not None and existing.department_slug != slug):
raise HTTPException(status_code=404, detail="Unknown Goal for department")
store.delete_goal(goal_id)
registry.invalidate()
@@ -369,23 +404,55 @@ def create_goal(slug: str, body: GoalCreate) -> Goal:
return _create_goal(slug, body)
[email protected]("/goals", response_model=list[GoalView])
+def list_all_goals() -> list[GoalView]:
+ """Every goal, with or without a department, with its owner resolved."""
+ from openexecutive.departments.goals import list_goal_views
+
+ return [
+ GoalView(
+ **v.goal.model_dump(),
+ owner_id=v.owner_id,
+ owner_name=v.owner_name,
+ department_title=v.department_title,
+ )
+ for v in list_goal_views()
+ ]
+
+
@router.post("/goals", response_model=Goal, status_code=status.HTTP_201_CREATED)
def create_goal_in_area(body: GoalCreateInArea) -> Goal:
- """Add a goal by area name, creating the area when there is none by that
- name. The Goals page uses it when the workspace has no areas yet (setup
- creates none for a solo workspace or a team that names none). Like
- ``POST /departments``, a new area gets no specialist."""
- title = body.area or DEFAULT_GOAL_AREA
+ """Add a goal. With ``area`` blank it has no department; a named area is
+ matched to an existing department by slug or title, else created (like
+ ``POST /departments``, with no specialist; its goals are then graded by
+ the weekly goal review, ``departments.goal_review``)."""
+ title = body.area.strip()
store.initialize_db()
- known = [d.config for d in store.list_departments()]
- match = store.match_department(title, known)
- if match is None:
- try:
- match = store.create_department(title).config
- except ValueError as exc:
- raise HTTPException(status_code=422, detail=str(exc)) from exc
- registry.invalidate()
- return _create_goal(match.slug, GoalCreate.model_validate(body.model_dump(exclude={"area"})))
+ slug: str | None = None
+ if title:
+ known = [d.config for d in store.list_departments()]
+ match = store.match_department(title, known)
+ if match is None:
+ try:
+ match = store.create_department(title).config
+ except ValueError as exc:
+ raise HTTPException(status_code=422, detail=str(exc)) from exc
+ registry.invalidate()
+ slug = match.slug
+ return _create_goal(slug, GoalCreate.model_validate(body.model_dump(exclude={"area"})))
+
+
[email protected]("/goals/{goal_id}", response_model=Goal)
+def patch_any_goal(goal_id: int, body: GoalPatch) -> Goal:
+ """Edit a goal wherever it is, including moving it between departments
+ (``department_slug``, null = none) or owners (``owner_person_id``)."""
+ return _patch_goal(None, goal_id, body)
+
+
[email protected]("/goals/{goal_id}", status_code=status.HTTP_204_NO_CONTENT)
+def delete_any_goal(goal_id: int) -> Response:
+ _delete_goal_impl(None, goal_id)
+ return Response(status_code=status.HTTP_204_NO_CONTENT)
@router.patch("/departments/{slug}/goals/{goal_id}", response_model=Goal)
diff --git a/packages/core/openexecutive/api/routes/today.py b/packages/core/openexecutive/api/routes/today.py
index 51b90ff1..4e84eb6b 100644
--- a/packages/core/openexecutive/api/routes/today.py
+++ b/packages/core/openexecutive/api/routes/today.py
@@ -39,6 +39,7 @@ from openexecutive.clients.cockpit import ClientCockpitCard, format_practice_for
if TYPE_CHECKING:
from openexecutive.alerts.models import Alert
from openexecutive.briefing.reader import Reader
+ from openexecutive.departments.models import Goal
from openexecutive.people.models import Person
logger = logging.getLogger(__name__)
@@ -51,6 +52,10 @@ StaleInsight = tuple["Person", dict[str, Any], str]
# Most attention-worthy (off-track/at-risk) goals shown inline on a Department
# card before the card defers the rest to the department page.
_DEPT_ATTENTION_GOAL_CAP = 3
+# The briefing row that holds the goals with no department (slug ""). It is
+# shaped like a department so every reader of `departments` (the narrative,
+# the header, the digest, the fingerprint) counts its at-risk goals too.
+UNASSIGNED_GOALS_TITLE = "Other goals"
router = APIRouter()
@@ -68,9 +73,14 @@ class GoalBrief(BaseModel):
current: str
target: str
status: str # "at_risk" | "off_track" (the only statuses surfaced here)
+ # Who the goal is on: its own owner, else the department's lead, else the
+ # principal (``departments.goals.effective_owner_id``). Additive.
+ owner_id: int | None = None
+ owner_name: str = ""
class DepartmentBriefItem(BaseModel):
+ # "" for the row of goals with no department (UNASSIGNED_GOALS_TITLE).
slug: str
title: str
authority_level: str
@@ -743,38 +753,55 @@ def _build_today(
if slug:
dept_awaiting[slug] = dept_awaiting.get(slug, 0) + 1
- dept_items = []
- for ds in depts:
- cfg = ds.config
- at_risk = sum(1 for g in ds.goals if g.status == "at_risk")
- off_track = sum(1 for g in ds.goals if g.status == "off_track")
+ from openexecutive.departments.goals import list_goal_views
+
+ try:
+ views = list_goal_views()
+ except Exception:
+ logger.warning("today: goal owners unreadable", exc_info=True)
+ views = []
+ owner_by_goal = {v.goal.id: (v.owner_id, v.owner_name) for v in views}
+
+ def _brief_row(
+ slug: str, title: str, authority_level: str, goals: list[Goal]
+ ) -> DepartmentBriefItem:
# Surface the actual problem goals inline on the card — off_track
# (worse) before at_risk, capped so a department with many goals can't
# blow out the card. Goals already loaded, so no extra query. The id
# tiebreaker makes intra-tier order deterministic regardless of how
- # ds.goals was loaded (today it's ORDER BY id; this pins it).
+ # the goals were loaded (today it's ORDER BY id; this pins it).
attention = sorted(
- (g for g in ds.goals if g.status in ("off_track", "at_risk")),
+ (g for g in goals if g.status in ("off_track", "at_risk")),
key=lambda g: (0 if g.status == "off_track" else 1, g.id or 0),
)[:_DEPT_ATTENTION_GOAL_CAP]
- dept_items.append(DepartmentBriefItem(
- slug=cfg.slug,
- title=cfg.title,
- authority_level=cfg.authority_level.value,
- goal_count=len(ds.goals),
- at_risk_count=at_risk,
- off_track_count=off_track,
- awaiting_count=dept_awaiting.get(cfg.slug, 0),
+ return DepartmentBriefItem(
+ slug=slug,
+ title=title,
+ authority_level=authority_level,
+ goal_count=len(goals),
+ at_risk_count=sum(1 for g in goals if g.status == "at_risk"),
+ off_track_count=sum(1 for g in goals if g.status == "off_track"),
+ awaiting_count=dept_awaiting.get(slug, 0) if slug else 0,
attention_goals=[
GoalBrief(
key_result=g.key_result,
current=g.current,
target=g.target,
status=g.status,
+ owner_id=owner_by_goal.get(g.id, (None, ""))[0],
+ owner_name=owner_by_goal.get(g.id, (None, ""))[1],
)
for g in attention
],
- ))
+ )
+
+ dept_items = [
+ _brief_row(ds.config.slug, ds.config.title, ds.config.authority_level.value, ds.goals)
+ for ds in depts
+ ]
+ unassigned = [v.goal for v in views if not v.goal.department_slug]
+ if unassigned:
+ dept_items.append(_brief_row("", UNASSIGNED_GOALS_TITLE, "", unassigned))
# Per-person insight notes only earn their model call when the brief has a
# roster to show: the UI renders the People sidebar only for more than one
@@ -1566,7 +1593,19 @@ def _viewer_slice(response: TodayResponse, viewer: PersonBriefItem) -> dict[str,
p for p in _action_proposals(response.proposals)
if p.routed_to_person_id == viewer.id
]
- departments = [d for d in response.departments if d.slug in depts]
+ departments = [d for d in response.departments if d.slug and d.slug in depts]
+ # Of the goals with no department, only the ones on this teammate.
+ for d in response.departments:
+ if d.slug:
+ continue
+ mine = [g for g in d.attention_goals if g.owner_id == viewer.id]
+ if mine:
+ departments.append(d.model_copy(update={
+ "goal_count": len(mine),
+ "at_risk_count": sum(1 for g in mine if g.status == "at_risk"),
+ "off_track_count": sum(1 for g in mine if g.status == "off_track"),
+ "attention_goals": mine,
+ }))
return {
"departments": [d.model_dump() for d in departments],
"people": [],
diff --git a/packages/core/openexecutive/api/routes/workspace.py b/packages/core/openexecutive/api/routes/workspace.py
index 077b7949..f8300ff7 100644
--- a/packages/core/openexecutive/api/routes/workspace.py
+++ b/packages/core/openexecutive/api/routes/workspace.py
@@ -45,10 +45,20 @@ def _response(*, with_role: bool = True) -> WorkspaceResponse:
effective_timezone=workspace_settings.get_user_timezone().key,
company_domains=domains,
company_domains_custom=with_role and bool(ws.company_domains),
+ has_departments=_has_departments(),
**role.model_dump(),
)
+def _has_departments() -> bool:
+ from openexecutive.departments import registry
+
+ try:
+ return bool(registry.list_states())
+ except Exception: # noqa: BLE001 - an unreadable table reads as none.
+ return False
+
+
@router.get("/workspace", response_model=WorkspaceResponse)
def get_workspace(request: Request) -> WorkspaceResponse:
from openexecutive.api.routes.chat import _caller_is_principal_or_unclaimed
diff --git a/packages/core/openexecutive/architecture/architecture-facts.yaml b/packages/core/openexecutive/architecture/architecture-facts.yaml
index a9e18ae6..99e1ee0b 100644
--- a/packages/core/openexecutive/architecture/architecture-facts.yaml
+++ b/packages/core/openexecutive/architecture/architecture-facts.yaml
@@ -1255,6 +1255,35 @@ routing:
and `contacts_reachable_now()`, decides whether a turn may reach a
contact at all (egress, calendar attendees, `message_person` and the
raw DM tools) — see `integrations.channel_access`.
+ standalone_goals: |
+ A goal has an owner and, optionally, a department
+ (departments.models.Goal: `department_slug` and `owner_person_id` are
+ both nullable). Why: departments are heavyweight (a lead, authority,
+ a channel, a check-in) and most small teams and solo users never want
+ them, but every goal still needs someone it is on and a weekly check.
+ The owner is resolved at read time (`departments.goals.
+ effective_owner_id`): own owner, else the department's head, else the
+ principal; storing NULL keeps a goal following its department when the
+ head changes. Coverage: a department with a specialist grades its own
+ goals in its check-in; every other goal (no department, or a department
+ with no specialist) is graded weekly by the `goal_review` scheduled kind
+ (`departments.goal_review`, `GOAL_REVIEW_TIME`, default
+ weekly@mon@09:00, both modes) with `cso` (`goals.FALLBACK_REVIEWER`),
+ reusing the check-in's verdict contract and `persist_goal_verdicts`.
+ It skips goals graded within six days and unedited since, so a quiet
+ week costs no model call. Deleting a department detaches its goals
+ (an unowned goal takes the head as owner first) instead of deleting
+ them. Migration `_migrate_goals_stand_alone` rebuilds the table once to
+ drop NOT NULL, then adds `owner_person_id` (no backfill). Routes:
+ `GET /goals` (with owner name and department title), `POST /goals`
+ (blank area = no department), `PATCH`/`DELETE /goals/{id}`. The org
+ block renders goals with no department with their goal_id (team:
+ `## Goals With No Department`; solo: `### No area`); the brief adds an
+ "Other goals" row (slug "") shaped like a department so every reader of
+ `departments` counts them, and attention goals carry the owner. The UI
+ shows the Departments tab only when `GET /workspace` reports
+ `has_departments`, and adding a teammate while solo switches the
+ workspace to team mode without asking.
department_tools: |
`list_department_goals` and `update_department_goal`
(openexecutive.orchestrator.department_tools) let the Executive
@@ -1262,8 +1291,11 @@ routing:
a chat turn — used when the user reports progress ("we shipped
the migration") or a setback ("we lost the deal"). Phase B —
closes the loop opened by `department_check_in` workflow in Phase
- A (see `departments.goal_review_persistence`). Both tools require
- `department_slug`; `update_department_goal` requires `goal_id` +
+ A (see `departments.goal_review_persistence`). Neither needs a
+ department: `list_department_goals` without `department_slug` lists
+ every goal with its owner and department, and `update_department_goal`
+ names a goal by `goal_id` alone (a `department_slug` it is given must
+ match the goal's department). `update_department_goal` requires `goal_id` +
`rationale` and at least one of `status`/`current`. `rationale` is
stored in the audit log (never on the goal row) so future readers
see the provenance of every chat-driven change. The handler enforces
@@ -1341,7 +1373,12 @@ routing:
stable tool prefix. The solo persona teaches it (`_SOLO_CREATE_GOAL`);
team mode learns it from the tool description, so the team persona
stays byte-identical.
- Evals: `department_goal_update_005`.
+ Goals stand on their own: `create_goal` leaves `area` out unless the
+ principal names one (a goal with no area creates no department) and
+ takes an optional `owner_person_id` (a non-archived team member, else
+ refused). The duplicate check and the 8-goal cap apply to the goals
+ with no department as one group.
+ Evals: `department_goal_update_005`, `department_goal_update_006`.
`record_decision_outcome` (orchestrator/decision_tools.py, both modes)
records how a past decision turned out. The weekly review lists up to
three decisions older than 30 days with an empty outcome as
diff --git a/packages/core/openexecutive/architecture/prebuilt/agents.json b/packages/core/openexecutive/architecture/prebuilt/agents.json
index 9a5ba278..a904992e 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. That context is per call and never cached: `<company_stage>` (the stage from the company profile — specialists never see the profile itself), in solo mode `<principal_role>` (what kind of principal the advice is for, in plain words, with their title and remit — `router.principal_role_context`), `<department_memory>`, `<past_decisions>`, `<failure_cases>` (the shipped case studies, and under them the workspace's own lessons that match the call, `memory/lessons.py`), `<relevant_knowledge>` and `<conversation_context>`, outermost first. The specialist's own system prompt is a static domain constant under one `cache_control` block, so it stays byte-identical across companies and profile edits. A chat turn takes the stage from its session's profile (the one the Executive reasons over, and the one an eval scenario injects); workflow steps and the MCP server's `consult_specialist` read it fresh from the profile on disk. The role tag follows the turn's mode: a chat turn pins the role on its session with the mode (`pin_turn_principal_role`: the session's `principal_role` override, else the workspace settings) and sends it in solo and nothing in team, so the org block, every specialist in the turn and any workflow the turn starts see the same role; callers with no chat turn read it fresh (`load_principal_role`: the current session's mode and role, else the workspace's), and a failed read sends no tag rather than failing the consult. The CFO, CSO and sales prompts key their advice on it: for a bootstrapped, self-funded or solo company they drop venture fundraising benchmarks and work from cash, and raise only if the founder wants to.\n\nRouting uses one `consult_specialist` tool. When to call it is spelled out in the persona's Domain Expertise section (\"Going deeper\") and in the tool's own description: any question that asks for judgment in a specialist's area (a decision, plan, analysis, negotiation, hire, contract term, pricing or fundraising move, board message, or a department's own targets and stance, since the specialist holds that department's memory) is consulted before the answer, several at once across areas; lookups in mail, calendar or documents, scheduling, status checks, routine drafting and questions about how the Executive works are answered without one. Chat eval scenarios hold this: `required_routing` names specialists the turn must consult and `no_routing: true` says it must consult none, and the runner fails a scenario that misses either (`evals.scenarios.routing_check`). Beside it the Executive carries two skill tools, `search_skills` and `load_skill` (skills are shown to users as **playbooks**, and every playbook belongs to a workflow: one that follows it, or its own Quick workflow). Chat finds and reads playbooks but never creates or changes one: work worth repeating is offered as a workflow through `draft_workflow`, with the method written into its steps, because workflows read playbooks at run time (approved scheduled ones included) and this loop also runs on inbound email and chat, so only a person 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, Quick ones included, 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. Goals have three tools: `list_department_goals`, `update_department_goal` (progress the user reports) and `create_goal` (a new goal the principal states, filed under an area by slug or title and creating the area when none matches — see Org). `create_goal` runs only for the principal on a verified surface, and no unattended run is offered it: the tools in `schedule_tools.UNATTENDED_WITHHELD_TOOLS` are dropped from reflection's and research's toolkits by `unattended_toolkit`, and from the chat loop when its Session is marked `unattended` — the scheduler's PROACTIVE TRIGGER run, whose prompt quotes stored intent text; a call the model emits anyway gets an error tool_result. `record_decision_outcome` records how a past decision turned out — the weekly review lists decisions older than 30 days with no outcome as `[decision N]` — writing `decisions.outcome` (`episodic.update_decision`) and auditing the rationale; it has `create_goal`'s gate (the principal on a verified surface only; everyone else gets an audited refusal) and is in `UNATTENDED_WITHHELD_TOOLS` too. A missing or unknown id returns the decisions still waiting on an outcome, so the model can retry with the right one. Its schema is static; the solo persona has one line on it, and team mode learns it from the tool description, so the team persona is byte-identical. 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. `assign_open_loop` opens one on request (\"ask Ben to send me the Q3 numbers by Friday\") for the principal or a rostered teammate on a verified surface — never an email, a turn private to the principal or an unattended run, which are also withheld the tool — and only when `task` appears verbatim in what the speaker typed this turn, at most 5 per turn; that turn's extraction pass then opens no second loop for the same owner. The owner is told once on their own channel when someone else assigns it, and the result's `notified` says how that went, so the Executive reports it rather than messaging them as well. 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, a channel whose adapter verified the sender itself (`Session.speaker_verified`, with the `caller_person_id` it resolved, never on a turn an email started), or a private Telegram chat when `TELEGRAM_WEBHOOK_SECRET` is set to a value Telegram can send (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 team member's People row is also the web sign-in and outbound-email allow-list. `upsert_person` takes `kind` (`team` / `contact`; a new person defaults to `contact` in solo mode, an update keeps the current kind) and `email_aliases` (other addresses the person writes from — the full list, replacing the current one; they match mail and may be emailed but never sign in, and one already on someone else is refused), and after every write any pending roster request whose sender now matches someone is closed and its held messages replayed. `resolve_roster_request` answers a **roster request** — someone not on the People list who wrote in and is waiting (see Org): `approve` (a new person; `kind` defaults to team for a company-domain sender, else contact, when the principal did not say), `link` (someone already listed, by `person_id`; `replace_channel_id` only when the principal said so) or `decline`. It has the roster tools' gate (the principal on a verified surface; audited refusal otherwise), is in `UNATTENDED_WITHHELD_TOOLS`, and answers only an id in `Session.trusted_roster_request_ids` — the ids the server printed that turn in a `<roster_requests>` block (`briefing.context.format_roster_requests_for_prompt`, up to 10 pending requests), which `render_and_trust` appends to the `<briefing>` digest on the principal's own verified turn only and records on the session in the same step, so an id the model invents or reads out of a message adds nobody. Each line is server-derived — id, channel, address or account id, the sender's name sanitised and marked unverified, a company-domain hint, the message count — and never what they wrote. The block rides in the **user turn**, like the digest, so the cached system blocks are unchanged; the tool definition is static, and the new tool only extends the sorted tool list. The web chat route resets the trusted set every turn, and a resolved id is removed from it. and `list_people` returns both kinds with `kind` — contacts only on the principal's own verified turn (they are private to the principal; anyone else gets the team as if no contact existed), each with what is remembered about them from the principal's own mail and meetings (`what_you_deal_with`, `topics`, `recent_activity`, from `people.contact_notes`) so the Executive can suggest who to ask, and their contact details (`details`: phones, links, address), both on that turn only — while `lookup_person` searches the team only. `ask_about_person` on one of the principal's contacts, on the principal's own turn, returns that contact note instead of peer memory (contacts never chat, so peer memory has nothing on them); otherwise it reads a person's peer memory fully only on their own verified turn; anyone else's answers only to a verified principal or teammate, and only when that person turned on \"Share my work style with the team\", framed to how they work and never their view of a colleague, and otherwise returns the same \"hasn't chosen to share\" result whether or not anything is known. A teammate's own mail with the Executive is theirs the same way: every mailbox call the model makes through the MCP gateway (Gmail or Outlook, by `call_tool`, from a script, or a workflow step run from chat) passes through `orchestrator.teammate_mail`. A search excludes every other teammate's address server-side, except on mail the reader is also on, and is filtered again entry by entry; any other call that names a message or thread (read, attachment, reply, forward, label) must use an id a filtered search returned to the same reader in this conversation (`Session.mail_ids_seen`) or the inbound email the turn answers; reads are filtered message by message, so a message naming another teammate is left out unless the reader is in its From / To / Cc; a reply that would quote such a thread, or an Outlook forward, reply or attachment read of such a message, is refused; and a conversation in which a teammate other than the principal was shown their own mail becomes theirs alone, as Act as me's do. Outside mail and the reader's own are untouched; an email turn reads as its sender only when Gmail authenticated it, and any other unverified reader sees no teammate's mail, a background run the model drives reads as the principal and a workflow step outside any session as nobody, an Outlook inbox rule that forwards or names another teammate is refused, and the poller and the brief, which read the mailbox themselves, are unaffected. Their own chats are theirs too: every audit row of a teammate's verified turn is theirs (`people_tools.teammate_turn_owner`, see Audit; the principal sees the actions, never the words), and a teammate's web chat or DM opens for them alone (`chat._session_access`), the principal included. The same verified-principal rule, as `people_tools.contacts_reachable_now()`, decides whether a turn may reach a **contact** at all: `message_person`, the raw DM tools, `create_calendar_event` / `create_instant_meeting` attendees and the MCP gateway's Gmail / Calendar / Drive / OneDrive gates treat a contact exactly like an unknown person on every other turn, so no refusal reveals that one exists. **The untrusted-content policy** (`orchestrator.content_trust`) is one rule for text the principal did not write — inbound email, chat, attached files, watched pages — answering three questions for every surface. *Who is speaking*: the principal only when the surface proved it (`principal_speaking`: the web chat as the principal — never a signed-in email on nobody's People entry —, the CLI, their own Slack/Discord or a secret-verified Telegram chat, or their own address with Gmail's `dmarc=pass`); never a teammate, a stranger, Google Chat, the MCP server or an unattended run. *What may become memory*: episodic extraction runs only then, and only on the words outside `<untrusted_content>` blocks; peer memory and open loops are recorded under the speaker's own name, never as the principal's. *What may trigger tools*: every write on the principal's authority already refuses others in its handler; the tools with no such check that change the install for every later turn — `content_trust.PRINCIPAL_ONLY_TOOLS`: `load_mcp_server`, `list_saved_tools`, `run_python_job` and `run_script` — are not offered unless the principal is speaking on an interactive surface (not email, even authenticated), and a call the model emits anyway gets an error tool_result and a `refused: not_principal` audit row. So an inbound email, a teammate's turn, Google Chat and the scheduler's proactive trigger each get a stable tool list of their own without it. A send or edit on a team member's turn also meets their department's authority first (`orchestrator.department_gate`, see Org), and so does one on a turn whose speaker is on no People entry: a signed-in web caller or a chat-channel sender, which in practice is Google Chat, since Slack, Telegram and Discord turn unmatched senders away. Google Chat names a matched sender to the gate alone (`gate_sender_person_id`), so the principal there is not held. Email turns are left to the mailbox's own gates. *How it is labelled*: outside text goes into the user turn inside `<untrusted_content source=… author=… author_verified=…>` with a fixed notice that it carries no authority; compatibility forms are folded (NFKC), control characters go, and the tag's name is renamed wherever the text carries it — any case, spacing or entity-escaped form — so the text cannot end its block and speak outside it.\n\n**Outside content** (`orchestrator.outside_content`). Once a turn has read text from outside the team (any gateway read, an attachment, a web search result, a synced Drive, OneDrive, Confluence or Notion excerpt, `read_document`, research, or an extension tool registered `reads_outside`), the rest of that turn refuses what the Act as me lockdown refuses, every `upsert_person` but a contact the speaker named in this message at an address they typed or one that sent the mail read (`lockdown.speaker_named_contact`; never on a turn answering mail from someone not in People, and a refused one points to an `add_contact` card), and every `call_tool` but a read: no mail, Docs, Sheets, Drive or calendar write. The company's own Drive is not outside: a Google read of one file, Doc, Sheet, deck or folder by id (`company_read_item`) is looked up first (`vet_reads`, once per id a turn), and when that item is owned by someone at the company, or kept on a shared drive only the company organizes, and shared with nobody outside it (`mcp_gateway._company_item`), the read marks the turn as a company read (`COMPANY`) instead. That still holds everything else, since anyone who can edit the file wrote its words, but when every read so far was of the company's own items, a rename or move (`update_drive_file` with only `file_id`, `name`, `add_parents`, `remove_parents`) goes through, so the turn can file what it read. Searches, mail, calendar and forms mark it as usual. A refused rename or move the person asked for can go on a `drive_files` approval card instead. A round that reads also holds that round's other such calls; the read itself runs. Scripts are checked call by call. The offered tools never change, so the cached prefix stays the same, and the hold ends with the turn. Mail from someone not in People (a contact or a stranger) counts as outside content from the start of its turn (`Session.sender_off_team`), so the whole turn is held, with no direct messages or watchlist removals either; it can still raise an alert, private to the principal, which is how that mail reaches them. Someone added to People in a turn (or given a new address or chat account) is not emailed, messaged, invited or shared with until the next one. What a turn held is remembered for the conversation's next turn (`note_held`, in process, for an hour). It is kept per conversation and speaker. When that speaker's next message is a go (a short yes such as \"go\" or \"yes, do it\", or one opening with go, go ahead, do it or proceed as its own clause: `GO_RE`), the first round that reads has its reads refused once (`defers_read`, with an error that names no tool and asks for nothing new), so the steps the person just approved run before a new read holds them again; from the next round reads run as usual. It runs only what the model calls in that turn, under every usual check. A shared chat, and a turn answering mail from someone not in People, remember nothing. In the web chat the go is a tap: while it waits, the reply carries **Approve** and **Not now** buttons naming the held steps in plain words (`pending_held`, `step_words`: only names it knows; any other gateway tool shows its app's generic label, since the model's tool name can be steered by what it read), and Approve sends \"Go ahead\" as the person's own next message. The refusal on a web turn (`approve_hint`, set from `Session.from_web_chat`) tells the model to point them at Approve rather than ask them to say go; other surfaces still ask for a typed go.\n\nHow much a read holds is the owner's setting, **When I read outside content** (`orchestrator.outside_mode`, one row in `outside_content_mode`, changed only by the principal through `GET`/`PUT /executive/outside-content` on Settings → Your Executive), fixed per turn in `begin_turn` (`TurnOutside.mode`). **Ask every time** (`ask`) is the hold above. **Only for outsiders** (`outsiders`, the default) skips what came from the team: a Gmail search that shows only ids and links, a Gmail message read where every message's sender is a teammate (not a contact) and Gmail authenticated it (`fact_confirmation.sender_authenticated` on a raw read of each id, at most 10) and no other address appears, and a calendar read naming only the team where the Executive itself organized every event (a teammate's invite counts as outside, since its organizer is whatever the mail that brought it says) (Google's `get_events` only when `detailed` or for one event, since the plain listing doesn't say who made each event; Microsoft 365's calendar reads) (`mark_read` / `from_the_team`, checked on the result; an `@` the address pattern can't read counts as a stranger). Attachments and synced folders (a file carries whoever wrote it, not whoever sent it), web pages, fetched documents, vendor apps, Outlook mail and every other gateway read still hold. **Don't ask** (`trust`) applies only on the principal's own turn on an interactive surface that isn't email or a shared chat (`content_trust.principal_only_withheld` empty): no read marks the turn, and reading their own mail holds nothing either (the Act as me lockdown and `app_control` are skipped via `trusted_turn`); anyone else's turn gets `outsiders`. Whatever the setting, a shared chat, another AI app's turn and mail from someone not in People are `ask`, sends still go only to people on People, and someone added this turn is reached no earlier than the next one. An unreadable setting is `ask`.\n\nA turn about the principal's private mail (`Session.private_to_principal`) reaches the principal only. It is neither offered nor allowed to run `schedule_tools.PRIVATE_TURN_WITHHELD_TOOLS` — everything that reaches someone else, publishes where the team reads, or starts work outside the turn: the broadcasts, meeting bookings and cancellations, `run_workflow` and research, follow-ups and workflow nudges, watches, artifacts, goal updates, saved workflows, skill drafts, and `load_mcp_server` (it connects to any URL, which can carry the turn's content). Through `search_tools` and `call_tool` it reaches only `schedule_tools.PRIVATE_TURN_MCP_TOOLS`: Google Workspace reads (mail, calendar, and Drive, Docs and Sheets search and file reads, with their Microsoft 365 twins; OneDrive's `download-bytes` only for a file's content) and the Gmail send and draft the gateway narrows to the principal. A search shows it nothing else, and a call to anything else (Google Chat, a Docs or Drive write, `manage_event`, another server) is refused (`schedule_tools.private_turn_withholds`). A call the model emits anyway, MCP tools included, gets an error tool_result and writes an audit row, and every audit row the turn writes is the principal's alone.\n\nA turn another AI app asks over the MCP server (`Session.from_mcp_client`, set by `ask_executive`) reads and advises but never acts, unless the request may act (below). It is neither offered nor allowed to run `schedule_tools.MCP_CLIENT_WITHHELD_TOOLS`: the private-turn and unattended sets, plus every direct message (`message_person`, the Slack, Discord and Telegram DMs), alert acks and new alerts, brief edits, closing open loops, roster and department-head writes, watchlist changes, workflow drafts and form proposals. It gets no Act as me, `recall_history` or extension tools, and of the gateway tools only `schedule_tools.MCP_CLIENT_MCP_TOOLS`: the private-turn reads without the Gmail and Outlook send and draft tools. The set is fixed, so the variant keeps a stable cached tool prefix. A call the model emits anyway, through `use_tool` or `call_tool` included, gets an error tool_result telling it the conversation comes from another AI app, so it can read and advise but not send, post, book or change anything, and writes an audit row (`refused: mcp_client`); `MCPGateway.call_tool` refuses the same calls again.\n\nA request may let that turn act (`Session.mcp_client_may_act`: the `x-mcp-client-actions: on` header on a request the shared secret authenticated, or `MCP_CLIENT_ACTIONS` where no secret is set). It then runs the speaker's own changes inside Open Executive (`schedule_tools.MCP_CLIENT_RUNS_WHEN_ACTING`: alerts, open loops, follow-ups, the watch list, goals, decision outcomes, facts and company profile writes; never the roster), each under its own owner-only and person checks, since the turn counts as a verified surface for its caller. It is still denied a fixed set, `MCP_CLIENT_ACTING_WITHHELD_TOOLS` (DMs, calendar writes, broadcasts, `load_mcp_server`, scripts, Python jobs, workflows, research and the rest of the read-only set), with a refusal telling the person to do it in Open Executive. A message or a meeting goes on an approval card instead (`propose_actions`), which is carried out at once when the person's Handle it for me covers it, everyone on it has been on the roster for a week, and `action_cards.on_its_own_refusal` finds nothing against it, and otherwise waits for their tap. Every audit row it writes names the app (`via`).\n\nA web chat its owner shared (`Session.shared_chat`) mixes people. The note naming who is in it says which of them owns it and that the others' lines are messages from them, not the owner's instructions. While someone other than the owner has written since the owner's last message (`Session.others_spoke_last`, set per turn by the chat route from the saved history, the speaker included, and true when the history can't be read), the turn is neither offered nor allowed to run `schedule_tools.SHARED_CHAT_WITHHELD_TOOLS`: direct messages, the broadcasts, meeting invites and cancellations, follow-ups, roster writes and workflows (a run, a save or a suggested schedule acts later with the full tool set). Through `call_tool` it can't send, reply, forward or draft mail in Gmail or Outlook, or make a calendar change that mails attendees (`schedule_tools.shared_chat_withholds`). That holds on the owner's own turn right after someone else's line too, so a request carried over from it can't send; the owner's next message with nobody else's in between lifts it. A call the model emits anyway gets an error tool_result and writes an audit row (`refused: shared_chat`). The principal-only tools stay out of every shared chat (`content_trust.principal_only_withheld`).\n\nOn every turn the Executive knows what is connected without searching: block 0's *Connected Systems* section names the connected Google services, other MCP servers, the messaging channels, Notion sync, Confluence sync (when on) and Act as me, and pins the Google tool names it calls directly with `call_tool`. Both the service list and the pinned names are narrowed to what workspace-mcp actually loaded (`WORKSPACE_MCP_TOOLS`, `WORKSPACE_MCP_TOOL_TIER`), so a service left out is not named and its tools are not pinned — being told a tool is already available when it is not in the index costs a failed call the model cannot explain to itself. `search_tools` is for anything not listed. When work repeats over many items, the Executive can also call `run_script` (`workflows/step_script.py`, offered when the gateway runs, unless `CHAT_SCRIPTS=false`, and only on the principal's own turns — `PRINCIPAL_ONLY_TOOLS`, withheld on an unattended pass too, because it spends the turn's whole call budget on code the model just wrote): one short Python script, run in a sandboxed Monty worker with no files, network or environment, whose only reach is the gateway tools `call_tool` could reach (those `search_tools` has returned; the gateway keeps that set for its own process-wide session, not per conversation). Each call it makes is a `call_tool` in every way that matters — the gateway's discovery, deny-list and recipient gates, Take the lead's gate on an unattended run (or the department gate on a team member's turn, see Org), and the same action chip and `tool_invocation` row (marked `via: run_script`, `ok: false` when it raised), as each call happens; the script itself gets a `kind: script` row with its source and result. Its wall clock is half the turn's deadline, so a long script ends with the list of calls it made rather than being cut off with the turn, and a stopped turn closes it and its worker. A turn private to the principal is not offered it, and the Act as me lockdown withholds it whole. Besides gateway tools, a chat script may call a fixed list of the Executive's own tools (`step_script.CHAT_OWN_TOOLS`: reads, alerts, open loops, goals, the watch list, follow-ups, `message_person`, `upsert_person` — nothing that broadcasts, books calendars, edits memory or skills, or starts workflows or research), each only when the turn is offered it and through the turn's own handler (Take the lead's gate included), with the same chip and a `kind: skill`, `via: run_script` audit row. A direct call needs a `tool_use` each, so a turn's scripts share a budget instead: `CHAT_SCRIPT_MAX_CALLS` (default 200) calls in all, and per-turn caps on own tools that could otherwise act in bulk (`CHAT_OWN_TOOL_CAPS`: `message_person` 10 — messaging the whole roster would be a broadcast — `upsert_person` 25, `create_alert` 50); a refused call tells the model to say what is left. A call stopped mid-flight by the script's clock or the turn still gets a `cancelled` audit row, since it may have run. Because every round re-reads the conversation, the loop also nudges at the moment of choice: after a round whose results include a list of five or more items (`step_script.lists_many`), with `run_script` on offer and not used that round, it adds the constant `FANOUT_HINT` as a text block in that round's user message (never a cached block), once a turn, pointing the per-item work at one built tool. For library work on files (PDFs, spreadsheets, charts, images) the chat also has `run_python_job` (see Workflows → Python jobs): Python with a fixed library set in a Deno-isolated WebAssembly sandbox, fed Knowledge files by name, the message's own attachments as sent, or text it already holds, and able to keep a job that worked as a Custom tool, with result files linked for the principal to download; it is offered only on the principal's own turns and only where the sandbox is installed (not offered otherwise, so the tool prefix stays fixed per process). Agent Activity shows each run as one \"Built tool\" card (debug event `script_run`: ok, the calls it made, how many, how long, and the kept or reused tool's name). The persona's tool-building section is present only when chat scripts can actually run (the setting and Monty installed). `TOOL_BUILDING_ADDENDUM` in the cached persona tells the Executive when to build a tool — a job that looks something up and then checks or acts on each result, paged results, more than about ten items, or an answer that needs three or more reads (find, open, read; the tool returns only what answers the question, not whole documents, and only what is about to be edited or quoted at length is read in full), while a handful of items already named go as direct calls in one turn — and never to say it has none, and to talk about it as building a tool or doing it in one go. On the principal's own verified, interactive turns, a script that works can be saved as a named tool (`save_as`; elsewhere the script runs but is not saved) and run again with `run_script(tool=…, inputs=…)`; `list_saved_tools` (a constant definition, in `PRINCIPAL_ONLY_TOOLS` with `load_mcp_server`, so offered only while the principal is speaking on a verified, interactive surface; `run_script(tool=…)` is refused on any other turn) lists them, and each call a saved tool makes is a gateway call like any other (see Workflows → Saved tools). The tool's definition is a constant, so the cached tool prefix does not move. 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 (3 built-in and 2 company chunks by default, see the RAG section) before the specialist sees the question. The fan-out is failure-isolated per call: a specialist that raises or returns no text becomes an `UNAVAILABLE` tool_result (`router.specialist_unavailable_result`) instead of failing the whole turn, and its area — \"finance\", \"legal\", never the specialist's name — is reported to the user under the web reply, or by the Executive in its reply on other channels, unless another call to it answered that turn. A failed specialist does not count as consulted, so it takes no committee seat. Cancellation (Stop) still propagates. The Executive then synthesizes the returned analyses into one reply.\n\n`remember_fact`, `forget_fact` and `update_company_profile` (`orchestrator/fact_tools.py`; the last two sit in the `memory` group of `open_tools`, since they are rarely needed) make a correction stick: the first two keep or retire a standing fact in `memory.facts`, and the third changes one field of the company profile. They share `record_decision_outcome`'s gate (the principal on a verified surface, an audited refusal for everyone else) and are in `UNATTENDED_WITHHELD_TOOLS`. `remember_fact` alone also admits a rostered teammate on a verified surface (web signed in, their own Slack or Discord): the fact is stored attributed (`recorded_by_role=\"teammate\"`, rendered `(per <name>)`), and is held as a `proposed` row (`awaiting_approval`) until the principal approves it, unless the principal marked that teammate trusted (\"needs my approval\" off; on by default) — and even then when it would replace the principal's fact. All three are also in `PRIVATE_TURN_WITHHELD_TOOLS`, since what they write or retire is read on everyone's turns. On the principal's own authenticated email (primary address, with Gmail's own `Authentication-Results` reporting `dmarc=pass`, not forwarded) the three tools check the request as usual, then hold it as `awaiting_confirmation`. It applies only when the principal replies to a one-time token emailed to their own address (`integrations.fact_confirmation`); the split into a check step and an `apply_*` step lets chat and the confirmed reply share one apply path. Each write also needs a `source_quote` found in the speaker's own words this turn. The active facts reach every specialist as a `<standing_facts>` user-turn tag: `route_to_specialist` reads them (None → the store, \"\" → none) for chat consults and workflow steps alike, and `BaseAgent.analyze` places the tag next to `<past_decisions>`, never in the cached specialist system prompt.\n\nThe ten 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| `sales` | `SalesAgent` | sales |\n| `board_comms` | `BoardCommsAgent` | board |\n| `triage` | `TriageAgent` | triage |\n\nModels: specialists default to `claude-sonnet-5-5`; the deep-reasoning tier (CSO, CFO, GC, Board) runs on `DEEP_REASONING_MODEL`, `claude-sonnet-5-5` by default, with adaptive thinking; routing/fast classification uses `claude-haiku-5-5`. Requests are fitted to the model's generation on the way out (`feature_gate.fit_claude_generation`): 5-generation Claude models never receive `temperature` / `top_p` / `top_k`, and Haiku 5.5, which thinks unless told otherwise, gets thinking turned off when the caller asked for none. 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. A PDF `document` block is translated too: it becomes an OpenAI `file` part, and OpenRouter requests carrying one add the `file-parser` plugin (`native` for models whose catalog entry lists `file` input, else `PDF_OPENROUTER_ENGINE`, default `mistral-ocr`). `FeatureSpec.supports_pdf_input` gates it per model — off for a local server unless `LOCAL_PDF_INPUT` — and a gated-off PDF becomes a text note rather than vanishing. 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-5`, `claude-sonnet-5`, `claude-haiku-5-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. Every Council agent also takes **additional instructions** (`agent_overrides.instructions`): text appended after its prompt by `agents.overrides.append_instructions` inside an `<additional_instructions>` block. `BaseAgent.base_system_prompt()` is the built-in prompt or its full replacement (what the Council's editor shows); `effective_system_prompt()` is that plus the instructions (what every call sends), and the Executive gets the same text through `build_system_blocks(persona_instructions=…)`. Unlike a replaced prompt, instructions leave the agent on its built-in prompt, so prompt improvements keep reaching it. A **Quality** choice above the agents (`agents.presets`) sets every agent's model and deep reasoning at once: **Fast** puts every agent on a small model (`claude-haiku-5-5`, else `claude-haiku-4-5`) with deep reasoning off, **Balanced** returns each agent to its built-in defaults, and **Thorough** puts the Executive and the domain specialists on the largest allowed model (`claude-opus-5-5`, else `claude-opus-5`) with deep reasoning on where the model supports it, leaving triage and the helpers below on their defaults. Presets change quality only; they never cap spend. Each preset resolves against the install's model allowlist at request time and is offered only when one of its models is allowed. Applying one writes ordinary per-agent overrides (model and deep reasoning only), so history, rollback and later per-agent edits keep working; an agent changed on its own afterwards shows as **Custom**. Each Council agent has a **visibility**: `core` for the Executive and the domain specialists (`BaseAgent.visibility = \"core\"`, which a new specialist must declare) and `internal` (the default) for triage and the helper agents below. Thorough moves only core agents. The Council opens in a **simple view**: the Quality choice, the voice picker, and only the core agents, each with its additional instructions and a model badge. **Show all agents** lists the internal ones too, and **Advanced** opens the full page (the browser remembers the choice). 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. When the workspace is in solo mode, `onboarding_interviewer`'s first user turn is prefixed with a short hint (`interview.solo_hint(role_kind)`, one static constant per role kind from the onboarding role step): the draft names only the principal, as principal, and no departments; an owner is asked about the offer, customers, pricing, cash and runway, an in-house executive about their organisation (drafted as the company — their employer), function, remit, manager, team size as context and what they are measured on, an independent about their practice, clients and pricing, and with no role given the role-neutral `SOLO_HINT` asks which they are. The hint rides in the user turn and the tool array is unchanged, so the cached system prompt and tool prefix are the same in both modes.\n\n**Voice.** The Executive answers in one voice persona, substituted into block 0 at `{VOICE_PERSONA}` (`personas/loader.get_active_body`) from the Executive override's `voice_persona_slug`. Three general voices ship in `personas/builtin/`: **Direct** (`default`, the slug used when none is set: answer first, brief and decisive), **Supportive** (a warm coach who explains the why and checks how the plan sits) and **Analytical** (numbers first, options and trade-offs, then one recommendation). They are offered by a shared picker in setup (`/onboard`, after the workspace choice) and in Settings → Executive, which saves through `PATCH /agents/executive`; a built-in voice's frontmatter carries the picker's one-line `description` and `sample` reply. The named-executive voices are marked `legacy: true`: the picker hides them, but they still load, so an install that picked one keeps it, and the Agent Council lists them under \"Legacy voices\". Voice files hold disposition only; the response-length ladder lives in `prompts/executive_persona.py`, and a test keeps numeric length rules out of every voice file. An eval scenario may set `voice_persona` to answer in a voice; it rides on `Session.voice_persona_slug`, which wins over the override for that session only.\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\n**Solo mode.** When the workspace (or the turn's session) is solo — one person using Open Executive for themselves — the Executive works for that one person, the principal, whatever their role: they may run their own business, lead a function inside a larger organisation, or work independently, and the persona reads which from the context instead of assuming it — the role lines under \"Your Principal\" in the org block, when the principal gave their role (workspace settings: kind, title, reports to, remit, measured on). Its persona swaps the team sections (\"You Are a Member of This Executive Team\", \"Choosing Who to Tell\", \"Departments & Org Coordination\") for \"You Work for One Person\", \"The People in Their World\", \"Who Hears From You\" and \"Goals and Areas\". Solo means only the principal uses Open Executive — not that they have no people: their manager, direct reports, peers, clients, investors and board are contacts. The Executive helps the principal work with them (a 1:1 or review prep, an update or budget case for their manager or board, a negotiation) but does not coordinate them, contacts them only when the principal asks and only if they are a contact, and never offers to loop the principal in. Every specialist stays relevant — HR for the principal's own reports, board and investor communications for reporting upward. Goals are grouped by *area* (the tools' `department_slug` is the area's slug). The chat loop withholds `send_department_message`, `send_company_broadcast` and `set_department_head` from its tool list, and a call to one of them anyway gets a JSON error tool_result instead of running. The mode is resolved once per turn and pinned on the session, so the persona, the org block, the tools and every tool handler agree — a switch made mid-turn applies from the next turn. Team mode is unchanged.\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\n`recall_history` (Always in the loop, `orchestrator.history_tools`) reads the speaker's own notes, on the same terms as `ghostwrite_email` below: its own registry, offered only on a verified turn in a conversation private to them with their switch on; its `due` flag lists only dated notes, soonest first (see Memory). The ghostwriter below also gets the writer's notes from mail every recipient was on, as a consistency check (`<writer_noted>`).\n\nThe morning reflection, which has no question to look up and no specialist to consult, gets one more read-only tool of its own: `search_knowledge` (`orchestrator.knowledge_tools`), the same knowledge lookup a chat turn makes, for what the company's documents say about a customer, contract, price or policy before it acts.\n\nA fifth, `remind_me` (`orchestrator.reminder_tools`), sets a plain-text reminder sent to the speaker alone when it is due; it opens no mailbox, so it never locks a turn. A sixth, `propose_actions` (`orchestrator.action_card_tools`), does nothing itself: it leaves the speaker a card of up to five actions (a meeting, a message, a new contact) that happen only when they tap Approve, so it stays on after a turn read mail; it is where what an email itself asks for goes, since that is never done on the email's say-so. Four read-only tools beside it read the speaker's own mailbox on the same terms — `search_my_email`, `read_my_email`, `read_my_email_attachment`, `my_email_awaiting_reply` (`orchestrator.mail_read_tools`) — and `my_calendar` their own calendar while Read my calendar is on, capped per turn, other people's messages and attached files returned as untrusted blocks (see Act as me). Beside them, `save_my_email_attachment` copies one attached file, when the speaker asked in their own words, into a fixed folder of the Executive's own Drive or OneDrive and shares it with them alone, every call built in codeOne tool writes under someone else's name, and it is fenced in code rather than the prompt. `ghostwrite_email` (**Act as me**, `orchestrator.delegation_tools`) writes an email as the person the Executive is speaking with and saves it as a draft in their own mailbox, Gmail or Outlook (`delegation.gmail.gmail_for` picks the client by the person's credential); chat never sends it (the person sends it themselves, or taps Send on its card). It lives in its own registry, never `_ALL_SKILL_TOOLS`, so reflection, research and workflow toolkits can never carry it. The chat loop adds it only on a turn `delegation.settings.pin_turn_delegation` offered it to — the principal, or a team member once the owner lets them, with it on, verified, in a conversation private to them (the web chat, a Slack or Discord DM, a verified private Telegram chat), on an attended turn — and builds that turn's handler map from both registries, so on any other turn a call to it is an unknown tool. From the round that calls it until the turn ends, the dispatch guard refuses only what opens an outside address, runs a script or workflow, or posts to everyone (`delegation.lockdown`), without changing the offered list; messages and invites to the roster, follow-ups, facts in the person's own words and a contact they name still run, each fenced in its own path. A later turn in the conversation stays private to its owner but holds nothing: the person asking again, having read the reply, is their own request. A contact add the lockdown refuses becomes an approval card in the chat instead (`propose_actions`). Recipients are chosen in code, never by the model (a draft's new email may go to any address, named back to check when it is neither on the roster nor typed), and the text comes from the **ghostwriter** (`delegation.ghostwriter`), a tool-less call with a constant prompt plus the person's \"How I write\" profile. The ghostwriter is deliberately not a Council agent: the Council's edit routes have no principal check. See **Act as Me (Delegation)**. A second tool joins the same way: `recall_history` (`orchestrator.history_tools`, Always in the loop) reads the speaker's own notes of what they said, by email or in chat. It has its own registry and per-turn handler map too, and the loop adds it only when `history_tools.recall_person` finds the speaker verified, in a conversation private to them, on an interactive turn that isn't private to the principal, with their notes switch on. It doesn't need Act as me. After every chat turn the Executive also hands the speaker's own words to `history_chat.schedule_chat_notes`, which takes notes in the background when their switch is on and the surface verified them (see **Memory**). A meeting `create_calendar_event` proposes works the same way when the person chatting is the one who approves it: its chip carries the `decision_id` and the chat shows the meeting card (Approve, Edit, Dismiss) under the reply, while the briefing keeps it too. A tool result held for someone else's approval (`waiting_for_approval`, the department gate) gets a *Waiting for approval* chip, never a done one.\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`). `run_workflow` runs the weekly review, and in solo mode the morning brief, only for the principal on a verified surface (`Workflow.principal_only_modes`, `create_goal`'s rule); anyone else gets an audited refusal that does not name the rule. A run whose `result` event reports `private_to_principal` (the morning brief on the principal's own verified turn, when it read their private rows) still returns its artifact into that turn, but the stored run keeps `persistence.PRIVATE_RUN_ARTIFACT` instead of the text, since run history is readable by everyone signed in. 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). Every artifact belongs to someone: a draft to the person whose turn published it (`artifact_records.current_viewer`; with nobody speaking, the scheduler or the CLI, the principal), and a run someone started by hand to them, while scheduled runs are the team's. The tools, the recall, `message_person`'s link and mail attachments only ever reach the speaker's own (a link is refused when the recipient couldn't open it), not even the principal sees a teammate's, and a speaker who isn't on the People list publishes nothing. A workflow's own session inside someone's turn (the research synthesis) is pinned to that turn's viewer (`Session.documents_viewer`). 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\n**Extensions** (`orchestrator.extensions`). An install can add chat tools and kinds of document without changing this code. `OPENEXECUTIVE_EXTENSIONS` names Python modules. The first turn, or the first Documents read, imports each one and calls its `register()`. A module that fails is logged and skipped. `register_tool` takes an `ExtraTool`: a definition, an async handler, an optional `tool_groups` group (new or existing) and an optional chip. It refuses a name the loop already knows (`executive.builtin_tool_names`). An extension tool is never in `_ALL_SKILL_TOOLS`, so reflection, research and the synthesis never see it. The chat loop adds it per turn, like the Act as me tools, but never on an unattended run, a turn private to the principal or to a speaker who isn't on the People list (mail from a stranger), and only where its own `offered(session)` says. A tool registered `known_caller=False` is the one exception to the People-list rule: it is asked on a turn with no verified caller too (a surface of the extension's own that names its user without proving who is speaking), so `register_tool` requires it to have an `offered` that checks who is asking; it is still never offered on an unattended, private, AI-app or replay turn. That predicate depends only on the kind of turn, so each kind of turn keeps one cached tool list. Act as me's lockdown refuses it once the turn has read the owner's mail, because it is unclassified and the lockdown fails closed, unless it was registered with `after_mail_read=True`: a tool that only reads the install's own data and carries nothing the model wrote anywhere outside. Its chip goes through `action_chips.summarize_action`, which applies the same no-chip rules for an error or refusal and keeps a link to a path inside the app. A `waiting_for_approval` result is the tool's own chip's to describe, never core's generic \"Waiting for approval\": the department gate never holds an extension tool. A tool may also name the chat's activity line while it runs (`activity_label`) and keep its dispatch audit row private (`private_row`: its input or result quotes the speaker's own data). `register_collection` adds a kind of document: a drafted artifact tagged `collection:<name>` carries that collection on its record. The Documents page gives each collection its own filter. The collection's `on_change` hears about archive, restore and delete before they happen; if it raises, the change does not happen. `draft_artifact(supersedes=…)` refuses a collection's document. The alert pipeline strips `collection:` tags, so only the extension's own code files a document in its collection. A module that fails partway through `register()` leaves nothing registered. A tool registered with `workflow=True` is also offered to workflow action steps as `oe__<name>` (see Workflows); `read_only=True` marks one that only reads. A step runs with nobody in the turn, so `offered` isn't asked: `extensions.in_workflow_step(name)` is True for that tool, during its call only, and the handler decides what an unattended call may do.\n\nDocuments come in the other way through `read_document` (`orchestrator.document_tools`): it reads a PDF, Word, Excel, CSV, Markdown or text file by `path` — one another tool saved, such as a Gmail attachment (`get_gmail_attachment_content`) or a Drive file (`get_drive_file_download_url`) — or a company document by `filename`, with an optional PDF `pages` range. A scanned PDF is converted (`knowledge.pdf_reader`: local OCR by default; with `PDF_PROVIDER_READING=true`, the deployment's own model through its provider's PDF support, falling back to local OCR) rather than returned empty. Reads are confined to the tool download folders — the same resolve-then-contain check as `oe__read_file` — plus the company docs folder, and it is withheld on turns private to the principal (`PRIVATE_TURN_WITHHELD_TOOLS`): those come from a contact's email, whose own attachments the poller has already read into the turn, and must not steer the Executive into company documents.\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. For questions about the product itself, the always-offered `read_user_guide` tool (`orchestrator/guide_tools.py`) returns any `guide/prebuilt/<id>.json` section; its description lists the section ids, fixed at import, so it never changes the cached tools prefix.\n\n**Take the lead** (`orchestrator.take_the_lead`) is how the Executive acts on its own, behind one gate. It has two switches, both off until someone turns them on. **As the Executive** is the principal's alone (`PUT /take-the-lead`). With it on, the unattended passes (reflection, research, the scheduler's proactive trigger) keep the acting tools solo mode otherwise withholds from them: booking, starting workflows, and messaging teammates rather than only the principal. `schedule_tools.unattended_toolkit` and the chat loop's unattended path then wrap every acting tool (`ACTING_TOOLS`, plus any MCP tool whose name sends, creates, updates, deletes or shares) in `gated_handlers` / `gated_call_tool`. The principal-only tools (`UNATTENDED_WITHHELD_TOOLS`) stay withheld, and every guard inside a handler still applies, including department approval levels (a booking in a department on Proposes is still a proposal) and the contact-egress rule. New mail or chat (any turn with an `origin_channel`) wakes the existing reflection early (`take_the_lead.wake`): one run waiting at most, five minutes after the first message and no more than every 30 minutes, as a one-off `take_the_lead_wake` scheduled action. Pause holds it like any scheduled work. **As you** is the Handle it for me dial's top step (delegation section).\n\n**The gate** is plain code (`take_the_lead.check`). Six kinds of action wait for a yes first, each with an Ask first switch, all on to start. The switch is the decision ledger's own mode for the class `take_the_lead_action:<kind>` (`propose` asks first, the default; `auto_execute` doesn't). The kinds are money, contracts and legal, hiring and people decisions, deleting/cancelling/sharing, someone new (an address on neither the roster nor the contacts) and big sends (a broadcast or department message, or more than five people). On top of these, the company (set by the principal) and each person (for their own As you) add structured rules: a person or address, a domain, words, or an amount at or above a figure. Added rules always hold, and an error reading them holds the action. The one thing the gate lets straight through is a direct message (`message_person` or a Slack, Telegram or Discord DM) whose only recipient is the principal (`_only_to_principal`): they are who it would wait for, so a card would only ask them to approve a message to themselves. Anything that reaches or acts on anyone else is checked, and a roster that can't be read is not the principal. A held action becomes a `take_the_lead_action` decision instance with a companion `DECISION_ALERT_SOURCE` card on Today, routed to the first teammate holding one of its People approval ranges (`take_the_lead.approval_ranges`, plain code, closest fit first: money to `spend_lt_2k`, `spend_lt_10k` or `spend_gt_10k` by its largest amount, with a higher range able to approve a lower one and no amount read as large, or to `customer_credit` for credit and payment terms; vendor contracts to `vendor_onboarding` then `legal_sign`, other contracts to `legal_sign`; hiring to `hiring_signoff`; anything else about the board or investors to `board_comms`; in Personal as in team mode), or else the principal through the authority gate's fallback (`departments.authority._route_proposal`). Deletes and shares always go to the principal. Only the principal and that approver see or resolve it (`DecisionClassSpec.principal_and_approver`). Approving it claims the row and carries out the exact call once (`take_the_lead.carry_out`: the unwrapped handler, or the gateway's `call_tool`, on an unattended session, with contact egress only when the principal approves). Declining drops it. Everything done or held is a row in `take_the_lead_log`. What it did and what was approved show in Recent activity (`today._build_activity`, kind `took_the_lead`), named but never quoted, since that feed is the team's. The held card's own `decision_resolved` row is left out because its payload quotes the message. `GET /today/activity` also adds the caller's own Handle it sends (kind `sent_as_you`, actor `you`), which are never in the shared feed.\n\n**In training.** The As the Executive switch has three positions: Off, **In training** and On (`take_the_lead.training`). In training, an action the gate would let through still waits, as a `training` hold for the principal alone, unless the principal has allowed that action with that person or thing (`take_the_lead.allowance`: \"Message Priya Nair\" covers a message to her on any channel; \"Book meetings with Priya Nair and Sam Lee\" meetings with exactly them; a workflow by id; a connected tool by name and the file it names, never one that reaches people such as a mail send or a share). The card carries Approve with a **Do this on its own next time** tick (`allow`), **Edit** (the message, a meeting's title, times or description, a task and its due date: `take_the_lead.apply_edits`) and Decline. Allowing is the principal's alone and needs a request the API can tie to them, as turning it on does; the six kinds and the added rules hold whatever is allowed. An edit approved with \"Do it like this next time\" is kept as an example (only the edited text, the principal's own words), and `take_the_lead.learned_note` hands the examples and the fact it's in training to the reflection and research passes in their user turn. After `SUGGEST_AFTER` (3) unchanged approvals of the same action in 30 days, Settings suggests allowing it. What it's learned is one list keyed by feature (`take_the_lead_allowed.feature`), so other features that learn from approvals can join it; each keeps its own switch. Act as me is the second (`act_as_me`, per person, `delegation.training`), with a training switch per setting (Replies, Follow-ups, Suggested actions, Drafts): its rows carry the person's id and the setting in their key, are listed and removed by that person alone, count toward their own cap, and never reach `learned_note`.\n\n**AI disclosure.** Nothing the Executive sends to people outside the web chat goes without saying it is an AI: plain code adds the line in the MCP gateway (mail) and at each chat send (Slack, Telegram, Discord, Google Chat replies, its DMs and room posts), never the prompt, so the persona and the cached system blocks are unchanged and a reply the model writes can't drop it. Replies the inbox watcher writes as a person carry their own line by that person's switches. See Integrations → **AI disclosure** and Act as me → **AI line on replies**.\n\n**App control from chat** (`orchestrator/app_control.py`, catalog in `orchestrator/app_control_catalog.py`). Three tools in the `app` tool group let the Executive do what the app's buttons do when the person asks (\"pin this\", \"delete that chat\", \"turn off Handle it for me\"): `find_in_app(kind, query)` lists what the speaker may change (their chats, topics, documents, workflow runs, settings; files, memory, departments, skills and workflows for the principal), `do_in_app(action, id, value)` does one action (`id: \"this\"` is the chat they are in), and `open_in_app(screen)` returns an in-app link. Each action calls the API route its button calls, as a function, with a request naming the turn's verified speaker (`correction_tools._speaker`; an email or unattended turn gets a refusal), so the route's own checks decide what this person may do. Actions whose route checks nothing about the caller (their page is the principal's) are `principal_only`. Deletes, shares, turning on Act as me, Handle it for me or Take the lead, removing a Take the lead rule, clearing every card and approving a workflow's waiting step never run in the turn: they become an `app_action` decision card, private to the speaker, shown under the reply; the tap runs the action with the tapper's own request through `POST /decisions/{id}/approve` (claimed once; a card older than a day is turned down). After a turn reads outside text or the speaker's mail, every action becomes a card. The tools are withheld from unattended and AI-app turns, and `do_in_app` from a shared chat someone else spoke in. Snoozing a card uses `ack_alert`'s trust rule: only ids the server showed or found this turn. Extensions add kinds, actions and screens with `register_kind` / `register_action` / `register_screen` at startup. The person's notes stay with `recall_history`; account, sign-in and billing stay on their screens.",
+ "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. That context is per call and never cached: `<company_stage>` (the stage from the company profile — specialists never see the profile itself), in solo mode `<principal_role>` (what kind of principal the advice is for, in plain words, with their title and remit — `router.principal_role_context`), `<department_memory>`, `<past_decisions>`, `<failure_cases>` (the shipped case studies, and under them the workspace's own lessons that match the call, `memory/lessons.py`), `<relevant_knowledge>` and `<conversation_context>`, outermost first. The specialist's own system prompt is a static domain constant under one `cache_control` block, so it stays byte-identical across companies and profile edits. A chat turn takes the stage from its session's profile (the one the Executive reasons over, and the one an eval scenario injects); workflow steps and the MCP server's `consult_specialist` read it fresh from the profile on disk. The role tag follows the turn's mode: a chat turn pins the role on its session with the mode (`pin_turn_principal_role`: the session's `principal_role` override, else the workspace settings) and sends it in solo and nothing in team, so the org block, every specialist in the turn and any workflow the turn starts see the same role; callers with no chat turn read it fresh (`load_principal_role`: the current session's mode and role, else the workspace's), and a failed read sends no tag rather than failing the consult. The CFO, CSO and sales prompts key their advice on it: for a bootstrapped, self-funded or solo company they drop venture fundraising benchmarks and work from cash, and raise only if the founder wants to.\n\nRouting uses one `consult_specialist` tool. When to call it is spelled out in the persona's Domain Expertise section (\"Going deeper\") and in the tool's own description: any question that asks for judgment in a specialist's area (a decision, plan, analysis, negotiation, hire, contract term, pricing or fundraising move, board message, or a department's own targets and stance, since the specialist holds that department's memory) is consulted before the answer, several at once across areas; lookups in mail, calendar or documents, scheduling, status checks, routine drafting and questions about how the Executive works are answered without one. Chat eval scenarios hold this: `required_routing` names specialists the turn must consult and `no_routing: true` says it must consult none, and the runner fails a scenario that misses either (`evals.scenarios.routing_check`). Beside it the Executive carries two skill tools, `search_skills` and `load_skill` (skills are shown to users as **playbooks**, and every playbook belongs to a workflow: one that follows it, or its own Quick workflow). Chat finds and reads playbooks but never creates or changes one: work worth repeating is offered as a workflow through `draft_workflow`, with the method written into its steps, because workflows read playbooks at run time (approved scheduled ones included) and this loop also runs on inbound email and chat, so only a person 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, Quick ones included, 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. Goals have three tools: `list_department_goals`, `update_department_goal` (progress the user reports) and `create_goal` (a new goal the principal states, filed under an area by slug or title and creating the area when none matches — see Org). `create_goal` runs only for the principal on a verified surface, and no unattended run is offered it: the tools in `schedule_tools.UNATTENDED_WITHHELD_TOOLS` are dropped from reflection's and research's toolkits by `unattended_toolkit`, and from the chat loop when its Session is marked `unattended` — the scheduler's PROACTIVE TRIGGER run, whose prompt quotes stored intent text; a call the model emits anyway gets an error tool_result. `record_decision_outcome` records how a past decision turned out — the weekly review lists decisions older than 30 days with no outcome as `[decision N]` — writing `decisions.outcome` (`episodic.update_decision`) and auditing the rationale; it has `create_goal`'s gate (the principal on a verified surface only; everyone else gets an audited refusal) and is in `UNATTENDED_WITHHELD_TOOLS` too. A missing or unknown id returns the decisions still waiting on an outcome, so the model can retry with the right one. Its schema is static; the solo persona has one line on it, and team mode learns it from the tool description, so the team persona is byte-identical. 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. `assign_open_loop` opens one on request (\"ask Ben to send me the Q3 numbers by Friday\") for the principal or a rostered teammate on a verified surface — never an email, a turn private to the principal or an unattended run, which are also withheld the tool — and only when `task` appears verbatim in what the speaker typed this turn, at most 5 per turn; that turn's extraction pass then opens no second loop for the same owner. The owner is told once on their own channel when someone else assigns it, and the result's `notified` says how that went, so the Executive reports it rather than messaging them as well. 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, a channel whose adapter verified the sender itself (`Session.speaker_verified`, with the `caller_person_id` it resolved, never on a turn an email started), or a private Telegram chat when `TELEGRAM_WEBHOOK_SECRET` is set to a value Telegram can send (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 team member's People row is also the web sign-in and outbound-email allow-list. `upsert_person` takes `kind` (`team` / `contact`; a new person defaults to `contact` in solo mode, an update keeps the current kind) and `email_aliases` (other addresses the person writes from — the full list, replacing the current one; they match mail and may be emailed but never sign in, and one already on someone else is refused), and after every write any pending roster request whose sender now matches someone is closed and its held messages replayed. `resolve_roster_request` answers a **roster request** — someone not on the People list who wrote in and is waiting (see Org): `approve` (a new person; `kind` defaults to team for a company-domain sender, else contact, when the principal did not say), `link` (someone already listed, by `person_id`; `replace_channel_id` only when the principal said so) or `decline`. It has the roster tools' gate (the principal on a verified surface; audited refusal otherwise), is in `UNATTENDED_WITHHELD_TOOLS`, and answers only an id in `Session.trusted_roster_request_ids` — the ids the server printed that turn in a `<roster_requests>` block (`briefing.context.format_roster_requests_for_prompt`, up to 10 pending requests), which `render_and_trust` appends to the `<briefing>` digest on the principal's own verified turn only and records on the session in the same step, so an id the model invents or reads out of a message adds nobody. Each line is server-derived — id, channel, address or account id, the sender's name sanitised and marked unverified, a company-domain hint, the message count — and never what they wrote. The block rides in the **user turn**, like the digest, so the cached system blocks are unchanged; the tool definition is static, and the new tool only extends the sorted tool list. The web chat route resets the trusted set every turn, and a resolved id is removed from it. and `list_people` returns both kinds with `kind` — contacts only on the principal's own verified turn (they are private to the principal; anyone else gets the team as if no contact existed), each with what is remembered about them from the principal's own mail and meetings (`what_you_deal_with`, `topics`, `recent_activity`, from `people.contact_notes`) so the Executive can suggest who to ask, and their contact details (`details`: phones, links, address), both on that turn only — while `lookup_person` searches the team only. `ask_about_person` on one of the principal's contacts, on the principal's own turn, returns that contact note instead of peer memory (contacts never chat, so peer memory has nothing on them); otherwise it reads a person's peer memory fully only on their own verified turn; anyone else's answers only to a verified principal or teammate, and only when that person turned on \"Share my work style with the team\", framed to how they work and never their view of a colleague, and otherwise returns the same \"hasn't chosen to share\" result whether or not anything is known. A teammate's own mail with the Executive is theirs the same way: every mailbox call the model makes through the MCP gateway (Gmail or Outlook, by `call_tool`, from a script, or a workflow step run from chat) passes through `orchestrator.teammate_mail`. A search excludes every other teammate's address server-side, except on mail the reader is also on, and is filtered again entry by entry; any other call that names a message or thread (read, attachment, reply, forward, label) must use an id a filtered search returned to the same reader in this conversation (`Session.mail_ids_seen`) or the inbound email the turn answers; reads are filtered message by message, so a message naming another teammate is left out unless the reader is in its From / To / Cc; a reply that would quote such a thread, or an Outlook forward, reply or attachment read of such a message, is refused; and a conversation in which a teammate other than the principal was shown their own mail becomes theirs alone, as Act as me's do. Outside mail and the reader's own are untouched; an email turn reads as its sender only when Gmail authenticated it, and any other unverified reader sees no teammate's mail, a background run the model drives reads as the principal and a workflow step outside any session as nobody, an Outlook inbox rule that forwards or names another teammate is refused, and the poller and the brief, which read the mailbox themselves, are unaffected. Their own chats are theirs too: every audit row of a teammate's verified turn is theirs (`people_tools.teammate_turn_owner`, see Audit; the principal sees the actions, never the words), and a teammate's web chat or DM opens for them alone (`chat._session_access`), the principal included. The same verified-principal rule, as `people_tools.contacts_reachable_now()`, decides whether a turn may reach a **contact** at all: `message_person`, the raw DM tools, `create_calendar_event` / `create_instant_meeting` attendees and the MCP gateway's Gmail / Calendar / Drive / OneDrive gates treat a contact exactly like an unknown person on every other turn, so no refusal reveals that one exists. **The untrusted-content policy** (`orchestrator.content_trust`) is one rule for text the principal did not write — inbound email, chat, attached files, watched pages — answering three questions for every surface. *Who is speaking*: the principal only when the surface proved it (`principal_speaking`: the web chat as the principal — never a signed-in email on nobody's People entry —, the CLI, their own Slack/Discord or a secret-verified Telegram chat, or their own address with Gmail's `dmarc=pass`); never a teammate, a stranger, Google Chat, the MCP server or an unattended run. *What may become memory*: episodic extraction runs only then, and only on the words outside `<untrusted_content>` blocks; peer memory and open loops are recorded under the speaker's own name, never as the principal's. *What may trigger tools*: every write on the principal's authority already refuses others in its handler; the tools with no such check that change the install for every later turn — `content_trust.PRINCIPAL_ONLY_TOOLS`: `load_mcp_server`, `list_saved_tools`, `run_python_job` and `run_script` — are not offered unless the principal is speaking on an interactive surface (not email, even authenticated), and a call the model emits anyway gets an error tool_result and a `refused: not_principal` audit row. So an inbound email, a teammate's turn, Google Chat and the scheduler's proactive trigger each get a stable tool list of their own without it. A send or edit on a team member's turn also meets their department's authority first (`orchestrator.department_gate`, see Org), and so does one on a turn whose speaker is on no People entry: a signed-in web caller or a chat-channel sender, which in practice is Google Chat, since Slack, Telegram and Discord turn unmatched senders away. Google Chat names a matched sender to the gate alone (`gate_sender_person_id`), so the principal there is not held. Email turns are left to the mailbox's own gates. *How it is labelled*: outside text goes into the user turn inside `<untrusted_content source=… author=… author_verified=…>` with a fixed notice that it carries no authority; compatibility forms are folded (NFKC), control characters go, and the tag's name is renamed wherever the text carries it — any case, spacing or entity-escaped form — so the text cannot end its block and speak outside it.\n\n**Outside content** (`orchestrator.outside_content`). Once a turn has read text from outside the team (any gateway read, an attachment, a web search result, a synced Drive, OneDrive, Confluence or Notion excerpt, `read_document`, research, or an extension tool registered `reads_outside`), the rest of that turn refuses what the Act as me lockdown refuses, every `upsert_person` but a contact the speaker named in this message at an address they typed or one that sent the mail read (`lockdown.speaker_named_contact`; never on a turn answering mail from someone not in People, and a refused one points to an `add_contact` card), and every `call_tool` but a read: no mail, Docs, Sheets, Drive or calendar write. The company's own Drive is not outside: a Google read of one file, Doc, Sheet, deck or folder by id (`company_read_item`) is looked up first (`vet_reads`, once per id a turn), and when that item is owned by someone at the company, or kept on a shared drive only the company organizes, and shared with nobody outside it (`mcp_gateway._company_item`), the read marks the turn as a company read (`COMPANY`) instead. That still holds everything else, since anyone who can edit the file wrote its words, but when every read so far was of the company's own items, a rename or move (`update_drive_file` with only `file_id`, `name`, `add_parents`, `remove_parents`) goes through, so the turn can file what it read. Searches, mail, calendar and forms mark it as usual. A refused rename or move the person asked for can go on a `drive_files` approval card instead. A round that reads also holds that round's other such calls; the read itself runs. Scripts are checked call by call. The offered tools never change, so the cached prefix stays the same, and the hold ends with the turn. Mail from someone not in People (a contact or a stranger) counts as outside content from the start of its turn (`Session.sender_off_team`), so the whole turn is held, with no direct messages or watchlist removals either; it can still raise an alert, private to the principal, which is how that mail reaches them. Someone added to People in a turn (or given a new address or chat account) is not emailed, messaged, invited or shared with until the next one. What a turn held is remembered for the conversation's next turn (`note_held`, in process, for an hour). It is kept per conversation and speaker. When that speaker's next message is a go (a short yes such as \"go\" or \"yes, do it\", or one opening with go, go ahead, do it or proceed as its own clause: `GO_RE`), the first round that reads has its reads refused once (`defers_read`, with an error that names no tool and asks for nothing new), so the steps the person just approved run before a new read holds them again; from the next round reads run as usual. It runs only what the model calls in that turn, under every usual check. A shared chat, and a turn answering mail from someone not in People, remember nothing. In the web chat the go is a tap: while it waits, the reply carries **Approve** and **Not now** buttons naming the held steps in plain words (`pending_held`, `step_words`: only names it knows; any other gateway tool shows its app's generic label, since the model's tool name can be steered by what it read), and Approve sends \"Go ahead\" as the person's own next message. The refusal on a web turn (`approve_hint`, set from `Session.from_web_chat`) tells the model to point them at Approve rather than ask them to say go; other surfaces still ask for a typed go.\n\nHow much a read holds is the owner's setting, **When I read outside content** (`orchestrator.outside_mode`, one row in `outside_content_mode`, changed only by the principal through `GET`/`PUT /executive/outside-content` on Settings → Your Executive), fixed per turn in `begin_turn` (`TurnOutside.mode`). **Ask every time** (`ask`) is the hold above. **Only for outsiders** (`outsiders`, the default) skips what came from the team: a Gmail search that shows only ids and links, a Gmail message read where every message's sender is a teammate (not a contact) and Gmail authenticated it (`fact_confirmation.sender_authenticated` on a raw read of each id, at most 10) and no other address appears, and a calendar read naming only the team where the Executive itself organized every event (a teammate's invite counts as outside, since its organizer is whatever the mail that brought it says) (Google's `get_events` only when `detailed` or for one event, since the plain listing doesn't say who made each event; Microsoft 365's calendar reads) (`mark_read` / `from_the_team`, checked on the result; an `@` the address pattern can't read counts as a stranger). Attachments and synced folders (a file carries whoever wrote it, not whoever sent it), web pages, fetched documents, vendor apps, Outlook mail and every other gateway read still hold. **Don't ask** (`trust`) applies only on the principal's own turn on an interactive surface that isn't email or a shared chat (`content_trust.principal_only_withheld` empty): no read marks the turn, and reading their own mail holds nothing either (the Act as me lockdown and `app_control` are skipped via `trusted_turn`); anyone else's turn gets `outsiders`. Whatever the setting, a shared chat, another AI app's turn and mail from someone not in People are `ask`, sends still go only to people on People, and someone added this turn is reached no earlier than the next one. An unreadable setting is `ask`.\n\nA turn about the principal's private mail (`Session.private_to_principal`) reaches the principal only. It is neither offered nor allowed to run `schedule_tools.PRIVATE_TURN_WITHHELD_TOOLS` — everything that reaches someone else, publishes where the team reads, or starts work outside the turn: the broadcasts, meeting bookings and cancellations, `run_workflow` and research, follow-ups and workflow nudges, watches, artifacts, goal updates, saved workflows, skill drafts, and `load_mcp_server` (it connects to any URL, which can carry the turn's content). Through `search_tools` and `call_tool` it reaches only `schedule_tools.PRIVATE_TURN_MCP_TOOLS`: Google Workspace reads (mail, calendar, and Drive, Docs and Sheets search and file reads, with their Microsoft 365 twins; OneDrive's `download-bytes` only for a file's content) and the Gmail send and draft the gateway narrows to the principal. A search shows it nothing else, and a call to anything else (Google Chat, a Docs or Drive write, `manage_event`, another server) is refused (`schedule_tools.private_turn_withholds`). A call the model emits anyway, MCP tools included, gets an error tool_result and writes an audit row, and every audit row the turn writes is the principal's alone.\n\nA turn another AI app asks over the MCP server (`Session.from_mcp_client`, set by `ask_executive`) reads and advises but never acts, unless the request may act (below). It is neither offered nor allowed to run `schedule_tools.MCP_CLIENT_WITHHELD_TOOLS`: the private-turn and unattended sets, plus every direct message (`message_person`, the Slack, Discord and Telegram DMs), alert acks and new alerts, brief edits, closing open loops, roster and department-head writes, watchlist changes, workflow drafts and form proposals. It gets no Act as me, `recall_history` or extension tools, and of the gateway tools only `schedule_tools.MCP_CLIENT_MCP_TOOLS`: the private-turn reads without the Gmail and Outlook send and draft tools. The set is fixed, so the variant keeps a stable cached tool prefix. A call the model emits anyway, through `use_tool` or `call_tool` included, gets an error tool_result telling it the conversation comes from another AI app, so it can read and advise but not send, post, book or change anything, and writes an audit row (`refused: mcp_client`); `MCPGateway.call_tool` refuses the same calls again.\n\nA request may let that turn act (`Session.mcp_client_may_act`: the `x-mcp-client-actions: on` header on a request the shared secret authenticated, or `MCP_CLIENT_ACTIONS` where no secret is set). It then runs the speaker's own changes inside Open Executive (`schedule_tools.MCP_CLIENT_RUNS_WHEN_ACTING`: alerts, open loops, follow-ups, the watch list, goals, decision outcomes, facts and company profile writes; never the roster), each under its own owner-only and person checks, since the turn counts as a verified surface for its caller. It is still denied a fixed set, `MCP_CLIENT_ACTING_WITHHELD_TOOLS` (DMs, calendar writes, broadcasts, `load_mcp_server`, scripts, Python jobs, workflows, research and the rest of the read-only set), with a refusal telling the person to do it in Open Executive. A message or a meeting goes on an approval card instead (`propose_actions`), which is carried out at once when the person's Handle it for me covers it, everyone on it has been on the roster for a week, and `action_cards.on_its_own_refusal` finds nothing against it, and otherwise waits for their tap. Every audit row it writes names the app (`via`).\n\nA web chat its owner shared (`Session.shared_chat`) mixes people. The note naming who is in it says which of them owns it and that the others' lines are messages from them, not the owner's instructions. While someone other than the owner has written since the owner's last message (`Session.others_spoke_last`, set per turn by the chat route from the saved history, the speaker included, and true when the history can't be read), the turn is neither offered nor allowed to run `schedule_tools.SHARED_CHAT_WITHHELD_TOOLS`: direct messages, the broadcasts, meeting invites and cancellations, follow-ups, roster writes and workflows (a run, a save or a suggested schedule acts later with the full tool set). Through `call_tool` it can't send, reply, forward or draft mail in Gmail or Outlook, or make a calendar change that mails attendees (`schedule_tools.shared_chat_withholds`). That holds on the owner's own turn right after someone else's line too, so a request carried over from it can't send; the owner's next message with nobody else's in between lifts it. A call the model emits anyway gets an error tool_result and writes an audit row (`refused: shared_chat`). The principal-only tools stay out of every shared chat (`content_trust.principal_only_withheld`).\n\nOn every turn the Executive knows what is connected without searching: block 0's *Connected Systems* section names the connected Google services, other MCP servers, the messaging channels, Notion sync, Confluence sync (when on) and Act as me, and pins the Google tool names it calls directly with `call_tool`. Both the service list and the pinned names are narrowed to what workspace-mcp actually loaded (`WORKSPACE_MCP_TOOLS`, `WORKSPACE_MCP_TOOL_TIER`), so a service left out is not named and its tools are not pinned — being told a tool is already available when it is not in the index costs a failed call the model cannot explain to itself. `search_tools` is for anything not listed. When work repeats over many items, the Executive can also call `run_script` (`workflows/step_script.py`, offered when the gateway runs, unless `CHAT_SCRIPTS=false`, and only on the principal's own turns — `PRINCIPAL_ONLY_TOOLS`, withheld on an unattended pass too, because it spends the turn's whole call budget on code the model just wrote): one short Python script, run in a sandboxed Monty worker with no files, network or environment, whose only reach is the gateway tools `call_tool` could reach (those `search_tools` has returned; the gateway keeps that set for its own process-wide session, not per conversation). Each call it makes is a `call_tool` in every way that matters — the gateway's discovery, deny-list and recipient gates, Take the lead's gate on an unattended run (or the department gate on a team member's turn, see Org), and the same action chip and `tool_invocation` row (marked `via: run_script`, `ok: false` when it raised), as each call happens; the script itself gets a `kind: script` row with its source and result. Its wall clock is half the turn's deadline, so a long script ends with the list of calls it made rather than being cut off with the turn, and a stopped turn closes it and its worker. A turn private to the principal is not offered it, and the Act as me lockdown withholds it whole. Besides gateway tools, a chat script may call a fixed list of the Executive's own tools (`step_script.CHAT_OWN_TOOLS`: reads, alerts, open loops, goals, the watch list, follow-ups, `message_person`, `upsert_person` — nothing that broadcasts, books calendars, edits memory or skills, or starts workflows or research), each only when the turn is offered it and through the turn's own handler (Take the lead's gate included), with the same chip and a `kind: skill`, `via: run_script` audit row. A direct call needs a `tool_use` each, so a turn's scripts share a budget instead: `CHAT_SCRIPT_MAX_CALLS` (default 200) calls in all, and per-turn caps on own tools that could otherwise act in bulk (`CHAT_OWN_TOOL_CAPS`: `message_person` 10 — messaging the whole roster would be a broadcast — `upsert_person` 25, `create_alert` 50); a refused call tells the model to say what is left. A call stopped mid-flight by the script's clock or the turn still gets a `cancelled` audit row, since it may have run. Because every round re-reads the conversation, the loop also nudges at the moment of choice: after a round whose results include a list of five or more items (`step_script.lists_many`), with `run_script` on offer and not used that round, it adds the constant `FANOUT_HINT` as a text block in that round's user message (never a cached block), once a turn, pointing the per-item work at one built tool. For library work on files (PDFs, spreadsheets, charts, images) the chat also has `run_python_job` (see Workflows → Python jobs): Python with a fixed library set in a Deno-isolated WebAssembly sandbox, fed Knowledge files by name, the message's own attachments as sent, or text it already holds, and able to keep a job that worked as a Custom tool, with result files linked for the principal to download; it is offered only on the principal's own turns and only where the sandbox is installed (not offered otherwise, so the tool prefix stays fixed per process). Agent Activity shows each run as one \"Built tool\" card (debug event `script_run`: ok, the calls it made, how many, how long, and the kept or reused tool's name). The persona's tool-building section is present only when chat scripts can actually run (the setting and Monty installed). `TOOL_BUILDING_ADDENDUM` in the cached persona tells the Executive when to build a tool — a job that looks something up and then checks or acts on each result, paged results, more than about ten items, or an answer that needs three or more reads (find, open, read; the tool returns only what answers the question, not whole documents, and only what is about to be edited or quoted at length is read in full), while a handful of items already named go as direct calls in one turn — and never to say it has none, and to talk about it as building a tool or doing it in one go. On the principal's own verified, interactive turns, a script that works can be saved as a named tool (`save_as`; elsewhere the script runs but is not saved) and run again with `run_script(tool=…, inputs=…)`; `list_saved_tools` (a constant definition, in `PRINCIPAL_ONLY_TOOLS` with `load_mcp_server`, so offered only while the principal is speaking on a verified, interactive surface; `run_script(tool=…)` is refused on any other turn) lists them, and each call a saved tool makes is a gateway call like any other (see Workflows → Saved tools). The tool's definition is a constant, so the cached tool prefix does not move. 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 (3 built-in and 2 company chunks by default, see the RAG section) before the specialist sees the question. The fan-out is failure-isolated per call: a specialist that raises or returns no text becomes an `UNAVAILABLE` tool_result (`router.specialist_unavailable_result`) instead of failing the whole turn, and its area — \"finance\", \"legal\", never the specialist's name — is reported to the user under the web reply, or by the Executive in its reply on other channels, unless another call to it answered that turn. A failed specialist does not count as consulted, so it takes no committee seat. Cancellation (Stop) still propagates. The Executive then synthesizes the returned analyses into one reply.\n\n`remember_fact`, `forget_fact` and `update_company_profile` (`orchestrator/fact_tools.py`; the last two sit in the `memory` group of `open_tools`, since they are rarely needed) make a correction stick: the first two keep or retire a standing fact in `memory.facts`, and the third changes one field of the company profile. They share `record_decision_outcome`'s gate (the principal on a verified surface, an audited refusal for everyone else) and are in `UNATTENDED_WITHHELD_TOOLS`. `remember_fact` alone also admits a rostered teammate on a verified surface (web signed in, their own Slack or Discord): the fact is stored attributed (`recorded_by_role=\"teammate\"`, rendered `(per <name>)`), and is held as a `proposed` row (`awaiting_approval`) until the principal approves it, unless the principal marked that teammate trusted (\"needs my approval\" off; on by default) — and even then when it would replace the principal's fact. All three are also in `PRIVATE_TURN_WITHHELD_TOOLS`, since what they write or retire is read on everyone's turns. On the principal's own authenticated email (primary address, with Gmail's own `Authentication-Results` reporting `dmarc=pass`, not forwarded) the three tools check the request as usual, then hold it as `awaiting_confirmation`. It applies only when the principal replies to a one-time token emailed to their own address (`integrations.fact_confirmation`); the split into a check step and an `apply_*` step lets chat and the confirmed reply share one apply path. Each write also needs a `source_quote` found in the speaker's own words this turn. The active facts reach every specialist as a `<standing_facts>` user-turn tag: `route_to_specialist` reads them (None → the store, \"\" → none) for chat consults and workflow steps alike, and `BaseAgent.analyze` places the tag next to `<past_decisions>`, never in the cached specialist system prompt.\n\nThe ten 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| `sales` | `SalesAgent` | sales |\n| `board_comms` | `BoardCommsAgent` | board |\n| `triage` | `TriageAgent` | triage |\n\nModels: specialists default to `claude-sonnet-5-5`; the deep-reasoning tier (CSO, CFO, GC, Board) runs on `DEEP_REASONING_MODEL`, `claude-sonnet-5-5` by default, with adaptive thinking; routing/fast classification uses `claude-haiku-5-5`. Requests are fitted to the model's generation on the way out (`feature_gate.fit_claude_generation`): 5-generation Claude models never receive `temperature` / `top_p` / `top_k`, and Haiku 5.5, which thinks unless told otherwise, gets thinking turned off when the caller asked for none. 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. A PDF `document` block is translated too: it becomes an OpenAI `file` part, and OpenRouter requests carrying one add the `file-parser` plugin (`native` for models whose catalog entry lists `file` input, else `PDF_OPENROUTER_ENGINE`, default `mistral-ocr`). `FeatureSpec.supports_pdf_input` gates it per model — off for a local server unless `LOCAL_PDF_INPUT` — and a gated-off PDF becomes a text note rather than vanishing. 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-5`, `claude-sonnet-5`, `claude-haiku-5-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. Every Council agent also takes **additional instructions** (`agent_overrides.instructions`): text appended after its prompt by `agents.overrides.append_instructions` inside an `<additional_instructions>` block. `BaseAgent.base_system_prompt()` is the built-in prompt or its full replacement (what the Council's editor shows); `effective_system_prompt()` is that plus the instructions (what every call sends), and the Executive gets the same text through `build_system_blocks(persona_instructions=…)`. Unlike a replaced prompt, instructions leave the agent on its built-in prompt, so prompt improvements keep reaching it. A **Quality** choice above the agents (`agents.presets`) sets every agent's model and deep reasoning at once: **Fast** puts every agent on a small model (`claude-haiku-5-5`, else `claude-haiku-4-5`) with deep reasoning off, **Balanced** returns each agent to its built-in defaults, and **Thorough** puts the Executive and the domain specialists on the largest allowed model (`claude-opus-5-5`, else `claude-opus-5`) with deep reasoning on where the model supports it, leaving triage and the helpers below on their defaults. Presets change quality only; they never cap spend. Each preset resolves against the install's model allowlist at request time and is offered only when one of its models is allowed. Applying one writes ordinary per-agent overrides (model and deep reasoning only), so history, rollback and later per-agent edits keep working; an agent changed on its own afterwards shows as **Custom**. Each Council agent has a **visibility**: `core` for the Executive and the domain specialists (`BaseAgent.visibility = \"core\"`, which a new specialist must declare) and `internal` (the default) for triage and the helper agents below. Thorough moves only core agents. The Council opens in a **simple view**: the Quality choice, the voice picker, and only the core agents, each with its additional instructions and a model badge. **Show all agents** lists the internal ones too, and **Advanced** opens the full page (the browser remembers the choice). 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. When the workspace is in solo mode, `onboarding_interviewer`'s first user turn is prefixed with a short hint (`interview.solo_hint(role_kind)`, one static constant per role kind from the onboarding role step): the draft names only the principal, as principal, and no departments; an owner is asked about the offer, customers, pricing, cash and runway, an in-house executive about their organisation (drafted as the company — their employer), function, remit, manager, team size as context and what they are measured on, an independent about their practice, clients and pricing, and with no role given the role-neutral `SOLO_HINT` asks which they are. The hint rides in the user turn and the tool array is unchanged, so the cached system prompt and tool prefix are the same in both modes.\n\n**Voice.** The Executive answers in one voice persona, substituted into block 0 at `{VOICE_PERSONA}` (`personas/loader.get_active_body`) from the Executive override's `voice_persona_slug`. Three general voices ship in `personas/builtin/`: **Direct** (`default`, the slug used when none is set: answer first, brief and decisive), **Supportive** (a warm coach who explains the why and checks how the plan sits) and **Analytical** (numbers first, options and trade-offs, then one recommendation). They are offered by a shared picker in setup (`/onboard`, after the workspace choice) and in Settings → Executive, which saves through `PATCH /agents/executive`; a built-in voice's frontmatter carries the picker's one-line `description` and `sample` reply. The named-executive voices are marked `legacy: true`: the picker hides them, but they still load, so an install that picked one keeps it, and the Agent Council lists them under \"Legacy voices\". Voice files hold disposition only; the response-length ladder lives in `prompts/executive_persona.py`, and a test keeps numeric length rules out of every voice file. An eval scenario may set `voice_persona` to answer in a voice; it rides on `Session.voice_persona_slug`, which wins over the override for that session only.\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\n**Goals without departments.** The goal tools (`orchestrator.department_tools`) no longer assume a department: `list_department_goals` with no `department_slug` lists every goal with its owner and department, `update_department_goal` names a goal by `goal_id` alone, and `create_goal` takes an optional `area` and `owner_person_id` (a team member). The org block renders goals with no department with their `goal_id`, and their action chips link to `/goals` (see Org).\n\n**Solo mode.** When the workspace (or the turn's session) is solo — one person using Open Executive for themselves — the Executive works for that one person, the principal, whatever their role: they may run their own business, lead a function inside a larger organisation, or work independently, and the persona reads which from the context instead of assuming it — the role lines under \"Your Principal\" in the org block, when the principal gave their role (workspace settings: kind, title, reports to, remit, measured on). Its persona swaps the team sections (\"You Are a Member of This Executive Team\", \"Choosing Who to Tell\", \"Departments & Org Coordination\") for \"You Work for One Person\", \"The People in Their World\", \"Who Hears From You\" and \"Goals and Areas\". Solo means only the principal uses Open Executive — not that they have no people: their manager, direct reports, peers, clients, investors and board are contacts. The Executive helps the principal work with them (a 1:1 or review prep, an update or budget case for their manager or board, a negotiation) but does not coordinate them, contacts them only when the principal asks and only if they are a contact, and never offers to loop the principal in. Every specialist stays relevant — HR for the principal's own reports, board and investor communications for reporting upward. Goals are grouped by *area* (the tools' `department_slug` is the area's slug). The chat loop withholds `send_department_message`, `send_company_broadcast` and `set_department_head` from its tool list, and a call to one of them anyway gets a JSON error tool_result instead of running. The mode is resolved once per turn and pinned on the session, so the persona, the org block, the tools and every tool handler agree — a switch made mid-turn applies from the next turn. Team mode is unchanged.\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\n`recall_history` (Always in the loop, `orchestrator.history_tools`) reads the speaker's own notes, on the same terms as `ghostwrite_email` below: its own registry, offered only on a verified turn in a conversation private to them with their switch on; its `due` flag lists only dated notes, soonest first (see Memory). The ghostwriter below also gets the writer's notes from mail every recipient was on, as a consistency check (`<writer_noted>`).\n\nThe morning reflection, which has no question to look up and no specialist to consult, gets one more read-only tool of its own: `search_knowledge` (`orchestrator.knowledge_tools`), the same knowledge lookup a chat turn makes, for what the company's documents say about a customer, contract, price or policy before it acts.\n\nA fifth, `remind_me` (`orchestrator.reminder_tools`), sets a plain-text reminder sent to the speaker alone when it is due; it opens no mailbox, so it never locks a turn. A sixth, `propose_actions` (`orchestrator.action_card_tools`), does nothing itself: it leaves the speaker a card of up to five actions (a meeting, a message, a new contact) that happen only when they tap Approve, so it stays on after a turn read mail; it is where what an email itself asks for goes, since that is never done on the email's say-so. Four read-only tools beside it read the speaker's own mailbox on the same terms — `search_my_email`, `read_my_email`, `read_my_email_attachment`, `my_email_awaiting_reply` (`orchestrator.mail_read_tools`) — and `my_calendar` their own calendar while Read my calendar is on, capped per turn, other people's messages and attached files returned as untrusted blocks (see Act as me). Beside them, `save_my_email_attachment` copies one attached file, when the speaker asked in their own words, into a fixed folder of the Executive's own Drive or OneDrive and shares it with them alone, every call built in codeOne tool writes under someone else's name, and it is fenced in code rather than the prompt. `ghostwrite_email` (**Act as me**, `orchestrator.delegation_tools`) writes an email as the person the Executive is speaking with and saves it as a draft in their own mailbox, Gmail or Outlook (`delegation.gmail.gmail_for` picks the client by the person's credential); chat never sends it (the person sends it themselves, or taps Send on its card). It lives in its own registry, never `_ALL_SKILL_TOOLS`, so reflection, research and workflow toolkits can never carry it. The chat loop adds it only on a turn `delegation.settings.pin_turn_delegation` offered it to — the principal, or a team member once the owner lets them, with it on, verified, in a conversation private to them (the web chat, a Slack or Discord DM, a verified private Telegram chat), on an attended turn — and builds that turn's handler map from both registries, so on any other turn a call to it is an unknown tool. From the round that calls it until the turn ends, the dispatch guard refuses only what opens an outside address, runs a script or workflow, or posts to everyone (`delegation.lockdown`), without changing the offered list; messages and invites to the roster, follow-ups, facts in the person's own words and a contact they name still run, each fenced in its own path. A later turn in the conversation stays private to its owner but holds nothing: the person asking again, having read the reply, is their own request. A contact add the lockdown refuses becomes an approval card in the chat instead (`propose_actions`). Recipients are chosen in code, never by the model (a draft's new email may go to any address, named back to check when it is neither on the roster nor typed), and the text comes from the **ghostwriter** (`delegation.ghostwriter`), a tool-less call with a constant prompt plus the person's \"How I write\" profile. The ghostwriter is deliberately not a Council agent: the Council's edit routes have no principal check. See **Act as Me (Delegation)**. A second tool joins the same way: `recall_history` (`orchestrator.history_tools`, Always in the loop) reads the speaker's own notes of what they said, by email or in chat. It has its own registry and per-turn handler map too, and the loop adds it only when `history_tools.recall_person` finds the speaker verified, in a conversation private to them, on an interactive turn that isn't private to the principal, with their notes switch on. It doesn't need Act as me. After every chat turn the Executive also hands the speaker's own words to `history_chat.schedule_chat_notes`, which takes notes in the background when their switch is on and the surface verified them (see **Memory**). A meeting `create_calendar_event` proposes works the same way when the person chatting is the one who approves it: its chip carries the `decision_id` and the chat shows the meeting card (Approve, Edit, Dismiss) under the reply, while the briefing keeps it too. A tool result held for someone else's approval (`waiting_for_approval`, the department gate) gets a *Waiting for approval* chip, never a done one.\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`). `run_workflow` runs the weekly review, and in solo mode the morning brief, only for the principal on a verified surface (`Workflow.principal_only_modes`, `create_goal`'s rule); anyone else gets an audited refusal that does not name the rule. A run whose `result` event reports `private_to_principal` (the morning brief on the principal's own verified turn, when it read their private rows) still returns its artifact into that turn, but the stored run keeps `persistence.PRIVATE_RUN_ARTIFACT` instead of the text, since run history is readable by everyone signed in. 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). Every artifact belongs to someone: a draft to the person whose turn published it (`artifact_records.current_viewer`; with nobody speaking, the scheduler or the CLI, the principal), and a run someone started by hand to them, while scheduled runs are the team's. The tools, the recall, `message_person`'s link and mail attachments only ever reach the speaker's own (a link is refused when the recipient couldn't open it), not even the principal sees a teammate's, and a speaker who isn't on the People list publishes nothing. A workflow's own session inside someone's turn (the research synthesis) is pinned to that turn's viewer (`Session.documents_viewer`). 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\n**Extensions** (`orchestrator.extensions`). An install can add chat tools and kinds of document without changing this code. `OPENEXECUTIVE_EXTENSIONS` names Python modules. The first turn, or the first Documents read, imports each one and calls its `register()`. A module that fails is logged and skipped. `register_tool` takes an `ExtraTool`: a definition, an async handler, an optional `tool_groups` group (new or existing) and an optional chip. It refuses a name the loop already knows (`executive.builtin_tool_names`). An extension tool is never in `_ALL_SKILL_TOOLS`, so reflection, research and the synthesis never see it. The chat loop adds it per turn, like the Act as me tools, but never on an unattended run, a turn private to the principal or to a speaker who isn't on the People list (mail from a stranger), and only where its own `offered(session)` says. A tool registered `known_caller=False` is the one exception to the People-list rule: it is asked on a turn with no verified caller too (a surface of the extension's own that names its user without proving who is speaking), so `register_tool` requires it to have an `offered` that checks who is asking; it is still never offered on an unattended, private, AI-app or replay turn. That predicate depends only on the kind of turn, so each kind of turn keeps one cached tool list. Act as me's lockdown refuses it once the turn has read the owner's mail, because it is unclassified and the lockdown fails closed, unless it was registered with `after_mail_read=True`: a tool that only reads the install's own data and carries nothing the model wrote anywhere outside. Its chip goes through `action_chips.summarize_action`, which applies the same no-chip rules for an error or refusal and keeps a link to a path inside the app. A `waiting_for_approval` result is the tool's own chip's to describe, never core's generic \"Waiting for approval\": the department gate never holds an extension tool. A tool may also name the chat's activity line while it runs (`activity_label`) and keep its dispatch audit row private (`private_row`: its input or result quotes the speaker's own data). `register_collection` adds a kind of document: a drafted artifact tagged `collection:<name>` carries that collection on its record. The Documents page gives each collection its own filter. The collection's `on_change` hears about archive, restore and delete before they happen; if it raises, the change does not happen. `draft_artifact(supersedes=…)` refuses a collection's document. The alert pipeline strips `collection:` tags, so only the extension's own code files a document in its collection. A module that fails partway through `register()` leaves nothing registered. A tool registered with `workflow=True` is also offered to workflow action steps as `oe__<name>` (see Workflows); `read_only=True` marks one that only reads. A step runs with nobody in the turn, so `offered` isn't asked: `extensions.in_workflow_step(name)` is True for that tool, during its call only, and the handler decides what an unattended call may do.\n\nDocuments come in the other way through `read_document` (`orchestrator.document_tools`): it reads a PDF, Word, Excel, CSV, Markdown or text file by `path` — one another tool saved, such as a Gmail attachment (`get_gmail_attachment_content`) or a Drive file (`get_drive_file_download_url`) — or a company document by `filename`, with an optional PDF `pages` range. A scanned PDF is converted (`knowledge.pdf_reader`: local OCR by default; with `PDF_PROVIDER_READING=true`, the deployment's own model through its provider's PDF support, falling back to local OCR) rather than returned empty. Reads are confined to the tool download folders — the same resolve-then-contain check as `oe__read_file` — plus the company docs folder, and it is withheld on turns private to the principal (`PRIVATE_TURN_WITHHELD_TOOLS`): those come from a contact's email, whose own attachments the poller has already read into the turn, and must not steer the Executive into company documents.\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. For questions about the product itself, the always-offered `read_user_guide` tool (`orchestrator/guide_tools.py`) returns any `guide/prebuilt/<id>.json` section; its description lists the section ids, fixed at import, so it never changes the cached tools prefix.\n\n**Take the lead** (`orchestrator.take_the_lead`) is how the Executive acts on its own, behind one gate. It has two switches, both off until someone turns them on. **As the Executive** is the principal's alone (`PUT /take-the-lead`). With it on, the unattended passes (reflection, research, the scheduler's proactive trigger) keep the acting tools solo mode otherwise withholds from them: booking, starting workflows, and messaging teammates rather than only the principal. `schedule_tools.unattended_toolkit` and the chat loop's unattended path then wrap every acting tool (`ACTING_TOOLS`, plus any MCP tool whose name sends, creates, updates, deletes or shares) in `gated_handlers` / `gated_call_tool`. The principal-only tools (`UNATTENDED_WITHHELD_TOOLS`) stay withheld, and every guard inside a handler still applies, including department approval levels (a booking in a department on Proposes is still a proposal) and the contact-egress rule. New mail or chat (any turn with an `origin_channel`) wakes the existing reflection early (`take_the_lead.wake`): one run waiting at most, five minutes after the first message and no more than every 30 minutes, as a one-off `take_the_lead_wake` scheduled action. Pause holds it like any scheduled work. **As you** is the Handle it for me dial's top step (delegation section).\n\n**The gate** is plain code (`take_the_lead.check`). Six kinds of action wait for a yes first, each with an Ask first switch, all on to start. The switch is the decision ledger's own mode for the class `take_the_lead_action:<kind>` (`propose` asks first, the default; `auto_execute` doesn't). The kinds are money, contracts and legal, hiring and people decisions, deleting/cancelling/sharing, someone new (an address on neither the roster nor the contacts) and big sends (a broadcast or department message, or more than five people). On top of these, the company (set by the principal) and each person (for their own As you) add structured rules: a person or address, a domain, words, or an amount at or above a figure. Added rules always hold, and an error reading them holds the action. The one thing the gate lets straight through is a direct message (`message_person` or a Slack, Telegram or Discord DM) whose only recipient is the principal (`_only_to_principal`): they are who it would wait for, so a card would only ask them to approve a message to themselves. Anything that reaches or acts on anyone else is checked, and a roster that can't be read is not the principal. A held action becomes a `take_the_lead_action` decision instance with a companion `DECISION_ALERT_SOURCE` card on Today, routed to the first teammate holding one of its People approval ranges (`take_the_lead.approval_ranges`, plain code, closest fit first: money to `spend_lt_2k`, `spend_lt_10k` or `spend_gt_10k` by its largest amount, with a higher range able to approve a lower one and no amount read as large, or to `customer_credit` for credit and payment terms; vendor contracts to `vendor_onboarding` then `legal_sign`, other contracts to `legal_sign`; hiring to `hiring_signoff`; anything else about the board or investors to `board_comms`; in Personal as in team mode), or else the principal through the authority gate's fallback (`departments.authority._route_proposal`). Deletes and shares always go to the principal. Only the principal and that approver see or resolve it (`DecisionClassSpec.principal_and_approver`). Approving it claims the row and carries out the exact call once (`take_the_lead.carry_out`: the unwrapped handler, or the gateway's `call_tool`, on an unattended session, with contact egress only when the principal approves). Declining drops it. Everything done or held is a row in `take_the_lead_log`. What it did and what was approved show in Recent activity (`today._build_activity`, kind `took_the_lead`), named but never quoted, since that feed is the team's. The held card's own `decision_resolved` row is left out because its payload quotes the message. `GET /today/activity` also adds the caller's own Handle it sends (kind `sent_as_you`, actor `you`), which are never in the shared feed.\n\n**In training.** The As the Executive switch has three positions: Off, **In training** and On (`take_the_lead.training`). In training, an action the gate would let through still waits, as a `training` hold for the principal alone, unless the principal has allowed that action with that person or thing (`take_the_lead.allowance`: \"Message Priya Nair\" covers a message to her on any channel; \"Book meetings with Priya Nair and Sam Lee\" meetings with exactly them; a workflow by id; a connected tool by name and the file it names, never one that reaches people such as a mail send or a share). The card carries Approve with a **Do this on its own next time** tick (`allow`), **Edit** (the message, a meeting's title, times or description, a task and its due date: `take_the_lead.apply_edits`) and Decline. Allowing is the principal's alone and needs a request the API can tie to them, as turning it on does; the six kinds and the added rules hold whatever is allowed. An edit approved with \"Do it like this next time\" is kept as an example (only the edited text, the principal's own words), and `take_the_lead.learned_note` hands the examples and the fact it's in training to the reflection and research passes in their user turn. After `SUGGEST_AFTER` (3) unchanged approvals of the same action in 30 days, Settings suggests allowing it. What it's learned is one list keyed by feature (`take_the_lead_allowed.feature`), so other features that learn from approvals can join it; each keeps its own switch. Act as me is the second (`act_as_me`, per person, `delegation.training`), with a training switch per setting (Replies, Follow-ups, Suggested actions, Drafts): its rows carry the person's id and the setting in their key, are listed and removed by that person alone, count toward their own cap, and never reach `learned_note`.\n\n**AI disclosure.** Nothing the Executive sends to people outside the web chat goes without saying it is an AI: plain code adds the line in the MCP gateway (mail) and at each chat send (Slack, Telegram, Discord, Google Chat replies, its DMs and room posts), never the prompt, so the persona and the cached system blocks are unchanged and a reply the model writes can't drop it. Replies the inbox watcher writes as a person carry their own line by that person's switches. See Integrations → **AI disclosure** and Act as me → **AI line on replies**.\n\n**App control from chat** (`orchestrator/app_control.py`, catalog in `orchestrator/app_control_catalog.py`). Three tools in the `app` tool group let the Executive do what the app's buttons do when the person asks (\"pin this\", \"delete that chat\", \"turn off Handle it for me\"): `find_in_app(kind, query)` lists what the speaker may change (their chats, topics, documents, workflow runs, settings; files, memory, departments, skills and workflows for the principal), `do_in_app(action, id, value)` does one action (`id: \"this\"` is the chat they are in), and `open_in_app(screen)` returns an in-app link. Each action calls the API route its button calls, as a function, with a request naming the turn's verified speaker (`correction_tools._speaker`; an email or unattended turn gets a refusal), so the route's own checks decide what this person may do. Actions whose route checks nothing about the caller (their page is the principal's) are `principal_only`. Deletes, shares, turning on Act as me, Handle it for me or Take the lead, removing a Take the lead rule, clearing every card and approving a workflow's waiting step never run in the turn: they become an `app_action` decision card, private to the speaker, shown under the reply; the tap runs the action with the tapper's own request through `POST /decisions/{id}/approve` (claimed once; a card older than a day is turned down). After a turn reads outside text or the speaker's mail, every action becomes a card. The tools are withheld from unattended and AI-app turns, and `do_in_app` from a shared chat someone else spoke in. Snoozing a card uses `ack_alert`'s trust rule: only ids the server showed or found this turn. Extensions add kinds, actions and screens with `register_kind` / `register_action` / `register_screen` at startup. The person's notes stay with `recall_history`; account, sign-in and billing stay on their screens.",
"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 / sales<br/>board_comms / triage\"]\n Mode{{\"Team or solo<br/>(persona + tools per turn)\"}} --> Exec\n Exec -->|\"ghostwrite_email (Act as me)\"| Gw[\"ghostwriter<br/>(tool-less, not a Council agent)\"]\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 Mode compute\n class Cso compute\n class Cfo compute\n class Gc compute\n class More compute\n class Claude external\n class Gw compute",
- "generated_at": "2026-10-20T11:14:41Z"
+ "generated_at": "2026-10-21T00:00:00Z"
}
diff --git a/packages/core/openexecutive/architecture/prebuilt/api.json b/packages/core/openexecutive/architecture/prebuilt/api.json
index faa03fb9..f9d9a763 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). A request it lets through is marked `request.state.shared_secret_ok`, which is what lets an MCP request turn on \"may act\" with `x-mcp-client-actions: on` (`mcp_server.may_act`; with no secret the header is ignored and `MCP_CLIENT_ACTIONS` decides). With local login (`OE_LOCAL_LOGIN=1`, which only `make dev` sets, and only while neither Google nor SSO sign-in is set up) a second middleware answers 403 to any request whose raw `Host` is not `localhost`, `127.0.0.1` or `[::1]` (except a webhook that verifies its caller: Google Chat and Slack always, Telegram only with a `TELEGRAM_WEBHOOK_SECRET` Telegram can send), and to any write whose `Sec-Fetch-Site` is present and not `same-origin`/`none`. The UI signs that owner in with no password and this API usually has no secret, so without it a web page in the owner's browser could drive the API as the principal — by DNS-rebinding its own hostname to 127.0.0.1, or by posting a plain form from another site or localhost port. CORS is restricted to the UI origins in `BACKEND_ALLOWED_ORIGINS`, plus the `make dev` UI on `localhost:3000` only when `OE_PUBLIC_DEPLOYMENT` is unset, so a public instance never answers a localhost page with credentials. 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\n**Who is calling** is read in one place, `api/caller.py`, which answers with a `Caller` kind and email; a test fails on any other read of an `x-caller-*` header. By default (`open`) it is the `x-caller-email` the UI proxy stamps from the sign-in, trusted because whoever holds the shared secret is trusted as the proxy, and a request with none runs as the principal. **Signed callers** remove that trust. With `CALLER_ASSERTION_PUBLIC_KEYS` set, the proxy signs every request with an Ed25519 key only the UI holds, and a third middleware checks the `x-caller-assertion` header:\n\n- **What it covers.** It is good for one method, the exact path and query, at most 120 seconds, and one use. The API keeps used ids in memory.\n- **What it names.** A `user`, by email, or the `operator`: local login, which runs as the principal.\n- **No caller header at all** is a `service`, for scripts or MCP clients holding only the secret. It is never the principal, not even on an install with no owner yet, so it can't save a first setup.\n- **Anything else is a 401.** That includes an `x-caller-email` without an assertion (`caller_assertion_required`), and a bad, expired, reused or mismatched assertion (`caller_assertion_invalid`).\n\nPublic keys that can't be read stop the boot, rather than fall back to trusting the header. `scripts/make-caller-keys.py` makes the pair, and `scripts/mint-caller-assertion.py` signs one request for curl. The API holds only public keys. Setup's API-protection check warns while a shared secret is set without them.\n\nEndpoints grouped by router:\n\n| Router | Key endpoints | Purpose |\n|---|---|---|\n| `chat` | `POST /chat`, `POST /chat/stop`, `POST /chat/add`, `POST /chat/background`, `GET /chat/voice`, `POST /chat/transcribe` | SSE stream of a live Executive turn, with a `: keepalive` comment every `CHAT_STREAM_KEEPALIVE_S` while the turn is quiet. `POST /chat/background` starts a new chat that the server answers to the end with nobody connected (a phone approving a card, then closing the app): it answers `202` with the new `session_id` once the same caller, access and quota checks as `/chat` pass, the turn saves itself as a `/chat` turn does, and one caller may have three running at once (`429` beyond that). `POST /chat/add` hands the running turn a message the person typed while it works; the turn takes it at its next step and the stream names it in a `message_added` event, and a second `POST /chat` on the same conversation waits for the first to finish. `GET /chat/voice` says whether the chat mic shows (`available`, `max_seconds`); `POST /chat/transcribe` takes one recording (multipart `file`) and answers `{text}` for the message box, nothing kept: `404` when speech to text isn't set up, `400` for a file that isn't audio, `413` over 25 MB, `502` when the speech server fails. 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`. After the reply — a stopped or timed-out one too, before the `stopped` / `error` / `done` frames — a turn that looked at anything sends one `sources` event, `{type, session_id, sources: [{kind, title, url}], unavailable: [area]}`: `kind` is `company`, `knowledge`, `notion`, `research`, `document` or `web`, `url` is only ever an http(s) link or, for an earlier document, `/artifacts/<id>`, at most 12 sources (6 from the web, pages the reply cites first), and `unavailable` names parts of the analysis (\"finance\") whose specialist failed or said nothing every time it was asked. It is persisted with the reply as `chat_messages.sources`. When the turn held steps for an outside read that still wait on the speaker's go (`outside_content.pending_held`), it then sends one `held_steps` event, `{type, session_id, steps: [plain words]}` (not after a stop or a timeout), which the UI shows as Approve / Not now under the reply; Approve sends \"Go ahead\". `GET /sessions/{id}/messages` puts the same `held_steps` on the last reply while they still wait (never for a shared chat's member). A request that carries `x-caller-email` marks its turn signed in (`Session.web_caller_signed_in`), which Act as me needs on a deployment without local login. |\n| `sessions` | `GET /sessions`, `GET /sessions/shared-with-me`, `GET /sessions/topics`, `PATCH\\|DELETE /sessions/topics/{topic_id}`, `POST /sessions/topics/{topic_id}/merge`, `POST /sessions/topic-areas/rename`, `POST /sessions/topic-areas/ungroup`, `GET\\|PATCH /sessions/{id}`, `GET /sessions/{id}/messages`, `DELETE /sessions/{id}`, `POST /sessions/{id}/messages/{message_id}/feedback`, `GET /sessions/{id}/followup`, `GET\\|PUT /sessions/{id}/shares`, `DELETE /sessions/{id}/shares/me`, `GET /sessions/{id}/people`, `GET /sessions/{id}/live`, `POST /sessions/{id}/typing`, `GET /sessions/{id}/export`, `POST /sessions/{id}/rewind` | List, read and delete saved chat sessions (assistant messages carry their row `id` and any `feedback`). The list is scoped to the caller, and each chat carries `preview`: its last message as one plain line, Markdown marks stripped and cut at a word near 120 characters, with `You:` before the person's own words. With `?q=` it is a search: the caller's own chats whose title or message text contains the words (case-insensitive, `LIKE` with wildcards escaped), each with `match_count` (messages that contain them; 0 for a title-only match) and `snippet` (the newest matching message, around the match, prefixed `You:` or `Executive:`). Scoped exactly like the list, so nobody else's conversation can match. The Chats page searches this way and opens a result with `?find=`, so the chat starts on that message and steps through the others. Each of the owner's chats also carries `topic_id`, the topic it is filed under (`memory.chat_topics`). `GET /sessions/topics` lists the caller's topics (`id`, `name`, `chat_count`, `kept`, `pinned_at`, `area`, `updated_at`) and, when some of their chats have no topic yet or some topics no area, starts filing them in the background from their titles and answers `organizing: true` until done. `PATCH /sessions/topics/{topic_id}` renames (a name another of their topics has merges the two) or pins one, `POST …/merge` moves its chats into another (`into_id`), and `DELETE` ungroups it, leaving its chats under no topic; another person's topic is a 404. `POST /sessions/topic-areas/rename` (`area`, `name`) renames one of the caller's areas and `…/ungroup` (`area`) drops it, its topics standing alone; an area they don't have is a 404. `PATCH /sessions/{id}` also takes `topic_id` (null for none) or `topic_name` (made if new) to file the chat, which then is never refiled on its own. A chat-app conversation started with /new is left off the list until its first turn (`memory.conversations`). 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. A teammate's own chat (a web chat, a DM, a private Telegram chat; not a channel or group conversation, `chat._shared_space`) is theirs alone, the principal included, as their mail with the Executive is. 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). Messages from `GET /sessions/{id}/messages` carry each assistant reply's saved `sources` (the same shape as the chat stream's `sources` event, without `type`), so a reloaded chat shows them again. The owner (not the principal on someone else's chat; the principal for an ownerless one) also has the chat controls. `PATCH` takes `{title?, pinned?}`: a name they give is kept (`sessions.title_locked`, so the automatic title never replaces it) and a pinned chat lists first, newest pin first, with `pinned_at`. `PUT /sessions/{id}/shares {person_ids}` adds exactly those team members to it (not contacts, the archived or the owner: 422), audited `session_shared`; a chat that read its owner's own mail (`mail_private`) is never shared (409) and stops being open to those it was shared with before, and a chat-app conversation is never shared (409). Those added get it from `GET /sessions/shared-with-me` (with `shared_with_you`, `shared_by`, `shared_at`) and **write in it with the owner**: `POST /chat` with its id runs their turn as themselves (`chat._shared_member` widens the turn's access, never its ownership), and they may read it, its messages (without the owner's ratings) and its export. They can't rate, rename, delete, share or redo it, and `DELETE /sessions/{id}/shares/me` takes them out of it (audited `session_shared`, with them under `removed`). In a chat several people are in, messages carry `sender_person_id` and `sender_name` (a message from before it was shared is the owner's), `GET /sessions/{id}/people` returns `{you, people: [{person_id, full_name, owner}]}` (owner first; empty for a chat of one), and redo is refused (409) when the last message is someone else's. `GET /sessions/{id}/live` is a server-sent event stream each open page holds (`api.chat_live`, one in-process broker): `ready` first (with the running turn so far, if any), then `turn_started` (who sent what), the reply's `chunk` / `thinking` / `activity` / `action_taken` / `phase`, `turn_ended` (the page reads the chat again), `typing` (from `POST /sessions/{id}/typing`, at most once per 2 s per person) and `people`. `removed`, `deleted` and `resync` (a page that fell 1024 events behind) end it; the access check runs again on every 20 s keepalive. At most 12 pages per person, 40 per chat and 2000 per process (429). Archiving someone takes them out of every chat shared with them, and their open streams close at the next keepalive. The page closes it while its tab is hidden. `GET /sessions/{id}/export` returns the chat as a Markdown file (`memory.chat_export`: each message under its writer's People name or `Executive`, the reply's sources listed under it). `POST /sessions/{id}/rewind {last_message_id}` takes back the last turn for Try again and Edit: under the conversation's turn lock it deletes the last reply and the messages it answered, but only while that reply is still the chat's last row, and returns those messages' words (`{message}`), which the page sends again as an ordinary `/chat` turn through the usual gates. 409 while a turn is answering, for a stale reply id, and for a chat-app conversation (its reply also lives in Slack, Telegram or Discord); audited `session_rewound`. |\n| `today` | `GET /today`, `GET /today/activity`, `GET /today/activity/daily`, `GET /today/brief-delivery`, `GET /today/value`, `GET /today/top-three`, `GET /today/weekly-review`, `POST /today/seen` | Morning-brief aggregation (in the install's first week, for the principal, `first_week_card` `{needs_goal, findings: [{title, summary}], brief_tomorrow}` or null), recent-action rail, Pulse heartbeat heatmap (per-day activity counts), and the owner's month tally for Pulse's Done for you (`GET /today/value?period=month|week&offset=N`: counted lines beside the period before plus the finished reports, owner only, 403 otherwise; see Today). `GET /today` carries the viewer's cached \"What's going on\" `narrative` with `narrative_generated_at` (when it was written) and `narrative_stale` (a fresher one is being written — the page re-polls; see Today), the same text split for Home's Right now card (`narrative_lead`, `narrative_points` `[{text, since}]`, `narrative_move`), `narrative_seen_at` (this reader's last look, which `POST /today/seen` records and returns as `{seen_at}`) and, for the principal, `morning_brief` `{at, text}` and `calendar_next` `[{title, start, all_day}]`. A proposal backed by a roster request carries `roster_request` (the new sender's server-derived details and held-message previews; the principal's only) and is answered through the `people` routes below. `brief-delivery` returns the latest morning brief or end-of-day digest that didn't reach the owner, as `{brief, at, problem, fix, readable}` in plain language (`readable` is false when it couldn't be written, so there is nothing to read), or null — null while briefs go out, once the cause is fixed, while the scheduler is off, and for anyone but the owner (`chat._caller_is_principal_or_unclaimed`); it carries no address or channel id. `top-three` and `weekly-review` feed the solo Briefing's own cards and answer only in solo mode and only to the principal (`workflows._caller_is_the_principal`: a principal match or no caller header, never an unclaimed roster); anyone else, and team mode, get null. `top-three` returns `{items: [{key, kind, text, why, slot}]}` — the morning brief's top three from the same code (`build_top_three(principal_due_soon())`), `slot` a free block like `10:00–11:00`, `\"\"` when none is left, null when no calendar was read — and is kept off `GET /today` because its calendar read may take up to 4 s. `weekly-review` returns the latest completed `weekly_review` run as `{run_id, completed_at, period, top_three, excerpt}` (next week's top three as plain text; `excerpt` when that list is empty), or null when none has completed. |\n| `people` | `GET\\|POST\\|PATCH /people`, `POST /people/{id}/archive`, `GET /people/requests`, `GET /people/requests/{id}`, `POST /people/requests/{id}/approve`, `POST /people/requests/{id}/decline`, `GET\\|POST /people/{id}/open-loops` (a `POST` tells the owner once and returns `notified`: `sent` with the channel, `held`, `not_reached` or `skipped`; see Attunement), `POST /open-loops/{loop_id}/close`, `GET /people/{id}/outreach`, `GET\\|PUT\\|DELETE /people/{id}/attunement` | Roster CRUD and scope lookups. Every `Person` carries `kind` (`team` / `contact`). `GET /people` lists team members only unless `?include_contacts=true` (the People page asks for both; the department-head and workflow pickers keep the default); `POST` / `PATCH` accept `kind`, and a principal contact is a 422 either way. They also take `email_aliases` (other addresses the person writes from, at most 10; on `PATCH` the full list replaces the current one, omitted leaves it): an alias matches their mail and may be emailed but never signs in; a malformed one is a 422, and an alias — or a new primary `email` — that is already someone else's address or alias is a 409. Every `POST` / `PATCH` then closes any pending roster request whose sender now matches someone and replays its held messages. Adding, editing and archiving (`POST`, `PATCH`, `/archive`) are the principal's only, or anyone's while no one is principal yet so a first setup can add its owner (`chat._caller_is_principal_or_unclaimed`, the check behind `PUT /workspace`; a request with no `x-caller-email`, such as the CLI or local login, counts as the principal). Anyone else, a person editing their own row included, gets 403 before the person lookup, so it can't probe which ids exist. Contacts are private to the principal (`caller_is_principal`: the signed-in email is the principal's, or no `x-caller-email`; stricter than the owner rule above, so while no one is principal nobody is): for anyone else `include_contacts` is ignored, a contact's id is a 404 on `GET /people/{id}` and open-loops (exactly as for a missing id; `PATCH` and archive are already a 403 for them), and creating a contact or turning someone into one is a 403, even on a first setup with no principal yet. `GET /people/me` returns `{person_id, is_principal}` so the UI offers contacts to the principal only. `GET /people/by-scope/{token}` never returns a contact. 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`). `POST /people/{id}/open-loops` `{task, due_date?}` assigns that person a task (201 with the loop; `due_date` is a local date, due 17:00 in the user's timezone, clamped to 60 days, default 2 days): any active team member may assign anyone on the team, 403 for anyone else; 409 for an archived person, a contact (as seen by the principal), a person at the open-loop cap, a duplicate or open loops turned off; 422 for an empty task. Nobody is messaged at assignment — the owner is chased once it is due. `/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 and frees their aliases. The **roster-request** routes (declared before `/people/{person_id}`) are the principal's alone (`caller_is_principal`; anyone else gets 404, as for a missing id): `GET /people/requests?status=pending|approved|linked|declined|expired|superseded|all` lists up to 100 (`id`, `channel`, `channel_ref`, sanitised `display_name`, `profile_email`, `on_company_domain`, `suggested_kind`, `suggested_person_id` / `_name`, `status`, `resolved_person_id` / `_kind`, `message_count`, timestamps, `ack_sent`, and `previews` of the held messages while pending — shown to the principal, never to a model); `approve` takes either `link_person_id` (+ `replace_channel_id`) or `full_name` + `kind` (no default: 422 without both) + optional `role`; `decline` takes no body. An answered request is a 409, a chat id or address already on someone else is a 409; the held messages are replayed (or dropped) in the background. |\n| `contacts` | `GET /contacts/changes?person_id=`, `PUT /contacts/keeper`, `POST /contacts/changes/seen`, `POST /contacts/changes/{id}/undo`, `POST /contacts/changes/{id}/accept`, `POST /contacts/changes/{id}/dismiss`, `GET /contacts/{person_id}/note` | The contact keeper (see Org), principal only (404 for anyone else). `GET /contacts/{person_id}/note` returns what is remembered about one contact or teammate (`note`, `topics`, `last_emailed_at`, `last_heard_at`, `last_met_at`, `next_meeting_at`, `next_meeting_title`, `emailed_count`, `met_count`, `note_written_at`, `updated_at`), 404 when there is nothing yet or they are not active. `GET` returns `{mode, status, last_run_at, changes}`: the switch (`on` / `ask` / `off`), how the last pass went (`ok`, `act_as_me_off`, `not_connected`, …) and the last 30 days of changes (each `id`, `person_id`, `action` add/update, `field`, `email`, `full_name`, `old_value`, `new_value`, `reason`, `evidence`, `status` applied/suggested/undone/dismissed, `seen`, `created_at`); with `person_id`, that person's every change. `PUT` sets the switch; `seen` is Got it; `undo` / `accept` / `dismiss` return the change, 409 when there is nothing to undo or decide. |\n| `chat-directory` | `GET /chat-directory/people`, `GET /chat-directory/channels`, `GET /chat-directory/slack/lookup?email=` | The Slack, Discord and Telegram people and rooms the bots can reach, by name, for the People and department pickers (`integrations/chat_directory.py`). Each answers `{slack, discord, telegram}`, every one `{configured, ok, options: [{id, name, detail, email}], truncated, members_available}`: `configured` false (and no options) when that bot has no token, `ok` false when the provider could not be read, `members_available` false when Discord refuses to list server members (the Server Members intent is off). `lookup` returns `{configured, match}`, the Slack person with that work email or null. Cached in-process for 60 s; tokens are never returned. The principal's alone, like changing the People list (`chat._caller_is_principal_or_unclaimed`); channels also open while no one is principal yet, people and lookup wait for one; a 403 otherwise, and the pickers then keep only the by-hand id field. |\n| `departments` | `GET\\|POST\\|PATCH\\|DELETE /departments`, `.../goals`, `POST /goals` | Department state and per-department goals. `POST /goals` takes a goal plus `area` (a name, ≤80): an existing area by slug or title, else a new one of that name (no specialist, as with `POST /departments`), else **General** when blank; the Goals page uses it while a workspace has no areas (setup makes none for solo or a team that names none). `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, i.e. the check-in is off); a changed `check_in` cancels the pending check-in and queues the next one on the new schedule. `GET` and `PATCH /departments/{slug}` return the department state plus `next_check_in_at` (ISO UTC of the pending check-in, `null` when it is off, the workspace is solo or none is queued); the list route does not carry it. A new `head_person_id` must be a team member: an unknown id and one of the principal's contacts get the same name-free 422 (`person_id N is not on the team.`), so the route — open to any signed-in user — never reveals that a contact exists; an unchanged head is not re-checked. `POST .../goals` requires only `key_result`: a missing or blank `period_value` is filled with the current period for `period_type` in the user's zone (the same label `create_goal` uses), and `target` defaults to empty. `PATCH .../goals/{id}` rejects a blank `key_result` or `period_value` with a 422; `target` may be cleared. |\n| `agents` | `GET /agents`, `GET /agents/models`, `GET /agents/models/options`, `GET /agents/presets`, `POST /agents/presets/{id}`, `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. `AgentDetail` carries `instructions` (additional instructions, appended after `prompt`, which stays the built-in prompt or its replacement); `PATCH` and `/test` accept `instructions` (max 4,000 chars, blank clears it). `GET /agents/presets` lists the Fast, Balanced and Thorough quality presets (each with `available` and the resolved `model` for this install) plus `active` (null when the council is Custom), `base` and `custom_agents`; `POST /agents/presets/{id}` applies one by writing per-agent model and deep-reasoning overrides and returns the same shape (404 unknown preset, 409 when the install allows none of its models). Each `AgentMeta` carries `visibility` (`core` or `internal`) so the Council's simple view can list core agents first. |\n| `personas` | `GET\\|PUT\\|POST\\|DELETE /personas` | Executive persona definitions. |\n| `alerts` | `POST /alerts/{id}/approve`, `GET /alerts/approvals/{id}`, `POST /alerts/{id}/ack`, `POST /alerts/bulk-ack`, `POST /alerts/{id}/snooze`, `POST /alerts/{id}/reopen`, `POST /alerts/review` | Groom the briefing queue. `approve` (body `{edited_body?}`, 202) carries a proposal card out on the server and records who approved it and when (`alerts.approvals`, see Today): it queues the scheduled action a department-gated card held, or runs one Executive turn as the approver in a new chat (`session_id`). 409 for a card already approved or closed, a decision-backed card (approved at `/decisions`), a roster request or a drafted artifact; 403 unless the caller is the card's routed person or the principal (an unrouted card is the principal's); 429 when the caller already has three background turns running. `GET /alerts/approvals/{id}` reads one back (`running`, then `done` / `failed` with `outcome`) for its approver, the card's person or the principal (404 for anyone else). `snooze` (`until`, an ISO time up to 30 days ahead; `null` clears it, the Undo) hides an `unread` card until then by setting `snoozed_until` (409 on a closed card or a roster request); the TTL then counts from the snooze, so a card snoozed past its TTL still comes back. `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`, `supersedes_id` and, for an extension's kind of document, `collection` / `collection_label` on every summary (`orchestrator.extensions`; archive, restore and delete tell the collection first and answer 502 if it refuses). `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. Every route answers for the signed-in caller (`artifact_records.Viewer`): a drafted artifact is its owner's alone (`alerts.owner_person_id`, the person whose conversation published it; none = the principal's), a workflow output follows its run (`persistence.run_visible_to`), and anything the caller may not see is a 404 like a missing id, the principal included. `POST /alerts/{id}/ack` and `/reopen` answer 404 for someone else's drafted artifact the same way. |\n| `decisions` | `GET /decisions`, `POST /decisions/{id}/{approve,reject,cancel}`, `GET`/`PUT /decisions/classes/meeting_scheduling`, `GET /audit/reliability` | Approval-gated decision instances (e.g. calendar bookings). What approve/reject/cancel do is per class (`DECISION_CLASSES`, one `DecisionClassSpec` each; meeting booking books on approve and deletes on cancel; `delegation_reply`, an inbox reply card, is its approver's alone (`approver_only`) — hidden from everyone else, the principal included when it is a team member's — sends its Gmail draft on approve and, after a reject, deletes the draft unless it was edited; `delegation_invite`, a meeting invite card, is its approver's alone too, and answers the invite in their own calendar on approve (`edits.answer`) and nothing on reject; `department_action`, a team member's chat send or edit their department held (see Org), is the principal's and its approver's alone (`principal_and_approver`), makes that exact call on approve and audits `department_action_done` / `_failed` / `_declined`), and an instance of a class with no spec gets 409 instead of being carried out as another. Only the principal, or the person the decision went to for approval (`approver_person_id`), may approve, reject or cancel it. Anyone else gets 403, and a decision nobody was asked about, or one private to the principal, is the principal's alone. The resolver is recorded as `resolver_person_id`, and a reject that loses the race to another answer is a 409. `GET /audit/reliability` is the principal's alone (403 otherwise), because it counts private decisions too. A proposed booking is surfaced on the briefing as a companion alert; approve/reject/cancel here also clear that alert. An approval whose caller resolves to the principal runs the booking inside `grant_contact_egress()`, so a meeting the principal proposed with a contact can be created. Such a booking's payload is marked `private`: it is proposed to the principal, left out of anyone else's `GET /decisions`, and a 404 for them on `GET /decisions/{id}` and every action route. Reviewed in the briefing — there is no separate proposals page. The class routes read and set how meetings are handled: both return `{decision_class: \"meeting_scheduling\", mode: \"propose\" \\| \"auto_execute\"}` (default `propose`); the `PUT` body is `{mode}`, principal-only (403 otherwise, open before a principal exists — but then only `propose` can be set: `auto_execute` is a 409 until a non-archived principal is on the roster), 422 on any other mode, and a change writes a `decision_class_mode_changed` audit row. In solo mode the class mode decides a booking, and `auto_execute` applies only to a turn the principal started on a verified surface — any other turn gets a proposal. |\n| `delegation` | `GET`/`PUT /delegation`, `GET`/`PUT`/`DELETE /delegation/voice`, `POST /delegation/voice/learn`, `POST /delegation/voice/describe`, `POST /delegation/voice/signature`, `PUT /delegation/inbox`, `POST /delegation/inbox/check`, `GET /delegation/replies`, `PUT /delegation/replies/{id}/text`, `PUT /delegation/replies/{id}/recipients`, `POST /delegation/replies/{id}/answer`, `GET /delegation/actions`, `GET /delegation/invites`, `PUT /delegation/handle-it`, `PUT /delegation/disclosure`, `PUT /delegation/training`, `DELETE /delegation/learned/{id}`, `GET /delegation/handled`, `PUT /delegation/team` | Act as me — the **caller's own** delegation only; nobody sets it for anyone else. It answers the principal, and a team member once the owner lets them; anyone else gets 403 `not_available_yet`. `GET /delegation` returns `{enabled, gmail: {status, message, email, connect_command, outlook_connect_command, provider}, inbox: {enabled, status, message, watch_since, last_poll_at, checking}, handle_it: {enabled, mode, available, sent_today, lead, lead_available}, training: {replies, follow_ups, actions, drafts, learned}, disclosure: {enabled, handle_it, approved_sends, line}, team}`, where `team` is the owner's switch for the principal while `DELEGATION_TEAM_MEMBERS` allows it — `{enabled, members: [{person_id, name, enabled, inbox, drafts_30d, sent_30d}]}`, counts only — and `null` otherwise. `PUT /delegation/handle-it` takes `{enabled?, mode?}` (`mode` is `careful`, `balanced` or `bold`; anything else is a 422 `bad_mode`) from a caller the API knows is that person — 403 `not_yours`, 409 `caller_signing_required` with only the shared secret — and turning it on needs Act as me and Draft replies to my inbox on (409 `act_as_me_off` / `inbox_off`); `GET /delegation/handled` returns `{replies: [{decision_id, sent_at, to_name, to_email, subject, body, open_questions, gmail_link, source, summary}]}`, the caller's replies and follow-ups (`source` `follow_up`) sent on its own in the last 7 days, and the meeting invites it accepted on its own (`source` `invite`, `subject` the meeting's title, `summary` one line such as \"Accepted Dana's Pilot review, Wed 21 Oct, 14:30\"); a card on `GET /delegation/replies` carries `source` the same way, `can_allow` while Replies (Follow-ups, on a follow-up) is in training, and `learns_style` while Drafts is. `PUT /delegation/disclosure` takes `{handle_it?, approved_sends?}` (any other field is a 422), the caller's own switches for the AI line on replies sent as them (`disclosure.enabled` is the install's `AI_DISCLOSURE`); turning one on needs no signed sign-in, turning one off does (409 `caller_signing_required`), and a change is audited as `delegation_disclosure_changed`. `PUT /delegation/training` takes `{replies?, follow_ups?, actions?, drafts?, actions_on?}` (any other field is a 422; `actions_on` is Suggested actions On, and `actions` and `actions_on` set true clear each other) and returns the `GET /delegation` shape, whose `training` carries `actions_on` too; putting Replies or Follow-ups in, or Suggested actions out of training or On, needs no signed sign-in, anything else does (409 `caller_signing_required`), and putting Replies or Follow-ups in turns Take the lead as you off (`PUT /delegation/take-the-lead` on answers 409 `in_training` while they are). `training.learned` is `[{id, label, setting, example, uses, created_at}]`, what the caller allowed or kept in training (`setting` `replies`, `follow_ups`, `actions` or `drafts`; the kept example, or \"\"); `DELETE /delegation/learned/{id}` removes one of the caller's own (404 for anyone else's). `PUT /delegation/team` takes `{enabled}` from the principal alone (403 `principal_only`; 409 `not_available` when the install doesn't allow it). The Gmail `status` is `connected`, `not_configured`, `needs_reconnect`, `mismatch`, `no_email`, `shared_mailbox` or `error`, checked live with Google on each call. `PUT` takes `{enabled}` (any other field is a 422); turning it on needs the caller's own Gmail connected, otherwise a 409 whose code says why (`gmail_not_connected`, `gmail_needs_reconnect`, `gmail_mismatch`, `no_email`, `shared_mailbox`, `gmail_error`). The voice routes show, learn (from the caller's sent mail, one pass at a time — a 409 `in_progress`, `locked`, `too_soon`, `not_enough_mail`, `no_profile` or `changed` when it was locked or edited while learning, or a Gmail code), write it from the caller's own description (`POST /delegation/voice/describe` with `{description}`: one model call applies their words to the profile they have and returns it with a short `sample_reply`, saving nothing, so they review it and save it with `PUT`; a 409 `empty`, `too_long`, `in_progress`, `too_many` past 10 an hour or `no_profile`; no mailbox needed), edit and lock, and reset \"How I write\": a typed field that fails validation is a 422 `invalid_voice` listing each `rejected` field, and `clear_exemplars` / `clear_signature` drop those. `POST /delegation/voice/signature` reads the signature from the caller's Gmail settings again and changes nothing else (a locked profile stays locked), with the same Gmail codes as learning: a 409 when their mailbox isn't connected, it refuses the sign-in or the check itself fails (`gmail_error`), and a 502 `gmail_error` when reading the signature fails. On an Outlook mailbox it is a 409 `signature_unavailable`, since Outlook gives apps no signature to read, and the stored one is left alone. A caller `can_delegate` refuses — anyone but the principal, for now — gets 403 `not_available_yet`, which hides the Settings card. A request with no `x-caller-email` is a 403 `sign_in_required` unless the API runs under local login — a header-less call is not a sign-in (the caller is read through `api/caller.py`, as on every principal-only route). `PUT /delegation/inbox` takes `{enabled}` and turns **Draft replies to my inbox** on or off, returning the same shape as `GET /delegation`: on needs Act as me on (409 `act_as_me_off`) and the mailbox connected (the Gmail codes above, which keep their names for an Outlook mailbox too), and turning Act as me off turns it off too. `POST /delegation/inbox/check` starts a scan now in the background and answers 202 with the `inbox` state (409 `inbox_off` or `in_progress`). `GET /delegation/replies` returns `{cards: [...]}`, the caller's open reply cards from the database alone (no Gmail call): the decision id, the sender's name, address, relation and whether it was verified, the subject, when it arrived, what they wrote, a one-line `gist` (what they asked and what the draft says, written with the draft and brought up to date when an answer rewrites it; empty on an older card), the draft's recipients, subject and body, `open_questions`, `flags` and a Gmail link built from a fixed prefix. **Send** is `POST /decisions/{id}/approve`: it sends the card's draft exactly as it is in Gmail, after checking again that the caller is its owner — which on a server needs signed callers (409 `caller_signing_required` otherwise) — that both switches are on (`inbox_off`), no client slot is active (`client_slot`), the Gmail is connected (the Gmail codes), the draft is still there and unanswered (`draft_gone`, `you_replied`) and its recipients are allowed (`no_recipients`, `too_many_recipients`, `executive_recipient`, `not_from_you`). Recipients that changed, or a newer message in the thread, answer 409 `{code: \"confirm\", message, reasons, recipients}`; approving again with `edits: {recipients: <the list shown>, thread_moved_on: true}` is the second yes. Send with the *on its own next time* tick adds `edits.allow: true`: 422 `cant_allow` unless Replies (Follow-ups, on a follow-up card) is in training, 409 `learned_full` when their list is full, both before anything is sent; `edits.example: true` keeps a draft edited in the mailbox as how they write to that person while Drafts is in training. A draft edited in Gmail between those checks and the send is not sent (`draft_changed`). A double tap sends once (`already_handled`); Gmail refusing answers 429 `rate_limited` or 502 `gmail_error` with nothing sent, and a send Gmail didn't confirm answers 502 `send_unconfirmed` and is settled by the next inbox scan. Dismiss is `POST /decisions/{id}/reject`. `GET /delegation/invites` returns `{cards: [...]}`, the caller's own meeting invite cards (`delegation_invite`, Read my calendar on): `decision_id`, `status`, `created_at`, `from_name`, `from_email`, `relation`, `title`, `when` (in the workspace time zone), `start`, `end`, `all_day`, `clashes` (busy times only, `\"14:00–14:30\"`), `clash_checked`, `can_answer` (false for a sign-in that reads but can't answer the calendar; then `connect_command`), `can_allow` (Replies in training) and `waited_because`. **Accept** / **Decline** is `POST /decisions/{id}/approve` with `edits: {answer: \"accept\" | \"decline\"}` (accept is the default; `allow: true` with accept for the *Accept from them on its own next time* tick), on the same caller checks Send uses (403 `not_yours`, 409 `caller_signing_required`); 409 `calendar_write_needed` when the sign-in can't answer (the card stays), `gone` when the event left their calendar, `expired` once the meeting started, `already_handled`; 502 `calendar_error` leaves the card for another try. **Dismiss** is `POST /decisions/{id}/reject` and answers nothing. `GET /delegation/actions` returns `{cards: [...]}`, the caller's own approval cards (`delegation_actions`): the decision id, when it was made, a one-line `why`, and each action's `index`, `kind` (`invite`, `message`, `add_contact`), `summary` and `text` (a message as it will be sent, or a meeting's description). **Approve** is `POST /decisions/{id}/approve` with `edits: {only: [indexes]}` (and `allow: true` for the *Do this on its own next time* tick while Suggested actions is in training: 422 `cant_allow` otherwise or when nothing on it can be allowed, 409 `learned_full`; a card carries `can_allow`); it needs the card's own person signed in (403 `not_yours`, 409 `caller_signing_required`), Act as me on (409 `act_as_me_off`) and a card under a week old (409 `expired`), runs once (409 `already_handled`), and returns the decision with `final_payload_json.results`: per action `done`, `waiting` (sent to whoever approves meetings), `failed` with why, or `skipped`. Every change writes a private audit row. |\n| `history` | `GET /memories/history` (`?q=`), `PUT /memories/history/settings`, `PATCH`/`DELETE /memories/history/{id}`, `POST /memories/history/{id}/forget-conversation` | Always in the loop: the **caller's own** notes and switches only, resolved as for Act as me (a signed-in person on the roster, or the principal under local login; otherwise 403 `sign_in_required` / `not_on_roster`). `GET` returns `{notes, reply_notes, retention_days, effective_retention_days, company_retention_days, retention_choices, can_keep_notes, can_note_replies, can_set_company_retention, share_work_style, can_share_work_style}` (`can_keep_notes`: a team member on the People list may turn notes on; `can_note_replies`: they can use Act as me, so email replies are noted too; `share_work_style`: their own \"Share my work style with the team\" switch, `can_share_work_style`: a team member in a team workspace). `PUT` turns notes on only for someone who may keep them, and `share_work_style` on only for someone who may share it (403 `not_available` for either; turning either off always works), takes a person's retention only when shorter than the company's (422 `invalid_setting`), and the company retention only from the principal (403 `principal_only`). `PATCH` pins or corrects a note; `DELETE` forgets it; `forget-conversation` is \"Don't remember this\". A note that isn't the caller's is 404. Every change is audited privately to its person. |\n| `reflection` | `GET /memories/reflection` (`?person_id=`), `DELETE /memories/reflection/misses/{id}` | Learning: the turns the conversation review graded a miss (`memory.chat_review`), with the person's words, the reply, the tools run, what they wanted instead, the `kind` (`company` / `product`), the finer `cause` (null when the grade gave none) and the signals, plus `weeks` (`{week, graded, misses}` per ISO week, newest first) and `sees_everyone`. The caller is resolved as for `history` (403 `sign_in_required` / `not_on_roster`); each person sees their own, the principal those from chats `chat._session_access` lets them open (a teammate's own web chat or DM and a mail-private conversation stay their owner's; channels and groups are open), or one person's with `?person_id=` (a teammate naming someone else gets 403 `not_yours`); the weekly counts carry no words and are not filtered. The same response carries `lessons` (`memory/lessons.py`: live first, then retired, each with `shown`/`fine_after`/`miss_after` and `retired_reason`), filtered by the same rule, and `DELETE /memories/reflection/lessons/{id}` retires one (204; 404 for a lesson the caller may not see, already retired, or missing). `DELETE` forgets one miss (`is_principal_or_self`; 404 `not_found` otherwise) and writes a `chat_review` audit row. Each miss also carries its nightly replay (`memory/replay.py`): `replay_state` (`open` / `closed` / `evidence`), `replayed_at`, `closed_at`, `replay_notes`; and the response carries `replay` (`{misses, would_pass, evidence, last_run_at}`: of the caller's visible misses from the last 30 days, how many would go right today). |\n| `notifications` | `GET /notifications/settings`, `PUT /notifications/settings` | Settings → Notifications: the **caller's own** settings only, resolved as for the notes (a signed-in person on the People list, or the principal under local login; otherwise 403 `sign_in_required` / `not_on_roster`). `GET` returns `{quiet_hours: {enabled, start, end, days}, delivery, urgent_through, timezone, effective_timezone, held_count, gets_briefs, updated_at}` — `days` is `every_day` or `weekdays`, `delivery` `instant` or `digest`, `timezone` the zone they chose (`\"\"` for the workspace's), `held_count` how many messages wait for their quiet hours or brief (counted, never listed), `gets_briefs` whether they are the principal. `PUT` takes `{quiet_hours, delivery, urgent_through, timezone}` and replaces them (extra fields, equal start and end, a bad time or an unknown zone → 422); switching `digest` → `instant` makes what waited for the brief go now. Audited as `notification_settings_changed`. See Org. |\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), plus `scripts`: how many `run_script` scripts ran (and worked, and in workflows), the tool calls they made, their time, and `turns_avoided` — an upper bound on the model turns those calls would otherwise have needed (each call past a script's first) — and `python_jobs`: how many Python jobs ran (and worked, ran a kept Custom tool, took a chat attachment), their time, CPU, largest peak memory and bytes in and out, and the tokens and charge of the turns that ran one. The Token usage page shows it as a Scripts section. Rows private to the principal (`private_to_principal`: a turn about their private mail, or a row naming one of their contacts on their own turn) are theirs alone: for any other caller, resolved as for `/alerts`, the usage totals leave them out. Once a principal is on the roster, anyone else reads only their own rows (a teammate's own turns, their Act as me work) in the list, by id and in a session, and the principal reads those as actions only — what was done, when and in whose conversation, with the text, details and `full` left out, and no text search over them; any other row's id is a 404, and a session shows only the rows the caller reads. |\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. Only `/health` is unauthenticated; `/health/honcho` sits behind the gate like everything else, because the exemption is an exact-path set. `/health` also carries `google_tools_missing`, the pinned Google tools startup priming could not find: `[]` once it has checked and they are all there, a list of names when a workspace-mcp rename or the configured services and tool tier left one out, and `null` for no answer — Google Workspace is not configured, or the probe has not finished or it failed. Only `[]` asserts they are present. It also carries `gateway`, the MCP gateway's state from its supervisor (`orchestrator.gateway_boot`): `state` is `off` (MCP not enabled), `no_servers` (enabled, the config names none), `starting` (an attempt is running), `up` or `down` (every attempt so far failed; `next_retry_at` is the next one), with `attempts`, `up_since` and `email_poller` (whether the poller that rides on the gateway runs); the failure's own text stays out, since the route is open to anyone, and goes to the log and the owner's notice on Home. A hosted instance whose gateway never came up used to answer `ok` here with no email going out or in. Only `[]` asserts the tools are present, so a probe that died cannot read as healthy; Setup status says which of the three `null` means. |\n| `version` | `GET /version` | The running version, the latest release on GitHub and `update_available`, for Settings → About. The GitHub answer is cached 6h, only a semver `tag_name` is used and the release link is built from it; `UPDATE_CHECK_ENABLED=false` skips the call and still returns the running version. No in-app updater: upgrading is host-side (`docs/deployment.md#upgrading`). |\n| `setup_status` | `GET /setup/status` | Settings → Setup status: one light per part of the install — AI model, company setup, owner, the Executive's address, API protection, Gmail, your own mailbox (Act as me), Slack, Discord, Telegram, Google Chat, the scheduler, the daily brief (when and where it goes) and Honcho — as `{checked_at, checks: [{id, label, state, summary, fix, link, last_activity}]}`, where `state` is `ok`, `warn`, `error` or `off` (optional and not set up), `fix` says what to do in plain language, `link` is an in-app page that helps (`/people`, `/onboard`) and `last_activity` is the channel's latest `integration_inbound` audit time. It tests live, with at most one free read-only call per service, each bounded to 5 s: Anthropic `models.list` (so an organisation key missing `ANTHROPIC_WORKSPACE_ID` shows up), Slack `auth.test`, Telegram `getMe` and `getWebhookInfo`, Discord `users/@me` only while the bot is still connecting, and — once the owner's own Gmail credential exists — Google's token refresh and Gmail `users/me/profile`. It also reads the listeners the lifespan leaves on `app.state` (Slack's socket, the Discord bot and its task, the MCP gateway), the scheduler heartbeat and the pause switch. When `google_workspace` is configured, the lifespan also starts `MCPGateway.prime_pinned_tools()` in the background (held on `app.state.mcp_prime_task`, cancelled at shutdown), so the pinned Google tools named in the prompt are callable without a search. With `DRIVE_SYNC_ENABLED` the lifespan also bootstraps the `drive_sync_scan` heartbeat beside Notion's (see Scheduler); the Drive folder sync has no HTTP route, only the `openexecutive sync-drive` / `purge-drive` CLI. With `CONFLUENCE_SYNC_ENABLED` it bootstraps the `confluence_sync_scan` heartbeat the same way; that sync is run by hand with `openexecutive sync-confluence` / `purge-confluence`. Sample values copied from `.env.example` are named as such without being sent anywhere. No token reaches a response or a log line: probes report a status code, a service's short error code or an exception's class name. Requests within 5 s of a run get that run's answer and concurrent requests share one run (kept per app on `app.state`), so the button can't become a stream of calls to those services. Gated like every other route; the UI adds a sign-in light of its own, from its own settings. |\n| `documents` | `POST\\|GET\\|DELETE /documents`, `GET /documents/{filename}`, `GET /documents/sources`, `POST /documents/sources/{drive\\|onedrive\\|notion}/sync`, `GET /documents/{drive\\|onedrive\\|notion}`, `GET /documents/{drive\\|onedrive\\|notion}/{id}` | Upload, list, view extracted text, and delete indexed company docs. `GET /documents` rows carry `source: \"upload\"` and the `domain` the upload was indexed under. The connected-source routes back the knowledge page's single Company documents list: `/documents/sources` gives each source's `{id, label, enabled, syncing, last_run, last_error, interval_minutes, file_count}`; `/documents/drive`, `/documents/onedrive` and `/documents/notion` list synced files from the sync state (`{enabled, last_run, last_error, files: [{id, name, url, modified_at, synced_at, indexed}]}`; a Drive row also carries `unreadable_reason`, why a file with `indexed: false` has no text — e.g. a scan OCR could not read — or null); `/documents/{drive\\|onedrive\\|notion}/{id}` returns the stored text (a OneDrive id is `<drive id>:<item id>`) for an id on record (the path comes from the state, never the caller). They are read-only — a synced file is removed where it lives. `POST …/sync` starts one tick of the same sync the scheduler runs as a background task (202); 409 when the source is not connected or a tick is already running (every sync holds a per-process run lock, so a manual run never overlaps the heartbeat; the route also keeps its own started task per source and re-checks just before starting one, so two simultaneous requests start one tick, not two), 429 with `Retry-After` within 60 s of the last successful run or of the end of the last tick in this process, failed ones included, so a failing or slow source can't be re-run back-to-back. The page's text view never loads images from synced content (a remote image would be a read beacon for whoever edits the shared folder). 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 nine specialist domains (including `sales`) or `general`; anything else is a 400 rather than a 200 that indexes where no specialist can retrieve. A scanned PDF is converted (`knowledge.pdf_reader`) before it is indexed and in the text view, as are scanned PDFs in `POST /chat/upload` and the client / onboarding intake uploads. The upload is streamed to disk 1 MB at a time and refused with a 413 once it passes 50 MB, and the file is parsed in a short-lived child process (see the RAG section), so a large document does not stay in the API process's memory. A Word or Excel file that cannot be parsed, or whose parse runs out of time, is a 422 with a readable reason. When every parser is busy, the response is a 503 with `Retry-After`. |\n| `executive` | `GET /executive/status`, `POST /executive/pause`, `POST /executive/resume`, `GET`/`PUT /executive/outside-content` | 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, name}` — `held_actions` counts due `pending` rows that fire on resume, and `name` is the Executive's name (`EXEC_DISPLAY_NAME`), which the web chat shows over its replies. `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. `GET /executive/outside-content` returns `{mode, can_change}` for the owner's **When I read outside content** setting (`ask`, `outsiders` or `trust`; `orchestrator.outside_mode`), and `PUT` with `{mode}` changes it for the principal only (403 otherwise), writing an `outside_content_mode_changed` audit row. |\n| `workspace` | `GET /workspace`, `PUT /workspace` | Solo/team mode, the user's time zone and the principal's role (`memory.workspace_settings`). Both return `{mode, timezone, effective_timezone, role_kind, role_title, reports_to, remit, measured_on, company_domains, company_domains_custom}` — `timezone` is what the user set (null when unset), `effective_timezone` the zone in effect (`timezone`, else `USER_TIMEZONE`, else UTC), and each role field is null until set. `PUT` is a partial update: only the fields sent change; `mode` is `solo` or `team` (not null), `timezone` an IANA zone, or null/blank to clear it; `role_kind` is `owner`, `in_house`, `independent` or `other`, and `role_title` / `reports_to` / `remit` / `measured_on` are free text (trimmed, at most 120 / 120 / 500 / 300 characters), each null or blank to clear it; an unknown zone, a bad mode or role kind, an over-long role field or an unknown field is a 422 and changes nothing. Switching to solo cancels every pending department check-in, switching to team re-schedules them, and a new zone re-times the pending briefs and reflection; a role change has no side effects (the next turn reads it). `company_domains` is the company's own email domains (a teammate matches by local part on them — see Org): `GET` returns the ones in effect (the stored list, or the domain of the principal's primary address, with `company_domains_custom` false) only to the same caller the role is shown to, `[]` for anyone else; `PUT` takes a list (at most 10 plain domain names, never a free-mail provider's — 422 otherwise, the value never quoted) or null / `[]` to go back to deriving them, and a change is audited with the new list. Each change writes a `workspace_settings_changed` audit row (a role change adds `details.role_fields_changed`, the names of the fields that changed — never their text). The role is the principal's: `GET` returns it only to a caller `PUT` would accept and reads it as nulls for anyone else. `PUT` is the principal's alone (`is_principal_or_self`, 403 otherwise; a header-less caller resolves to the principal as in `chat`) and open while no principal is rostered, so first-run setup can pick a mode. Both work before onboarding — unlike `company-profile`, nothing here needs a profile. |\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/describe`, `POST /watchlist/{slug}/approve`, `POST /watchlist/{slug}/decline` | External-monitoring watchlist + signals. `POST /watchlist/describe` `{text}` drafts a watch from a sentence (one forced tool call on the utility-fast model, `monitoring.describe`; the company profile's name, competitors, vendors and tickers ride in the user turn) and saves nothing: it returns the create fields (`slug`, `signal_type`, `target`, `display_label`, `trigger`, `cadence`, `mode`, `severity_floor`, `severity_ceiling`, `notes`) plus four plain lines (`watching`, `tell_you_when`, `how_often`, `how_loud`) written by code from those fields, after the create route's checks (registered kind, cadence, severity, the URL guard, the rss feed check, a free slug); 422 with a plain reason when it can't be a watch, 429 past 30 drafts an hour, 502/504 when the model fails. `GET /watchlist/{slug}` also returns `noise` `{recent_alerts, recent_dismissed, noisy}` (its last 8 alerts, noisy at 6 dismissed, `monitoring.noise`), and `PATCH` takes `quiet_noise_nudge: true` to stop that question for the alerts so far. `display_label` on create maps to the adapter's label key for every kind. 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`, `POST /workflows/runs/{run_id}/rerun`, `GET /workflows/tools/search?q=`, `GET /workflows/tools/describe?names=` | Workflow catalog, run management, and user-created (dynamic) workflow CRUD. `rerun` queues a failed scheduled run (a department check-in, a saved workflow on a cadence) once more, due now (see Scheduler); the principal may, and for a saved workflow the person it delivers to; 409 for a run that did not fail, one started from `/jobs` (\"Start this one again from its page\") or one already queued again. 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/{name}/runs` is a 403 (\"Only the principal can run this workflow.\"), audited, before any run row exists, when the workflow is one only the principal may start in the workspace's mode (`weekly_review` always, `morning_brief` in solo) and the caller is not the principal. A request with no `x-caller-email` counts as the principal; with no principal on the roster, no signed-in caller does. This governs starting a run only. A run started by hand (this endpoint, or `run_workflow` / research in chat) records its starter as `owner_person_id` and is theirs alone: `GET /workflows/runs` lists the team's (scheduled, no owner) runs plus the caller's own and the ones waiting on them, and `GET` / `DELETE /workflows/runs/{run_id}` and `POST /workflows/runs/{run_id}/decision` are a 404 for anyone else's, the principal included. A signed-in email that is on nobody's People entry cannot start one (403), and a run whose starter can't be read is refused (503); its steps read and draft documents as the starter only. `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`, `background` (true for the system-run built-ins the UI files under “System”) and `quick` (true for a Quick workflow, one per playbook nothing else follows, named `quick_<playbook>`). 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| `evals` | `/evals/scenarios`, `/evals/runs` | Eval scenarios and run results. `POST /evals/runs` is a 403 when a workflow scenario names a workflow that only the principal may start in the mode it runs in (the weekly review; the morning brief in solo) and the caller is not the principal — the Jobs page's rule for starting a run; stored results are read under the existing `/evals/runs` rules. |\n| `memories` | `/memories/{decisions,initiatives,advice}`, `GET /memories/facts`, `POST /memories/facts/{fact_id}/{retire,approve,decline}`, `GET /memories/facts/approval`, `PUT /memories/facts/approval/{person_id}`, `GET /memories/people`, `GET /memories/people/{person_id}/conclusions` | Episodic-memory record management; the standing facts the Pulse Corrections tab reads (`{facts: [...], can_retire, retirable_ids, can_review}`; each fact carries `recorded_by_role` / `recorded_by_name`; `?include_inactive=` default true, honoured for the principal only; anyone else gets the active rows plus their own `proposed` ones, with the provenance (`session_id`, `turn_id`, `recorded_by_person_id`, `retired_reason`, and `source_quote` except on their own facts) blanked, never retired, replaced or declined text; `?limit=` 1–500) and their retire (the principal any fact, a teammate only one they recorded that the principal has not approved — else 403; the audit row names the teammate; 404 for an unknown or `profile` row, 409 when no longer active; writes a private `fact_retired` audit row); approve / decline a teammate's `proposed` fact (principal only, else 403; 409 when it is not proposed; private `fact_reviewed` row); and the per-teammate \"needs my approval\" switch (on by default; `GET` lists `[{person_id, full_name, needs_approval}]` for every active team member but the principal, `true` for anyone not yet set; `PUT` takes `{needs_approval}`, 404 for anyone else; both principal only; private `fact_approval_changed` row); 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). Peer memory is each person's own: the overview holds only the caller's entry (none for a caller off the roster; `conclusion_total` counts only theirs), the principal included, and `/conclusions` for anyone but the caller is a 404. |\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/understand`, `/onboard/interview/start`, `/onboard/interview/message`, `/onboard/interview/draft`, `/onboard/interview/revise`, `/onboard/interview/{id}` (GET resumes, DELETE starts over), `/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). `revise` changes one earlier answer (0 = the description) and runs the interview again from there. `commit` answers 403 when the draft would make a different person the owner and the caller is not the current owner (setup demotes the old principal, and any signed-in user can open it). It also takes an optional `owner_email` — the principal's sign-in email, which the review screen pre-fills from the signed-in user — checked before anything is written (422 if it is malformed, already another person's, or would replace the principal's existing email — setup only fills in a missing one; 403 if the caller is not the owner and it is not the address they signed in with, since the roster is the sign-in allow-list) and saved on the principal's People row, so the owner's chats resolve to them from the first turn. |\n| `workflow_designer` | `POST /workflows/designer/start`, `POST /workflows/designer/edit`, `POST /workflows/designer/message`, `POST /workflows/designer/draft`, `GET /workflows/designer/{session_id}` | The conversational New workflow wizard, and editing a saved workflow by conversation. `/edit` (`{name}`) opens a session on a saved custom workflow with no model call: the stored definition is the starting draft, and every response then carries `editing` (its name) and `original` (the stored definition as the session opened on it); drafts keep that name and its on/off state whatever the model writes (404 for an unknown workflow). The UI saves one with `POST /workflows/custom/{name}/save-edit` (`{session_id, definition}`): the server saves the session's own draft, never a client-sent body, and only when it equals the `definition` the user reviewed (a later message is a 409, so the click saves only what was shown); it re-validates it, keeps the stored on/off state, and writes only if the stored workflow is still the version the conversation opened on — otherwise 409, as it is for a session about another workflow or one with nothing drafted yet. It sits under `/workflows/custom` so anything that limits writes to custom workflows covers it too. 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| `python_jobs` | `GET /python-jobs/{job_id}/{name}` | A result file a Python job (`run_python_job`) wrote, the principal's alone (403 otherwise), served as a download (`Content-Disposition: attachment`, `Content-Security-Policy: sandbox`, `nosniff`, `Cache-Control: no-store`); 404 for a bad id or name or a file past its 7 days. |\n| `saved_tools` | `GET /saved-tools`, `GET\\|PUT /saved-tools/{name}`, `POST /saved-tools/{name}/rollback` | The scripts the Executive saved as tools (Settings → Advanced → Saved tools), the owner's alone (403 otherwise). The list gives each tool's name, description, on/off, current version, `kind` (`script` or `python`, a kept Python job) and the tools it calls, plus whether `SAVED_TOOLS_ENABLED` is on; the detail adds the script, every version and the last 20 runs. `PUT {enabled?, workflows?, version?}` turns one on or off (off also turns it off for workflows, so turning it back on never re-arms unattended runs), and turns the named `version` — the one the owner looked at, never whatever is current by then — on for workflows (or workflows off); a Python tool never turns on for workflows (409) — turning workflows on lets more run unattended, so it needs a request tied to the owner (signed sign-ins or local login, as Take the lead's switches do; 409 otherwise); `rollback {version}` makes that version the one that runs. Both are audited as `saved_tool_changed`. The Executive saves tools itself through `run_script`; there is no create route. |\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. Its final answer saves the profile and adds people with their emails and a principal, so once there is an owner only they can send it (403, and the session rolls back so the owner can still finish it). `/onboard/start` reads the workspace mode once for the session: solo skips the Team Size, Team Members and Fractional Executives steps. Each status response's `current_step` / `total_steps` count only the steps that session asks, and `optional` says whether the current step can be skipped. |\n| `company-profile` | `GET\\|PATCH /company-profile` | Structured company profile. |\n| `alerts` (private cards) | `POST /alerts/{id}/ack`, `/reopen`, `/alerts/bulk-ack` | An alert tagged `private:principal` (see Today) is a 404 on ack and reopen for anyone but the principal, and their bulk sweep skips it. A roster-request card (source `roster_request`) is a 409 on `ack` even for the principal — it is answered at `/people/requests/{id}`, since acking would leave the sender waiting with nothing to show it — and, as an exempt source, `bulk-ack` and `reopen` skip it. |\n| `auth` | `GET /auth/allowed-emails` | Non-archived **team members** with an email, offered to the UI's sign-in gate — a contact is never on it, so adding a client to reach them by email no longer lets them sign in. 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. With local login (`make dev` with Google sign-in not set up — the UI then listens on 127.0.0.1 only) the UI signs in without an email, sends no `x-caller-email`, and the backend resolves the caller to the principal, as it does for the CLI. |\n| `fixtures` | `/fixtures`, `/fixtures/{name}/load` | Demo-company fixture load/reset/snapshot. `POST /fixtures/reset` leaves no departments, like a new install (`departments_seeded` is always 0). |\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`, `POST /webhook/slack` | Inbound integration callbacks (self-verified). `/webhook/slack` answers 503 unless `SLACK_SIGNING_SECRET` is set. |\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, answered as the verified caller (`api.caller`) by the web app's rules. See the MCP Server section. | A card the Executive left for something asked in chat (`app_action`, `orchestrator/app_control.py`) is its person's alone too: its payload holds `action`, `id`, `value`, `title` and the `card` line shown; **Confirm** is `POST /decisions/{id}/approve`, which runs the action through the route its button calls with that request (a refusal comes back as that route's status and words, and the card is marked `failed`), and a card older than a day is turned down with 409.\n\n**What it does for you** (`api/routes/may_do.py`): `GET /what-it-may-do` is read-only. It returns `{paused, sections}`, three sections in order (`as_you`, `executive`, `departments`), each `{key, title, available, unavailable, notes, rows, footer, goes}`, and each row `{id, what, outcome, then, why, setting, items}`: `outcome` is `goes`, `waits`, `always_waits`, `drafts` or `off`, and `setting` names where to change it (`act_as_me`, `handle_it`, `take_the_lead`, `pause`, `department:<slug>`, or empty). `as_you` is the caller's own (`available` false, with why, when they can't have Act as me); `executive` is the principal's alone (`available` false for anyone else); `departments` is everyone's. Any team member on People may call it; a contact, someone not on People, or a request with no caller outside local login gets 403. See Delegation → What it does for you.\n\n**How far it goes as you** (`api/routes/delegation.py`): `PUT /delegation/reach` takes `{step}`, one of `off`, `when_asked`, `inbox`, `careful`, `balanced`, `bold`, `everything`, and answers the caller's delegation state as `GET /delegation` does. Going down turns the switches above the step off, highest first; going up runs each switch's own route in order (`PUT /delegation`, `PUT /delegation/inbox`, `PUT /delegation/handle-it`, `PUT /delegation/take-the-lead`), so the first refusal (409 `gmail_not_connected`, a signed sign-in missing, `in_training`, 403 for Everything when not the owner) stops it at a whole step. See Delegation → How far it goes as you.\n\n**Take the lead** (`api/routes/take_the_lead.py`): `GET /take-the-lead` returns the As the Executive switch, its six Ask first switches (`{kind, label, hint, on}`, the hint a plain line on what each one catches), the company's rules, whether this server can tie a change to the owner (`available`), and whether the Executive is paused. `PUT /take-the-lead` takes `{enabled?, ask_first?}`, and `POST /take-the-lead/rules` / `DELETE /take-the-lead/rules/{id}` add or remove a company rule (`{kind: person|domain|words|amount, value}`, 422 on a bad one). All four are the principal's alone (403). Anything that lets more happen on its own (turning it on, turning an Ask first off, removing a rule) needs a caller the API can tie to them (`delegation.verified.caller_refusal`, else 409). `GET /today/activity` adds `took_the_lead` rows (what Take the lead did, named, not quoted) and, for the caller alone, `sent_as_you` rows for what Handle it for me sent as them (and the meeting invites it accepted as them, \"Accepted Dana's Pilot review, Wed 21 Oct, 14:30\") and, for the principal, one `contacts_kept` row a day the contact keeper changed something (`detail` like \"2 added, 1 updated\"). Under `/delegation`: `PUT /delegation/take-the-lead {enabled}` is Take the lead as you (the owner's only for now; turning it on turns Handle it for me on), and `GET|POST /delegation/take-the-lead/rules` and `DELETE …/rules/{id}` manage the caller's own rules. `HandleItOut` gains `lead` and `lead_available`. A `take_the_lead_action` decision is approved or rejected through the existing `/decisions/{id}/approve|reject`. Training: the response also carries `training` (In training: everything waits unless allowed), `learned` (`{id, label, feature, example, uses, created_at}`: what it was allowed, the edit kept as an example by field) and `suggested` (`{key, label, approvals}`); `PUT` takes `training?` too, and leaving training while on needs the same provable owner as turning it on. `POST /take-the-lead/learned {key}` allows a current suggestion (404 for anything else; provable owner), `DELETE /take-the-lead/learned/{id}` makes it ask first again. `learned` also lists the owner's own Act as me senders (`feature` `act_as_me`), never anyone else's, and Remove works on those too. On a `take_the_lead_action` card, `POST /decisions/{id}/approve` takes `edits.input` (the card's editable fields, 422 for any other; the principal's alone, 403 for an area approver) and `edits.allow: true` (a training card only, 422 otherwise; the principal from a provable request, 403 otherwise), finishing `approved_with_edit` when a field changed.",
+ "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). A request it lets through is marked `request.state.shared_secret_ok`, which is what lets an MCP request turn on \"may act\" with `x-mcp-client-actions: on` (`mcp_server.may_act`; with no secret the header is ignored and `MCP_CLIENT_ACTIONS` decides). With local login (`OE_LOCAL_LOGIN=1`, which only `make dev` sets, and only while neither Google nor SSO sign-in is set up) a second middleware answers 403 to any request whose raw `Host` is not `localhost`, `127.0.0.1` or `[::1]` (except a webhook that verifies its caller: Google Chat and Slack always, Telegram only with a `TELEGRAM_WEBHOOK_SECRET` Telegram can send), and to any write whose `Sec-Fetch-Site` is present and not `same-origin`/`none`. The UI signs that owner in with no password and this API usually has no secret, so without it a web page in the owner's browser could drive the API as the principal — by DNS-rebinding its own hostname to 127.0.0.1, or by posting a plain form from another site or localhost port. CORS is restricted to the UI origins in `BACKEND_ALLOWED_ORIGINS`, plus the `make dev` UI on `localhost:3000` only when `OE_PUBLIC_DEPLOYMENT` is unset, so a public instance never answers a localhost page with credentials. 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\n**Who is calling** is read in one place, `api/caller.py`, which answers with a `Caller` kind and email; a test fails on any other read of an `x-caller-*` header. By default (`open`) it is the `x-caller-email` the UI proxy stamps from the sign-in, trusted because whoever holds the shared secret is trusted as the proxy, and a request with none runs as the principal. **Signed callers** remove that trust. With `CALLER_ASSERTION_PUBLIC_KEYS` set, the proxy signs every request with an Ed25519 key only the UI holds, and a third middleware checks the `x-caller-assertion` header:\n\n- **What it covers.** It is good for one method, the exact path and query, at most 120 seconds, and one use. The API keeps used ids in memory.\n- **What it names.** A `user`, by email, or the `operator`: local login, which runs as the principal.\n- **No caller header at all** is a `service`, for scripts or MCP clients holding only the secret. It is never the principal, not even on an install with no owner yet, so it can't save a first setup.\n- **Anything else is a 401.** That includes an `x-caller-email` without an assertion (`caller_assertion_required`), and a bad, expired, reused or mismatched assertion (`caller_assertion_invalid`).\n\nPublic keys that can't be read stop the boot, rather than fall back to trusting the header. `scripts/make-caller-keys.py` makes the pair, and `scripts/mint-caller-assertion.py` signs one request for curl. The API holds only public keys. Setup's API-protection check warns while a shared secret is set without them.\n\nEndpoints grouped by router:\n\n| Router | Key endpoints | Purpose |\n|---|---|---|\n| `chat` | `POST /chat`, `POST /chat/stop`, `POST /chat/add`, `POST /chat/background`, `GET /chat/voice`, `POST /chat/transcribe` | SSE stream of a live Executive turn, with a `: keepalive` comment every `CHAT_STREAM_KEEPALIVE_S` while the turn is quiet. `POST /chat/background` starts a new chat that the server answers to the end with nobody connected (a phone approving a card, then closing the app): it answers `202` with the new `session_id` once the same caller, access and quota checks as `/chat` pass, the turn saves itself as a `/chat` turn does, and one caller may have three running at once (`429` beyond that). `POST /chat/add` hands the running turn a message the person typed while it works; the turn takes it at its next step and the stream names it in a `message_added` event, and a second `POST /chat` on the same conversation waits for the first to finish. `GET /chat/voice` says whether the chat mic shows (`available`, `max_seconds`); `POST /chat/transcribe` takes one recording (multipart `file`) and answers `{text}` for the message box, nothing kept: `404` when speech to text isn't set up, `400` for a file that isn't audio, `413` over 25 MB, `502` when the speech server fails. 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`. After the reply — a stopped or timed-out one too, before the `stopped` / `error` / `done` frames — a turn that looked at anything sends one `sources` event, `{type, session_id, sources: [{kind, title, url}], unavailable: [area]}`: `kind` is `company`, `knowledge`, `notion`, `research`, `document` or `web`, `url` is only ever an http(s) link or, for an earlier document, `/artifacts/<id>`, at most 12 sources (6 from the web, pages the reply cites first), and `unavailable` names parts of the analysis (\"finance\") whose specialist failed or said nothing every time it was asked. It is persisted with the reply as `chat_messages.sources`. When the turn held steps for an outside read that still wait on the speaker's go (`outside_content.pending_held`), it then sends one `held_steps` event, `{type, session_id, steps: [plain words]}` (not after a stop or a timeout), which the UI shows as Approve / Not now under the reply; Approve sends \"Go ahead\". `GET /sessions/{id}/messages` puts the same `held_steps` on the last reply while they still wait (never for a shared chat's member). A request that carries `x-caller-email` marks its turn signed in (`Session.web_caller_signed_in`), which Act as me needs on a deployment without local login. |\n| `sessions` | `GET /sessions`, `GET /sessions/shared-with-me`, `GET /sessions/topics`, `PATCH\\|DELETE /sessions/topics/{topic_id}`, `POST /sessions/topics/{topic_id}/merge`, `POST /sessions/topic-areas/rename`, `POST /sessions/topic-areas/ungroup`, `GET\\|PATCH /sessions/{id}`, `GET /sessions/{id}/messages`, `DELETE /sessions/{id}`, `POST /sessions/{id}/messages/{message_id}/feedback`, `GET /sessions/{id}/followup`, `GET\\|PUT /sessions/{id}/shares`, `DELETE /sessions/{id}/shares/me`, `GET /sessions/{id}/people`, `GET /sessions/{id}/live`, `POST /sessions/{id}/typing`, `GET /sessions/{id}/export`, `POST /sessions/{id}/rewind` | List, read and delete saved chat sessions (assistant messages carry their row `id` and any `feedback`). The list is scoped to the caller, and each chat carries `preview`: its last message as one plain line, Markdown marks stripped and cut at a word near 120 characters, with `You:` before the person's own words. With `?q=` it is a search: the caller's own chats whose title or message text contains the words (case-insensitive, `LIKE` with wildcards escaped), each with `match_count` (messages that contain them; 0 for a title-only match) and `snippet` (the newest matching message, around the match, prefixed `You:` or `Executive:`). Scoped exactly like the list, so nobody else's conversation can match. The Chats page searches this way and opens a result with `?find=`, so the chat starts on that message and steps through the others. Each of the owner's chats also carries `topic_id`, the topic it is filed under (`memory.chat_topics`). `GET /sessions/topics` lists the caller's topics (`id`, `name`, `chat_count`, `kept`, `pinned_at`, `area`, `updated_at`) and, when some of their chats have no topic yet or some topics no area, starts filing them in the background from their titles and answers `organizing: true` until done. `PATCH /sessions/topics/{topic_id}` renames (a name another of their topics has merges the two) or pins one, `POST …/merge` moves its chats into another (`into_id`), and `DELETE` ungroups it, leaving its chats under no topic; another person's topic is a 404. `POST /sessions/topic-areas/rename` (`area`, `name`) renames one of the caller's areas and `…/ungroup` (`area`) drops it, its topics standing alone; an area they don't have is a 404. `PATCH /sessions/{id}` also takes `topic_id` (null for none) or `topic_name` (made if new) to file the chat, which then is never refiled on its own. A chat-app conversation started with /new is left off the list until its first turn (`memory.conversations`). 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. A teammate's own chat (a web chat, a DM, a private Telegram chat; not a channel or group conversation, `chat._shared_space`) is theirs alone, the principal included, as their mail with the Executive is. 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). Messages from `GET /sessions/{id}/messages` carry each assistant reply's saved `sources` (the same shape as the chat stream's `sources` event, without `type`), so a reloaded chat shows them again. The owner (not the principal on someone else's chat; the principal for an ownerless one) also has the chat controls. `PATCH` takes `{title?, pinned?}`: a name they give is kept (`sessions.title_locked`, so the automatic title never replaces it) and a pinned chat lists first, newest pin first, with `pinned_at`. `PUT /sessions/{id}/shares {person_ids}` adds exactly those team members to it (not contacts, the archived or the owner: 422), audited `session_shared`; a chat that read its owner's own mail (`mail_private`) is never shared (409) and stops being open to those it was shared with before, and a chat-app conversation is never shared (409). Those added get it from `GET /sessions/shared-with-me` (with `shared_with_you`, `shared_by`, `shared_at`) and **write in it with the owner**: `POST /chat` with its id runs their turn as themselves (`chat._shared_member` widens the turn's access, never its ownership), and they may read it, its messages (without the owner's ratings) and its export. They can't rate, rename, delete, share or redo it, and `DELETE /sessions/{id}/shares/me` takes them out of it (audited `session_shared`, with them under `removed`). In a chat several people are in, messages carry `sender_person_id` and `sender_name` (a message from before it was shared is the owner's), `GET /sessions/{id}/people` returns `{you, people: [{person_id, full_name, owner}]}` (owner first; empty for a chat of one), and redo is refused (409) when the last message is someone else's. `GET /sessions/{id}/live` is a server-sent event stream each open page holds (`api.chat_live`, one in-process broker): `ready` first (with the running turn so far, if any), then `turn_started` (who sent what), the reply's `chunk` / `thinking` / `activity` / `action_taken` / `phase`, `turn_ended` (the page reads the chat again), `typing` (from `POST /sessions/{id}/typing`, at most once per 2 s per person) and `people`. `removed`, `deleted` and `resync` (a page that fell 1024 events behind) end it; the access check runs again on every 20 s keepalive. At most 12 pages per person, 40 per chat and 2000 per process (429). Archiving someone takes them out of every chat shared with them, and their open streams close at the next keepalive. The page closes it while its tab is hidden. `GET /sessions/{id}/export` returns the chat as a Markdown file (`memory.chat_export`: each message under its writer's People name or `Executive`, the reply's sources listed under it). `POST /sessions/{id}/rewind {last_message_id}` takes back the last turn for Try again and Edit: under the conversation's turn lock it deletes the last reply and the messages it answered, but only while that reply is still the chat's last row, and returns those messages' words (`{message}`), which the page sends again as an ordinary `/chat` turn through the usual gates. 409 while a turn is answering, for a stale reply id, and for a chat-app conversation (its reply also lives in Slack, Telegram or Discord); audited `session_rewound`. |\n| `today` | `GET /today`, `GET /today/activity`, `GET /today/activity/daily`, `GET /today/brief-delivery`, `GET /today/value`, `GET /today/top-three`, `GET /today/weekly-review`, `POST /today/seen` | Morning-brief aggregation (in the install's first week, for the principal, `first_week_card` `{needs_goal, findings: [{title, summary}], brief_tomorrow}` or null), recent-action rail, Pulse heartbeat heatmap (per-day activity counts), and the owner's month tally for Pulse's Done for you (`GET /today/value?period=month|week&offset=N`: counted lines beside the period before plus the finished reports, owner only, 403 otherwise; see Today). `GET /today` carries the viewer's cached \"What's going on\" `narrative` with `narrative_generated_at` (when it was written) and `narrative_stale` (a fresher one is being written — the page re-polls; see Today), the same text split for Home's Right now card (`narrative_lead`, `narrative_points` `[{text, since}]`, `narrative_move`), `narrative_seen_at` (this reader's last look, which `POST /today/seen` records and returns as `{seen_at}`) and, for the principal, `morning_brief` `{at, text}` and `calendar_next` `[{title, start, all_day}]`. A proposal backed by a roster request carries `roster_request` (the new sender's server-derived details and held-message previews; the principal's only) and is answered through the `people` routes below. `brief-delivery` returns the latest morning brief or end-of-day digest that didn't reach the owner, as `{brief, at, problem, fix, readable}` in plain language (`readable` is false when it couldn't be written, so there is nothing to read), or null — null while briefs go out, once the cause is fixed, while the scheduler is off, and for anyone but the owner (`chat._caller_is_principal_or_unclaimed`); it carries no address or channel id. `top-three` and `weekly-review` feed the solo Briefing's own cards and answer only in solo mode and only to the principal (`workflows._caller_is_the_principal`: a principal match or no caller header, never an unclaimed roster); anyone else, and team mode, get null. `top-three` returns `{items: [{key, kind, text, why, slot}]}` — the morning brief's top three from the same code (`build_top_three(principal_due_soon())`), `slot` a free block like `10:00–11:00`, `\"\"` when none is left, null when no calendar was read — and is kept off `GET /today` because its calendar read may take up to 4 s. `weekly-review` returns the latest completed `weekly_review` run as `{run_id, completed_at, period, top_three, excerpt}` (next week's top three as plain text; `excerpt` when that list is empty), or null when none has completed. |\n| `people` | `GET\\|POST\\|PATCH /people`, `POST /people/{id}/archive`, `GET /people/requests`, `GET /people/requests/{id}`, `POST /people/requests/{id}/approve`, `POST /people/requests/{id}/decline`, `GET\\|POST /people/{id}/open-loops` (a `POST` tells the owner once and returns `notified`: `sent` with the channel, `held`, `not_reached` or `skipped`; see Attunement), `POST /open-loops/{loop_id}/close`, `GET /people/{id}/outreach`, `GET\\|PUT\\|DELETE /people/{id}/attunement` | Roster CRUD and scope lookups. Every `Person` carries `kind` (`team` / `contact`). `GET /people` lists team members only unless `?include_contacts=true` (the People page asks for both; the department-head and workflow pickers keep the default); `POST` / `PATCH` accept `kind`, and a principal contact is a 422 either way. They also take `email_aliases` (other addresses the person writes from, at most 10; on `PATCH` the full list replaces the current one, omitted leaves it): an alias matches their mail and may be emailed but never signs in; a malformed one is a 422, and an alias — or a new primary `email` — that is already someone else's address or alias is a 409. Every `POST` / `PATCH` then closes any pending roster request whose sender now matches someone and replays its held messages. Adding, editing and archiving (`POST`, `PATCH`, `/archive`) are the principal's only, or anyone's while no one is principal yet so a first setup can add its owner (`chat._caller_is_principal_or_unclaimed`, the check behind `PUT /workspace`; a request with no `x-caller-email`, such as the CLI or local login, counts as the principal). Anyone else, a person editing their own row included, gets 403 before the person lookup, so it can't probe which ids exist. Contacts are private to the principal (`caller_is_principal`: the signed-in email is the principal's, or no `x-caller-email`; stricter than the owner rule above, so while no one is principal nobody is): for anyone else `include_contacts` is ignored, a contact's id is a 404 on `GET /people/{id}` and open-loops (exactly as for a missing id; `PATCH` and archive are already a 403 for them), and creating a contact or turning someone into one is a 403, even on a first setup with no principal yet. `GET /people/me` returns `{person_id, is_principal}` so the UI offers contacts to the principal only. `GET /people/by-scope/{token}` never returns a contact. 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`). `POST /people/{id}/open-loops` `{task, due_date?}` assigns that person a task (201 with the loop; `due_date` is a local date, due 17:00 in the user's timezone, clamped to 60 days, default 2 days): any active team member may assign anyone on the team, 403 for anyone else; 409 for an archived person, a contact (as seen by the principal), a person at the open-loop cap, a duplicate or open loops turned off; 422 for an empty task. Nobody is messaged at assignment — the owner is chased once it is due. `/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 and frees their aliases. The **roster-request** routes (declared before `/people/{person_id}`) are the principal's alone (`caller_is_principal`; anyone else gets 404, as for a missing id): `GET /people/requests?status=pending|approved|linked|declined|expired|superseded|all` lists up to 100 (`id`, `channel`, `channel_ref`, sanitised `display_name`, `profile_email`, `on_company_domain`, `suggested_kind`, `suggested_person_id` / `_name`, `status`, `resolved_person_id` / `_kind`, `message_count`, timestamps, `ack_sent`, and `previews` of the held messages while pending — shown to the principal, never to a model); `approve` takes either `link_person_id` (+ `replace_channel_id`) or `full_name` + `kind` (no default: 422 without both) + optional `role`; `decline` takes no body. An answered request is a 409, a chat id or address already on someone else is a 409; the held messages are replayed (or dropped) in the background. |\n| `contacts` | `GET /contacts/changes?person_id=`, `PUT /contacts/keeper`, `POST /contacts/changes/seen`, `POST /contacts/changes/{id}/undo`, `POST /contacts/changes/{id}/accept`, `POST /contacts/changes/{id}/dismiss`, `GET /contacts/{person_id}/note` | The contact keeper (see Org), principal only (404 for anyone else). `GET /contacts/{person_id}/note` returns what is remembered about one contact or teammate (`note`, `topics`, `last_emailed_at`, `last_heard_at`, `last_met_at`, `next_meeting_at`, `next_meeting_title`, `emailed_count`, `met_count`, `note_written_at`, `updated_at`), 404 when there is nothing yet or they are not active. `GET` returns `{mode, status, last_run_at, changes}`: the switch (`on` / `ask` / `off`), how the last pass went (`ok`, `act_as_me_off`, `not_connected`, …) and the last 30 days of changes (each `id`, `person_id`, `action` add/update, `field`, `email`, `full_name`, `old_value`, `new_value`, `reason`, `evidence`, `status` applied/suggested/undone/dismissed, `seen`, `created_at`); with `person_id`, that person's every change. `PUT` sets the switch; `seen` is Got it; `undo` / `accept` / `dismiss` return the change, 409 when there is nothing to undo or decide. |\n| `chat-directory` | `GET /chat-directory/people`, `GET /chat-directory/channels`, `GET /chat-directory/slack/lookup?email=` | The Slack, Discord and Telegram people and rooms the bots can reach, by name, for the People and department pickers (`integrations/chat_directory.py`). Each answers `{slack, discord, telegram}`, every one `{configured, ok, options: [{id, name, detail, email}], truncated, members_available}`: `configured` false (and no options) when that bot has no token, `ok` false when the provider could not be read, `members_available` false when Discord refuses to list server members (the Server Members intent is off). `lookup` returns `{configured, match}`, the Slack person with that work email or null. Cached in-process for 60 s; tokens are never returned. The principal's alone, like changing the People list (`chat._caller_is_principal_or_unclaimed`); channels also open while no one is principal yet, people and lookup wait for one; a 403 otherwise, and the pickers then keep only the by-hand id field. |\n| `departments` | `GET\\|POST\\|PATCH\\|DELETE /departments`, `.../goals`, `GET\\|POST /goals`, `PATCH\\|DELETE /goals/{id}` | Department state and goals. A goal has an optional department and an optional `owner_person_id` (a non-archived team member, else 422). `GET /goals` lists every goal with `owner_id`/`owner_name` (its own owner, else its department's head, else the principal) and `department_title`. `POST /goals` takes a goal plus `area` (a name, ≤80): an existing department by slug or title, else a new one of that name (no specialist, as with `POST /departments`), else no department when blank. `PATCH /goals/{id}` edits any goal and may move it (`department_slug`, null = none; `owner_person_id`, null = follow the department) — only the fields sent change; `DELETE /goals/{id}` removes any goal. The department-scoped goal routes still reach only that department's goals. `DELETE /departments/{slug}` keeps its goals with no department, on their owners. `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, i.e. the check-in is off); a changed `check_in` cancels the pending check-in and queues the next one on the new schedule. `GET` and `PATCH /departments/{slug}` return the department state plus `next_check_in_at` (ISO UTC of the pending check-in, `null` when it is off, the workspace is solo or none is queued); the list route does not carry it. A new `head_person_id` must be a team member: an unknown id and one of the principal's contacts get the same name-free 422 (`person_id N is not on the team.`), so the route — open to any signed-in user — never reveals that a contact exists; an unchanged head is not re-checked. `POST .../goals` requires only `key_result`: a missing or blank `period_value` is filled with the current period for `period_type` in the user's zone (the same label `create_goal` uses), and `target` defaults to empty. `PATCH .../goals/{id}` rejects a blank `key_result` or `period_value` with a 422; `target` may be cleared. |\n| `agents` | `GET /agents`, `GET /agents/models`, `GET /agents/models/options`, `GET /agents/presets`, `POST /agents/presets/{id}`, `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. `AgentDetail` carries `instructions` (additional instructions, appended after `prompt`, which stays the built-in prompt or its replacement); `PATCH` and `/test` accept `instructions` (max 4,000 chars, blank clears it). `GET /agents/presets` lists the Fast, Balanced and Thorough quality presets (each with `available` and the resolved `model` for this install) plus `active` (null when the council is Custom), `base` and `custom_agents`; `POST /agents/presets/{id}` applies one by writing per-agent model and deep-reasoning overrides and returns the same shape (404 unknown preset, 409 when the install allows none of its models). Each `AgentMeta` carries `visibility` (`core` or `internal`) so the Council's simple view can list core agents first. |\n| `personas` | `GET\\|PUT\\|POST\\|DELETE /personas` | Executive persona definitions. |\n| `alerts` | `POST /alerts/{id}/approve`, `GET /alerts/approvals/{id}`, `POST /alerts/{id}/ack`, `POST /alerts/bulk-ack`, `POST /alerts/{id}/snooze`, `POST /alerts/{id}/reopen`, `POST /alerts/review` | Groom the briefing queue. `approve` (body `{edited_body?}`, 202) carries a proposal card out on the server and records who approved it and when (`alerts.approvals`, see Today): it queues the scheduled action a department-gated card held, or runs one Executive turn as the approver in a new chat (`session_id`). 409 for a card already approved or closed, a decision-backed card (approved at `/decisions`), a roster request or a drafted artifact; 403 unless the caller is the card's routed person or the principal (an unrouted card is the principal's); 429 when the caller already has three background turns running. `GET /alerts/approvals/{id}` reads one back (`running`, then `done` / `failed` with `outcome`) for its approver, the card's person or the principal (404 for anyone else). `snooze` (`until`, an ISO time up to 30 days ahead; `null` clears it, the Undo) hides an `unread` card until then by setting `snoozed_until` (409 on a closed card or a roster request); the TTL then counts from the snooze, so a card snoozed past its TTL still comes back. `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`, `supersedes_id` and, for an extension's kind of document, `collection` / `collection_label` on every summary (`orchestrator.extensions`; archive, restore and delete tell the collection first and answer 502 if it refuses). `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. Every route answers for the signed-in caller (`artifact_records.Viewer`): a drafted artifact is its owner's alone (`alerts.owner_person_id`, the person whose conversation published it; none = the principal's), a workflow output follows its run (`persistence.run_visible_to`), and anything the caller may not see is a 404 like a missing id, the principal included. `POST /alerts/{id}/ack` and `/reopen` answer 404 for someone else's drafted artifact the same way. |\n| `decisions` | `GET /decisions`, `POST /decisions/{id}/{approve,reject,cancel}`, `GET`/`PUT /decisions/classes/meeting_scheduling`, `GET /audit/reliability` | Approval-gated decision instances (e.g. calendar bookings). What approve/reject/cancel do is per class (`DECISION_CLASSES`, one `DecisionClassSpec` each; meeting booking books on approve and deletes on cancel; `delegation_reply`, an inbox reply card, is its approver's alone (`approver_only`) — hidden from everyone else, the principal included when it is a team member's — sends its Gmail draft on approve and, after a reject, deletes the draft unless it was edited; `delegation_invite`, a meeting invite card, is its approver's alone too, and answers the invite in their own calendar on approve (`edits.answer`) and nothing on reject; `department_action`, a team member's chat send or edit their department held (see Org), is the principal's and its approver's alone (`principal_and_approver`), makes that exact call on approve and audits `department_action_done` / `_failed` / `_declined`), and an instance of a class with no spec gets 409 instead of being carried out as another. Only the principal, or the person the decision went to for approval (`approver_person_id`), may approve, reject or cancel it. Anyone else gets 403, and a decision nobody was asked about, or one private to the principal, is the principal's alone. The resolver is recorded as `resolver_person_id`, and a reject that loses the race to another answer is a 409. `GET /audit/reliability` is the principal's alone (403 otherwise), because it counts private decisions too. A proposed booking is surfaced on the briefing as a companion alert; approve/reject/cancel here also clear that alert. An approval whose caller resolves to the principal runs the booking inside `grant_contact_egress()`, so a meeting the principal proposed with a contact can be created. Such a booking's payload is marked `private`: it is proposed to the principal, left out of anyone else's `GET /decisions`, and a 404 for them on `GET /decisions/{id}` and every action route. Reviewed in the briefing — there is no separate proposals page. The class routes read and set how meetings are handled: both return `{decision_class: \"meeting_scheduling\", mode: \"propose\" \\| \"auto_execute\"}` (default `propose`); the `PUT` body is `{mode}`, principal-only (403 otherwise, open before a principal exists — but then only `propose` can be set: `auto_execute` is a 409 until a non-archived principal is on the roster), 422 on any other mode, and a change writes a `decision_class_mode_changed` audit row. In solo mode the class mode decides a booking, and `auto_execute` applies only to a turn the principal started on a verified surface — any other turn gets a proposal. |\n| `delegation` | `GET`/`PUT /delegation`, `GET`/`PUT`/`DELETE /delegation/voice`, `POST /delegation/voice/learn`, `POST /delegation/voice/describe`, `POST /delegation/voice/signature`, `PUT /delegation/inbox`, `POST /delegation/inbox/check`, `GET /delegation/replies`, `PUT /delegation/replies/{id}/text`, `PUT /delegation/replies/{id}/recipients`, `POST /delegation/replies/{id}/answer`, `GET /delegation/actions`, `GET /delegation/invites`, `PUT /delegation/handle-it`, `PUT /delegation/disclosure`, `PUT /delegation/training`, `DELETE /delegation/learned/{id}`, `GET /delegation/handled`, `PUT /delegation/team` | Act as me — the **caller's own** delegation only; nobody sets it for anyone else. It answers the principal, and a team member once the owner lets them; anyone else gets 403 `not_available_yet`. `GET /delegation` returns `{enabled, gmail: {status, message, email, connect_command, outlook_connect_command, provider}, inbox: {enabled, status, message, watch_since, last_poll_at, checking}, handle_it: {enabled, mode, available, sent_today, lead, lead_available}, training: {replies, follow_ups, actions, drafts, learned}, disclosure: {enabled, handle_it, approved_sends, line}, team}`, where `team` is the owner's switch for the principal while `DELEGATION_TEAM_MEMBERS` allows it — `{enabled, members: [{person_id, name, enabled, inbox, drafts_30d, sent_30d}]}`, counts only — and `null` otherwise. `PUT /delegation/handle-it` takes `{enabled?, mode?}` (`mode` is `careful`, `balanced` or `bold`; anything else is a 422 `bad_mode`) from a caller the API knows is that person — 403 `not_yours`, 409 `caller_signing_required` with only the shared secret — and turning it on needs Act as me and Draft replies to my inbox on (409 `act_as_me_off` / `inbox_off`); `GET /delegation/handled` returns `{replies: [{decision_id, sent_at, to_name, to_email, subject, body, open_questions, gmail_link, source, summary}]}`, the caller's replies and follow-ups (`source` `follow_up`) sent on its own in the last 7 days, and the meeting invites it accepted on its own (`source` `invite`, `subject` the meeting's title, `summary` one line such as \"Accepted Dana's Pilot review, Wed 21 Oct, 14:30\"); a card on `GET /delegation/replies` carries `source` the same way, `can_allow` while Replies (Follow-ups, on a follow-up) is in training, and `learns_style` while Drafts is. `PUT /delegation/disclosure` takes `{handle_it?, approved_sends?}` (any other field is a 422), the caller's own switches for the AI line on replies sent as them (`disclosure.enabled` is the install's `AI_DISCLOSURE`); turning one on needs no signed sign-in, turning one off does (409 `caller_signing_required`), and a change is audited as `delegation_disclosure_changed`. `PUT /delegation/training` takes `{replies?, follow_ups?, actions?, drafts?, actions_on?}` (any other field is a 422; `actions_on` is Suggested actions On, and `actions` and `actions_on` set true clear each other) and returns the `GET /delegation` shape, whose `training` carries `actions_on` too; putting Replies or Follow-ups in, or Suggested actions out of training or On, needs no signed sign-in, anything else does (409 `caller_signing_required`), and putting Replies or Follow-ups in turns Take the lead as you off (`PUT /delegation/take-the-lead` on answers 409 `in_training` while they are). `training.learned` is `[{id, label, setting, example, uses, created_at}]`, what the caller allowed or kept in training (`setting` `replies`, `follow_ups`, `actions` or `drafts`; the kept example, or \"\"); `DELETE /delegation/learned/{id}` removes one of the caller's own (404 for anyone else's). `PUT /delegation/team` takes `{enabled}` from the principal alone (403 `principal_only`; 409 `not_available` when the install doesn't allow it). The Gmail `status` is `connected`, `not_configured`, `needs_reconnect`, `mismatch`, `no_email`, `shared_mailbox` or `error`, checked live with Google on each call. `PUT` takes `{enabled}` (any other field is a 422); turning it on needs the caller's own Gmail connected, otherwise a 409 whose code says why (`gmail_not_connected`, `gmail_needs_reconnect`, `gmail_mismatch`, `no_email`, `shared_mailbox`, `gmail_error`). The voice routes show, learn (from the caller's sent mail, one pass at a time — a 409 `in_progress`, `locked`, `too_soon`, `not_enough_mail`, `no_profile` or `changed` when it was locked or edited while learning, or a Gmail code), write it from the caller's own description (`POST /delegation/voice/describe` with `{description}`: one model call applies their words to the profile they have and returns it with a short `sample_reply`, saving nothing, so they review it and save it with `PUT`; a 409 `empty`, `too_long`, `in_progress`, `too_many` past 10 an hour or `no_profile`; no mailbox needed), edit and lock, and reset \"How I write\": a typed field that fails validation is a 422 `invalid_voice` listing each `rejected` field, and `clear_exemplars` / `clear_signature` drop those. `POST /delegation/voice/signature` reads the signature from the caller's Gmail settings again and changes nothing else (a locked profile stays locked), with the same Gmail codes as learning: a 409 when their mailbox isn't connected, it refuses the sign-in or the check itself fails (`gmail_error`), and a 502 `gmail_error` when reading the signature fails. On an Outlook mailbox it is a 409 `signature_unavailable`, since Outlook gives apps no signature to read, and the stored one is left alone. A caller `can_delegate` refuses — anyone but the principal, for now — gets 403 `not_available_yet`, which hides the Settings card. A request with no `x-caller-email` is a 403 `sign_in_required` unless the API runs under local login — a header-less call is not a sign-in (the caller is read through `api/caller.py`, as on every principal-only route). `PUT /delegation/inbox` takes `{enabled}` and turns **Draft replies to my inbox** on or off, returning the same shape as `GET /delegation`: on needs Act as me on (409 `act_as_me_off`) and the mailbox connected (the Gmail codes above, which keep their names for an Outlook mailbox too), and turning Act as me off turns it off too. `POST /delegation/inbox/check` starts a scan now in the background and answers 202 with the `inbox` state (409 `inbox_off` or `in_progress`). `GET /delegation/replies` returns `{cards: [...]}`, the caller's open reply cards from the database alone (no Gmail call): the decision id, the sender's name, address, relation and whether it was verified, the subject, when it arrived, what they wrote, a one-line `gist` (what they asked and what the draft says, written with the draft and brought up to date when an answer rewrites it; empty on an older card), the draft's recipients, subject and body, `open_questions`, `flags` and a Gmail link built from a fixed prefix. **Send** is `POST /decisions/{id}/approve`: it sends the card's draft exactly as it is in Gmail, after checking again that the caller is its owner — which on a server needs signed callers (409 `caller_signing_required` otherwise) — that both switches are on (`inbox_off`), no client slot is active (`client_slot`), the Gmail is connected (the Gmail codes), the draft is still there and unanswered (`draft_gone`, `you_replied`) and its recipients are allowed (`no_recipients`, `too_many_recipients`, `executive_recipient`, `not_from_you`). Recipients that changed, or a newer message in the thread, answer 409 `{code: \"confirm\", message, reasons, recipients}`; approving again with `edits: {recipients: <the list shown>, thread_moved_on: true}` is the second yes. Send with the *on its own next time* tick adds `edits.allow: true`: 422 `cant_allow` unless Replies (Follow-ups, on a follow-up card) is in training, 409 `learned_full` when their list is full, both before anything is sent; `edits.example: true` keeps a draft edited in the mailbox as how they write to that person while Drafts is in training. A draft edited in Gmail between those checks and the send is not sent (`draft_changed`). A double tap sends once (`already_handled`); Gmail refusing answers 429 `rate_limited` or 502 `gmail_error` with nothing sent, and a send Gmail didn't confirm answers 502 `send_unconfirmed` and is settled by the next inbox scan. Dismiss is `POST /decisions/{id}/reject`. `GET /delegation/invites` returns `{cards: [...]}`, the caller's own meeting invite cards (`delegation_invite`, Read my calendar on): `decision_id`, `status`, `created_at`, `from_name`, `from_email`, `relation`, `title`, `when` (in the workspace time zone), `start`, `end`, `all_day`, `clashes` (busy times only, `\"14:00–14:30\"`), `clash_checked`, `can_answer` (false for a sign-in that reads but can't answer the calendar; then `connect_command`), `can_allow` (Replies in training) and `waited_because`. **Accept** / **Decline** is `POST /decisions/{id}/approve` with `edits: {answer: \"accept\" | \"decline\"}` (accept is the default; `allow: true` with accept for the *Accept from them on its own next time* tick), on the same caller checks Send uses (403 `not_yours`, 409 `caller_signing_required`); 409 `calendar_write_needed` when the sign-in can't answer (the card stays), `gone` when the event left their calendar, `expired` once the meeting started, `already_handled`; 502 `calendar_error` leaves the card for another try. **Dismiss** is `POST /decisions/{id}/reject` and answers nothing. `GET /delegation/actions` returns `{cards: [...]}`, the caller's own approval cards (`delegation_actions`): the decision id, when it was made, a one-line `why`, and each action's `index`, `kind` (`invite`, `message`, `add_contact`), `summary` and `text` (a message as it will be sent, or a meeting's description). **Approve** is `POST /decisions/{id}/approve` with `edits: {only: [indexes]}` (and `allow: true` for the *Do this on its own next time* tick while Suggested actions is in training: 422 `cant_allow` otherwise or when nothing on it can be allowed, 409 `learned_full`; a card carries `can_allow`); it needs the card's own person signed in (403 `not_yours`, 409 `caller_signing_required`), Act as me on (409 `act_as_me_off`) and a card under a week old (409 `expired`), runs once (409 `already_handled`), and returns the decision with `final_payload_json.results`: per action `done`, `waiting` (sent to whoever approves meetings), `failed` with why, or `skipped`. Every change writes a private audit row. |\n| `history` | `GET /memories/history` (`?q=`), `PUT /memories/history/settings`, `PATCH`/`DELETE /memories/history/{id}`, `POST /memories/history/{id}/forget-conversation` | Always in the loop: the **caller's own** notes and switches only, resolved as for Act as me (a signed-in person on the roster, or the principal under local login; otherwise 403 `sign_in_required` / `not_on_roster`). `GET` returns `{notes, reply_notes, retention_days, effective_retention_days, company_retention_days, retention_choices, can_keep_notes, can_note_replies, can_set_company_retention, share_work_style, can_share_work_style}` (`can_keep_notes`: a team member on the People list may turn notes on; `can_note_replies`: they can use Act as me, so email replies are noted too; `share_work_style`: their own \"Share my work style with the team\" switch, `can_share_work_style`: a team member in a team workspace). `PUT` turns notes on only for someone who may keep them, and `share_work_style` on only for someone who may share it (403 `not_available` for either; turning either off always works), takes a person's retention only when shorter than the company's (422 `invalid_setting`), and the company retention only from the principal (403 `principal_only`). `PATCH` pins or corrects a note; `DELETE` forgets it; `forget-conversation` is \"Don't remember this\". A note that isn't the caller's is 404. Every change is audited privately to its person. |\n| `reflection` | `GET /memories/reflection` (`?person_id=`), `DELETE /memories/reflection/misses/{id}` | Learning: the turns the conversation review graded a miss (`memory.chat_review`), with the person's words, the reply, the tools run, what they wanted instead, the `kind` (`company` / `product`), the finer `cause` (null when the grade gave none) and the signals, plus `weeks` (`{week, graded, misses}` per ISO week, newest first) and `sees_everyone`. The caller is resolved as for `history` (403 `sign_in_required` / `not_on_roster`); each person sees their own, the principal those from chats `chat._session_access` lets them open (a teammate's own web chat or DM and a mail-private conversation stay their owner's; channels and groups are open), or one person's with `?person_id=` (a teammate naming someone else gets 403 `not_yours`); the weekly counts carry no words and are not filtered. The same response carries `lessons` (`memory/lessons.py`: live first, then retired, each with `shown`/`fine_after`/`miss_after` and `retired_reason`), filtered by the same rule, and `DELETE /memories/reflection/lessons/{id}` retires one (204; 404 for a lesson the caller may not see, already retired, or missing). `DELETE` forgets one miss (`is_principal_or_self`; 404 `not_found` otherwise) and writes a `chat_review` audit row. Each miss also carries its nightly replay (`memory/replay.py`): `replay_state` (`open` / `closed` / `evidence`), `replayed_at`, `closed_at`, `replay_notes`; and the response carries `replay` (`{misses, would_pass, evidence, last_run_at}`: of the caller's visible misses from the last 30 days, how many would go right today). |\n| `notifications` | `GET /notifications/settings`, `PUT /notifications/settings` | Settings → Notifications: the **caller's own** settings only, resolved as for the notes (a signed-in person on the People list, or the principal under local login; otherwise 403 `sign_in_required` / `not_on_roster`). `GET` returns `{quiet_hours: {enabled, start, end, days}, delivery, urgent_through, timezone, effective_timezone, held_count, gets_briefs, updated_at}` — `days` is `every_day` or `weekdays`, `delivery` `instant` or `digest`, `timezone` the zone they chose (`\"\"` for the workspace's), `held_count` how many messages wait for their quiet hours or brief (counted, never listed), `gets_briefs` whether they are the principal. `PUT` takes `{quiet_hours, delivery, urgent_through, timezone}` and replaces them (extra fields, equal start and end, a bad time or an unknown zone → 422); switching `digest` → `instant` makes what waited for the brief go now. Audited as `notification_settings_changed`. See Org. |\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), plus `scripts`: how many `run_script` scripts ran (and worked, and in workflows), the tool calls they made, their time, and `turns_avoided` — an upper bound on the model turns those calls would otherwise have needed (each call past a script's first) — and `python_jobs`: how many Python jobs ran (and worked, ran a kept Custom tool, took a chat attachment), their time, CPU, largest peak memory and bytes in and out, and the tokens and charge of the turns that ran one. The Token usage page shows it as a Scripts section. Rows private to the principal (`private_to_principal`: a turn about their private mail, or a row naming one of their contacts on their own turn) are theirs alone: for any other caller, resolved as for `/alerts`, the usage totals leave them out. Once a principal is on the roster, anyone else reads only their own rows (a teammate's own turns, their Act as me work) in the list, by id and in a session, and the principal reads those as actions only — what was done, when and in whose conversation, with the text, details and `full` left out, and no text search over them; any other row's id is a 404, and a session shows only the rows the caller reads. |\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. Only `/health` is unauthenticated; `/health/honcho` sits behind the gate like everything else, because the exemption is an exact-path set. `/health` also carries `google_tools_missing`, the pinned Google tools startup priming could not find: `[]` once it has checked and they are all there, a list of names when a workspace-mcp rename or the configured services and tool tier left one out, and `null` for no answer — Google Workspace is not configured, or the probe has not finished or it failed. Only `[]` asserts they are present. It also carries `gateway`, the MCP gateway's state from its supervisor (`orchestrator.gateway_boot`): `state` is `off` (MCP not enabled), `no_servers` (enabled, the config names none), `starting` (an attempt is running), `up` or `down` (every attempt so far failed; `next_retry_at` is the next one), with `attempts`, `up_since` and `email_poller` (whether the poller that rides on the gateway runs); the failure's own text stays out, since the route is open to anyone, and goes to the log and the owner's notice on Home. A hosted instance whose gateway never came up used to answer `ok` here with no email going out or in. Only `[]` asserts the tools are present, so a probe that died cannot read as healthy; Setup status says which of the three `null` means. |\n| `version` | `GET /version` | The running version, the latest release on GitHub and `update_available`, for Settings → About. The GitHub answer is cached 6h, only a semver `tag_name` is used and the release link is built from it; `UPDATE_CHECK_ENABLED=false` skips the call and still returns the running version. No in-app updater: upgrading is host-side (`docs/deployment.md#upgrading`). |\n| `setup_status` | `GET /setup/status` | Settings → Setup status: one light per part of the install — AI model, company setup, owner, the Executive's address, API protection, Gmail, your own mailbox (Act as me), Slack, Discord, Telegram, Google Chat, the scheduler, the daily brief (when and where it goes) and Honcho — as `{checked_at, checks: [{id, label, state, summary, fix, link, last_activity}]}`, where `state` is `ok`, `warn`, `error` or `off` (optional and not set up), `fix` says what to do in plain language, `link` is an in-app page that helps (`/people`, `/onboard`) and `last_activity` is the channel's latest `integration_inbound` audit time. It tests live, with at most one free read-only call per service, each bounded to 5 s: Anthropic `models.list` (so an organisation key missing `ANTHROPIC_WORKSPACE_ID` shows up), Slack `auth.test`, Telegram `getMe` and `getWebhookInfo`, Discord `users/@me` only while the bot is still connecting, and — once the owner's own Gmail credential exists — Google's token refresh and Gmail `users/me/profile`. It also reads the listeners the lifespan leaves on `app.state` (Slack's socket, the Discord bot and its task, the MCP gateway), the scheduler heartbeat and the pause switch. When `google_workspace` is configured, the lifespan also starts `MCPGateway.prime_pinned_tools()` in the background (held on `app.state.mcp_prime_task`, cancelled at shutdown), so the pinned Google tools named in the prompt are callable without a search. With `DRIVE_SYNC_ENABLED` the lifespan also bootstraps the `drive_sync_scan` heartbeat beside Notion's (see Scheduler); the Drive folder sync has no HTTP route, only the `openexecutive sync-drive` / `purge-drive` CLI. With `CONFLUENCE_SYNC_ENABLED` it bootstraps the `confluence_sync_scan` heartbeat the same way; that sync is run by hand with `openexecutive sync-confluence` / `purge-confluence`. Sample values copied from `.env.example` are named as such without being sent anywhere. No token reaches a response or a log line: probes report a status code, a service's short error code or an exception's class name. Requests within 5 s of a run get that run's answer and concurrent requests share one run (kept per app on `app.state`), so the button can't become a stream of calls to those services. Gated like every other route; the UI adds a sign-in light of its own, from its own settings. |\n| `documents` | `POST\\|GET\\|DELETE /documents`, `GET /documents/{filename}`, `GET /documents/sources`, `POST /documents/sources/{drive\\|onedrive\\|notion}/sync`, `GET /documents/{drive\\|onedrive\\|notion}`, `GET /documents/{drive\\|onedrive\\|notion}/{id}` | Upload, list, view extracted text, and delete indexed company docs. `GET /documents` rows carry `source: \"upload\"` and the `domain` the upload was indexed under. The connected-source routes back the knowledge page's single Company documents list: `/documents/sources` gives each source's `{id, label, enabled, syncing, last_run, last_error, interval_minutes, file_count}`; `/documents/drive`, `/documents/onedrive` and `/documents/notion` list synced files from the sync state (`{enabled, last_run, last_error, files: [{id, name, url, modified_at, synced_at, indexed}]}`; a Drive row also carries `unreadable_reason`, why a file with `indexed: false` has no text — e.g. a scan OCR could not read — or null); `/documents/{drive\\|onedrive\\|notion}/{id}` returns the stored text (a OneDrive id is `<drive id>:<item id>`) for an id on record (the path comes from the state, never the caller). They are read-only — a synced file is removed where it lives. `POST …/sync` starts one tick of the same sync the scheduler runs as a background task (202); 409 when the source is not connected or a tick is already running (every sync holds a per-process run lock, so a manual run never overlaps the heartbeat; the route also keeps its own started task per source and re-checks just before starting one, so two simultaneous requests start one tick, not two), 429 with `Retry-After` within 60 s of the last successful run or of the end of the last tick in this process, failed ones included, so a failing or slow source can't be re-run back-to-back. The page's text view never loads images from synced content (a remote image would be a read beacon for whoever edits the shared folder). 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 nine specialist domains (including `sales`) or `general`; anything else is a 400 rather than a 200 that indexes where no specialist can retrieve. A scanned PDF is converted (`knowledge.pdf_reader`) before it is indexed and in the text view, as are scanned PDFs in `POST /chat/upload` and the client / onboarding intake uploads. The upload is streamed to disk 1 MB at a time and refused with a 413 once it passes 50 MB, and the file is parsed in a short-lived child process (see the RAG section), so a large document does not stay in the API process's memory. A Word or Excel file that cannot be parsed, or whose parse runs out of time, is a 422 with a readable reason. When every parser is busy, the response is a 503 with `Retry-After`. |\n| `executive` | `GET /executive/status`, `POST /executive/pause`, `POST /executive/resume`, `GET`/`PUT /executive/outside-content` | 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, name}` — `held_actions` counts due `pending` rows that fire on resume, and `name` is the Executive's name (`EXEC_DISPLAY_NAME`), which the web chat shows over its replies. `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. `GET /executive/outside-content` returns `{mode, can_change}` for the owner's **When I read outside content** setting (`ask`, `outsiders` or `trust`; `orchestrator.outside_mode`), and `PUT` with `{mode}` changes it for the principal only (403 otherwise), writing an `outside_content_mode_changed` audit row. |\n| `workspace` | `GET /workspace`, `PUT /workspace` | Solo/team mode, the user's time zone and the principal's role (`memory.workspace_settings`). Both return `{mode, timezone, effective_timezone, role_kind, role_title, reports_to, remit, measured_on, company_domains, company_domains_custom}` — `timezone` is what the user set (null when unset), `effective_timezone` the zone in effect (`timezone`, else `USER_TIMEZONE`, else UTC), and each role field is null until set. `PUT` is a partial update: only the fields sent change; `mode` is `solo` or `team` (not null), `timezone` an IANA zone, or null/blank to clear it; `role_kind` is `owner`, `in_house`, `independent` or `other`, and `role_title` / `reports_to` / `remit` / `measured_on` are free text (trimmed, at most 120 / 120 / 500 / 300 characters), each null or blank to clear it; an unknown zone, a bad mode or role kind, an over-long role field or an unknown field is a 422 and changes nothing. Switching to solo cancels every pending department check-in, switching to team re-schedules them, and a new zone re-times the pending briefs and reflection; a role change has no side effects (the next turn reads it). `company_domains` is the company's own email domains (a teammate matches by local part on them — see Org): `GET` returns the ones in effect (the stored list, or the domain of the principal's primary address, with `company_domains_custom` false) only to the same caller the role is shown to, `[]` for anyone else; `PUT` takes a list (at most 10 plain domain names, never a free-mail provider's — 422 otherwise, the value never quoted) or null / `[]` to go back to deriving them, and a change is audited with the new list. Each change writes a `workspace_settings_changed` audit row (a role change adds `details.role_fields_changed`, the names of the fields that changed — never their text). The role is the principal's: `GET` returns it only to a caller `PUT` would accept and reads it as nulls for anyone else. `PUT` is the principal's alone (`is_principal_or_self`, 403 otherwise; a header-less caller resolves to the principal as in `chat`) and open while no principal is rostered, so first-run setup can pick a mode. Both work before onboarding — unlike `company-profile`, nothing here needs a profile. |\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/describe`, `POST /watchlist/{slug}/approve`, `POST /watchlist/{slug}/decline` | External-monitoring watchlist + signals. `POST /watchlist/describe` `{text}` drafts a watch from a sentence (one forced tool call on the utility-fast model, `monitoring.describe`; the company profile's name, competitors, vendors and tickers ride in the user turn) and saves nothing: it returns the create fields (`slug`, `signal_type`, `target`, `display_label`, `trigger`, `cadence`, `mode`, `severity_floor`, `severity_ceiling`, `notes`) plus four plain lines (`watching`, `tell_you_when`, `how_often`, `how_loud`) written by code from those fields, after the create route's checks (registered kind, cadence, severity, the URL guard, the rss feed check, a free slug); 422 with a plain reason when it can't be a watch, 429 past 30 drafts an hour, 502/504 when the model fails. `GET /watchlist/{slug}` also returns `noise` `{recent_alerts, recent_dismissed, noisy}` (its last 8 alerts, noisy at 6 dismissed, `monitoring.noise`), and `PATCH` takes `quiet_noise_nudge: true` to stop that question for the alerts so far. `display_label` on create maps to the adapter's label key for every kind. 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`, `POST /workflows/runs/{run_id}/rerun`, `GET /workflows/tools/search?q=`, `GET /workflows/tools/describe?names=` | Workflow catalog, run management, and user-created (dynamic) workflow CRUD. `rerun` queues a failed scheduled run (a department check-in, a saved workflow on a cadence) once more, due now (see Scheduler); the principal may, and for a saved workflow the person it delivers to; 409 for a run that did not fail, one started from `/jobs` (\"Start this one again from its page\") or one already queued again. 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/{name}/runs` is a 403 (\"Only the principal can run this workflow.\"), audited, before any run row exists, when the workflow is one only the principal may start in the workspace's mode (`weekly_review` always, `morning_brief` in solo) and the caller is not the principal. A request with no `x-caller-email` counts as the principal; with no principal on the roster, no signed-in caller does. This governs starting a run only. A run started by hand (this endpoint, or `run_workflow` / research in chat) records its starter as `owner_person_id` and is theirs alone: `GET /workflows/runs` lists the team's (scheduled, no owner) runs plus the caller's own and the ones waiting on them, and `GET` / `DELETE /workflows/runs/{run_id}` and `POST /workflows/runs/{run_id}/decision` are a 404 for anyone else's, the principal included. A signed-in email that is on nobody's People entry cannot start one (403), and a run whose starter can't be read is refused (503); its steps read and draft documents as the starter only. `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`, `background` (true for the system-run built-ins the UI files under “System”) and `quick` (true for a Quick workflow, one per playbook nothing else follows, named `quick_<playbook>`). 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| `evals` | `/evals/scenarios`, `/evals/runs` | Eval scenarios and run results. `POST /evals/runs` is a 403 when a workflow scenario names a workflow that only the principal may start in the mode it runs in (the weekly review; the morning brief in solo) and the caller is not the principal — the Jobs page's rule for starting a run; stored results are read under the existing `/evals/runs` rules. |\n| `memories` | `/memories/{decisions,initiatives,advice}`, `GET /memories/facts`, `POST /memories/facts/{fact_id}/{retire,approve,decline}`, `GET /memories/facts/approval`, `PUT /memories/facts/approval/{person_id}`, `GET /memories/people`, `GET /memories/people/{person_id}/conclusions` | Episodic-memory record management; the standing facts the Pulse Corrections tab reads (`{facts: [...], can_retire, retirable_ids, can_review}`; each fact carries `recorded_by_role` / `recorded_by_name`; `?include_inactive=` default true, honoured for the principal only; anyone else gets the active rows plus their own `proposed` ones, with the provenance (`session_id`, `turn_id`, `recorded_by_person_id`, `retired_reason`, and `source_quote` except on their own facts) blanked, never retired, replaced or declined text; `?limit=` 1–500) and their retire (the principal any fact, a teammate only one they recorded that the principal has not approved — else 403; the audit row names the teammate; 404 for an unknown or `profile` row, 409 when no longer active; writes a private `fact_retired` audit row); approve / decline a teammate's `proposed` fact (principal only, else 403; 409 when it is not proposed; private `fact_reviewed` row); and the per-teammate \"needs my approval\" switch (on by default; `GET` lists `[{person_id, full_name, needs_approval}]` for every active team member but the principal, `true` for anyone not yet set; `PUT` takes `{needs_approval}`, 404 for anyone else; both principal only; private `fact_approval_changed` row); 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). Peer memory is each person's own: the overview holds only the caller's entry (none for a caller off the roster; `conclusion_total` counts only theirs), the principal included, and `/conclusions` for anyone but the caller is a 404. |\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/understand`, `/onboard/interview/start`, `/onboard/interview/message`, `/onboard/interview/draft`, `/onboard/interview/revise`, `/onboard/interview/{id}` (GET resumes, DELETE starts over), `/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). `revise` changes one earlier answer (0 = the description) and runs the interview again from there. `commit` answers 403 when the draft would make a different person the owner and the caller is not the current owner (setup demotes the old principal, and any signed-in user can open it). It also takes an optional `owner_email` — the principal's sign-in email, which the review screen pre-fills from the signed-in user — checked before anything is written (422 if it is malformed, already another person's, or would replace the principal's existing email — setup only fills in a missing one; 403 if the caller is not the owner and it is not the address they signed in with, since the roster is the sign-in allow-list) and saved on the principal's People row, so the owner's chats resolve to them from the first turn. |\n| `workflow_designer` | `POST /workflows/designer/start`, `POST /workflows/designer/edit`, `POST /workflows/designer/message`, `POST /workflows/designer/draft`, `GET /workflows/designer/{session_id}` | The conversational New workflow wizard, and editing a saved workflow by conversation. `/edit` (`{name}`) opens a session on a saved custom workflow with no model call: the stored definition is the starting draft, and every response then carries `editing` (its name) and `original` (the stored definition as the session opened on it); drafts keep that name and its on/off state whatever the model writes (404 for an unknown workflow). The UI saves one with `POST /workflows/custom/{name}/save-edit` (`{session_id, definition}`): the server saves the session's own draft, never a client-sent body, and only when it equals the `definition` the user reviewed (a later message is a 409, so the click saves only what was shown); it re-validates it, keeps the stored on/off state, and writes only if the stored workflow is still the version the conversation opened on — otherwise 409, as it is for a session about another workflow or one with nothing drafted yet. It sits under `/workflows/custom` so anything that limits writes to custom workflows covers it too. 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| `python_jobs` | `GET /python-jobs/{job_id}/{name}` | A result file a Python job (`run_python_job`) wrote, the principal's alone (403 otherwise), served as a download (`Content-Disposition: attachment`, `Content-Security-Policy: sandbox`, `nosniff`, `Cache-Control: no-store`); 404 for a bad id or name or a file past its 7 days. |\n| `saved_tools` | `GET /saved-tools`, `GET\\|PUT /saved-tools/{name}`, `POST /saved-tools/{name}/rollback` | The scripts the Executive saved as tools (Settings → Advanced → Saved tools), the owner's alone (403 otherwise). The list gives each tool's name, description, on/off, current version, `kind` (`script` or `python`, a kept Python job) and the tools it calls, plus whether `SAVED_TOOLS_ENABLED` is on; the detail adds the script, every version and the last 20 runs. `PUT {enabled?, workflows?, version?}` turns one on or off (off also turns it off for workflows, so turning it back on never re-arms unattended runs), and turns the named `version` — the one the owner looked at, never whatever is current by then — on for workflows (or workflows off); a Python tool never turns on for workflows (409) — turning workflows on lets more run unattended, so it needs a request tied to the owner (signed sign-ins or local login, as Take the lead's switches do; 409 otherwise); `rollback {version}` makes that version the one that runs. Both are audited as `saved_tool_changed`. The Executive saves tools itself through `run_script`; there is no create route. |\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. Its final answer saves the profile and adds people with their emails and a principal, so once there is an owner only they can send it (403, and the session rolls back so the owner can still finish it). `/onboard/start` reads the workspace mode once for the session: solo skips the Team Size, Team Members and Fractional Executives steps. Each status response's `current_step` / `total_steps` count only the steps that session asks, and `optional` says whether the current step can be skipped. |\n| `company-profile` | `GET\\|PATCH /company-profile` | Structured company profile. |\n| `alerts` (private cards) | `POST /alerts/{id}/ack`, `/reopen`, `/alerts/bulk-ack` | An alert tagged `private:principal` (see Today) is a 404 on ack and reopen for anyone but the principal, and their bulk sweep skips it. A roster-request card (source `roster_request`) is a 409 on `ack` even for the principal — it is answered at `/people/requests/{id}`, since acking would leave the sender waiting with nothing to show it — and, as an exempt source, `bulk-ack` and `reopen` skip it. |\n| `auth` | `GET /auth/allowed-emails` | Non-archived **team members** with an email, offered to the UI's sign-in gate — a contact is never on it, so adding a client to reach them by email no longer lets them sign in. 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. With local login (`make dev` with Google sign-in not set up — the UI then listens on 127.0.0.1 only) the UI signs in without an email, sends no `x-caller-email`, and the backend resolves the caller to the principal, as it does for the CLI. |\n| `fixtures` | `/fixtures`, `/fixtures/{name}/load` | Demo-company fixture load/reset/snapshot. `POST /fixtures/reset` leaves no departments, like a new install (`departments_seeded` is always 0). |\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`, `POST /webhook/slack` | Inbound integration callbacks (self-verified). `/webhook/slack` answers 503 unless `SLACK_SIGNING_SECRET` is set. |\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, answered as the verified caller (`api.caller`) by the web app's rules. See the MCP Server section. | A card the Executive left for something asked in chat (`app_action`, `orchestrator/app_control.py`) is its person's alone too: its payload holds `action`, `id`, `value`, `title` and the `card` line shown; **Confirm** is `POST /decisions/{id}/approve`, which runs the action through the route its button calls with that request (a refusal comes back as that route's status and words, and the card is marked `failed`), and a card older than a day is turned down with 409.\n\n**What it does for you** (`api/routes/may_do.py`): `GET /what-it-may-do` is read-only. It returns `{paused, sections}`, three sections in order (`as_you`, `executive`, `departments`), each `{key, title, available, unavailable, notes, rows, footer, goes}`, and each row `{id, what, outcome, then, why, setting, items}`: `outcome` is `goes`, `waits`, `always_waits`, `drafts` or `off`, and `setting` names where to change it (`act_as_me`, `handle_it`, `take_the_lead`, `pause`, `department:<slug>`, or empty). `as_you` is the caller's own (`available` false, with why, when they can't have Act as me); `executive` is the principal's alone (`available` false for anyone else); `departments` is everyone's. Any team member on People may call it; a contact, someone not on People, or a request with no caller outside local login gets 403. See Delegation → What it does for you.\n\n**How far it goes as you** (`api/routes/delegation.py`): `PUT /delegation/reach` takes `{step}`, one of `off`, `when_asked`, `inbox`, `careful`, `balanced`, `bold`, `everything`, and answers the caller's delegation state as `GET /delegation` does. Going down turns the switches above the step off, highest first; going up runs each switch's own route in order (`PUT /delegation`, `PUT /delegation/inbox`, `PUT /delegation/handle-it`, `PUT /delegation/take-the-lead`), so the first refusal (409 `gmail_not_connected`, a signed sign-in missing, `in_training`, 403 for Everything when not the owner) stops it at a whole step. See Delegation → How far it goes as you.\n\n**Take the lead** (`api/routes/take_the_lead.py`): `GET /take-the-lead` returns the As the Executive switch, its six Ask first switches (`{kind, label, hint, on}`, the hint a plain line on what each one catches), the company's rules, whether this server can tie a change to the owner (`available`), and whether the Executive is paused. `PUT /take-the-lead` takes `{enabled?, ask_first?}`, and `POST /take-the-lead/rules` / `DELETE /take-the-lead/rules/{id}` add or remove a company rule (`{kind: person|domain|words|amount, value}`, 422 on a bad one). All four are the principal's alone (403). Anything that lets more happen on its own (turning it on, turning an Ask first off, removing a rule) needs a caller the API can tie to them (`delegation.verified.caller_refusal`, else 409). `GET /today/activity` adds `took_the_lead` rows (what Take the lead did, named, not quoted) and, for the caller alone, `sent_as_you` rows for what Handle it for me sent as them (and the meeting invites it accepted as them, \"Accepted Dana's Pilot review, Wed 21 Oct, 14:30\") and, for the principal, one `contacts_kept` row a day the contact keeper changed something (`detail` like \"2 added, 1 updated\"). Under `/delegation`: `PUT /delegation/take-the-lead {enabled}` is Take the lead as you (the owner's only for now; turning it on turns Handle it for me on), and `GET|POST /delegation/take-the-lead/rules` and `DELETE …/rules/{id}` manage the caller's own rules. `HandleItOut` gains `lead` and `lead_available`. A `take_the_lead_action` decision is approved or rejected through the existing `/decisions/{id}/approve|reject`. Training: the response also carries `training` (In training: everything waits unless allowed), `learned` (`{id, label, feature, example, uses, created_at}`: what it was allowed, the edit kept as an example by field) and `suggested` (`{key, label, approvals}`); `PUT` takes `training?` too, and leaving training while on needs the same provable owner as turning it on. `POST /take-the-lead/learned {key}` allows a current suggestion (404 for anything else; provable owner), `DELETE /take-the-lead/learned/{id}` makes it ask first again. `learned` also lists the owner's own Act as me senders (`feature` `act_as_me`), never anyone else's, and Remove works on those too. On a `take_the_lead_action` card, `POST /decisions/{id}/approve` takes `edits.input` (the card's editable fields, 422 for any other; the principal's alone, 403 for an area approver) and `edits.allow: true` (a training card only, 422 otherwise; the principal from a provable request, 403 otherwise), finishing `approved_with_edit` when a field changed.",
"mermaid": null,
- "generated_at": "2026-10-20T21:30:00Z"
+ "generated_at": "2026-10-21T00:00:00Z"
}
diff --git a/packages/core/openexecutive/architecture/prebuilt/caching.json b/packages/core/openexecutive/architecture/prebuilt/caching.json
index d0d68674..f4c5f301 100644
--- a/packages/core/openexecutive/architecture/prebuilt/caching.json
+++ b/packages/core/openexecutive/architecture/prebuilt/caching.json
@@ -1,7 +1,7 @@
{
"section_id": "caching",
"title": "Prompt Caching",
- "markdown": "The Executive system prompt is partitioned for Anthropic prompt caching by `openexecutive.prompts.cache_manager.build_system_blocks`. It emits at most two `cache_control` blocks, consolidated down from four to stay within Anthropic's 4-block API limit alongside the tool definitions and the agent loop's intra-turn marker.\n\n- **Block 0 — persona + knowledge (1h TTL, always present):** the executive persona constant — `EXECUTIVE_PERSONA_PROMPT` for a team, `EXECUTIVE_PERSONA_SOLO_PROMPT` in solo mode — or an admin override, which wins as-is in either mode, with the `{VOICE_PERSONA}` substitution, then the admin's Council **additional instructions** for the Executive (`persona_instructions`, wrapped in `<additional_instructions>`; blank leaves the block byte-identical, and like the override it changes only on save), conditional `WEB_SEARCH_ADDENDUM` / `MCP_ADDENDUM`, the constant `TOOL_BUILDING_ADDENDUM` (when to build a tool with `run_script`, check `list_saved_tools` first, keep what will be needed again, and talk about it without saying \"script\"; present with a gateway unless `CHAT_SCRIPTS=false`, a setting, so constant per deployment), the identity addendum (exec name/email, impersonation guard), the *Connected Systems* section (whose Google part is derived from `WORKSPACE_MCP_TOOLS` and `WORKSPACE_MCP_TOOL_TIER` — process-constant settings, so it is as cacheable as the rest), the constant `DELEGATION_ADDENDUM` while anyone on the install has Act as me on, the timezone addendum, and `KNOWLEDGE_INDEX_SUMMARY`. The timezone addendum names the user's zone, read fresh on every build from the workspace settings (`memory.workspace_settings.get_user_timezone`: the workspace's zone, else `USER_TIMEZONE`, else UTC). Every component is a constant or changes only when an admin or the user changes a setting, so the TTL is long. Setting a new time zone changes the addendum, so the 1h block misses once on that change and is warm again from the next turn — accepted, since a stale zone would mis-schedule follow-ups. Act as me works the same way: its addendum is keyed on the install-level setting (`delegation.settings.block0_delegation_on`), never on the turn or the speaker, so switching it on or off misses the 1h block once; off, block 0 is byte-identical to an install without the feature.\n The *Connected Systems* section (`prompts.connected_systems.render_connected_systems`) tells the model what is connected so it never has to discover it: Google Workspace on or off (on only when `google_workspace` is among the servers the running gateway started with, `MCPGateway.server_names`, so a gateway that failed to start never reads as connected; and *needs reconnecting* instead of connected while the server is in `MCPGateway.needs_reconnect` — set when a Google tool answers with an authorization failure such as `invalid_grant` (`mcp_gateway.grant_failure`), cleared by the next answer that is not one or by `mark_reconnected` — so the model stops promising mail it cannot read; the set changing re-renders block 0 and costs one cache miss), and when on, how to act from its own account plus the pinned Google tool names by service (`GOOGLE_TOOL_MANIFEST`: Gmail, Calendar, Drive, Docs, Sheets, as workspace-mcp 2.1.0 names them) to call directly; any other configured MCP servers by name (`_comment` keys skipped); Slack / Discord / Telegram / Google Chat on or off from their settings (names only, never a token); Notion knowledge sync; a Confluence knowledge sync line only when that sync is on (a setting, so constant per deployment); and one constant Act as me line that points at `DELEGATION_ADDENDUM`, so switching Act as me still changes block 0 by that addendum alone. The \"never ask which address to send from\" guidance lives here now, shown only while Google is connected; the identity addendum keeps the name, address and impersonation guard. Every input is fixed per process and the output is sorted, so block 0 stays warm; it is appended even under a persona override. It replaces what the model used to learn from `search_tools`, an uncached proxy whose results were gone by the next turn.\n- **Block 1 — company + org (5m TTL, only if non-empty):** `company_profile.to_prompt_block()` plus `render_org_block(mode=…)` — for a team: departments, heads, principals, charters and the People roster; in solo: the principal's own line, their role lines when set (a static lead-in marking the role private to the principal, then kind in plain words, title, reports to, remit, measured on — from the role pinned for the turn: the workspace settings, or a session's `principal_role` override), and their goals grouped by area. The role is set once per install and changes only when the principal edits it, so it is as stable as the rest of the block. Shorter TTL so org edits propagate quickly. The principal's contacts are private to them, so `build_system_blocks(include_contacts=...)` adds the `## Contacts` section, after the team or solo block, only on the principal's own verified turn (`executive._contacts_in_prompt`). That gives block 1 exactly two stable variants per mode — with and without contacts — and never anything per-request; every other turn's block is byte-identical to an install with no contacts.\n\n## Solo mode: one prefix per mode\n\nSolo mode — one person using Open Executive for themselves — changes three cached parts, all resolved **once per turn** by `pin_turn_workspace_mode(session)` (the session's override, else the workspace setting) so they always agree: the block-0 persona, the block-1 org block, and the tool list, which drops `send_company_broadcast`, `send_department_message` and `set_department_head` *before* the sort, so it stays sorted and keeps its 1h marker on the last tool. The resolved mode is pinned on the session for the rest of the turn, so the tool handlers use it too and a switch made mid-turn applies from the next turn. Every part is a constant or stable per install, so each mode keeps its own warm cache and switching modes misses once.\n\nThe two personas share most of their text. `prompts/executive_persona.py` holds plain string literals — a shared head, body and tail plus team or solo sections — concatenated at import and never formatted, so both prompts are constants. The team prompt is byte-for-byte what it was before the split; a test pins its sha256.\n\nTool schemas are static: nothing in a definition depends on company data — `create_goal` takes its area as free text rather than an enum of the current departments, which would change the cached tool prefix every time an area was added, and `record_decision_outcome` takes a plain decision id. The solo persona is still one constant: its goal and decision-outcome lines (`_SOLO_CREATE_GOAL`, `_SOLO_DECISION_OUTCOME`) are literals concatenated at import, and the team persona is byte-identical (a test pins its sha256). The scheduler's proactive-trigger run (a Session marked `unattended`) is sent the list without `schedule_tools.UNATTENDED_WITHHELD_TOOLS`, so it has a stable tool prefix of its own, as each mode does. So does a turn private to the principal (`Session.private_to_principal`: mail from one of their contacts, or mail they forwarded): it is sent the list without `schedule_tools.PRIVATE_TURN_WITHHELD_TOOLS`, dropped before the sort, so private turns in a mode share one sorted prefix with its marker on the last tool. Act as me adds tools rather than dropping any: on a turn `delegation.settings.pin_turn_delegation` offered it to (the principal's own verified, attended turn in a private conversation, with it on), `ghostwrite_email`, the mailbox and calendar reads (`search_my_email`, `read_my_email`, `read_my_email_attachment`, `my_email_awaiting_reply`, `my_email_read_before`, `my_calendar`, and `save_my_email_attachment`, which copies a file out of it), `remind_me` and `propose_actions` join the pool together before the sort, so those turns share one more sorted prefix and every other turn's list is byte-identical to before. The offer never depends on the Gmail connection, so a lapsed token never flips the prefix. `recall_history` (Always in the loop) joins the same way, before the sort, on a turn whose speaker may read their own notes; its offer reads only their switch and the surface, never the notes themselves. The chat note-taker runs after the turn, outside the cached prompt. Tool definitions are sorted by name so their serialized order is stable across requests; the `web_search` server tool is appended after the sorted list so it never receives a `cache_control` marker. The last client tool carries the third marker (1h TTL).\n\n## Tools opened on demand\n\nThe less common tools are not in the list at all. `orchestrator.tool_groups` puts them in named groups — calendar, people, memory, corrections, goals, watch_and_alerts, workflows, documents, app, messaging — and `tool_groups.split` takes them out of the turn's offered tools after every filter above (mode, unattended, private turn) and before the sort, adding two small tools in their place: `open_tools(group)`, whose description names each offered group and its tools, and `use_tool(name, input)`. When the model opens a group, the loop answers with that group's tools (name, description, input schema) as a **tool result**. It never adds them to the list: the list is the start of the cached prefix, so a list that grew mid-turn would miss the cache for the tools, both system blocks and the whole history. The list is the same on every call of every turn, and a group's descriptions are paid for only on a turn that opens it. That took the direct list from about 19,500 tokens to about 6,500, re-sent on every model call.\n\n`open_tools`'s description and its results name only the tools the turn offers (`tool_groups.open_tools_tool`), so a private turn never sees a withheld tool's name. The description depends only on that set, which is fixed for each kind of turn, so each still has one stable list. A `use_tool` call is rewritten into the tool's own call, same id, before dispatch (`tool_groups.unwrap`); the model's assistant block stays as it was sent, so the result pairs with the id it used. The rewritten call meets the same guards, handler, progress events and audit rows as a direct call. `use_tool` takes only names in `tool_groups.DEFERRED`; anything else, or an input that is not an object, gets an error tool result. The everyday tools (`consult_specialist`, `propose_form_values`, `read_user_guide`, `message_person`, `lookup_person`, `list_people`, `remember_fact`, follow-ups, the MCP meta-tools) stay direct. The rarely used `ask_about_person` (people), `forget_fact` and `update_company_profile` (memory) sit in groups, which keeps about 5,000 characters of descriptions off every call.\n\n## The intra-turn marker\n\nThe fourth and final breakpoint belongs to the tool-use loop. After each iteration appends its `tool_result` blocks, `executive._apply_loop_cache_marker` moves a single ephemeral marker onto the **newest non-empty tool result**. Without it the loop caches only the static tools+system prefix, so every iteration re-sends the whole accumulated transcript at full input price — the runtime signature is `cache_read_input_tokens` pinned flat while the prompt grows iteration over iteration.\n\nThe marker **moves rather than accumulates**: each pass first sweeps every `tool_result` clean, then re-marks the newest one. A marker left in place per iteration would reach `max_iterations` breakpoints and blow the 4-block limit. Sweeping first also makes the helper idempotent — there is no bookkeeping index to drift.\n\nOn the loop's **first call** there is no tool result yet, so the same slot marks the **message being answered** instead (`executive._mark_turn_message`, 5m): the question plus this turn's context (facts, memory, knowledge excerpts). Without it the first call sends that context uncached and the second call writes the same tokens to the cache, so it is paid twice; with it the first call writes it once and later calls read it back. The marker sits on a copy of the message, never the caller's dict, and comes off (`_clear_turn_marker`) as soon as the loop marker lands on a tool result, so a request never carries both.\n\n## The history marker\n\nOnce a conversation has history, the agent loop also marks the **newest non-empty history turn** (normally the previous reply) with a **1h** breakpoint (`executive._apply_history_cache_marker`), so the next message reads the whole conversation back from cache and writes only what is new: the last exchange, this turn's context and its tool calls. History turns are rebuilt from plain text, so the previous turn's loop entries, which ended inside that turn's retrieved context and tool results, never match; without this marker every message re-wrote the whole conversation into the cache. 1h because people reply in minutes, not seconds.\n\nThe history marker takes the company block's slot: block 1 stays in the prefix, covered by the history marker, and dropping its 5m marker keeps the TTLs in the order the API requires, longer before shorter. On a first message (no history) block 1 keeps its 5m marker as before. `_build_messages` itself never marks history, so the committee revision call, which reuses those messages, keeps the plain layout. `Session.get_recent_history` moves its window's start in steps of 10 turns (keeping 20 to 30), so a long conversation's first history message, and the cached prefix with it, stays put between steps instead of shifting every turn. On the OpenRouter path the translator keeps assistant turns as typed text parts whenever a request carries the history marker (`translator._request_caches_assistant_text`), so the marker reaches Anthropic and every reply has the same shape whether or not it is the one marked. A rolling marker on every history turn used to claim a latent fifth breakpoint, which Anthropic rejects outright.\n\n**The breakpoint budget, in full:** last client tool (1h) + persona+knowledge (1h) + company+org (5m, first message only) or history (1h) + the turn's message on the first call, then the newest tool result (5m) = at most 4, longer TTLs first.\n\nRAG context is **never** placed in a cached system block — retrieved hits vary per query and would poison the cache. It is injected into the **user turn** instead. The chat surfaces (web chat, Telegram, Discord, Google Chat) cap it at `KNOWLEDGE_CHAT_MAX_CHARS` (default 6,000 characters, 0 = no cap): `retriever._fit_to_budget` keeps the closest chunks across every collection until the cap, because each excerpt is re-sent on every call of the turn.\n\nSpecialist calls follow the same rule. Each specialist caches only its static domain prompt (`BaseAgent.analyze`, one ephemeral block); everything per call — retrieved knowledge, failure cases, past decisions, department memory, the company's stage (`<company_stage>`) and, in solo mode, the principal's role (`<principal_role>`) — goes in the specialist's user turn, so the cached domain prompt is byte-identical across companies and profile edits.\n\nThe ghostwriter's call (Act as me) carries no cache markers: its system prompt is the constant `GHOSTWRITER_PROMPT` plus that person's voice block — short, and sent only when a draft is written — and the thread and the intent go in its user turn.\n\n## Tool-result bound\n\n`TOOL_RESULT_MAX_CHARS` (default 20,000 characters, about 5,000 tokens) caps a single tool result before it enters the prompt, applied at the one point every result reaches the model rather than at each producer — so it also covers specialist output, tool errors and the unknown-tool fallback, while non-model consumers (the `propose_form_values` JSON parse, the audit trail) still read the full text. A turn's results also share one reading budget, `TOOL_RESULTS_TURN_MAX_CHARS` (default 40,000 characters; 0 turns it off): once the turn's results reach it, each further result shows its first 3,000 characters and its marker says, in place of the advice to ask again more narrowly (that re-read would be cut too), that the question has read as much as it can, so the model answers from what it has and says what it could not read, and it never edits or rewrites anything from that cut result, so a partial read never becomes a lossy write. The read it needs to edit may be the one that was cut, so each question gets one full re-read (`executive._TurnReadingBudget`): repeating a cut call with exactly the same input is answered with the result the turn already has, under the per-result cap, and the marker says so while that re-read is left. The tool never runs again, because the budget cuts any tool's result and a repeated write would happen twice. After it is used, the marker says to offer the edit as its own request, which starts with a fresh budget. A turn therefore reads at most the budget plus one more result (`executive._turn_result_limit`). A specialist's answer is the analysis itself, not a read, so it neither counts nor is cut. A built tool's (`run_script`) result counts but is never cut below the per-result cap: it lists the writes that already ran, and a short cut would hide some and get them repeated. Tool discovery (`open_tools`, `search_tools`) is treated the same way, since its result is the schema the next call needs. The per-result cap is a circuit breaker, not a routine clipper: ordinary tool output (a status, an email thread, a specialist's analysis) stays under it. A long document read does not, and the marker asks for a narrower request, such as a page range or a section, because a result stays in the prompt for every remaining call of the turn. A cut result carries an explicit marker naming the tool and stating that the result is incomplete — truncating silently is worse than not truncating, because the model reads the cut text as the whole answer.\n\n**The invariant:** never put dynamic content in a `cache_control` block. A single mutating value breaks the cache and drives roughly a 10x cost increase.",
+ "markdown": "The Executive system prompt is partitioned for Anthropic prompt caching by `openexecutive.prompts.cache_manager.build_system_blocks`. It emits at most two `cache_control` blocks, consolidated down from four to stay within Anthropic's 4-block API limit alongside the tool definitions and the agent loop's intra-turn marker.\n\n- **Block 0 — persona + knowledge (1h TTL, always present):** the executive persona constant — `EXECUTIVE_PERSONA_PROMPT` for a team, `EXECUTIVE_PERSONA_SOLO_PROMPT` in solo mode — or an admin override, which wins as-is in either mode, with the `{VOICE_PERSONA}` substitution, then the admin's Council **additional instructions** for the Executive (`persona_instructions`, wrapped in `<additional_instructions>`; blank leaves the block byte-identical, and like the override it changes only on save), conditional `WEB_SEARCH_ADDENDUM` / `MCP_ADDENDUM`, the constant `TOOL_BUILDING_ADDENDUM` (when to build a tool with `run_script`, check `list_saved_tools` first, keep what will be needed again, and talk about it without saying \"script\"; present with a gateway unless `CHAT_SCRIPTS=false`, a setting, so constant per deployment), the identity addendum (exec name/email, impersonation guard), the *Connected Systems* section (whose Google part is derived from `WORKSPACE_MCP_TOOLS` and `WORKSPACE_MCP_TOOL_TIER` — process-constant settings, so it is as cacheable as the rest), the constant `DELEGATION_ADDENDUM` while anyone on the install has Act as me on, the timezone addendum, and `KNOWLEDGE_INDEX_SUMMARY`. The timezone addendum names the user's zone, read fresh on every build from the workspace settings (`memory.workspace_settings.get_user_timezone`: the workspace's zone, else `USER_TIMEZONE`, else UTC). Every component is a constant or changes only when an admin or the user changes a setting, so the TTL is long. Setting a new time zone changes the addendum, so the 1h block misses once on that change and is warm again from the next turn — accepted, since a stale zone would mis-schedule follow-ups. Act as me works the same way: its addendum is keyed on the install-level setting (`delegation.settings.block0_delegation_on`), never on the turn or the speaker, so switching it on or off misses the 1h block once; off, block 0 is byte-identical to an install without the feature.\n The *Connected Systems* section (`prompts.connected_systems.render_connected_systems`) tells the model what is connected so it never has to discover it: Google Workspace on or off (on only when `google_workspace` is among the servers the running gateway started with, `MCPGateway.server_names`, so a gateway that failed to start never reads as connected; and *needs reconnecting* instead of connected while the server is in `MCPGateway.needs_reconnect` — set when a Google tool answers with an authorization failure such as `invalid_grant` (`mcp_gateway.grant_failure`), cleared by the next answer that is not one or by `mark_reconnected` — so the model stops promising mail it cannot read; the set changing re-renders block 0 and costs one cache miss), and when on, how to act from its own account plus the pinned Google tool names by service (`GOOGLE_TOOL_MANIFEST`: Gmail, Calendar, Drive, Docs, Sheets, as workspace-mcp 2.1.0 names them) to call directly; any other configured MCP servers by name (`_comment` keys skipped); Slack / Discord / Telegram / Google Chat on or off from their settings (names only, never a token); Notion knowledge sync; a Confluence knowledge sync line only when that sync is on (a setting, so constant per deployment); and one constant Act as me line that points at `DELEGATION_ADDENDUM`, so switching Act as me still changes block 0 by that addendum alone. The \"never ask which address to send from\" guidance lives here now, shown only while Google is connected; the identity addendum keeps the name, address and impersonation guard. Every input is fixed per process and the output is sorted, so block 0 stays warm; it is appended even under a persona override. It replaces what the model used to learn from `search_tools`, an uncached proxy whose results were gone by the next turn.\n- **Block 1 — company + org (5m TTL, only if non-empty):** `company_profile.to_prompt_block()` plus `render_org_block(mode=…)` — for a team: departments, heads, principals, charters and the People roster; in solo: the principal's own line, their role lines when set (a static lead-in marking the role private to the principal, then kind in plain words, title, reports to, remit, measured on — from the role pinned for the turn: the workspace settings, or a session's `principal_role` override), and their goals grouped by area, then the goals with no area under `### No area`. In both modes a goal with no department renders with its `goal_id` (a team's under `## Goals With No Department`), and a goal with an owner of its own names that owner. The role is set once per install and changes only when the principal edits it, so it is as stable as the rest of the block. Shorter TTL so org edits propagate quickly. The principal's contacts are private to them, so `build_system_blocks(include_contacts=...)` adds the `## Contacts` section, after the team or solo block, only on the principal's own verified turn (`executive._contacts_in_prompt`). That gives block 1 exactly two stable variants per mode — with and without contacts — and never anything per-request; every other turn's block is byte-identical to an install with no contacts.\n\n## Solo mode: one prefix per mode\n\nSolo mode — one person using Open Executive for themselves — changes three cached parts, all resolved **once per turn** by `pin_turn_workspace_mode(session)` (the session's override, else the workspace setting) so they always agree: the block-0 persona, the block-1 org block, and the tool list, which drops `send_company_broadcast`, `send_department_message` and `set_department_head` *before* the sort, so it stays sorted and keeps its 1h marker on the last tool. The resolved mode is pinned on the session for the rest of the turn, so the tool handlers use it too and a switch made mid-turn applies from the next turn. Every part is a constant or stable per install, so each mode keeps its own warm cache and switching modes misses once.\n\nThe two personas share most of their text. `prompts/executive_persona.py` holds plain string literals — a shared head, body and tail plus team or solo sections — concatenated at import and never formatted, so both prompts are constants. The team prompt is byte-for-byte what it was before the split; a test pins its sha256.\n\nTool schemas are static: nothing in a definition depends on company data — `create_goal` takes its area as optional free text and its owner as a plain `owner_person_id`, rather than enums of the current departments or people, which would change the cached tool prefix every time an area was added, and `record_decision_outcome` takes a plain decision id. The solo persona is still one constant: its goal and decision-outcome lines (`_SOLO_CREATE_GOAL`, `_SOLO_DECISION_OUTCOME`) are literals concatenated at import, and the team persona is byte-identical (a test pins its sha256). The scheduler's proactive-trigger run (a Session marked `unattended`) is sent the list without `schedule_tools.UNATTENDED_WITHHELD_TOOLS`, so it has a stable tool prefix of its own, as each mode does. So does a turn private to the principal (`Session.private_to_principal`: mail from one of their contacts, or mail they forwarded): it is sent the list without `schedule_tools.PRIVATE_TURN_WITHHELD_TOOLS`, dropped before the sort, so private turns in a mode share one sorted prefix with its marker on the last tool. Act as me adds tools rather than dropping any: on a turn `delegation.settings.pin_turn_delegation` offered it to (the principal's own verified, attended turn in a private conversation, with it on), `ghostwrite_email`, the mailbox and calendar reads (`search_my_email`, `read_my_email`, `read_my_email_attachment`, `my_email_awaiting_reply`, `my_email_read_before`, `my_calendar`, and `save_my_email_attachment`, which copies a file out of it), `remind_me` and `propose_actions` join the pool together before the sort, so those turns share one more sorted prefix and every other turn's list is byte-identical to before. The offer never depends on the Gmail connection, so a lapsed token never flips the prefix. `recall_history` (Always in the loop) joins the same way, before the sort, on a turn whose speaker may read their own notes; its offer reads only their switch and the surface, never the notes themselves. The chat note-taker runs after the turn, outside the cached prompt. Tool definitions are sorted by name so their serialized order is stable across requests; the `web_search` server tool is appended after the sorted list so it never receives a `cache_control` marker. The last client tool carries the third marker (1h TTL).\n\n## Tools opened on demand\n\nThe less common tools are not in the list at all. `orchestrator.tool_groups` puts them in named groups — calendar, people, memory, corrections, goals, watch_and_alerts, workflows, documents, app, messaging — and `tool_groups.split` takes them out of the turn's offered tools after every filter above (mode, unattended, private turn) and before the sort, adding two small tools in their place: `open_tools(group)`, whose description names each offered group and its tools, and `use_tool(name, input)`. When the model opens a group, the loop answers with that group's tools (name, description, input schema) as a **tool result**. It never adds them to the list: the list is the start of the cached prefix, so a list that grew mid-turn would miss the cache for the tools, both system blocks and the whole history. The list is the same on every call of every turn, and a group's descriptions are paid for only on a turn that opens it. That took the direct list from about 19,500 tokens to about 6,500, re-sent on every model call.\n\n`open_tools`'s description and its results name only the tools the turn offers (`tool_groups.open_tools_tool`), so a private turn never sees a withheld tool's name. The description depends only on that set, which is fixed for each kind of turn, so each still has one stable list. A `use_tool` call is rewritten into the tool's own call, same id, before dispatch (`tool_groups.unwrap`); the model's assistant block stays as it was sent, so the result pairs with the id it used. The rewritten call meets the same guards, handler, progress events and audit rows as a direct call. `use_tool` takes only names in `tool_groups.DEFERRED`; anything else, or an input that is not an object, gets an error tool result. The everyday tools (`consult_specialist`, `propose_form_values`, `read_user_guide`, `message_person`, `lookup_person`, `list_people`, `remember_fact`, follow-ups, the MCP meta-tools) stay direct. The rarely used `ask_about_person` (people), `forget_fact` and `update_company_profile` (memory) sit in groups, which keeps about 5,000 characters of descriptions off every call.\n\n## The intra-turn marker\n\nThe fourth and final breakpoint belongs to the tool-use loop. After each iteration appends its `tool_result` blocks, `executive._apply_loop_cache_marker` moves a single ephemeral marker onto the **newest non-empty tool result**. Without it the loop caches only the static tools+system prefix, so every iteration re-sends the whole accumulated transcript at full input price — the runtime signature is `cache_read_input_tokens` pinned flat while the prompt grows iteration over iteration.\n\nThe marker **moves rather than accumulates**: each pass first sweeps every `tool_result` clean, then re-marks the newest one. A marker left in place per iteration would reach `max_iterations` breakpoints and blow the 4-block limit. Sweeping first also makes the helper idempotent — there is no bookkeeping index to drift.\n\nOn the loop's **first call** there is no tool result yet, so the same slot marks the **message being answered** instead (`executive._mark_turn_message`, 5m): the question plus this turn's context (facts, memory, knowledge excerpts). Without it the first call sends that context uncached and the second call writes the same tokens to the cache, so it is paid twice; with it the first call writes it once and later calls read it back. The marker sits on a copy of the message, never the caller's dict, and comes off (`_clear_turn_marker`) as soon as the loop marker lands on a tool result, so a request never carries both.\n\n## The history marker\n\nOnce a conversation has history, the agent loop also marks the **newest non-empty history turn** (normally the previous reply) with a **1h** breakpoint (`executive._apply_history_cache_marker`), so the next message reads the whole conversation back from cache and writes only what is new: the last exchange, this turn's context and its tool calls. History turns are rebuilt from plain text, so the previous turn's loop entries, which ended inside that turn's retrieved context and tool results, never match; without this marker every message re-wrote the whole conversation into the cache. 1h because people reply in minutes, not seconds.\n\nThe history marker takes the company block's slot: block 1 stays in the prefix, covered by the history marker, and dropping its 5m marker keeps the TTLs in the order the API requires, longer before shorter. On a first message (no history) block 1 keeps its 5m marker as before. `_build_messages` itself never marks history, so the committee revision call, which reuses those messages, keeps the plain layout. `Session.get_recent_history` moves its window's start in steps of 10 turns (keeping 20 to 30), so a long conversation's first history message, and the cached prefix with it, stays put between steps instead of shifting every turn. On the OpenRouter path the translator keeps assistant turns as typed text parts whenever a request carries the history marker (`translator._request_caches_assistant_text`), so the marker reaches Anthropic and every reply has the same shape whether or not it is the one marked. A rolling marker on every history turn used to claim a latent fifth breakpoint, which Anthropic rejects outright.\n\n**The breakpoint budget, in full:** last client tool (1h) + persona+knowledge (1h) + company+org (5m, first message only) or history (1h) + the turn's message on the first call, then the newest tool result (5m) = at most 4, longer TTLs first.\n\nRAG context is **never** placed in a cached system block — retrieved hits vary per query and would poison the cache. It is injected into the **user turn** instead. The chat surfaces (web chat, Telegram, Discord, Google Chat) cap it at `KNOWLEDGE_CHAT_MAX_CHARS` (default 6,000 characters, 0 = no cap): `retriever._fit_to_budget` keeps the closest chunks across every collection until the cap, because each excerpt is re-sent on every call of the turn.\n\nSpecialist calls follow the same rule. Each specialist caches only its static domain prompt (`BaseAgent.analyze`, one ephemeral block); everything per call — retrieved knowledge, failure cases, past decisions, department memory, the company's stage (`<company_stage>`) and, in solo mode, the principal's role (`<principal_role>`) — goes in the specialist's user turn, so the cached domain prompt is byte-identical across companies and profile edits.\n\nThe ghostwriter's call (Act as me) carries no cache markers: its system prompt is the constant `GHOSTWRITER_PROMPT` plus that person's voice block — short, and sent only when a draft is written — and the thread and the intent go in its user turn.\n\n## Tool-result bound\n\n`TOOL_RESULT_MAX_CHARS` (default 20,000 characters, about 5,000 tokens) caps a single tool result before it enters the prompt, applied at the one point every result reaches the model rather than at each producer — so it also covers specialist output, tool errors and the unknown-tool fallback, while non-model consumers (the `propose_form_values` JSON parse, the audit trail) still read the full text. A turn's results also share one reading budget, `TOOL_RESULTS_TURN_MAX_CHARS` (default 40,000 characters; 0 turns it off): once the turn's results reach it, each further result shows its first 3,000 characters and its marker says, in place of the advice to ask again more narrowly (that re-read would be cut too), that the question has read as much as it can, so the model answers from what it has and says what it could not read, and it never edits or rewrites anything from that cut result, so a partial read never becomes a lossy write. The read it needs to edit may be the one that was cut, so each question gets one full re-read (`executive._TurnReadingBudget`): repeating a cut call with exactly the same input is answered with the result the turn already has, under the per-result cap, and the marker says so while that re-read is left. The tool never runs again, because the budget cuts any tool's result and a repeated write would happen twice. After it is used, the marker says to offer the edit as its own request, which starts with a fresh budget. A turn therefore reads at most the budget plus one more result (`executive._turn_result_limit`). A specialist's answer is the analysis itself, not a read, so it neither counts nor is cut. A built tool's (`run_script`) result counts but is never cut below the per-result cap: it lists the writes that already ran, and a short cut would hide some and get them repeated. Tool discovery (`open_tools`, `search_tools`) is treated the same way, since its result is the schema the next call needs. The per-result cap is a circuit breaker, not a routine clipper: ordinary tool output (a status, an email thread, a specialist's analysis) stays under it. A long document read does not, and the marker asks for a narrower request, such as a page range or a section, because a result stays in the prompt for every remaining call of the turn. A cut result carries an explicit marker naming the tool and stating that the result is incomplete — truncating silently is worse than not truncating, because the model reads the cut text as the whole answer.\n\n**The invariant:** never put dynamic content in a `cache_control` block. A single mutating value breaks the cache and drives roughly a 10x cost increase.",
"mermaid": "flowchart TD\n Tools[\"Tool defs (sorted by name)<br/>less common ones behind open_tools<br/>last one: cache_control 1h\"] --> B0\n Mode{{\"effective_workspace_mode<br/>(team or solo, once per turn)\"}} --> Tools\n Mode --> B0\n Mode --> B1\n Deleg{{\"Act as me on?<br/>(install-level, not per turn)\"}} --> B0\n Offer{{\"ghostwrite_email offered?<br/>(pinned once per turn)\"}} --> Tools\n B0[\"Block 0: persona (team or solo) + knowledge<br/>cache_control 1h\"] --> B1\n B1[\"Block 1: company + org (team or solo render)<br/>cache_control 5m on a first message\"] --> Limit{{\"≤ 4 cache_control blocks\"}}\n Loop[\"Newest tool_result<br/>cache_control 5m (moves each iteration)\"] --> Limit\n Hist[\"Newest history turn<br/>cache_control 1h (replaces block 1 marker)\"] --> Limit\n Limit --> Turn[\"User turn\"]\n RAG[\"RAG hits<br/>(vary per query)\"] --> Turn\n Turn --> API[\"Anthropic API\"]\n class B0 cache\n class B1 cache\n class RAG hot\n class Turn hot\n class Tools compute\n class Mode compute\n class Loop cache\n class API external\n class Deleg compute\n class Offer compute",
- "generated_at": "2026-10-18T22:30:00Z"
+ "generated_at": "2026-10-21T00:00:00Z"
}
diff --git a/packages/core/openexecutive/architecture/prebuilt/org.json b/packages/core/openexecutive/architecture/prebuilt/org.json
index df3bdaf5..fbfaabc0 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**. A new install starts with **no departments**: nothing is created at boot. Setup's commit creates only the departments its draft names (none for a solo workspace or a team that names none), and the Executive's `create_goal` tool creates one when a goal names an area that has none. A department named after one of the eight catalogue areas in `departments/charters` (Strategy, Finance, People & Talent, Legal, Operations, Marketing, Product, Board & Investor Comms) starts from that area's charter, and setup and `create_goal` wire it to the matching specialist (at most one department per specialist). Workspaces created before this keep the departments they have. `seed_default_departments` still inserts the full catalogue once per database (tracked by a `default_departments_seeded` sentinel in `departments_meta`), but only tests and tooling call it.\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 5 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. Until a profile exists the owner (the principal)\nis sent to `/onboard` from Home and every shell page except Settings, unless\nthey chose \"I'll do this later\"; after the save and the voice step a last\nscreen shows what was kept and the two accounts worth connecting (the\nExecutive's own mailbox, and the owner's own for Act as me), and Home's\nbanner slot carries a getting-started checklist (profile, first question,\nthe two mailboxes, the team) until every required row is done or it is hidden\n(`ui/src/lib/firstRun.ts`).\n\nTwo properties matter here. First, **the interview never writes the profile**:\nthe exchange lives in a TTL'd session (2 h, 50 at most) that the API process\nholds and also writes through to the `onboarding_interviews` table of the\nepisodic SQLite database after every turn (`onboarding/interview_store.py`),\nso a restart or another worker finds it again (a newer stored row replaces\na held copy, so two workers never overwrite each other) and the browser,\nwhich keeps only the session id, resumes at the same question or draft via\n`GET /onboard/interview/{id}`. A session answers only to the caller who\nstarted it; anyone else gets the 404 an unknown id gets. Every answer stays on screen with an Edit link, on the draft review too: `POST /onboard/interview/revise` replaces one earlier answer (an edited description keeps its attached files), drops everything after it, resets the question count to what was asked before it, and runs the interviewer again, so it asks again from there or redrafts. A failed turn leaves the session as it was. Start over (on the \"Picking up where you left off\" banner) deletes the session at once with `DELETE /onboard/interview/{id}`. The single profile write happens at\n`POST /onboard/interview/commit`, so a rejected save leaves the draft editable\nand retryable, and a successful one deletes the stored transcript at once (it\ncarries the company's financials). 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 departments the workspace already\nhas, with their goals and `specialist_key` wiring, on a re-run of setup. A\ndrafted department that matches nothing is created, wired to the specialist\nwhose area it is named after (`specialist_key_for_area`) unless another\ndepartment already has that specialist. Matching goes through\n`departments.store.match_department` (slug as given or as the store would slug\nit, else case-insensitive title), the same rule the `create_goal` chat tool uses. `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 one\nexception is the owner's own sign-in email: the review screen has a separate\nfield for it, pre-filled with the current owner's email on a re-run and with the\nsigned-in user's on a first setup. The commit checks it before writing anything\n(malformed, already another person's — as their address or one of their\naliases — or different from the owner's existing\nemail is a 422 — setup only fills in a missing one) and then saves it on the\nprincipal's row. One case is adopted rather than rejected: when the address is\nthe one the caller signed in with and sits on the current principal's row\nunder another name (a hosted sign-up seeds that row from the address when no\nname was given), `adopt_owner_row` renames that row to the drafted name\nbefore the roster upsert, so the first save updates the owner's entry instead\nof failing with \"use the owner's name exactly as on the People page\". Without it the signed-in owner matched no Person,\nso their chat history stayed empty until they found the People page. With\nlocal login (`make dev` without Google or SSO sign-in) the field is optional: that\nsession carries no email, which the backend already reads as the principal.\nBecause the save demotes the old principal, only the current owner may draft\nsomeone else as \"This is me\" when setup is re-run (403 otherwise); a re-run\nthat keeps the owner, or a first setup, is open to anyone who can sign in. On such a re-run, someone who isn't the owner may fill in the owner's missing email only with the address they signed in with (403 otherwise): the roster is the sign-in allow-list, so any other address would let them sign in as the owner. That keeps the way in for an owner whose entry has no email, which is also where Setup status and the Executive send them, since the People page refuses anyone it can't recognise as the owner. Re-running setup stays open to everyone deliberately: the Company Profile and Departments pages already let anyone signed in change the same things. The original\n12-step form wizard remains available at `/onboard?mode=form` and backs the\n`openexecutive onboard` CLI. It adds people with their emails, so once there is an owner only they can save it.\n\nA first setup opens on one free-text box: the user describes their work in their own words, optionally attaching a one-pager. `POST /onboard/interview/understand` reads that text once (no session, nothing stored) and reports what it already says: Personal or Team, the principal's role (owner / founder, an executive inside an organisation, independent or fractional, or other), title, who they report to, the company and this year's focus. The next screen shows those for a quick confirm, with Personal / Team as the one required answer; confirming writes `PUT /workspace` (mode, the browser's time zone and, for Personal, the role) and then starts the interview with the same text, so it asks only about what is still missing, at most five questions. If the read fails the text is kept and the user simply picks. A re-run over an existing profile skips these steps; they are changed in Settings. The tone question comes last, after the draft is saved. In solo the interviewer's first user turn carries a short\nhint, one static constant per role kind (`onboarding.interview.solo_hint`):\nalways draft only the principal, as principal, and no departments; an owner is\nasked about the offer, customers, pricing, cash and runway; an in-house\nexecutive about their organisation (the company profile is their employer),\ntheir function and remit, their manager, their team size as context rather\nthan a roster, and what they are measured on; an independent about their\npractice, clients and pricing; with no role given, the role-neutral hint asks\nwhich of these they are. Each also asks their top goals. The hint never\ncarries the principal's own text, and it rides in the user turn, so the cached\nsystem prompt is the same constant in both modes. The solo review screen shows only **You**\n(name and role) and the sign-in email, and commits that one principal with no\ndepartments — the existing departments stay, as the areas goals are grouped\nby. The form wizard (and the CLI) read the mode when a session starts and skip\nthe Team Size, Team Members and Fractional Executives steps in solo; each\nstatus response numbers the steps it actually asks and flags whether the\ncurrent one is `optional`.\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) run a `department_check_in` workflow when due (never in solo mode, below), then chain the next occurrence. A new department starts with `check_in: weekly@mon@09:00` (`DEFAULT_CHECK_IN_CADENCE`; it was daily, and departments created before keep theirs). An empty spec turns the check-in off. `PATCH /departments/{slug}` rejects a spec that does not parse with a 422, and a changed `check_in` re-times the department at once (`cadence.reschedule_check_in` cancels the pending check-in and queues the next one on the new schedule, or none when it is off). The department page offers Daily / Weekly (day and time) / Off rather than the raw spec, and shows the next check-in from `next_check_in_at`. The check-in is skipped (and still chained) when the department has no specialist, no Goals, or nothing new since its Goals were last reviewed (a row private to the principal does not count as new: whether it runs is visible to the department). An idle initiative is chased with the department's head, or with the principal when there is none. A department may map to a specialist agent via `specialist_key`, or stay informational. No department is seeded for the `sales` specialist (existing installs keep their departments unchanged), so its consults skip the department-memory prefetch and the Honcho department sync, as `triage`'s do. An assigned head gets a generated department-head voice persona.\n\n**Goals from chat.** Besides the goal routes and the UI, the Executive keeps goals current from a chat turn: `update_department_goal` records reported progress, and `create_goal` starts tracking a new goal the principal states (\"20 paying clients by the end of Q4\"). Only the principal, on a surface that verified it is them (`people_tools.is_principal_on_verified_surface`, the roster tools' rule: the web chat, their own Slack or Discord, a private Telegram chat with a valid webhook secret), may call it: a goal renders in every turn's org block as one of the principal's own, so a goal from an inbound email, Google Chat, a teammate or an unattended run would be text carrying their authority. Anyone else gets a refusal (audited with the caller and surface) and nothing is written. `create_goal` names the area as free text — a slug or a title, resolved by `match_department` — so its schema is static and adding an area never changes the cached tool prefix. When nothing matches it creates the area (`create_department`), giving it a specialist only when the title is obviously one's domain (`specialist_key_for_area`: the default departments' slugs and titles, plus Sales) and no department holds that specialist yet; anything else is informational. It refuses a goal the area already tracks (pointing at `update_department_goal`), caps a turn at 5 new goals (a sweep is not a stated goal) and an area at 8 (common practice keeps 3–5 key results per objective, and every goal renders in the 4000-character org block, so one area cannot crowd the others out), returns only the exception type on a store failure, is audited with its rationale, and is never offered to an unattended run (`schedule_tools.UNATTENDED_WITHHELD_TOOLS`: reflection, research and the scheduler's proactive trigger). The solo persona teaches it; team mode learns it from the tool description, so the team persona stays byte-identical.\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### Solo and team mode\nAn install is either a **team** (the default) or **solo** — one person using Open Executive just for themselves. The mode lives with the user's time zone in its own one-row table, `workspace_settings` (`openexecutive.memory.workspace_settings`, `GET`/`PUT /workspace`), not on the company profile, because onboarding's commit and the form wizard rebuild the profile from scratch and would wipe it. Changing it is the principal's call (open while no principal exists, so first-run setup can choose).\n\nThe same row holds the **principal's role** (`PrincipalRole`, every field nullable): `role_kind` (`owner`, `in_house`, `independent` or `other`), `role_title`, `reports_to` (free text, e.g. \"VP of Operations, Dana Ruiz\"), `remit` (what they are responsible for) and `measured_on` (what they are judged on). Solo is about who uses Open Executive, not the principal's level — a business owner, an executive inside a larger organisation, an independent or fractional executive — and this is the context the solo persona reads the role from. Only solo mode reads it; a mode switch keeps it. `GET /workspace` returns it only to the principal (nulls for anyone else). The columns are added to an existing table additively, and a read of an older table (no role columns yet) never migrates it and reads the role as unset.\n\nSolo also changes how the Executive speaks and what it can do. It works for one person — the principal — without assuming their role (an owner, an executive inside a larger organisation, or an independent); the people in their world are contacts it helps them work with, not a team it routes to. The cached org block becomes the principal's own line (\"Your Principal\") — followed by their role lines when a role is set (a fixed lead-in marking the role private to the principal — use it to tailor advice and drafts, share it with no one else — then `- Role: <title> — <kind in plain words>`, `- Reports to:`, `- Responsible for:`, `- Measured on:`, each only when set, sanitized and capped) — plus their goals grouped by **area** (a department row is an area; no authority levels, heads, cadences, channels or roster), and posting to a department room, broadcasting to the company and assigning a department head are not offered. Specialists never see that block, so each consult in a solo turn also carries a `<principal_role>` tag in its user turn (kind, title and remit). The role is pinned on the session for the turn with the mode (`pin_turn_principal_role`), so the org block, the tag and any workflow the turn starts agree even if the role is edited mid-turn, so a VP inside a large company is told to make the case to their CFO rather than to raise a round. A follow-up the Executive schedules to the principal goes straight to them — its department and scope are dropped, so the authority gate never files a card asking the principal to approve a message to themselves. Meeting bookings are gated on the `meeting_scheduling` class mode, not a department (see below).\n\nSolo turns the department rhythm off without touching the org: switching to solo cancels every pending `dept_cadence` row, `bootstrap_cadences` does nothing (the check sits inside it, so boot, the fixture reset and client-slot activation all honour it), and the scheduler cancels any stray check-in without running or chaining it, and a check-in already running across the switch schedules no successor. Department and people rows are kept, so switching back to team re-schedules the check-ins at once. The boot-time org-completeness warnings (departments with no head) are skipped in solo. A chat `Session` can carry an explicit `workspace_mode` override (read through `effective_workspace_mode`), so a caller that runs many conversations on one Executive — evals, for one — can pick the mode per session instead of flipping the install-wide setting; a `principal_role` override (read through `effective_principal_role`: the override, then the turn's pin, then the setting) does the same for the role.\n\nIn the UI, a `WorkspaceProvider` in the root layout reads the mode and role once (and again after Settings changes them) and reads **team** while loading or on error, so a team install never flashes the solo UI. Solo swaps the sidebar's Company group for **You** — Goals, People and the profile — where `/goals` lists every goal grouped by area (a department row) and adds, edits and deletes them through the slug-scoped goal routes. Team mode lists Goals in the Company group too, after Departments, and the page says \"department\" instead of \"area\". Adding a goal asks only for the goal itself: the timeframe is a one-click chip (this quarter by default, filled with the current period's label), target and current are optional, and a new goal starts `on_track` until the check-in grades it. The profile entry follows the principal's role kind: **Business profile** for an owner, **Your work** for anyone else, including an unset role or one `GET /workspace` hides from a non-principal. One rule (`profileWording(mode, roleKind)` in `navConfig.ts`) also words the `/company-profile` breadcrumb, intro and section headings, the form wizard and the draft review; it is copy only, so no profile field is renamed, and team wording is unchanged. `/departments` and `/people` stay reachable by URL.\n\nThe setting is per company: a blank client slot starts on the defaults, a saved slot keeps its own (restoring one runs the additive column migration), a fixture load resets it and applies the fixture's optional `workspace.yaml` (`mode`, `timezone` and the optional role keys; read and validated before anything is swapped; a bad value is skipped, never a failed load; the load and unload responses report the mode and zone only, never the role), and the factory reset returns it to team with no zone and no role. The user's own settings survive a demo: the backup a fixture load takes (or reuses) always gets the live settings written to its `workspace.yaml` while the live state is the user's, and an unload from an older backup without one leaves the settings as they are. A zone that cannot be loaded is never fatal — the API answers 422, and a stored one reads as unset.\n\n### Authority gate\nEach department declares an `AuthorityLevel`, which `departments.authority.gate_action` checks whenever a department-scoped scheduled action comes due. The check-in cadence is the exception: it sends nothing itself, and each action it proposes is run through the gate and shown with its verdict in the report — so a propose-only department's check-ins actually run instead of becoming a one-shot approval card. `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. The scheduler records which action each card holds (`alert_held_actions`, written only as it files the card), so approving one (`POST /alerts/{id}/approve`, see Today) queues that exact action again without its department, the approval being the consent the gate waited for, and records who approved it. Calendar bookings follow the same rule in team mode. **A team member's chat turn goes through the gate too** (`orchestrator.department_gate`). On a turn whose caller is a team member other than the principal (attended, not private to the principal), every send or edit is checked before it runs: Take the lead's acting tools less `assign_open_loop` and `run_workflow` (`GATED_TOOLS`), and every connected tool `take_the_lead.mcp_tool_acts` flags, the Gmail send or a Docs edit among them (that check fails closed: only a name that starts with a read verb passes). The level is the strictest of the speaker's departments; no department reads as `propose_only`. `auto_execute` runs it. `propose_only` runs it when the speaker could approve it themselves (they hold a People approval range for every kind it touches, money, a contract, a people decision or the board, or wildcard), else holds it. `escalate` always holds it, for someone other than the speaker. A held action is a `department_action` decision with a card on its approver's Today (high severity when escalated; the principal's when it reaches someone outside the team), audited `department_action_held` with the speaker as actor; the model is told it waits and not to retry. Its card shows every field of the call in full and only then offers Approve, which makes that exact call on the server. Under `escalate`, putting someone on the chase and starting a workflow are refused, since they lead to sends later and can't wait on a card. Someone signed in on the web but on no People entry, or a chat-channel sender matched to no one (in practice Google Chat, the one channel that does not turn unmatched senders away), is gated like someone in no department. Google Chat matches its sender by the Google account email on its signed event and hands that entry to the gate alone (`Session.gate_sender_person_id`, never `caller_person_id`), so the principal's own sends there go and a teammate gets their department's authority; email is left to the mailbox's own gates. A gate that can't be read holds. Before this only unattended work and `propose_meeting` met the gate, so a propose-only or escalate department held nothing its own people asked for in chat. The principal's own turns are not gated, nor are unattended runs (Take the lead's gate and this section's scheduler gate cover those). In solo mode there is no operations department to consult: the booking is decided by the `meeting_scheduling` class mode — `propose` puts it on the briefing for whoever holds the **Meetings** approval range on People (`meeting_scheduling`), else the principal — a booking with a contact on it always stays the principal's — and `auto_execute` books right away only when the principal started the turn on a surface that verified it is them (the roster-write rule: the web chat, their own Slack or Discord, or a private Telegram chat with the webhook secret set). A booking asked for in an inbound email, by a contact, or by an unattended run is proposed to the principal instead, so text someone else wrote cannot put a meeting on their calendar. The principal sets it with `GET`/`PUT /decisions/classes/meeting_scheduling` (`{\"decision_class\": \"meeting_scheduling\", \"mode\": \"propose\" | \"auto_execute\"}`; the PUT is principal-only and audited). 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\nOne rule (`people/reach.py` `reach_order`) orders the channels the Executive reaches a person on, for briefs (`runner.delivery_order`), messages (`message_person` and the follow-up channel pick) and nudges (`prefer_channel_for()`, which also honours availability windows): their `preferred_channel`; with `any`, the chat app they last talked in (`last_channel`, written by `note_talked` at most hourly on a Slack, Discord or private Telegram turn from their own stored id); then Slack → Discord → Telegram; then email as the backup (first for an `email` preference). Each caller still skips a channel that isn't set up or an id it can't use. 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 to a value Telegram can send. 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 team member's People row is also the web sign-in allow-list, the outbound-email allow-list and approval routing. The People page follows the same rule: adding, editing and archiving people (`POST`/`PATCH /people`, `POST /people/{id}/archive`) are the principal's alone, or anyone's while no one is principal yet, so a first setup can add its owner (`chat._caller_is_principal_or_unclaimed`). Anyone else gets 403. That includes a teammate editing their own entry: its email and chat ids are how they sign in and how the Executive reaches them, and the rest decides their approvals and how they are chased. Their working style and open loops stay theirs. A signed-in owner whose email is on no People entry is refused too; they sign in with the email on their entry, or re-run the setup interview, which fills a missing one with the email they signed in with. The one roster change that can come from an email is the principal's tokened reply to a roster-request email, and the one a chat turn can make beyond these tools is `resolve_roster_request` — both below, both the principal's alone.\n\n### Each person's notifications\n\nEvery team member sets their own on Settings → Notifications (`GET`/`PUT /notifications/settings`, see API), stored one row per person in `person_notification_settings` (`people.notifications`): **quiet hours** (off by default; from–to in their zone, which may cross midnight; every day, or weekdays with the weekend quiet all day), **delivery** — *As they happen* (the default) or *In my briefs* — and **Let urgent things through** (on by default). No row means the defaults, which hold nothing back.\n\nThey apply only to the Executive's **own** outreach: a DM sent while a proactive source is tagged (`attunement.outcomes.tag_proactive` — the scheduler's nudge dispatch, the reflection, research findings, alert review). Replies in a conversation, a message someone asked for in chat, a follow-up someone scheduled (it was asked for at a time), the briefs themselves and reminders a person set are never held. Quiet hours are deliberately not part of the outbound guard's availability check, which runs on every DM — the brief included — and would refuse a brief scheduled inside the person's own quiet hours.\n\nTwo places apply them. **Nudge routing** asks `people.channel` with `quiet_hours=True` (`is_within_availability`, `next_window_for`, `prefer_channel_for`, `next_available_window`), so the nudge engine and the scheduler's `proactive_nudge` re-check defer a nudge to the end of quiet hours exactly as they defer to an availability window — nothing is written at 3am. **Every other proactive DM** meets `outbound_guard.check_hold` in the send handlers once the anti-spam guard has allowed it: if the recipient is in quiet hours, or chose *In my briefs*, the text is stored in `held_messages` (`people.held_messages`) and the tool returns `{\"status\": \"held\"}`; `message_person` stops there instead of trying another channel; alert review counts a route as made but not a nudge toward its cap, and holds no second nudge about an alert while one waits. If it can't be stored it is sent. A scheduler dispatch whose message was held is audited as `held`, not `delivered`. Quiet-hours rows go out when quiet hours end, as one *While you were away* message (see Scheduler); brief rows ride the principal's next morning brief or end-of-day digest as one *While you were away* block, and anyone else's go out on their own when those briefs run, since only the principal has a brief. Switching back to *As they happen* releases what waited. Whoever sends a row claims it first, so a brief and a release pass never both send it. Someone on leave or outside their availability windows is postponed to when that ends; any other failed delivery backs off (2, 4, 8 … minutes, at most an hour). Rows are capped at 50 per person and dropped after 7 days undelivered, each drop audited privately to the person as a count; a brief row with no brief to carry it for 36 hours goes on its own.\n\n**Urgent** messages — approval nudges (`nudge_stalled`) and alert-review DMs about a critical (`urgent`-severity) alert (`notifications.urgent_send`) — get through when the person lets urgent things through. A workflow approval question (`gate_delivery`, `notifications.approval_send`) is never held, whatever the setting, since only a reply to it resolves the gate. If quiet hours cover every availability window, a nudge falls back to the next window rather than being dropped. Not covered: nudges on the email channel (the MCP mail tool bypasses the send handlers, so routing defers them for quiet hours but they are never held for a brief), department channel broadcasts, and the alert dispatcher's own channels (the web stream, a self-addressed email, and a Slack DM that is still a stub). Department check-ins send no DM: what they propose becomes approval cards.\n\n### Team and contacts\nA `Person` is either on the **team** (`kind = \"team\"`, the default) or a **contact** (`kind = \"contact\"`): a client, contractor or advisor the Executive may need to email or invite but who must not get what a team row grants. Before contacts existed, emailing a client meant adding them as a Person, which also let them sign in and talk to the bot.\n\nContacts are **denied by default**. `people.store.list_people`, every `find_person_by_*` (and `find_person_by_channel_ref`), and the `people.registry` cache return team members only unless the caller passes `include_contacts=True`; `find_approvers` has no opt-in at all. So a contact is never in the web sign-in list (`GET /auth/allowed-emails`), the Slack / Telegram / Discord inbound gates, approvers, the alert review's roster slice, `/today`'s people list and insights, open-loop owners (an ask of a contact opens no loop, so the nudge engine never chases them), a workflow gate's approver or cadence recipient, the recap DM after a meeting, or a department head (`set_department_head` and `PATCH /departments/{slug}` refuse one). `get_person(id)` returns either kind and its security-relevant callers check `kind`.\n\nThe roster reads that **opt in** are few: the Executive's egress checks (Gmail, Calendar and Drive in the MCP gateway, calendar attendee resolution, and the chat DM tools), the People page's listing (`GET /people?include_contacts=true`), the chat `list_people` tool (both kinds, with `kind`), the org prompt block, and the roster-request intake (which looks a sender up with contacts included only to leave a contact out). Even there, reaching a contact needs **the principal's own turn**: `people_tools.contacts_reachable_now()` is true only on a turn the principal started on a surface that verified them — the same rule as roster writes above — or inside `grant_contact_egress()`, which the decisions approve route uses when the approver resolves to the principal. An inbound email (even from the principal's address), a teammate's turn, and unattended runs (scheduler, workflows, alert review) can still reach the team but not contacts. A workflow resumed by `apply_resolution`'s kick runs with no chat session, like the resumer's poll loop, so it never inherits the approver's turn.\n\n**Contacts are private to the principal.** A solo user may be an executive whose contacts include their boss, reports, board and clients, so nobody else using the install sees one. The rule is `contacts_reachable_now()` again: off the principal's own verified turn a contact does not exist — `list_people` returns the team with the same count, a contact's id or address gets exactly the error an unknown one gets (never a contact-specific refusal), and the org prompt block has no Contacts section. The API applies the same rule by caller (`people.caller_is_principal`: the signed-in email is the principal's, or no `x-caller-email` — CLI, local login; unlike the owner rule above, nobody is while no one is principal yet): `?include_contacts=true` is ignored for anyone else, a contact's id is a 404 on `GET /people/{id}` and its open loops exactly like a missing one (editing and archiving are already a 403 before any lookup), only the principal may create a contact or turn someone into one (403, a first setup with no principal included), and `GET /people/me` tells the UI whether to offer contacts at all.\n\nWhatever the Executive raises about a contact stays with the principal too. A meeting with a contact is proposed to the principal (not the scope's approver), its decision is hidden from everyone else's `/decisions` (404 by id), and its card carries `alerts.models.PRIVATE_ALERT_TAG`. So does an alert raised on a turn about the principal's private mail (`Session.private_to_principal`, set by the email poller for mail from a contact and for mail the principal forwards): the pipeline routes it to the principal, stores it without a live push or broadcast, and dedups it only against other private alerts. Private alerts appear on the principal's own `/today` and chat digest only — never a teammate's, the activity rail, the narrative, the morning brief, the end-of-day digest, the reflection or the alert review — and a teammate's ack, reopen or bulk sweep cannot touch one (404). A private turn itself reaches the principal and nobody else (email, DMs, invites). It is not offered, and cannot run, the tools that post to other people, publish where the team reads (artifacts, goal updates, saved workflows, skill drafts) or start work outside the turn (`schedule_tools.PRIVATE_TURN_WITHHELD_TOOLS`), and of the MCP tools it may use only Google Workspace reads and the Gmail send the gateway narrows to the principal. Its audit rows are the principal's alone, as is any row on the principal's own turn that names one of their contacts (see Audit Log). DMs to a contact stay off the activity rail.\n\n`upsert_person` takes `kind`: explicit wins; an update that omits it keeps the row's kind (the store's full-row UPDATE preserves it, so nothing promotes a contact to the team by accident); a new person defaults to `team`, or to `contact` in solo mode. On the principal's own verified turn the org prompt block lists contacts in a short `## Contacts` section after the team block (or, in solo, after `## Your Principal` and their goals) — name, role/company and whether an email is on file, capped at 25 — in both modes. Every other turn gets the team block, byte-identical to an install with no contacts, so the 5-minute cached block has two stable variants.\n\nOn the **People page** the principal sees **Team** and **Contacts** tabs; anyone else sees the team only (no Contacts tab, no kind selector). Solo mode opens on Contacts, and its Team tab shows only the principal. The add form has a kind selector and hides authority scopes, reply SLA and the principal checkbox for a contact; a contact's page hides scopes, SLA, availability windows, open loops, outreach and working style. Adding a team member in solo offers to switch the workspace to team mode, or keep solo.\n\n### Contacts the Executive keeps up to date\n`people.contact_keeper` keeps the principal's contacts current on its own, from **their own mailbox** under Act as me (`delegation.gmail_for`: Gmail or Outlook, never the MCP gateway). It runs in the background (the scheduler starts it every 6 hours), never in a chat turn, and only while the principal has Act as me on with their own mailbox connected. The switch **Keep my contacts up to date** (`contact_keeper_state.mode`: `on`, the default; `ask`; `off`) sits on the Contacts tab.\n\n- **Adds**: someone the principal emailed at least twice in 60 days (sent mail they wrote: no lists, bulk or auto mail, nothing Handle it for me sent, at most 10 recipients) or met (meetings from 30 days back to 14 ahead that they organised or accepted, at most 10 guests). Names come only from To/Cc headers and guest lists, never a mail's text. Skipped: their own and the Executive's addresses, anyone in People (archived included), role and no-reply addresses, company-domain addresses (`identity.is_company_address`), and anything blocked. At most 10 per run.\n- **Updates**: an alias when a known contact (two-word full name) is mailed twice at a new address under that exact name as the principal's To line wrote it, always as a suggestion whatever the switch (mail to the contact may go there, so one reply to a lookalike must not attach it; an undone or archived address never is); a fuller name for a one-word contact; a role (\"Head of Procurement, Acme\") read from the contact's newest mail (`latest_from`) when its sender is authenticated and the From address is theirs. The role read is one forced-tool model call on the mail's last 1,200 characters, kept only if every word is in the mail, it is at most 10 words and 80 characters, and it carries no link, address or instruction. At most 5 role reads per run and 20 a day, and an address again only after 14 days. A field the principal typed is never overwritten: a name or role is written only when empty or last set by the keeper.\n- **Record and Undo** (`people.contact_changes`): every change is a row (`contact_changes`) with its reason and evidence. Under `ask` it is stored as a suggestion and applied on **Add**. **Undo** archives an added contact or restores the old value if nobody changed it since; Undo and **Not now** block that address, field and value (`contact_keeper_blocks`) so they are never proposed again. A contact added from chat is recorded too (reason `asked`), so it has an Undo. Each run writes one private `contacts_kept` audit row with counts, no names.\n- **Contact details**: the same signature read copies the sender's other contact details (`Person.details`, table `person_details`: phone, mobile, website, LinkedIn, another profile, postal address). Each is kept only when the mail writes it (a phone's digits as one number, every word of an address, a link's host and path), a website only on the sender's own mail domain (never a free mail one) and a profile only on a known site (`people.contact_info`). One of each kind is the keeper's: a newer one replaces it, and a kind anyone typed a value for is left alone (no second phone next to a typed one). Each is a change with **Undo**. People and chat (`upsert_person`'s `details`) can type them too. The people routes and `list_people` return a person's details only to the principal and to that person; everyone else gets the row with `details` empty. They are for the reader only: nothing is ever sent to a phone or link.\n- **Team members** get the same signature read (role when empty, contact details) and the same note; their name and addresses are never changed.\n- **What it remembers** (`people.contact_notes`, table `contact_notes`): for every contact and team member, when the principal last emailed, heard from (the date of their newest authenticated mail) and met them, their next meeting, counts, and a short note with up to 6 topics on what they deal with each other about. The note is written by one forced-tool call only from the principal's **own** sent mail to that contact (their new text, without quoted mail; nothing Handle it for me sent) and the titles of meetings they organised, so nobody else's words go in. It is rewritten only when that mail or those meetings change, at most 5 a pass and 20 a day, and a note holding a link, address or tag is dropped. \"Last heard from\" is read for up to 20 people a pass, whatever the note budget. The Executive reads it on the principal's own turn in `list_people` (contacts and teammates) and `ask_about_person` (contacts), to suggest who to ask; the person's page shows it to the principal as **What I remember**. A teammate's note is the principal's alone too: it comes from the principal's mailbox, never the teammate's own mail to the Executive or their peer memory. Archiving someone deletes it.\n\nAll of it is the principal's alone: the routes answer only `caller_is_principal`, and the rows are private. An added contact is an ordinary contact, with the rules above.\n\n### Addresses: aliases and company domains\nA `Person` has one **primary** address (`email`) — the one they sign in with — and up to 10 **aliases** (`email_aliases`, the `person_emails` table: `email_norm` unique across the roster, `source` `manual` / `chat_tool` / `roster_request`, deleted with the person or when they are archived, so an archived person never blocks the address). An alias matches their mail and may be emailed, but **is never a login**: `find_person_by_email` stays primary-only and is what web sign-in and `/auth/allowed-emails` read; mail goes through `find_person_by_address` (primary or alias, case-insensitive, the team row winning over a contact) and `people.identity.resolve_email_sender`. Aliases are edited on the person's page (\"Other addresses\") and by `upsert_person`'s `email_aliases` (the full list, replacing the current one); an address that is already someone else's primary or alias is refused (`AddressInUseError`, a 409 on the API), and so is a new primary that is someone's alias. Onboarding still imports no addresses beyond the owner's own sign-in email, and an alias counts as taken there too.\n\nOn top of exact matches, `resolve_email_sender` applies a **company-domain rule, team only**: on one of the company's own domains an address's local part (lowercased, `+tag` dropped) matches a teammate whose own address on any company domain has that local part — `[email protected]` is the Anna whose address is `[email protected]`. A domain alone proves nothing: an unknown local part on the company domain matches nobody (it becomes a roster request, pre-filled as a teammate), and when two teammates would match, nobody does. The company's domains are the `company_domains` workspace setting (Settings → Workspace, `PUT /workspace`, at most 10), or, when that is unset, the domains of the principal's own addresses — never a free-mail provider's (`identity.FREEMAIL_DOMAINS`: gmail.com, outlook.com and the like, refused as a setting too), where a local part says nothing about who someone is. The outbound gates build `RosterAllow` from the same rule, so the Executive may email exactly the addresses inbound mail would match (see Integrations).\n\n### New senders: roster requests\nWhen someone not on the roster — and not one of the principal's contacts — writes in (an email address, a Slack or Discord user, a private verified Telegram chat), their message is held as a **roster request** (`people.roster_requests`: tables `roster_requests`, `roster_request_messages`, `roster_ack_log`) instead of being dropped; they get a fixed acknowledgement (an email sender only when Gmail authenticated them — see Integrations) and the principal gets a private card on `/today`, which says whether they were actually told (`surface_card(acknowledged=...)`, from `ack_sent_at` after the acknowledgement is attempted) and, for a chat or company-domain sender, a prompt on their delivery channel (the per-channel mechanics are in Integrations). A request holds at most 10 messages (later ones only count), is one per `(channel, sender)` while pending, and suggests a match only from a chat account whose profile email is already someone's (never from a display name, which the sender chooses) — and `suggested_kind = team` for an address (or a chat profile email) on a company domain.\n\nThe principal answers one of three ways, all ending in `roster_requests.resolve` (a claim on the row, so two answers race and one wins; nothing is written unless it succeeds):\n\n- **approve** — add them as a new Person with this address or chat id, `team` or `contact`;\n- **link** — they are someone already on the list writing from somewhere new: an email becomes that person's alias — never their primary, even if they had none, so a link never creates a login, a chat id fills that person's field (replacing a different one only when the principal says so; otherwise `ChannelIdConflict`);\n- **decline** — leave them off; they are not raised again for 30 days.\n\nOnly the principal answers, and only where they are verified: the **web card** (`POST /people/requests/{id}/approve|decline`, which requires an explicit team/contact choice), their **own Slack or Discord DM or verified private Telegram chat** (the `resolve_roster_request` chat tool, which answers only ids the server showed that turn in its `<roster_requests>` block — see Agents), or an **email reply from their own primary address** (not an alias) carrying the request's one-time token, which the gateway hides from every other read of the Executive's mailbox so no model turn can copy it. When the chat or email answer does not say team or contact, the default is team for a sender on a company domain, else contact — the least access. Whoever answers, the held messages are then replayed as if the sender had been on the roster all along (a new contact gets only held email, on the private contact path); a decline drops them. A roster write outside a request — the People page (`POST`/`PATCH /people`) or `upsert_person` — reconciles too: any pending request whose sender now matches someone closes as `superseded` and replays.\n\nUnanswered requests expire after `ROSTER_REQUEST_TTL_DAYS` (14). A held message's text is kept only until the request is resolved or expires (then purged, even on decline), its card, routes and audit rows are private to the principal (404 for anyone else), and the tables are wiped with the rest of the People data on a company swap or fixture load.\n",
+ "markdown": "The org model has two persistent registries backed by SQLite (both share `episodic_memory.db`): **departments** and **people**. A new install starts with **no departments**: nothing is created at boot. Setup's commit creates only the departments its draft names (none for a solo workspace or a team that names none), and the Executive's `create_goal` tool creates one when a goal names an area that has none. A department named after one of the eight catalogue areas in `departments/charters` (Strategy, Finance, People & Talent, Legal, Operations, Marketing, Product, Board & Investor Comms) starts from that area's charter, and setup and `create_goal` wire it to the matching specialist (at most one department per specialist). Workspaces created before this keep the departments they have. `seed_default_departments` still inserts the full catalogue once per database (tracked by a `default_departments_seeded` sentinel in `departments_meta`), but only tests and tooling call it.\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 5 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. Until a profile exists the owner (the principal)\nis sent to `/onboard` from Home and every shell page except Settings, unless\nthey chose \"I'll do this later\"; after the save and the voice step a last\nscreen shows what was kept and the two accounts worth connecting (the\nExecutive's own mailbox, and the owner's own for Act as me), and Home's\nbanner slot carries a getting-started checklist (profile, first question,\nthe two mailboxes, the team) until every required row is done or it is hidden\n(`ui/src/lib/firstRun.ts`).\n\nTwo properties matter here. First, **the interview never writes the profile**:\nthe exchange lives in a TTL'd session (2 h, 50 at most) that the API process\nholds and also writes through to the `onboarding_interviews` table of the\nepisodic SQLite database after every turn (`onboarding/interview_store.py`),\nso a restart or another worker finds it again (a newer stored row replaces\na held copy, so two workers never overwrite each other) and the browser,\nwhich keeps only the session id, resumes at the same question or draft via\n`GET /onboard/interview/{id}`. A session answers only to the caller who\nstarted it; anyone else gets the 404 an unknown id gets. Every answer stays on screen with an Edit link, on the draft review too: `POST /onboard/interview/revise` replaces one earlier answer (an edited description keeps its attached files), drops everything after it, resets the question count to what was asked before it, and runs the interviewer again, so it asks again from there or redrafts. A failed turn leaves the session as it was. Start over (on the \"Picking up where you left off\" banner) deletes the session at once with `DELETE /onboard/interview/{id}`. The single profile write happens at\n`POST /onboard/interview/commit`, so a rejected save leaves the draft editable\nand retryable, and a successful one deletes the stored transcript at once (it\ncarries the company's financials). 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 departments the workspace already\nhas, with their goals and `specialist_key` wiring, on a re-run of setup. A\ndrafted department that matches nothing is created, wired to the specialist\nwhose area it is named after (`specialist_key_for_area`) unless another\ndepartment already has that specialist. Matching goes through\n`departments.store.match_department` (slug as given or as the store would slug\nit, else case-insensitive title), the same rule the `create_goal` chat tool uses. `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 one\nexception is the owner's own sign-in email: the review screen has a separate\nfield for it, pre-filled with the current owner's email on a re-run and with the\nsigned-in user's on a first setup. The commit checks it before writing anything\n(malformed, already another person's — as their address or one of their\naliases — or different from the owner's existing\nemail is a 422 — setup only fills in a missing one) and then saves it on the\nprincipal's row. One case is adopted rather than rejected: when the address is\nthe one the caller signed in with and sits on the current principal's row\nunder another name (a hosted sign-up seeds that row from the address when no\nname was given), `adopt_owner_row` renames that row to the drafted name\nbefore the roster upsert, so the first save updates the owner's entry instead\nof failing with \"use the owner's name exactly as on the People page\". Without it the signed-in owner matched no Person,\nso their chat history stayed empty until they found the People page. With\nlocal login (`make dev` without Google or SSO sign-in) the field is optional: that\nsession carries no email, which the backend already reads as the principal.\nBecause the save demotes the old principal, only the current owner may draft\nsomeone else as \"This is me\" when setup is re-run (403 otherwise); a re-run\nthat keeps the owner, or a first setup, is open to anyone who can sign in. On such a re-run, someone who isn't the owner may fill in the owner's missing email only with the address they signed in with (403 otherwise): the roster is the sign-in allow-list, so any other address would let them sign in as the owner. That keeps the way in for an owner whose entry has no email, which is also where Setup status and the Executive send them, since the People page refuses anyone it can't recognise as the owner. Re-running setup stays open to everyone deliberately: the Company Profile and Departments pages already let anyone signed in change the same things. The original\n12-step form wizard remains available at `/onboard?mode=form` and backs the\n`openexecutive onboard` CLI. It adds people with their emails, so once there is an owner only they can save it.\n\nA first setup opens on one free-text box: the user describes their work in their own words, optionally attaching a one-pager. `POST /onboard/interview/understand` reads that text once (no session, nothing stored) and reports what it already says: Personal or Team, the principal's role (owner / founder, an executive inside an organisation, independent or fractional, or other), title, who they report to, the company and this year's focus. The next screen shows those for a quick confirm, with Personal / Team as the one required answer; confirming writes `PUT /workspace` (mode, the browser's time zone and, for Personal, the role) and then starts the interview with the same text, so it asks only about what is still missing, at most five questions. If the read fails the text is kept and the user simply picks. A re-run over an existing profile skips these steps; they are changed in Settings. The tone question comes last, after the draft is saved. In solo the interviewer's first user turn carries a short\nhint, one static constant per role kind (`onboarding.interview.solo_hint`):\nalways draft only the principal, as principal, and no departments; an owner is\nasked about the offer, customers, pricing, cash and runway; an in-house\nexecutive about their organisation (the company profile is their employer),\ntheir function and remit, their manager, their team size as context rather\nthan a roster, and what they are measured on; an independent about their\npractice, clients and pricing; with no role given, the role-neutral hint asks\nwhich of these they are. Each also asks their top goals. The hint never\ncarries the principal's own text, and it rides in the user turn, so the cached\nsystem prompt is the same constant in both modes. The solo review screen shows only **You**\n(name and role) and the sign-in email, and commits that one principal with no\ndepartments — the existing departments stay, as the areas goals are grouped\nby. The form wizard (and the CLI) read the mode when a session starts and skip\nthe Team Size, Team Members and Fractional Executives steps in solo; each\nstatus response numbers the steps it actually asks and flags whether the\ncurrent one is `optional`.\n\n### Departments\n**Goals stand on their own.** A `Goal` has an owner and, optionally, a department (`department_goals.department_slug` is nullable; `owner_person_id` is nullable too). Its owner is resolved at read time (`departments.goals.effective_owner_id`): its own `owner_person_id`, else its department's head, else the principal, so a goal that follows its department moves with a new head. A goal no department check-in grades — one with no department, or in a department with no specialist — is graded weekly by the `goal_review` scheduled kind (`departments.goal_review`, Monday 09:00 in the user's zone, both modes) with `cso` (`goals.FALLBACK_REVIEWER`), through the check-in's own verdict contract and `persist_goal_verdicts`; it skips goals graded within six days and not edited since, so a quiet week makes no model call. Deleting a department keeps its goals: each with no owner of its own takes the department's head as owner, then all lose the department (`store.delete_department`). An old database is migrated in place (`_migrate_goals_stand_alone`: the table is rebuilt once to drop the NOT NULL, then the owner column is added). `GET /goals` lists every goal with `owner_id`, `owner_name` and `department_title`; `PATCH`/`DELETE /goals/{id}` reach any goal and can move it between owners and departments (an owner must be a non-archived team member, never a contact).\n\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) run a `department_check_in` workflow when due (never in solo mode, below), then chain the next occurrence. A new department starts with `check_in: weekly@mon@09:00` (`DEFAULT_CHECK_IN_CADENCE`; it was daily, and departments created before keep theirs). An empty spec turns the check-in off. `PATCH /departments/{slug}` rejects a spec that does not parse with a 422, and a changed `check_in` re-times the department at once (`cadence.reschedule_check_in` cancels the pending check-in and queues the next one on the new schedule, or none when it is off). The department page offers Daily / Weekly (day and time) / Off rather than the raw spec, and shows the next check-in from `next_check_in_at`. The check-in is skipped (and still chained) when the department has no specialist, no Goals, or nothing new since its Goals were last reviewed (a row private to the principal does not count as new: whether it runs is visible to the department). An idle initiative is chased with the department's head, or with the principal when there is none. A department may map to a specialist agent via `specialist_key`, or stay informational. No department is seeded for the `sales` specialist (existing installs keep their departments unchanged), so its consults skip the department-memory prefetch and the Honcho department sync, as `triage`'s do. An assigned head gets a generated department-head voice persona.\n\n**Goals from chat.** Besides the goal routes and the UI, the Executive keeps goals current from a chat turn: `update_department_goal` records reported progress, and `create_goal` starts tracking a new goal the principal states (\"20 paying clients by the end of Q4\"). Neither needs a department: `list_department_goals` without `department_slug` lists every goal with its owner and department, `update_department_goal` names a goal by `goal_id` alone (a `department_slug` it is given must still match), and `create_goal` leaves `area` out unless the principal names one, taking an optional `owner_person_id` (a team member, from `list_people`). Only the principal, on a surface that verified it is them (`people_tools.is_principal_on_verified_surface`, the roster tools' rule: the web chat, their own Slack or Discord, a private Telegram chat with a valid webhook secret), may call it: a goal renders in every turn's org block as one of the principal's own, so a goal from an inbound email, Google Chat, a teammate or an unattended run would be text carrying their authority. Anyone else gets a refusal (audited with the caller and surface) and nothing is written. `create_goal` names the area as free text — a slug or a title, resolved by `match_department` — so its schema is static and adding an area never changes the cached tool prefix. When nothing matches it creates the area (`create_department`), giving it a specialist only when the title is obviously one's domain (`specialist_key_for_area`: the default departments' slugs and titles, plus Sales) and no department holds that specialist yet; anything else is informational. It refuses a goal the area (or, with no area, the goals with no department) already tracks (pointing at `update_department_goal`), caps a turn at 5 new goals (a sweep is not a stated goal) and an area, or the goals with no department, at 8 (common practice keeps 3–5 key results per objective, and every goal renders in the 4000-character org block, so one area cannot crowd the others out), returns only the exception type on a store failure, is audited with its rationale, and is never offered to an unattended run (`schedule_tools.UNATTENDED_WITHHELD_TOOLS`: reflection, research and the scheduler's proactive trigger). The solo persona teaches it; team mode learns it from the tool description, so the team persona stays byte-identical.\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### Solo and team mode\nAn install is either a **team** (the default) or **solo** — one person using Open Executive just for themselves. The mode lives with the user's time zone in its own one-row table, `workspace_settings` (`openexecutive.memory.workspace_settings`, `GET`/`PUT /workspace`), not on the company profile, because onboarding's commit and the form wizard rebuild the profile from scratch and would wipe it. Changing it is the principal's call (open while no principal exists, so first-run setup can choose).\n\nThe same row holds the **principal's role** (`PrincipalRole`, every field nullable): `role_kind` (`owner`, `in_house`, `independent` or `other`), `role_title`, `reports_to` (free text, e.g. \"VP of Operations, Dana Ruiz\"), `remit` (what they are responsible for) and `measured_on` (what they are judged on). Solo is about who uses Open Executive, not the principal's level — a business owner, an executive inside a larger organisation, an independent or fractional executive — and this is the context the solo persona reads the role from. Only solo mode reads it; a mode switch keeps it. `GET /workspace` returns it only to the principal (nulls for anyone else). The columns are added to an existing table additively, and a read of an older table (no role columns yet) never migrates it and reads the role as unset.\n\nSolo also changes how the Executive speaks and what it can do. It works for one person — the principal — without assuming their role (an owner, an executive inside a larger organisation, or an independent); the people in their world are contacts it helps them work with, not a team it routes to. The cached org block becomes the principal's own line (\"Your Principal\") — followed by their role lines when a role is set (a fixed lead-in marking the role private to the principal — use it to tailor advice and drafts, share it with no one else — then `- Role: <title> — <kind in plain words>`, `- Reports to:`, `- Responsible for:`, `- Measured on:`, each only when set, sanitized and capped) — plus their goals grouped by **area** (a department row is an area; no authority levels, heads, cadences, channels or roster), and posting to a department room, broadcasting to the company and assigning a department head are not offered. Specialists never see that block, so each consult in a solo turn also carries a `<principal_role>` tag in its user turn (kind, title and remit). The role is pinned on the session for the turn with the mode (`pin_turn_principal_role`), so the org block, the tag and any workflow the turn starts agree even if the role is edited mid-turn, so a VP inside a large company is told to make the case to their CFO rather than to raise a round. A follow-up the Executive schedules to the principal goes straight to them — its department and scope are dropped, so the authority gate never files a card asking the principal to approve a message to themselves. Meeting bookings are gated on the `meeting_scheduling` class mode, not a department (see below).\n\nSolo turns the department rhythm off without touching the org: switching to solo cancels every pending `dept_cadence` row, `bootstrap_cadences` does nothing (the check sits inside it, so boot, the fixture reset and client-slot activation all honour it), and the scheduler cancels any stray check-in without running or chaining it, and a check-in already running across the switch schedules no successor. Department and people rows are kept, so switching back to team re-schedules the check-ins at once. The boot-time org-completeness warnings (departments with no head) are skipped in solo. A chat `Session` can carry an explicit `workspace_mode` override (read through `effective_workspace_mode`), so a caller that runs many conversations on one Executive — evals, for one — can pick the mode per session instead of flipping the install-wide setting; a `principal_role` override (read through `effective_principal_role`: the override, then the turn's pin, then the setting) does the same for the role.\n\nIn the UI, a `WorkspaceProvider` in the root layout reads the mode and role once (and again after Settings changes them) and reads **team** while loading or on error, so a team install never flashes the solo UI. Solo swaps the sidebar's Company group for **You** — Goals, People and the profile. `/goals` reads `GET /goals` and groups every goal by owner (the viewer first), department (shown once one exists; \"area\" in solo) or status, and adds, edits, moves and deletes them through the department-free goal routes. Team mode lists Goals in the Company group too, and shows the **Departments** tab only once a department exists (`GET /workspace`'s `has_departments`; the Departments pages keep it, since that is where the first is added). Adding a goal asks only for the goal itself: the timeframe is a one-click chip (this quarter by default, filled with the current period's label), target and current are optional, the owner defaults to the viewer, the department to none, and a new goal starts `on_track` until its check-in or the weekly goal review grades it. Adding a teammate on the People page (or moving a contact onto the team) while solo switches the workspace to team mode on its own and says so, with a link to Workspace settings to switch back. The profile entry follows the principal's role kind: **Business profile** for an owner, **Your work** for anyone else, including an unset role or one `GET /workspace` hides from a non-principal. One rule (`profileWording(mode, roleKind)` in `navConfig.ts`) also words the `/company-profile` breadcrumb, intro and section headings, the form wizard and the draft review; it is copy only, so no profile field is renamed, and team wording is unchanged. `/departments` and `/people` stay reachable by URL.\n\nThe setting is per company: a blank client slot starts on the defaults, a saved slot keeps its own (restoring one runs the additive column migration), a fixture load resets it and applies the fixture's optional `workspace.yaml` (`mode`, `timezone` and the optional role keys; read and validated before anything is swapped; a bad value is skipped, never a failed load; the load and unload responses report the mode and zone only, never the role), and the factory reset returns it to team with no zone and no role. The user's own settings survive a demo: the backup a fixture load takes (or reuses) always gets the live settings written to its `workspace.yaml` while the live state is the user's, and an unload from an older backup without one leaves the settings as they are. A zone that cannot be loaded is never fatal — the API answers 422, and a stored one reads as unset.\n\n### Authority gate\nEach department declares an `AuthorityLevel`, which `departments.authority.gate_action` checks whenever a department-scoped scheduled action comes due. The check-in cadence is the exception: it sends nothing itself, and each action it proposes is run through the gate and shown with its verdict in the report — so a propose-only department's check-ins actually run instead of becoming a one-shot approval card. `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. The scheduler records which action each card holds (`alert_held_actions`, written only as it files the card), so approving one (`POST /alerts/{id}/approve`, see Today) queues that exact action again without its department, the approval being the consent the gate waited for, and records who approved it. Calendar bookings follow the same rule in team mode. **A team member's chat turn goes through the gate too** (`orchestrator.department_gate`). On a turn whose caller is a team member other than the principal (attended, not private to the principal), every send or edit is checked before it runs: Take the lead's acting tools less `assign_open_loop` and `run_workflow` (`GATED_TOOLS`), and every connected tool `take_the_lead.mcp_tool_acts` flags, the Gmail send or a Docs edit among them (that check fails closed: only a name that starts with a read verb passes). The level is the strictest of the speaker's departments; no department reads as `propose_only`. `auto_execute` runs it. `propose_only` runs it when the speaker could approve it themselves (they hold a People approval range for every kind it touches, money, a contract, a people decision or the board, or wildcard), else holds it. `escalate` always holds it, for someone other than the speaker. A held action is a `department_action` decision with a card on its approver's Today (high severity when escalated; the principal's when it reaches someone outside the team), audited `department_action_held` with the speaker as actor; the model is told it waits and not to retry. Its card shows every field of the call in full and only then offers Approve, which makes that exact call on the server. Under `escalate`, putting someone on the chase and starting a workflow are refused, since they lead to sends later and can't wait on a card. Someone signed in on the web but on no People entry, or a chat-channel sender matched to no one (in practice Google Chat, the one channel that does not turn unmatched senders away), is gated like someone in no department. Google Chat matches its sender by the Google account email on its signed event and hands that entry to the gate alone (`Session.gate_sender_person_id`, never `caller_person_id`), so the principal's own sends there go and a teammate gets their department's authority; email is left to the mailbox's own gates. A gate that can't be read holds. Before this only unattended work and `propose_meeting` met the gate, so a propose-only or escalate department held nothing its own people asked for in chat. The principal's own turns are not gated, nor are unattended runs (Take the lead's gate and this section's scheduler gate cover those). In solo mode there is no operations department to consult: the booking is decided by the `meeting_scheduling` class mode — `propose` puts it on the briefing for whoever holds the **Meetings** approval range on People (`meeting_scheduling`), else the principal — a booking with a contact on it always stays the principal's — and `auto_execute` books right away only when the principal started the turn on a surface that verified it is them (the roster-write rule: the web chat, their own Slack or Discord, or a private Telegram chat with the webhook secret set). A booking asked for in an inbound email, by a contact, or by an unattended run is proposed to the principal instead, so text someone else wrote cannot put a meeting on their calendar. The principal sets it with `GET`/`PUT /decisions/classes/meeting_scheduling` (`{\"decision_class\": \"meeting_scheduling\", \"mode\": \"propose\" | \"auto_execute\"}`; the PUT is principal-only and audited). 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\nOne rule (`people/reach.py` `reach_order`) orders the channels the Executive reaches a person on, for briefs (`runner.delivery_order`), messages (`message_person` and the follow-up channel pick) and nudges (`prefer_channel_for()`, which also honours availability windows): their `preferred_channel`; with `any`, the chat app they last talked in (`last_channel`, written by `note_talked` at most hourly on a Slack, Discord or private Telegram turn from their own stored id); then Slack → Discord → Telegram; then email as the backup (first for an `email` preference). Each caller still skips a channel that isn't set up or an id it can't use. 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 to a value Telegram can send. 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 team member's People row is also the web sign-in allow-list, the outbound-email allow-list and approval routing. The People page follows the same rule: adding, editing and archiving people (`POST`/`PATCH /people`, `POST /people/{id}/archive`) are the principal's alone, or anyone's while no one is principal yet, so a first setup can add its owner (`chat._caller_is_principal_or_unclaimed`). Anyone else gets 403. That includes a teammate editing their own entry: its email and chat ids are how they sign in and how the Executive reaches them, and the rest decides their approvals and how they are chased. Their working style and open loops stay theirs. A signed-in owner whose email is on no People entry is refused too; they sign in with the email on their entry, or re-run the setup interview, which fills a missing one with the email they signed in with. The one roster change that can come from an email is the principal's tokened reply to a roster-request email, and the one a chat turn can make beyond these tools is `resolve_roster_request` — both below, both the principal's alone.\n\n### Each person's notifications\n\nEvery team member sets their own on Settings → Notifications (`GET`/`PUT /notifications/settings`, see API), stored one row per person in `person_notification_settings` (`people.notifications`): **quiet hours** (off by default; from–to in their zone, which may cross midnight; every day, or weekdays with the weekend quiet all day), **delivery** — *As they happen* (the default) or *In my briefs* — and **Let urgent things through** (on by default). No row means the defaults, which hold nothing back.\n\nThey apply only to the Executive's **own** outreach: a DM sent while a proactive source is tagged (`attunement.outcomes.tag_proactive` — the scheduler's nudge dispatch, the reflection, research findings, alert review). Replies in a conversation, a message someone asked for in chat, a follow-up someone scheduled (it was asked for at a time), the briefs themselves and reminders a person set are never held. Quiet hours are deliberately not part of the outbound guard's availability check, which runs on every DM — the brief included — and would refuse a brief scheduled inside the person's own quiet hours.\n\nTwo places apply them. **Nudge routing** asks `people.channel` with `quiet_hours=True` (`is_within_availability`, `next_window_for`, `prefer_channel_for`, `next_available_window`), so the nudge engine and the scheduler's `proactive_nudge` re-check defer a nudge to the end of quiet hours exactly as they defer to an availability window — nothing is written at 3am. **Every other proactive DM** meets `outbound_guard.check_hold` in the send handlers once the anti-spam guard has allowed it: if the recipient is in quiet hours, or chose *In my briefs*, the text is stored in `held_messages` (`people.held_messages`) and the tool returns `{\"status\": \"held\"}`; `message_person` stops there instead of trying another channel; alert review counts a route as made but not a nudge toward its cap, and holds no second nudge about an alert while one waits. If it can't be stored it is sent. A scheduler dispatch whose message was held is audited as `held`, not `delivered`. Quiet-hours rows go out when quiet hours end, as one *While you were away* message (see Scheduler); brief rows ride the principal's next morning brief or end-of-day digest as one *While you were away* block, and anyone else's go out on their own when those briefs run, since only the principal has a brief. Switching back to *As they happen* releases what waited. Whoever sends a row claims it first, so a brief and a release pass never both send it. Someone on leave or outside their availability windows is postponed to when that ends; any other failed delivery backs off (2, 4, 8 … minutes, at most an hour). Rows are capped at 50 per person and dropped after 7 days undelivered, each drop audited privately to the person as a count; a brief row with no brief to carry it for 36 hours goes on its own.\n\n**Urgent** messages — approval nudges (`nudge_stalled`) and alert-review DMs about a critical (`urgent`-severity) alert (`notifications.urgent_send`) — get through when the person lets urgent things through. A workflow approval question (`gate_delivery`, `notifications.approval_send`) is never held, whatever the setting, since only a reply to it resolves the gate. If quiet hours cover every availability window, a nudge falls back to the next window rather than being dropped. Not covered: nudges on the email channel (the MCP mail tool bypasses the send handlers, so routing defers them for quiet hours but they are never held for a brief), department channel broadcasts, and the alert dispatcher's own channels (the web stream, a self-addressed email, and a Slack DM that is still a stub). Department check-ins send no DM: what they propose becomes approval cards.\n\n### Team and contacts\nA `Person` is either on the **team** (`kind = \"team\"`, the default) or a **contact** (`kind = \"contact\"`): a client, contractor or advisor the Executive may need to email or invite but who must not get what a team row grants. Before contacts existed, emailing a client meant adding them as a Person, which also let them sign in and talk to the bot.\n\nContacts are **denied by default**. `people.store.list_people`, every `find_person_by_*` (and `find_person_by_channel_ref`), and the `people.registry` cache return team members only unless the caller passes `include_contacts=True`; `find_approvers` has no opt-in at all. So a contact is never in the web sign-in list (`GET /auth/allowed-emails`), the Slack / Telegram / Discord inbound gates, approvers, the alert review's roster slice, `/today`'s people list and insights, open-loop owners (an ask of a contact opens no loop, so the nudge engine never chases them), a workflow gate's approver or cadence recipient, the recap DM after a meeting, or a department head (`set_department_head` and `PATCH /departments/{slug}` refuse one). `get_person(id)` returns either kind and its security-relevant callers check `kind`.\n\nThe roster reads that **opt in** are few: the Executive's egress checks (Gmail, Calendar and Drive in the MCP gateway, calendar attendee resolution, and the chat DM tools), the People page's listing (`GET /people?include_contacts=true`), the chat `list_people` tool (both kinds, with `kind`), the org prompt block, and the roster-request intake (which looks a sender up with contacts included only to leave a contact out). Even there, reaching a contact needs **the principal's own turn**: `people_tools.contacts_reachable_now()` is true only on a turn the principal started on a surface that verified them — the same rule as roster writes above — or inside `grant_contact_egress()`, which the decisions approve route uses when the approver resolves to the principal. An inbound email (even from the principal's address), a teammate's turn, and unattended runs (scheduler, workflows, alert review) can still reach the team but not contacts. A workflow resumed by `apply_resolution`'s kick runs with no chat session, like the resumer's poll loop, so it never inherits the approver's turn.\n\n**Contacts are private to the principal.** A solo user may be an executive whose contacts include their boss, reports, board and clients, so nobody else using the install sees one. The rule is `contacts_reachable_now()` again: off the principal's own verified turn a contact does not exist — `list_people` returns the team with the same count, a contact's id or address gets exactly the error an unknown one gets (never a contact-specific refusal), and the org prompt block has no Contacts section. The API applies the same rule by caller (`people.caller_is_principal`: the signed-in email is the principal's, or no `x-caller-email` — CLI, local login; unlike the owner rule above, nobody is while no one is principal yet): `?include_contacts=true` is ignored for anyone else, a contact's id is a 404 on `GET /people/{id}` and its open loops exactly like a missing one (editing and archiving are already a 403 before any lookup), only the principal may create a contact or turn someone into one (403, a first setup with no principal included), and `GET /people/me` tells the UI whether to offer contacts at all.\n\nWhatever the Executive raises about a contact stays with the principal too. A meeting with a contact is proposed to the principal (not the scope's approver), its decision is hidden from everyone else's `/decisions` (404 by id), and its card carries `alerts.models.PRIVATE_ALERT_TAG`. So does an alert raised on a turn about the principal's private mail (`Session.private_to_principal`, set by the email poller for mail from a contact and for mail the principal forwards): the pipeline routes it to the principal, stores it without a live push or broadcast, and dedups it only against other private alerts. Private alerts appear on the principal's own `/today` and chat digest only — never a teammate's, the activity rail, the narrative, the morning brief, the end-of-day digest, the reflection or the alert review — and a teammate's ack, reopen or bulk sweep cannot touch one (404). A private turn itself reaches the principal and nobody else (email, DMs, invites). It is not offered, and cannot run, the tools that post to other people, publish where the team reads (artifacts, goal updates, saved workflows, skill drafts) or start work outside the turn (`schedule_tools.PRIVATE_TURN_WITHHELD_TOOLS`), and of the MCP tools it may use only Google Workspace reads and the Gmail send the gateway narrows to the principal. Its audit rows are the principal's alone, as is any row on the principal's own turn that names one of their contacts (see Audit Log). DMs to a contact stay off the activity rail.\n\n`upsert_person` takes `kind`: explicit wins; an update that omits it keeps the row's kind (the store's full-row UPDATE preserves it, so nothing promotes a contact to the team by accident); a new person defaults to `team`, or to `contact` in solo mode. On the principal's own verified turn the org prompt block lists contacts in a short `## Contacts` section after the team block (or, in solo, after `## Your Principal` and their goals) — name, role/company and whether an email is on file, capped at 25 — in both modes. Every other turn gets the team block, byte-identical to an install with no contacts, so the 5-minute cached block has two stable variants.\n\nOn the **People page** the principal sees **Team** and **Contacts** tabs; anyone else sees the team only (no Contacts tab, no kind selector). Solo mode opens on Contacts, and its Team tab shows only the principal. The add form has a kind selector and hides authority scopes, reply SLA and the principal checkbox for a contact; a contact's page hides scopes, SLA, availability windows, open loops, outreach and working style. Adding a team member in solo offers to switch the workspace to team mode, or keep solo.\n\n### Contacts the Executive keeps up to date\n`people.contact_keeper` keeps the principal's contacts current on its own, from **their own mailbox** under Act as me (`delegation.gmail_for`: Gmail or Outlook, never the MCP gateway). It runs in the background (the scheduler starts it every 6 hours), never in a chat turn, and only while the principal has Act as me on with their own mailbox connected. The switch **Keep my contacts up to date** (`contact_keeper_state.mode`: `on`, the default; `ask`; `off`) sits on the Contacts tab.\n\n- **Adds**: someone the principal emailed at least twice in 60 days (sent mail they wrote: no lists, bulk or auto mail, nothing Handle it for me sent, at most 10 recipients) or met (meetings from 30 days back to 14 ahead that they organised or accepted, at most 10 guests). Names come only from To/Cc headers and guest lists, never a mail's text. Skipped: their own and the Executive's addresses, anyone in People (archived included), role and no-reply addresses, company-domain addresses (`identity.is_company_address`), and anything blocked. At most 10 per run.\n- **Updates**: an alias when a known contact (two-word full name) is mailed twice at a new address under that exact name as the principal's To line wrote it, always as a suggestion whatever the switch (mail to the contact may go there, so one reply to a lookalike must not attach it; an undone or archived address never is); a fuller name for a one-word contact; a role (\"Head of Procurement, Acme\") read from the contact's newest mail (`latest_from`) when its sender is authenticated and the From address is theirs. The role read is one forced-tool model call on the mail's last 1,200 characters, kept only if every word is in the mail, it is at most 10 words and 80 characters, and it carries no link, address or instruction. At most 5 role reads per run and 20 a day, and an address again only after 14 days. A field the principal typed is never overwritten: a name or role is written only when empty or last set by the keeper.\n- **Record and Undo** (`people.contact_changes`): every change is a row (`contact_changes`) with its reason and evidence. Under `ask` it is stored as a suggestion and applied on **Add**. **Undo** archives an added contact or restores the old value if nobody changed it since; Undo and **Not now** block that address, field and value (`contact_keeper_blocks`) so they are never proposed again. A contact added from chat is recorded too (reason `asked`), so it has an Undo. Each run writes one private `contacts_kept` audit row with counts, no names.\n- **Contact details**: the same signature read copies the sender's other contact details (`Person.details`, table `person_details`: phone, mobile, website, LinkedIn, another profile, postal address). Each is kept only when the mail writes it (a phone's digits as one number, every word of an address, a link's host and path), a website only on the sender's own mail domain (never a free mail one) and a profile only on a known site (`people.contact_info`). One of each kind is the keeper's: a newer one replaces it, and a kind anyone typed a value for is left alone (no second phone next to a typed one). Each is a change with **Undo**. People and chat (`upsert_person`'s `details`) can type them too. The people routes and `list_people` return a person's details only to the principal and to that person; everyone else gets the row with `details` empty. They are for the reader only: nothing is ever sent to a phone or link.\n- **Team members** get the same signature read (role when empty, contact details) and the same note; their name and addresses are never changed.\n- **What it remembers** (`people.contact_notes`, table `contact_notes`): for every contact and team member, when the principal last emailed, heard from (the date of their newest authenticated mail) and met them, their next meeting, counts, and a short note with up to 6 topics on what they deal with each other about. The note is written by one forced-tool call only from the principal's **own** sent mail to that contact (their new text, without quoted mail; nothing Handle it for me sent) and the titles of meetings they organised, so nobody else's words go in. It is rewritten only when that mail or those meetings change, at most 5 a pass and 20 a day, and a note holding a link, address or tag is dropped. \"Last heard from\" is read for up to 20 people a pass, whatever the note budget. The Executive reads it on the principal's own turn in `list_people` (contacts and teammates) and `ask_about_person` (contacts), to suggest who to ask; the person's page shows it to the principal as **What I remember**. A teammate's note is the principal's alone too: it comes from the principal's mailbox, never the teammate's own mail to the Executive or their peer memory. Archiving someone deletes it.\n\nAll of it is the principal's alone: the routes answer only `caller_is_principal`, and the rows are private. An added contact is an ordinary contact, with the rules above.\n\n### Addresses: aliases and company domains\nA `Person` has one **primary** address (`email`) — the one they sign in with — and up to 10 **aliases** (`email_aliases`, the `person_emails` table: `email_norm` unique across the roster, `source` `manual` / `chat_tool` / `roster_request`, deleted with the person or when they are archived, so an archived person never blocks the address). An alias matches their mail and may be emailed, but **is never a login**: `find_person_by_email` stays primary-only and is what web sign-in and `/auth/allowed-emails` read; mail goes through `find_person_by_address` (primary or alias, case-insensitive, the team row winning over a contact) and `people.identity.resolve_email_sender`. Aliases are edited on the person's page (\"Other addresses\") and by `upsert_person`'s `email_aliases` (the full list, replacing the current one); an address that is already someone else's primary or alias is refused (`AddressInUseError`, a 409 on the API), and so is a new primary that is someone's alias. Onboarding still imports no addresses beyond the owner's own sign-in email, and an alias counts as taken there too.\n\nOn top of exact matches, `resolve_email_sender` applies a **company-domain rule, team only**: on one of the company's own domains an address's local part (lowercased, `+tag` dropped) matches a teammate whose own address on any company domain has that local part — `[email protected]` is the Anna whose address is `[email protected]`. A domain alone proves nothing: an unknown local part on the company domain matches nobody (it becomes a roster request, pre-filled as a teammate), and when two teammates would match, nobody does. The company's domains are the `company_domains` workspace setting (Settings → Workspace, `PUT /workspace`, at most 10), or, when that is unset, the domains of the principal's own addresses — never a free-mail provider's (`identity.FREEMAIL_DOMAINS`: gmail.com, outlook.com and the like, refused as a setting too), where a local part says nothing about who someone is. The outbound gates build `RosterAllow` from the same rule, so the Executive may email exactly the addresses inbound mail would match (see Integrations).\n\n### New senders: roster requests\nWhen someone not on the roster — and not one of the principal's contacts — writes in (an email address, a Slack or Discord user, a private verified Telegram chat), their message is held as a **roster request** (`people.roster_requests`: tables `roster_requests`, `roster_request_messages`, `roster_ack_log`) instead of being dropped; they get a fixed acknowledgement (an email sender only when Gmail authenticated them — see Integrations) and the principal gets a private card on `/today`, which says whether they were actually told (`surface_card(acknowledged=...)`, from `ack_sent_at` after the acknowledgement is attempted) and, for a chat or company-domain sender, a prompt on their delivery channel (the per-channel mechanics are in Integrations). A request holds at most 10 messages (later ones only count), is one per `(channel, sender)` while pending, and suggests a match only from a chat account whose profile email is already someone's (never from a display name, which the sender chooses) — and `suggested_kind = team` for an address (or a chat profile email) on a company domain.\n\nThe principal answers one of three ways, all ending in `roster_requests.resolve` (a claim on the row, so two answers race and one wins; nothing is written unless it succeeds):\n\n- **approve** — add them as a new Person with this address or chat id, `team` or `contact`;\n- **link** — they are someone already on the list writing from somewhere new: an email becomes that person's alias — never their primary, even if they had none, so a link never creates a login, a chat id fills that person's field (replacing a different one only when the principal says so; otherwise `ChannelIdConflict`);\n- **decline** — leave them off; they are not raised again for 30 days.\n\nOnly the principal answers, and only where they are verified: the **web card** (`POST /people/requests/{id}/approve|decline`, which requires an explicit team/contact choice), their **own Slack or Discord DM or verified private Telegram chat** (the `resolve_roster_request` chat tool, which answers only ids the server showed that turn in its `<roster_requests>` block — see Agents), or an **email reply from their own primary address** (not an alias) carrying the request's one-time token, which the gateway hides from every other read of the Executive's mailbox so no model turn can copy it. When the chat or email answer does not say team or contact, the default is team for a sender on a company domain, else contact — the least access. Whoever answers, the held messages are then replayed as if the sender had been on the roster all along (a new contact gets only held email, on the private contact path); a decline drops them. A roster write outside a request — the People page (`POST`/`PATCH /people`) or `upsert_person` — reconciles too: any pending request whose sender now matches someone closes as `superseded` and replays.\n\nUnanswered requests expire after `ROSTER_REQUEST_TTL_DAYS` (14). A held message's text is kept only until the request is resolved or expires (then purged, even on decline), its card, routes and audit rows are private to the principal (404 for anyone else), and the tables are wiped with the rest of the People data on a company swap or fixture load.\n",
"mermaid": "flowchart TD\n People[\"People registry (Person, is_principal, kind)\"]\n Contacts[\"Contacts (kind = contact): egress only on the principal's turn\"]\n Req[\"Roster requests (new senders held for the 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 People -. include_contacts .-> Contacts\n Req -->|approve / link| People\n Dept -->|team room| Chan\n class People storage\n class Contacts storage\n class Req 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-10-20T11:06:00Z"
+ "generated_at": "2026-10-21T00:00:00Z"
}
diff --git a/packages/core/openexecutive/architecture/prebuilt/scheduler.json b/packages/core/openexecutive/architecture/prebuilt/scheduler.json
index 260d4098..f0370f66 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. Each due row runs in its own task, started with no audit scope (`audit.context.unscoped_audit_rows`): a scheduled action is unattended and never part of the turn that scheduled it, so its audit rows follow the ordinary rule. 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### Liveness heartbeat\n\nEvery tick ends by recording when it finished and what it did — `ran`, `paused`, `waiting_for_company`, `rotating`, or `failed` when the tick raised — and `run_scheduler` notes when it started. `scheduler_heartbeat()` returns both; they live in process memory, not the database. Settings → Setup status (`GET /setup/status`) reads them: no start means the task isn't running; no tick five minutes after starting, or none for three poll intervals (at least 90 s), means the loop has stopped; `failed` and `waiting_for_company` get their own light. Liveness is judged before the pause switch, because a paused scheduler still ticks: one that has stopped shows as stopped, where the Resume button wouldn't help. A restart clears the previous run's last tick. Due actions run as their own tasks, so a slow brief never ages the heartbeat.\n\n### A teammate's scheduled rows\n\n`schedule_followup` and `suggest_workflow` keep the speaker on the row (`scheduled_actions.created_by_person_id`, from `Session.caller_person_id`). A due row whose creator is the principal, or that has no creator (the system's own rows, rows from before the column), takes the ordinary dispatch. A row a teammate queued runs as that teammate (`runner._run_teammate_followup`), because its intent is their own text: it is cancelled unless the creator is still an active team member and the row's address is one of their own; the Executive only writes the message, on an unattended session with `run_for_person_id` naming the teammate, which makes it read-only like a turn from another AI app that may not act (`schedule_tools.read_only_turn`: none of `MCP_CLIENT_WITHHELD_TOOLS` and only the gateway reads in `MCP_CLIENT_MCP_TOOLS`); its context is the decisions and advice of the conversation that queued it (nothing when there is none), never the company-wide list; and the runner sends the text to the teammate's own address on the row's channel (`_send_on_plan`), retrying on a failed send. A fork that limits what a teammate's turns may use applies the same limit to the run through `run_for_person_id`.\n\n**A follow-up overtaken by events.** An ad hoc follow-up back to the person who set it (the row's creator, else its conversation's owner, the principal when it has none; and only when its address is their own, `runner._followup_owner`) fires with what they wrote in chat since it was set: up to 30 of their own messages, 300 characters each, across all their conversations (`session_store.own_messages_since`; only their words, never a reply or someone else's line), in `<since_scheduled>` tags as data. The run is asked first whether that shows it is already done or no longer needed, and if so to send nothing and answer `ALREADY_HANDLED: <why>`. The runner then records the row `cancelled` with `skipped: already handled (<why>)` and a `scheduled_action` audit row with phase `skipped`, instead of `done`. A teammate's row gets the same block and check before the runner sends what it wrote. A follow-up to anyone else, or with no chat since, fires exactly as before.\n\n### Cadence DSL\n\n`openexecutive.departments.cadence` supports, all in UTC for department and workflow cadences:\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 (the department page's **Off**). A new department starts weekly, `weekly@mon@09:00`. Changing a department's `check_in` through that route re-times it at once: `cadence.reschedule_check_in()` cancels its pending `dept_cadence` row and queues the next occurrence of the new spec (nothing when it is off or in solo); a check-in already running finishes, and its chain adds nothing because the new row is pending.\n\nWhen a department cadence is due, the runner invokes the `department_check_in` workflow and chains the following occurrence via `cadence.enqueue_next()`. The fire is not passed through the authority gate: the check-in sends nothing (it grades Goals, writes one audit row and a Honcho note), and every action it proposes carries its own `gate_action` verdict in the report. Before creating a run the runner applies a skip rule (`department_check_in.needs_check_in`): the check-in is skipped when the department has no specialist agent, has no Goals, or nothing is new since its Goals were last reviewed — no decision or audit row tagged to the department (the check-in's own review row aside) since the oldest Goal's `last_reviewed_at`, and no Goal edited after it was graded. A Goal never reviewed always runs it. A skip leaves no run in the activity rail, is recorded as `cancelled` with its reason (`skipped: …` in `last_error`) rather than `done` — a done cadence row means \"the check-in ran\" to the nudge engine — and still chains the next occurrence; so does a check-in that fails once its retries are spent, so one broken department does not fall out of its cycle. That final failure also files one Home card, \"*Finance* check-in didn't finish\" (`workflows.failure_alerts`, source `workflow_failed`, tagged `failed_run:<run id>`; repeats of the same check-in coalesce into it), because nobody watches a scheduled run; a scheduled saved workflow (`dynamic_workflow`) that fails files the same card, routed to the person it delivers to. The card's **Run again** (`POST /workflows/runs/{run_id}/rerun`) queues the same action, due now, with `scope_key` `rerun:<run id>`: it skips the skip rule and does not chain another occurrence, and re-timing the check-in leaves it queued (the dept chain is idempotent anyway; a saved workflow's `schedule_dynamic_workflow_cadence` is skipped). Chaining is idempotent: while a next occurrence for the department is already pending nothing is added, so a row that chained and then failed to record its outcome never leaves two. Seeded departments start with no Goals, so their weekly check-ins cost nothing until someone adds one. Deleting a department cancels its pending `dept_cadence` rows, and `cancel_orphaned_cadences()` sweeps orphans on boot.\n\nIn **solo mode** (one person using Open Executive just for themselves; see Org) there are no department check-ins: `bootstrap_cadences()` is a no-op, switching to solo cancels every pending `dept_cadence` row, a row that was already pending is marked `cancelled` by the runner without running and without chaining — ahead of the authority gate, so a `propose_only` department cannot turn it into an approval card, and cancelled rather than done because the nudge engine reads a done check-in as a recent department pulse — and a check-in already running across the switch finishes without `enqueue_next` scheduling another. Switching back to team re-bootstraps them. Solo has one kind of its own, the **weekly review** (`principal_weekly_review`, below): switching to solo seeds it (`seed_weekly_review`), switching to team cancels its pending row (`cancel_weekly_reviews`), and one that fires while the stored mode is team is marked `cancelled` without running or chaining. That check reads the mode strictly (`workspace_settings.read_stored_mode`) and fails open: a mode that can't be read (a locked database) is not taken for team, so one bad read neither retires the review nor breaks its chain — the next run checks again.\n\nThe parser also takes a zone: `_parse_cadence_spec(spec, after, tz=UTC)` builds the wall-clock time in `tz` and only then converts to UTC, so a local schedule stays at the same local time across daylight-saving changes (a time the spring-forward gap skips fires once, just after the jump; a time the fall-back repeats fires at its first occurrence).\n\n### The principal's rhythm\n\nThe morning brief (`principal_brief_morning`, 08:00), end-of-day digest (`principal_brief_eod`, 18:00) and reflection (`executive_reflection`, 07:30) are seeded once per database by `seed_principal_briefs()` and each chains its next occurrence when it fires. In a solo workspace it also seeds the **weekly review** (`principal_weekly_review`, Friday 16:00 local by default), which runs the `weekly_review` workflow and is delivered like the briefs; its `PRINCIPAL_WEEKLY_REVIEW_TIME` takes a whole weekly spec (`weekly@fri@16:00`), read as UTC when valid, like the pinned times below, and it chains only while the workspace is still solo — and never when a weekly row is already pending, so a switch to solo while a review finishes cannot leave two. Their default times are local to the user's zone — `memory.workspace_settings.get_user_timezone()`: the zone set through `PUT /workspace`, else `USER_TIMEZONE`, else UTC — computed with the cadence parser above. An operator who pinned a valid `HH:MM` in `PRINCIPAL_BRIEF_MORNING_TIME` / `PRINCIPAL_BRIEF_EOD_TIME` / `PRINCIPAL_REFLECTION_TIME` keeps that time read as UTC, as before zones existed, so a pinned time never moves; a malformed value is logged and treated as unset. An install that set `USER_TIMEZONE` but pinned nothing does move to that zone, from each kind's first fire after the upgrade (a row seeded before it keeps its old UTC time once). When the zone in effect changes, `reschedule_principal_rhythm()` re-times each kind's pending, not-yet-due row **in place** — it only updates `run_at` (guarded on the row being unchanged since it was read), never inserts or cancels, so it cannot race a chain into a duplicate. The new time is the next occurrence in the new zone after `max(now, last fired run + 12h)`, so a kind never runs twice within 12 hours; and if that is more than 12 hours later than the row's current time — moving would skip a day, as when someone switches to Europe/London at 07:59 UTC with the 08:00 UTC brief a minute away — the row keeps its time once. A kind with no such row is left alone: a row that is running, one between being marked done and its chain insert, or a due row held by a pause or a missing company profile. Its chain times the next one in the new zone, and the chain itself starts from `max(now, fired run + 12h)`, so a zone change while a brief runs cannot put a second brief a few hours after it. The weekly review follows the same rules with a 3.5-day gap (`_min_gap`) in place of 12 hours, so a zone change can neither run it twice in a week nor skip one.\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**Monthly tally.** On the first weekday of each month, in daytime (09:00–18:00 local), a tick hook beside the reminders (`_maybe_send_monthly_value` → `briefing.value_summary.maybe_send_monthly`, checked every 15 minutes) sends the owner last month's counted lines and a link to Pulse → Your month through `_deliver_to_principal`, in solo and team mode alike. It is claimed once per month (`briefing_narrative` scope `value_summary:YYYY-MM`, never released, so one try), skipped for an empty month, audited `value_summary_sent` / `value_summary_not_sent`, and off with `VALUE_SUMMARY_MONTHLY_ENABLED=false`. It is not a `scheduled_actions` row.\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.) The runner records which action each card holds (`alert_held_actions`, server-side only, never a tag a model could write): approving one (`POST /alerts/{id}/approve`) queues a copy of that exact action with no department, so it goes out on the next tick without meeting the gate again. A `dept_cadence` row is not gated at all — gating it turned every check-in on a propose-only department (all eight seeded ones) into a one-shot card, and the row never chained its next occurrence. 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\nAn idle initiative is chased with its department's head; with no head to resolve — no department (what the episodic extractor stores), an unknown department, or no head set — the principal owns it. That source used to skip every initiative without a head, so in practice it never fired. The principal gets self-addressed wording (\"<title>\" has not moved since <date> — still active, done, or dropped?). If channel routing cannot reach the principal (no channel configured, or unreachable beyond `NUDGE_MAX_DEFER_DAYS`), the nudge becomes an unrouted Briefing card instead, keyed on the initiative and the ISO week: at most one card per initiative per week, and while one is still unread the scan leaves it alone rather than refreshing it every 15 minutes. The emitted nudge still carries no department, and the usual caps and cooldowns apply. A department-tagged initiative is still skipped while its department's check-in actually ran inside the idle window; a skipped check-in does not count.\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`. The same throttled call also deletes Always in the loop notes past their expiry (`memory.history.sweep_expired`; reads already skip them, and it never raises). Each tick also calls `_maybe_remind_notes` → `memory.history_reminders.maybe_remind` (its own 15-minute throttle, 09:00–18:00 local, one task at a time): a person whose notes say something they promised by email is due today gets one message saying how many, through `deliver_to_person` — the brief's own channel order for any Person, never a shared channel (`delivery_order` now skips a Telegram group id, for the briefs too), with the senders' audit rows private to that person. A hook rather than a `scheduled_actions` row, which `/scheduled` would show to everyone (see Memory).\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\nThe /today **\"What's going on\" header** is kept current from the tick too, so it is fresh before anyone opens the page. `_maybe_refresh_narrative` is a throttled call inside the loop, like the alert sweep — no `scheduled_actions` row. It runs after the pause, company-profile and rotation gates, every `BRIEFING_NARRATIVE_REFRESH_MINUTES` (10; 0 turns it off) and only between `BRIEFING_NARRATIVE_REFRESH_START_HOUR` and `_END_HOUR` (06–22) in the user's zone. It starts `today.refresh_principal_narrative` as its own task, so a slow model call never holds the tick, and never starts a second while one runs. That refreshes the cached calendar read (`live_signals.refresh_calendar`, at most once per 15 minutes) and rewrites the principal's header only when its key moved — new mail, a held reply, a proposal, the hour — with the route's own per-scope lock, so a page view and the tick never write the same header twice (see Today).\n\nAct as me's **reminders** are loop-level too: `_maybe_send_reminders` starts `delegation.reminders.maybe_send` at most once a minute, which claims each due `delegation_reminders` row once (due times are stored in UTC, so they compare in order) (compare-and-set on `claimed_at`) and sends its stored text, prefixed \"Reminder you set on <date>:\", to the person who set it alone through `deliver_to_person`. No model and no tool run; a reminder missed by more than two days is dropped rather than sent late, and one due in the person's quiet hours or leave waits, unclaimed, until they end; audit rows are private to the person. They are not `scheduled_actions` rows for the same reason as the scan below: that list is everyone's, and its rows run an Executive turn when they fire.\n\n**Held messages** are loop-level as well: `_maybe_release_held` starts `people.held_messages.maybe_release` at most once a minute, which sends each person whatever is due to them — messages held for their quiet hours once those end, and brief-held messages made due when the briefs run — as one *While you were away* message through `deliver_to_person`, claims each row first so a brief can't send it too, marks them sent only once that went, postpones a person back in quiet hours, on leave or outside their windows to when that ends, backs off 2, 4, 8 … minutes (at most an hour) after any other failure, and audits every drop (too old, over the cap) privately as a count, and writes audit rows private to the person. The principal-brief handler appends the principal's brief-held messages to the morning brief or end-of-day digest it delivers (`_with_held_messages`; the stored run artifact is unchanged), claims them, marks them sent only when the brief went (otherwise frees the claim), then makes everyone else's due (`_release_others_digests`). The `proactive_nudge` re-check calls `prefer_channel_for` / `next_available_window` with `quiet_hours=True` (urgent for a `nudge:stalled:` scope key), so a nudge due in the person's quiet hours is deferred to their end like one outside an availability window. A dispatch whose message was held is audited `held`, not `delivered`. See Org for the notification settings.\n\nAct as me's **inbox watcher** is loop-level the same way: `_maybe_scan_inbox`, after the same gates, starts the due scans (`delegation.inbox.maybe_scan`) as one task and never a second while one runs. A person is due every `DELEGATION_INBOX_POLL_MINUTES` (default 5) once their **Draft replies to my inbox** switch is on, unless a Gmail failure set a back-off; nobody is scanned while a client slot is active. It is deliberately not a `scheduled_actions` row: those are listed on `/scheduled` for everyone and anyone may cancel them, and a scan reads the owner's own mail. Every row a scan writes is private to the principal (see Act as Me).\n\nThe **contact keeper** is loop-level too: `_maybe_keep_contacts`, right after the inbox watcher, calls `people.contact_keeper.maybe_run`, which starts one pass at most every 6 hours (an in-process start time plus the stored `last_run_at`, so a restart doesn't re-run it) and never a second while one runs. Like the scans it is not a `scheduled_actions` row, because it reads the principal's own mail. See Org.\n\n### Principal briefs\n\nThe `principal_brief_morning` / `principal_brief_eod` / `principal_weekly_review` rows (and the client-rotation digest) are delivered by `_deliver_to_principal`, not through a row channel. The principal's `preferred_channel` (`slack` / `discord` / `telegram` / `email` / `any`, where `any` means the chat app they last talked in) is tried first, then the other chat channels they have an id for (Slack → Discord → Telegram), by `people.reach.reach_order`. Email goes through the active MCP gateway: first when the preference is `email`, and otherwise last, as the backup after every chat channel. Before planning, the delivery asks the gateway supervisor for a start if the gateway is down (`runner.ensure_email_ready` → `mcp_gateway.ensure_active_gateway`, the lazy re-check), and a row action resolves the gateway at execution time rather than from what boot had, so a gateway that failed at boot and came up on a retry carries the brief. The outcome names what happened: `gateway_down` when email is set up but the gateway is not running (the Executive's fault, with the start failure, never `no_channel`, which blamed the owner's setup), and a `send_failed` detail that quotes each channel's own error (`email: invalid_grant …`, `slack_dm: channel_not_found`), stored with the outcome (`brief_state.record_delivery_outcome(detail=…)`) and shown on the Briefing notice and the Setup page's *Daily brief* light, whose fix says to reconnect when the detail shows a dead grant. Delivery stops at the first channel that sends, so an owner linked by email at setup keeps their Slack delivery without extra email, and gets the brief by email only when Slack is missing or fails. The email is formatted HTML (`utils.markdown_email`: raw HTML and images off, unsafe link schemes dropped) with a subject dated in the user's zone (\"Morning Brief — Fri 25 Sep\"). Email counts as ready only when the MCP gateway runs the Google Workspace server. Every run's outcome — delivered, no owner, nowhere to send it, every send failed, or the brief couldn't be written at all (the workflow failed or produced nothing) — is recorded with the channel's name (never an address) under `brief_state`, for the Briefing's notice and the Setup status \"Daily brief\" light (the weekly review's outcome too — `brief_state.DELIVERY_KINDS` — so a weekly review that wasn't sent is reported the same way). The light also turns amber when a brief got through only on a backup channel, naming the one that failed. `_run_principal_brief` sets `morning_brief.PRINCIPAL_DELIVERY` for the run, because it goes to the principal alone: only then (or on the principal's own verified chat turn) does the morning brief read what is private to them. When the workflow reports `private_to_principal` on its `result` event — it did read such a row — the run history keeps `persistence.PRIVATE_RUN_ARTIFACT` in place of the text (`stored_artifact`), since `/workflows/runs` is readable by everyone signed in; the principal gets the full text where it is delivered. When no channel can deliver at all (a web-only principal, or email with no gateway), the brief is still generated and stored as a run with its artifact — a web-only principal reads it on the Artifacts page — it is just not delivered, and the next occurrence is chained; see Workflows.\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. An optional `drive_sync_scan` heartbeat (`DRIVE_SYNC_ENABLED`, off by default, bootstrapped in the lifespan beside it) does the same for the configured Google Drive folders, into the isolated `drive_docs` collection (see RAG). An optional `onedrive_sync_scan` heartbeat (`ONEDRIVE_SYNC_ENABLED`, off by default) does the same for the configured OneDrive folders, into `onedrive_docs`. An optional `confluence_sync_scan` heartbeat (`CONFLUENCE_SYNC_ENABLED`, off by default, bootstrapped in the lifespan the same way) re-indexes the changed pages of the configured Confluence spaces into the isolated `confluence_wiki` collection, leaving out restricted pages, and purges pages that were deleted, moved out or restricted.\n\n**Take the lead wakes.** With Take the lead as the Executive on, a turn from a channel (mail, Slack, Discord, Telegram, Google Chat) calls `take_the_lead.wake`, which inserts one `take_the_lead_wake` `__internal__` action five minutes out. It does nothing while one is pending or running, and nothing within 30 minutes of the last wake. The runner's `_run_take_the_lead_wake` runs the same reflection as the daily rhythm (`_reflect`, shared with `_run_executive_reflection`), only if the switch is still on, and never chains. The pause holds it like every claim.\n\n**Conversation reviews.** A kept chat turn (`memory.chat_review.record_turn`) makes sure one `chat_review` `__internal__` action is waiting for that conversation (`channel_ref` = session id), 30 minutes (`CHAT_REVIEW_QUIET_MINUTES`) out. `_run_chat_review` marks it done, then `chat_review.run_scheduled` either schedules a fresh one for 30 minutes after the newest turn (the chat is still going) or reviews the turns not yet reviewed. It never chains, and the pause holds it like every claim.\n\n**Replay of the misses.** The `chat_replay` kind (`memory.replay`) is seeded with the briefs by `seed_principal_briefs()` and chains its next occurrence like the reflection (`_run_chat_replay`; `CHAT_REPLAY_TIME`, 03:30 in the user's zone, pinned as UTC when set). It replays the turns the conversation review graded a miss with the lessons and facts in force today, in a dry run, judges each, and records the night (`chat_review_replay_runs`) whether or not anything was due; a failed night still marks done and chains. The pause holds it like every claim.",
+ "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. Each due row runs in its own task, started with no audit scope (`audit.context.unscoped_audit_rows`): a scheduled action is unattended and never part of the turn that scheduled it, so its audit rows follow the ordinary rule. 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### Liveness heartbeat\n\nEvery tick ends by recording when it finished and what it did — `ran`, `paused`, `waiting_for_company`, `rotating`, or `failed` when the tick raised — and `run_scheduler` notes when it started. `scheduler_heartbeat()` returns both; they live in process memory, not the database. Settings → Setup status (`GET /setup/status`) reads them: no start means the task isn't running; no tick five minutes after starting, or none for three poll intervals (at least 90 s), means the loop has stopped; `failed` and `waiting_for_company` get their own light. Liveness is judged before the pause switch, because a paused scheduler still ticks: one that has stopped shows as stopped, where the Resume button wouldn't help. A restart clears the previous run's last tick. Due actions run as their own tasks, so a slow brief never ages the heartbeat.\n\n### A teammate's scheduled rows\n\n`schedule_followup` and `suggest_workflow` keep the speaker on the row (`scheduled_actions.created_by_person_id`, from `Session.caller_person_id`). A due row whose creator is the principal, or that has no creator (the system's own rows, rows from before the column), takes the ordinary dispatch. A row a teammate queued runs as that teammate (`runner._run_teammate_followup`), because its intent is their own text: it is cancelled unless the creator is still an active team member and the row's address is one of their own; the Executive only writes the message, on an unattended session with `run_for_person_id` naming the teammate, which makes it read-only like a turn from another AI app that may not act (`schedule_tools.read_only_turn`: none of `MCP_CLIENT_WITHHELD_TOOLS` and only the gateway reads in `MCP_CLIENT_MCP_TOOLS`); its context is the decisions and advice of the conversation that queued it (nothing when there is none), never the company-wide list; and the runner sends the text to the teammate's own address on the row's channel (`_send_on_plan`), retrying on a failed send. A fork that limits what a teammate's turns may use applies the same limit to the run through `run_for_person_id`.\n\n**A follow-up overtaken by events.** An ad hoc follow-up back to the person who set it (the row's creator, else its conversation's owner, the principal when it has none; and only when its address is their own, `runner._followup_owner`) fires with what they wrote in chat since it was set: up to 30 of their own messages, 300 characters each, across all their conversations (`session_store.own_messages_since`; only their words, never a reply or someone else's line), in `<since_scheduled>` tags as data. The run is asked first whether that shows it is already done or no longer needed, and if so to send nothing and answer `ALREADY_HANDLED: <why>`. The runner then records the row `cancelled` with `skipped: already handled (<why>)` and a `scheduled_action` audit row with phase `skipped`, instead of `done`. A teammate's row gets the same block and check before the runner sends what it wrote. A follow-up to anyone else, or with no chat since, fires exactly as before.\n\n### Cadence DSL\n\n`openexecutive.departments.cadence` supports, all in UTC for department and workflow cadences:\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 (the department page's **Off**). A new department starts weekly, `weekly@mon@09:00`. Changing a department's `check_in` through that route re-times it at once: `cadence.reschedule_check_in()` cancels its pending `dept_cadence` row and queues the next occurrence of the new spec (nothing when it is off or in solo); a check-in already running finishes, and its chain adds nothing because the new row is pending.\n\nWhen a department cadence is due, the runner invokes the `department_check_in` workflow and chains the following occurrence via `cadence.enqueue_next()`. The fire is not passed through the authority gate: the check-in sends nothing (it grades Goals, writes one audit row and a Honcho note), and every action it proposes carries its own `gate_action` verdict in the report. Before creating a run the runner applies a skip rule (`department_check_in.needs_check_in`): the check-in is skipped when the department has no specialist agent, has no Goals, or nothing is new since its Goals were last reviewed — no decision or audit row tagged to the department (the check-in's own review row aside) since the oldest Goal's `last_reviewed_at`, and no Goal edited after it was graded. A Goal never reviewed always runs it. A skip leaves no run in the activity rail, is recorded as `cancelled` with its reason (`skipped: …` in `last_error`) rather than `done` — a done cadence row means \"the check-in ran\" to the nudge engine — and still chains the next occurrence; so does a check-in that fails once its retries are spent, so one broken department does not fall out of its cycle. That final failure also files one Home card, \"*Finance* check-in didn't finish\" (`workflows.failure_alerts`, source `workflow_failed`, tagged `failed_run:<run id>`; repeats of the same check-in coalesce into it), because nobody watches a scheduled run; a scheduled saved workflow (`dynamic_workflow`) that fails files the same card, routed to the person it delivers to. The card's **Run again** (`POST /workflows/runs/{run_id}/rerun`) queues the same action, due now, with `scope_key` `rerun:<run id>`: it skips the skip rule and does not chain another occurrence, and re-timing the check-in leaves it queued (the dept chain is idempotent anyway; a saved workflow's `schedule_dynamic_workflow_cadence` is skipped). Chaining is idempotent: while a next occurrence for the department is already pending nothing is added, so a row that chained and then failed to record its outcome never leaves two. Seeded departments start with no Goals, so their weekly check-ins cost nothing until someone adds one. Goals no check-in grades (no department, or a department with no specialist) are graded by the recurring `goal_review` kind instead (`GOAL_REVIEW_TIME`, default `weekly@mon@09:00` in the user's zone, both modes), seeded with the principal's rhythm and chained like the reflection: it runs `departments.goal_review.run_review` under `unscoped_audit_rows()`, delivers nothing, and a failed week never breaks the chain. Deleting a department cancels its pending `dept_cadence` rows, and `cancel_orphaned_cadences()` sweeps orphans on boot.\n\nIn **solo mode** (one person using Open Executive just for themselves; see Org) there are no department check-ins: `bootstrap_cadences()` is a no-op, switching to solo cancels every pending `dept_cadence` row, a row that was already pending is marked `cancelled` by the runner without running and without chaining — ahead of the authority gate, so a `propose_only` department cannot turn it into an approval card, and cancelled rather than done because the nudge engine reads a done check-in as a recent department pulse — and a check-in already running across the switch finishes without `enqueue_next` scheduling another. Switching back to team re-bootstraps them. Solo has one kind of its own, the **weekly review** (`principal_weekly_review`, below): switching to solo seeds it (`seed_weekly_review`), switching to team cancels its pending row (`cancel_weekly_reviews`), and one that fires while the stored mode is team is marked `cancelled` without running or chaining. That check reads the mode strictly (`workspace_settings.read_stored_mode`) and fails open: a mode that can't be read (a locked database) is not taken for team, so one bad read neither retires the review nor breaks its chain — the next run checks again.\n\nThe parser also takes a zone: `_parse_cadence_spec(spec, after, tz=UTC)` builds the wall-clock time in `tz` and only then converts to UTC, so a local schedule stays at the same local time across daylight-saving changes (a time the spring-forward gap skips fires once, just after the jump; a time the fall-back repeats fires at its first occurrence).\n\n### The principal's rhythm\n\nThe morning brief (`principal_brief_morning`, 08:00), end-of-day digest (`principal_brief_eod`, 18:00) and reflection (`executive_reflection`, 07:30) are seeded once per database by `seed_principal_briefs()` and each chains its next occurrence when it fires. In a solo workspace it also seeds the **weekly review** (`principal_weekly_review`, Friday 16:00 local by default), which runs the `weekly_review` workflow and is delivered like the briefs; its `PRINCIPAL_WEEKLY_REVIEW_TIME` takes a whole weekly spec (`weekly@fri@16:00`), read as UTC when valid, like the pinned times below, and it chains only while the workspace is still solo — and never when a weekly row is already pending, so a switch to solo while a review finishes cannot leave two. Their default times are local to the user's zone — `memory.workspace_settings.get_user_timezone()`: the zone set through `PUT /workspace`, else `USER_TIMEZONE`, else UTC — computed with the cadence parser above. An operator who pinned a valid `HH:MM` in `PRINCIPAL_BRIEF_MORNING_TIME` / `PRINCIPAL_BRIEF_EOD_TIME` / `PRINCIPAL_REFLECTION_TIME` keeps that time read as UTC, as before zones existed, so a pinned time never moves; a malformed value is logged and treated as unset. An install that set `USER_TIMEZONE` but pinned nothing does move to that zone, from each kind's first fire after the upgrade (a row seeded before it keeps its old UTC time once). When the zone in effect changes, `reschedule_principal_rhythm()` re-times each kind's pending, not-yet-due row **in place** — it only updates `run_at` (guarded on the row being unchanged since it was read), never inserts or cancels, so it cannot race a chain into a duplicate. The new time is the next occurrence in the new zone after `max(now, last fired run + 12h)`, so a kind never runs twice within 12 hours; and if that is more than 12 hours later than the row's current time — moving would skip a day, as when someone switches to Europe/London at 07:59 UTC with the 08:00 UTC brief a minute away — the row keeps its time once. A kind with no such row is left alone: a row that is running, one between being marked done and its chain insert, or a due row held by a pause or a missing company profile. Its chain times the next one in the new zone, and the chain itself starts from `max(now, fired run + 12h)`, so a zone change while a brief runs cannot put a second brief a few hours after it. The weekly review follows the same rules with a 3.5-day gap (`_min_gap`) in place of 12 hours, so a zone change can neither run it twice in a week nor skip one.\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**Monthly tally.** On the first weekday of each month, in daytime (09:00–18:00 local), a tick hook beside the reminders (`_maybe_send_monthly_value` → `briefing.value_summary.maybe_send_monthly`, checked every 15 minutes) sends the owner last month's counted lines and a link to Pulse → Your month through `_deliver_to_principal`, in solo and team mode alike. It is claimed once per month (`briefing_narrative` scope `value_summary:YYYY-MM`, never released, so one try), skipped for an empty month, audited `value_summary_sent` / `value_summary_not_sent`, and off with `VALUE_SUMMARY_MONTHLY_ENABLED=false`. It is not a `scheduled_actions` row.\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.) The runner records which action each card holds (`alert_held_actions`, server-side only, never a tag a model could write): approving one (`POST /alerts/{id}/approve`) queues a copy of that exact action with no department, so it goes out on the next tick without meeting the gate again. A `dept_cadence` row is not gated at all — gating it turned every check-in on a propose-only department (all eight seeded ones) into a one-shot card, and the row never chained its next occurrence. 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\nAn idle initiative is chased with its department's head; with no head to resolve — no department (what the episodic extractor stores), an unknown department, or no head set — the principal owns it. That source used to skip every initiative without a head, so in practice it never fired. The principal gets self-addressed wording (\"<title>\" has not moved since <date> — still active, done, or dropped?). If channel routing cannot reach the principal (no channel configured, or unreachable beyond `NUDGE_MAX_DEFER_DAYS`), the nudge becomes an unrouted Briefing card instead, keyed on the initiative and the ISO week: at most one card per initiative per week, and while one is still unread the scan leaves it alone rather than refreshing it every 15 minutes. The emitted nudge still carries no department, and the usual caps and cooldowns apply. A department-tagged initiative is still skipped while its department's check-in actually ran inside the idle window; a skipped check-in does not count.\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`. The same throttled call also deletes Always in the loop notes past their expiry (`memory.history.sweep_expired`; reads already skip them, and it never raises). Each tick also calls `_maybe_remind_notes` → `memory.history_reminders.maybe_remind` (its own 15-minute throttle, 09:00–18:00 local, one task at a time): a person whose notes say something they promised by email is due today gets one message saying how many, through `deliver_to_person` — the brief's own channel order for any Person, never a shared channel (`delivery_order` now skips a Telegram group id, for the briefs too), with the senders' audit rows private to that person. A hook rather than a `scheduled_actions` row, which `/scheduled` would show to everyone (see Memory).\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\nThe /today **\"What's going on\" header** is kept current from the tick too, so it is fresh before anyone opens the page. `_maybe_refresh_narrative` is a throttled call inside the loop, like the alert sweep — no `scheduled_actions` row. It runs after the pause, company-profile and rotation gates, every `BRIEFING_NARRATIVE_REFRESH_MINUTES` (10; 0 turns it off) and only between `BRIEFING_NARRATIVE_REFRESH_START_HOUR` and `_END_HOUR` (06–22) in the user's zone. It starts `today.refresh_principal_narrative` as its own task, so a slow model call never holds the tick, and never starts a second while one runs. That refreshes the cached calendar read (`live_signals.refresh_calendar`, at most once per 15 minutes) and rewrites the principal's header only when its key moved — new mail, a held reply, a proposal, the hour — with the route's own per-scope lock, so a page view and the tick never write the same header twice (see Today).\n\nAct as me's **reminders** are loop-level too: `_maybe_send_reminders` starts `delegation.reminders.maybe_send` at most once a minute, which claims each due `delegation_reminders` row once (due times are stored in UTC, so they compare in order) (compare-and-set on `claimed_at`) and sends its stored text, prefixed \"Reminder you set on <date>:\", to the person who set it alone through `deliver_to_person`. No model and no tool run; a reminder missed by more than two days is dropped rather than sent late, and one due in the person's quiet hours or leave waits, unclaimed, until they end; audit rows are private to the person. They are not `scheduled_actions` rows for the same reason as the scan below: that list is everyone's, and its rows run an Executive turn when they fire.\n\n**Held messages** are loop-level as well: `_maybe_release_held` starts `people.held_messages.maybe_release` at most once a minute, which sends each person whatever is due to them — messages held for their quiet hours once those end, and brief-held messages made due when the briefs run — as one *While you were away* message through `deliver_to_person`, claims each row first so a brief can't send it too, marks them sent only once that went, postpones a person back in quiet hours, on leave or outside their windows to when that ends, backs off 2, 4, 8 … minutes (at most an hour) after any other failure, and audits every drop (too old, over the cap) privately as a count, and writes audit rows private to the person. The principal-brief handler appends the principal's brief-held messages to the morning brief or end-of-day digest it delivers (`_with_held_messages`; the stored run artifact is unchanged), claims them, marks them sent only when the brief went (otherwise frees the claim), then makes everyone else's due (`_release_others_digests`). The `proactive_nudge` re-check calls `prefer_channel_for` / `next_available_window` with `quiet_hours=True` (urgent for a `nudge:stalled:` scope key), so a nudge due in the person's quiet hours is deferred to their end like one outside an availability window. A dispatch whose message was held is audited `held`, not `delivered`. See Org for the notification settings.\n\nAct as me's **inbox watcher** is loop-level the same way: `_maybe_scan_inbox`, after the same gates, starts the due scans (`delegation.inbox.maybe_scan`) as one task and never a second while one runs. A person is due every `DELEGATION_INBOX_POLL_MINUTES` (default 5) once their **Draft replies to my inbox** switch is on, unless a Gmail failure set a back-off; nobody is scanned while a client slot is active. It is deliberately not a `scheduled_actions` row: those are listed on `/scheduled` for everyone and anyone may cancel them, and a scan reads the owner's own mail. Every row a scan writes is private to the principal (see Act as Me).\n\nThe **contact keeper** is loop-level too: `_maybe_keep_contacts`, right after the inbox watcher, calls `people.contact_keeper.maybe_run`, which starts one pass at most every 6 hours (an in-process start time plus the stored `last_run_at`, so a restart doesn't re-run it) and never a second while one runs. Like the scans it is not a `scheduled_actions` row, because it reads the principal's own mail. See Org.\n\n### Principal briefs\n\nThe `principal_brief_morning` / `principal_brief_eod` / `principal_weekly_review` rows (and the client-rotation digest) are delivered by `_deliver_to_principal`, not through a row channel. The principal's `preferred_channel` (`slack` / `discord` / `telegram` / `email` / `any`, where `any` means the chat app they last talked in) is tried first, then the other chat channels they have an id for (Slack → Discord → Telegram), by `people.reach.reach_order`. Email goes through the active MCP gateway: first when the preference is `email`, and otherwise last, as the backup after every chat channel. Before planning, the delivery asks the gateway supervisor for a start if the gateway is down (`runner.ensure_email_ready` → `mcp_gateway.ensure_active_gateway`, the lazy re-check), and a row action resolves the gateway at execution time rather than from what boot had, so a gateway that failed at boot and came up on a retry carries the brief. The outcome names what happened: `gateway_down` when email is set up but the gateway is not running (the Executive's fault, with the start failure, never `no_channel`, which blamed the owner's setup), and a `send_failed` detail that quotes each channel's own error (`email: invalid_grant …`, `slack_dm: channel_not_found`), stored with the outcome (`brief_state.record_delivery_outcome(detail=…)`) and shown on the Briefing notice and the Setup page's *Daily brief* light, whose fix says to reconnect when the detail shows a dead grant. Delivery stops at the first channel that sends, so an owner linked by email at setup keeps their Slack delivery without extra email, and gets the brief by email only when Slack is missing or fails. The email is formatted HTML (`utils.markdown_email`: raw HTML and images off, unsafe link schemes dropped) with a subject dated in the user's zone (\"Morning Brief — Fri 25 Sep\"). Email counts as ready only when the MCP gateway runs the Google Workspace server. Every run's outcome — delivered, no owner, nowhere to send it, every send failed, or the brief couldn't be written at all (the workflow failed or produced nothing) — is recorded with the channel's name (never an address) under `brief_state`, for the Briefing's notice and the Setup status \"Daily brief\" light (the weekly review's outcome too — `brief_state.DELIVERY_KINDS` — so a weekly review that wasn't sent is reported the same way). The light also turns amber when a brief got through only on a backup channel, naming the one that failed. `_run_principal_brief` sets `morning_brief.PRINCIPAL_DELIVERY` for the run, because it goes to the principal alone: only then (or on the principal's own verified chat turn) does the morning brief read what is private to them. When the workflow reports `private_to_principal` on its `result` event — it did read such a row — the run history keeps `persistence.PRIVATE_RUN_ARTIFACT` in place of the text (`stored_artifact`), since `/workflows/runs` is readable by everyone signed in; the principal gets the full text where it is delivered. When no channel can deliver at all (a web-only principal, or email with no gateway), the brief is still generated and stored as a run with its artifact — a web-only principal reads it on the Artifacts page — it is just not delivered, and the next occurrence is chained; see Workflows.\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. An optional `drive_sync_scan` heartbeat (`DRIVE_SYNC_ENABLED`, off by default, bootstrapped in the lifespan beside it) does the same for the configured Google Drive folders, into the isolated `drive_docs` collection (see RAG). An optional `onedrive_sync_scan` heartbeat (`ONEDRIVE_SYNC_ENABLED`, off by default) does the same for the configured OneDrive folders, into `onedrive_docs`. An optional `confluence_sync_scan` heartbeat (`CONFLUENCE_SYNC_ENABLED`, off by default, bootstrapped in the lifespan the same way) re-indexes the changed pages of the configured Confluence spaces into the isolated `confluence_wiki` collection, leaving out restricted pages, and purges pages that were deleted, moved out or restricted.\n\n**Take the lead wakes.** With Take the lead as the Executive on, a turn from a channel (mail, Slack, Discord, Telegram, Google Chat) calls `take_the_lead.wake`, which inserts one `take_the_lead_wake` `__internal__` action five minutes out. It does nothing while one is pending or running, and nothing within 30 minutes of the last wake. The runner's `_run_take_the_lead_wake` runs the same reflection as the daily rhythm (`_reflect`, shared with `_run_executive_reflection`), only if the switch is still on, and never chains. The pause holds it like every claim.\n\n**Conversation reviews.** A kept chat turn (`memory.chat_review.record_turn`) makes sure one `chat_review` `__internal__` action is waiting for that conversation (`channel_ref` = session id), 30 minutes (`CHAT_REVIEW_QUIET_MINUTES`) out. `_run_chat_review` marks it done, then `chat_review.run_scheduled` either schedules a fresh one for 30 minutes after the newest turn (the chat is still going) or reviews the turns not yet reviewed. It never chains, and the pause holds it like every claim.\n\n**Replay of the misses.** The `chat_replay` kind (`memory.replay`) is seeded with the briefs by `seed_principal_briefs()` and chains its next occurrence like the reflection (`_run_chat_replay`; `CHAT_REPLAY_TIME`, 03:30 in the user's zone, pinned as UTC when set). It replays the turns the conversation review graded a miss with the lessons and facts in force today, in a dry run, judges each, and records the night (`chat_review_replay_runs`) whether or not anything was due; a failed night still marks done and chains. The pause holds it like every claim.",
"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<br/>(skipped when nothing is new)\"]\n Solo[\"solo workspace →<br/>cancelled, no chain\"]\n Nudge[\"nudge_scan →<br/>nudge_engine scan\"]\n Brief[\"principal_brief_morning / _eod →<br/>morning_brief / end_of_day_digest<br/>(user's local time)\"]\n Weekly[\"principal_weekly_review (solo) →<br/>weekly_review, Fri 16:00 local\"]\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 Drive[\"drive_sync_scan →<br/>isolated Drive folder ingest\"]\n Confluence[\"confluence_sync_scan →<br/>isolated Confluence space 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 or email 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 -- \"dept_cadence (solo)\" --> Solo\n Claim -- \"nudge_scan\" --> Nudge\n Claim -- \"principal_brief_*\" --> Brief\n Claim -- \"principal_weekly_review\" --> Weekly\n Claim -- \"executive_reflection\" --> Reflect\n Claim -- \"external_monitor_scan\" --> ExtMon\n Claim -- \"watchlist_research_scan\" --> Research\n Claim -- \"notion_sync_scan\" --> Notion\n Claim -- \"drive_sync_scan\" --> Drive\n Claim -- \"confluence_sync_scan\" --> Confluence\n Nudge -- \"prefer_channel_for\" --> Prefer\n Prefer -- \"emits proactive_nudge\" --> Table\n Dispatch --> Channels\n Brief --> Principal\n Weekly --> Principal\n ExtMon --> Alerts\n Dept --> Chain\n Nudge --> Chain\n Brief --> Chain\n Weekly -- \"while solo\" --> Chain\n Reflect --> Chain\n ExtMon --> Chain\n Research --> Chain\n Notion --> Chain\n Drive --> Chain\n Confluence --> 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 Solo compute\n class Nudge compute\n class Brief compute\n class Weekly compute\n class Reflect compute\n class ExtMon compute\n class Research compute\n class Notion compute\n class Drive compute\n class Confluence compute\n class Chain compute\n class Prefer compute\n class Channels external\n class Principal external\n class Alerts hot",
- "generated_at": "2026-10-19T16:00:00Z"
+ "generated_at": "2026-10-21T00:00:00Z"
}
diff --git a/packages/core/openexecutive/architecture/prebuilt/schemas.json b/packages/core/openexecutive/architecture/prebuilt/schemas.json
index c1a6a529..ec9e4f37 100644
--- a/packages/core/openexecutive/architecture/prebuilt/schemas.json
+++ b/packages/core/openexecutive/architecture/prebuilt/schemas.json
@@ -1,7 +1,7 @@
{
"section_id": "schemas",
"title": "Data Schemas",
- "markdown": "The shapes below are the load-bearing data structures: episodic SQLite tables (in `episodic_memory.db`) and the Pydantic models for departments and people.\n\n### Episodic tables\n\n| Table | Key columns |\n|---|---|\n| `decisions` | `id`, `timestamp`, `domain`, `summary`, `rationale`, `outcome`, `tags`, `department`, `session_id` |\n| `initiatives` | `id`, `title`, `status`, `created_at`, `updated_at`, `summary`, `department` |\n| `advice_given` | `id`, `timestamp`, `domain`, `query_summary`, `advice_summary`, `department`, `session_id` |\n| `facts` | `id`, `kind` (fact / correction / profile), `subject`, `subject_key`, `statement`, `previous_statement`, `source_quote`, `source_channel`, `session_id`, `turn_id`, `recorded_by_person_id`, `created_at`, `status` (active / superseded / retired), `superseded_by`, `retired_at`, `retired_reason` |\n| `scheduled_actions` | `id`, `created_at`, `run_at`, `channel`, `channel_ref`, `intent_text`, `status`, `attempts`, `kind`, `department`, `assigned_to_person_id`, `awaiting_response_since`, `scope_key`, `required_scope`, `created_by_person_id` |\n| `outbound_context` | `id`, `created_at`, `channel`, `channel_ref`, `recipient_person_id`, `outbound_text`, `originating_session_id`, `outbound_message_id`, `consumed_at`, `status` |\n| `history_reminders` | (`person_id`, `day`) PK, `sent_at` — the days a person was reminded of notes due (`memory.history_reminders`), older days pruned on write |\n| `session_drive_files` | (`session_id`, `person_id`, `file_id`) PK, `name`, `mime_type`, `link`, `summary` (first 600 chars of an opened file), `opened`, `found_by` (the search query), `first_seen_at`, `last_seen_at` — Drive files a conversation found or opened (`memory.drive_reads`) |\n| `session_drive_searches` | `id`, `session_id`, `person_id`, `query`, `result_count`, `searched_at` — every Drive search a conversation ran |\n| `saved_tools` | `name` (PK), `description`, `enabled`, `current_version`, `workflow_version` (the version workflows may run, NULL until the owner turns it on; never set for a Python tool), `kind` (`script` for `run_script`, `python` for a kept `run_python_job`; added with default `script`), `created_at`, `updated_at` — scripts and Python jobs the Executive saved to run again (`workflows.saved_tools`) |\n| `saved_tool_versions` | (`name`, `version`) PK, `description`, `script`, `tools` (JSON: the tools the script called when saved), `origin` (`chat` or `workflow:<name>/<step>`), `created_at` |\n| `saved_tool_runs` | `id`, `name`, `version`, `ok`, `calls`, `duration_ms`, `origin`, `at` — the newest 200 runs per tool |\n| `chat_messages` | `id`, `session_id`, `role`, `content`, `created_at`, `action_chips`, `stopped`, `sender_person_id`, `feedback`, `feedback_note`, `feedback_by_person_id`, `sources` (JSON `{sources: [{kind, title, url}], unavailable: [area]}` — what an assistant reply looked at and which areas it left out; NULL on older rows) |\n| `attunement_usage` | `day` (PK, UTC date), `calls` — the per-day ceiling on open-loop extraction model calls |\n| `attunement_profiles` | `person_id` (PK), `rules` (JSON: up to 8 `{text, basis, evidence}`; basis `feedback`, `stated`, `edited` or `conversation`), `locked`, `updated_at`, `updated_by`, `last_pass_at`, `pass_day`, `passes_today`, `last_message_id` — per-person working style plus pass pacing |\n| `chat_review_turns` | `id`, `session_id`, `person_id`, `surface` (JSON: the verified surface flags), `message` (the speaker's own words), `reply`, `calls` (JSON: tools run, results cut short), `created_at`, `reviewed_at`, `mail` (1 when the turn read mail or its chat once did: tool results not kept, rows the person's own) — a verified speaker's chat turns for the conversation review, kept 7 days |\n| `chat_review_days` | `day` (PK, UTC date), `runs` — the per-day ceiling on conversation reviews |\n| `brief_requests` | `id`, `kind` (`leave_out` / `raise`), `text`, `source_quote`, `person_id`, `session_id`, `created_at`, `expires_at`, `removed_at` — what the principal asked of their brief in chat |\n| `attunement_profile_history` | `id`, `person_id`, `created_at`, `rules`, `locked`, `updated_by` — every change to a working style |\n| `proactive_outcomes` | `id`, `created_at`, `person_id`, `source`, `ref`, `channel`, `channel_ref`, `outbound_context_id`, `outcome` (`replied` / `acted` / `ignored` / `void`, NULL while open), `resolved_at` — one row per proactive DM (Attunement outcome ledger) |\n| `delegation_settings` | `person_id` (PK), `enabled` (default 0), `updated_at`, `updated_by` — Act as me, per person; no row means off |\n| `history_notes` | `id`, `person_id`, `visibility` (`private`), `source` (`approved_reply`), `channel` (`email`), `conversation_key` (a hash of the channel and thread, never the thread id), `counterpart`, `subject`, `kind` (`promised` / `agreed` / `declined` / `answered` / `asked` / `shared`), `summary`, `quote` (the person's own words), `due_date`, `trust`, `occurred_at`, `created_at`, `expires_at` (NULL: until forgotten), `pinned`, `correction`, `corrected_at`, `kept_from` (when the retention clock started: NULL means `occurred_at`; an unpin restarts it) — Always in the loop, one row per note |\n| `history_settings` | `id` (1), `retention_days` (NULL: until forgotten; no row means 90), `updated_at`, `updated_by` — the company retention |\n| `history_person_settings` | `person_id` (PK), `reply_notes` (default 0), `retention_days` (NULL: the company's), `updated_at`, `updated_by` |\n| `history_excluded` | `person_id`, `conversation_key` (PK together), `created_at` — conversations a person asked not to remember |\n| `history_chat_passes` | `person_id`, `day` (PK together, UTC `YYYY-MM-DD`), `passes` — note passes run on a person's chat messages that day, against the daily cap; older days pruned on write |\n| `delegation_voice` | `person_id` (PK), `profile` (JSON: `greetings` per audience, `sign_off`, `signature`, `length`, `formality`, up to 8 `habits`, up to 6 `avoid`, up to 3 `exemplars`), `locked`, `learned_at`, `sample_count`, `updated_at`, `updated_by` — \"How I write\" |\n| `delegation_voice_history` | `id`, `person_id`, `created_at`, `profile`, `locked`, `updated_by` — every change to a writing profile |\n| `delegation_drafts` | `id`, `person_id`, `source` (`chat` \\| `inbox`), `thread_id`, `draft_id`, `message_id`, `sent_message_id`, `created_at`, `gone_at` (a chat draft found missing from their mailbox: sent or deleted there) — one row of ids per draft Act as me saved in someone's Gmail (no address, subject or text): the daily limit counts it, and \"How I write\" skips a chat draft's thread and a sent draft's message |\n| `delegation_inbox_watch` | `person_id` (PK), `enabled`, `watch_since` (reset on every off→on), `last_poll_at`, `status`, `backoff_until`, `failures`, `mailbox_drafts` (also save each reply in their Drafts; default 0, the reply lives on its card alone), `updated_at`, `updated_by` — **Draft replies to my inbox**, per person; no row means off |\n| `delegation_inbox_messages` | `id`, `person_id`, `message_id`, `thread_id`, `received_at`, `sender_key` (a hash of the address, never the address), `relation`, `outcome` (`processing`, `retry` — left for a later scan, `skipped`, `not_needed`, `deferred`, `failed`, `drafted`, `sent`, `dismissed`, `closed`, `expired`), `reason`, `classified`, `attempts`, `draft_id`, `decision_id`, `flags` (JSON), `created_at`, `updated_at`; `UNIQUE(person_id, message_id)` — the inbox watcher's cursor: what happened to each message it looked at |\n| `delegation_handle_it` | `person_id` (PK), `enabled`, `mode` (`careful`, `balanced` or `bold`), `levels` (the per-kind setting `mode` replaced, kept for older rows), `updated_at`, `updated_by` — **Handle it for me**, per person; no row means off. A `training` mode from before per-setting training moves to `balanced` with Replies and Follow-ups in training |\n| `delegation_training` | `person_id`, `setting` (`replies`, `follow_ups`, `actions` or `drafts`), `enabled`, `updated_at`, `updated_by`; primary key `(person_id, setting)` — Act as me settings in training, per person; no row means not in training |\n| `delegation_disclosure` | `person_id` (PK), `handle_it`, `approved_sends` (each NULL = as the install's `AI_DISCLOSURE_HANDLE_IT` / `AI_DISCLOSURE_APPROVED_SENDS`), `updated_at`, `updated_by` — the AI line on replies sent as that person; no row means the install's defaults |\n| `delegation_handled` | `id`, `person_id`, `thread_id`, `decision_id`, `sent_message_id`, `sent_at`; index on `(person_id, sent_at)` — one row per reply or follow-up Handle it for me sent on its own, read for its one-per-thread-a-day and daily limits |\n\n| `dynamic_workflows` | `name` (PK), `definition` (JSON of `DynamicWorkflowDef`), `is_active`, `created_at`, `updated_at`, `owner_person_id` (creator; set on insert only, kept out of the definition JSON) |\n| `workflow_approved_targets` | (`workflow_name`, `value`) PK, `key`, `approved_at`, `run_id` — targets a workflow's tool steps may write to without asking again; cleared when the workflow is deleted |\n| `executive_control` | `id` (PK, always 1), `paused`, `paused_at`, `paused_by`, `reason`, `updated_at` — the operator pause switch (`scheduler.pause`); operator-level, so client-slot switches carry it across |\n| `app_migrations` | `name` (PK), `applied_at` — one-shot data migrations (sweeps that must run exactly once per DB); schema DDL stays idempotent and is not recorded here |\n\n`department` and `session_id` are additive columns (default `''`); `session_id` scopes per-thread recall. `scheduled_actions.status` ∈ pending / running / done / failed / cancelled, and `scheduled_actions.kind` includes `dynamic_workflow` (a cadence-fired user-created workflow run) and `open_loop` (an Attunement open loop: `assigned_to_person_id` is the owner, `awaiting_response_since` the due time — cleared when the loop closes — and `scope_key` `loop:{owner}:{hash}`, unique among open loops via the partial index `idx_scheduled_open_loop_scope`). `chat_messages.sender_person_id` is the resolved rostered sender of a user message (never the session owner's principal fallback; NULL on legacy rows and for unrostered senders); `feedback` is `up` / `down` on an assistant reply. `dynamic_workflows` stores user-created (dynamic) workflow definitions interpreted by the generic `DynamicWorkflow` engine; the JSON `definition` holds free-text input fields and an ordered step list (specialist / approval_gate / synthesis) plus an optional cadence.\n\n### Legacy tables (talent / staff onboarding)\n\nThe talent (executive-search) and staff-onboarding features were removed. Their tables —\n`engagements`, `candidates`, `offers`, `onboarding_templates`, `onboarding_plans`,\n`onboarding_tasks` — are **not dropped**: no code creates, reads or writes them any more,\nbut rows survive on upgraded installs. `clients.slots` still wipes them when a blank client\nslot is activated (existence-guarded, a no-op on fresh installs) so a slot can never inherit\na previous client's candidate data.\n\n### Department / Goal / ChecklistItem\n\n| Model | Fields |\n|---|---|\n| `DepartmentConfig` | `slug`, `title`, `specialist_key`, `charter`, `authority_level`, `head_person_id`, `head_persona_slug`, `cadences`, `slack_channel_id`, `discord_channel_id`, `telegram_chat_id` |\n| `Goal` | `id`, `department_slug`, `period_type`, `period_value`, `key_result`, `target`, `current`, `status`, `created_at`, `updated_at`, `last_reviewed_at` |\n| `DepartmentState` | `config`, `goals`, `headcount`, `budget_usd`, `member_person_ids`, `updated_at` |\n\n`authority_level` ∈ `auto_execute` / `propose_only` / `escalate`; `Goal.status` ∈ `on_track` / `at_risk` / `off_track`.\n\n### Person\n\n| Field group | Fields |\n|---|---|\n| Identity | `id`, `full_name`, `role`, `is_principal`, `kind`, `department_slugs` |\n| Contact | `email`, `email_aliases`, `slack_user_id`, `telegram_chat_id`, `discord_user_id`, `preferred_channel`, `last_channel` / `last_channel_at` (the chat app they last talked in, and when) |\n| Routing | `availability`, `authority_scope`, `response_sla_hours`, `on_leave_until`, `reports_to_person_id` |\n| Lifecycle | `archived`, `created_at`, `updated_at` |\n\nExactly one `Person` should have `is_principal=True` — the fallback approver when no delegated person matches.\n\n`kind` is `team` (the default) or `contact` — someone outside the team, such as a client or contractor. It is an additive column, `kind TEXT NOT NULL DEFAULT 'team'`, added by the same `PRAGMA table_info`-guarded migration as `discord_user_id`, so every existing row is a team member. The principal is always `team`: the store refuses to write a principal contact (`PrincipalContactError`), and `initialize_db` repairs a hand-edited one on boot. A stored value the code does not know reads as `contact`. Every roster read in `people.store` and `people.registry` returns team members only unless it passes `include_contacts=True` (see Org).\n\n`email` is the one address a person signs in with; `email_aliases` (read from the `person_emails` table, up to 10) are other addresses they write from — they match inbound mail and may be emailed, but never sign in (see Org).\n\n### People-side tables\n\nThese live next to `people` (created by `people.store.initialize_db`, which also runs `people.roster_requests.initialize_tables`):\n\n| Table | Key columns |\n|---|---|\n| `person_emails` | `id`, `person_id` (FK → `people`, `ON DELETE CASCADE`), `email`, `email_norm` (trimmed + lowercased, **UNIQUE** across the roster), `source` (`manual` / `chat_tool` / `roster_request`), `roster_request_id`, `created_at` — a person's aliases; deleted when they are archived |\n| `person_details` | `id`, `person_id` (FK → `people`, `ON DELETE CASCADE`), `kind` (`phone` / `mobile` / `website` / `linkedin` / `social` / `address`), `value` (cleaned by `people.contact_info.clean_detail`), `source` (`manual` / `chat_tool` / `contact_keeper`), `created_at`; **UNIQUE** (`person_id`, `kind`, `value`), at most 20 a person — other ways to reach someone, read as `Person.details`, never a channel anything is sent on |\n| `contact_notes` | `person_id` (PK), `note`, `topics` (JSON), `last_emailed_at`, `last_heard_at`, `last_met_at`, `next_meeting_at`, `next_meeting_title`, `emailed_count`, `met_count`, `activity_key`, `note_written_at`, `updated_at` — what the contact keeper remembers about a contact or teammate, the principal's alone (see Org); deleted when they are archived |\n| `contact_note_tries` | `day` (PK, UTC date), `tries` — how many notes the contact keeper asked the model for that day; caps them at 20 |\n| `roster_requests` | `id`, `channel` (`email` / `slack` / `discord` / `telegram`), `channel_ref` (the address or chat id), `display_name` (sanitised, unverified), `profile_email`, `on_company_domain`, `suggested_kind`, `suggested_person_id`, `status` (`pending` / `resolving` / `approved` / `linked` / `declined` / `expired` / `superseded`), `resolved_person_id`, `resolved_kind`, `resolved_via` (`web` / `slack` / `discord` / `telegram` / `email` / `people_page`), `resolved_at`, `token_hash` (the email answer token, hashed; cleared on resolve), `confirm_message_id`, `notified_at`, `notified_channel`, `ack_sent_at`, `alert_id`, `message_count`, `first_seen_at`, `last_seen_at`, `expires_at` — one pending row per `(channel, channel_ref)` (partial unique index) |\n| `roster_request_messages` | `id`, `request_id` (FK, cascade), `external_id` (unique per request, so a redelivery is held once), `payload_json` (what the adapter needs to replay it), `preview`, `received_at`, `replay_status` (`held` / `replaying` / `replayed` / `dropped` / `failed` / `unavailable`), `replayed_at` — at most 10 per request; `payload_json` and `preview` are blanked once a message is replayed or dropped |\n| `roster_ack_log` | `id`, `channel`, `channel_ref`, `sent_at` — one row per acknowledgement sent to a new sender, for the per-sender window and the daily cap |\n\n**Take the lead tables** (`orchestrator.take_the_lead`, created on first use, per company in `clients.slots` and `reset_all_state`): `take_the_lead` (`scope` PK: `executive` or `person:<id>`, `enabled`, `training` (added in place on older databases), `updated_at`, `updated_by`; each kind's Ask first is a `decision_class_state` row for `take_the_lead_action:<kind>`); `take_the_lead_rules` (`id`, `scope`: `company` or `person:<id>`, `kind` person|domain|words|amount, `value`, `created_by`, `created_at`); `take_the_lead_log` (`id`, `at`, `scope`, `source` reflection|research|scheduled, `tool`, `summary`, `status` done|waiting|approved|declined|failed, `why`, `decision_id`). A held action is a `decision_instances` row of class `take_the_lead_action` whose payload carries the tool, its input, whether it is an MCP tool, the gate kind or rule, the reason and the summary. `take_the_lead_allowed` (`id`, `key` unique: `<feature>|<action>|<who>`, `label`, `feature`, `example` (JSON of the edited fields, or empty), `uses`, `last_used_at`, `created_by`, `created_at`, `decision_id`, `removed_at`: set by Remove, so only approvals after it count toward a new suggestion, `person_id`: whose it is for a feature that learns per person, Act as me's `act_as_me|person:<id>|<reply|follow_up|message|invite|style>|<who>`, NULL for Take the lead; added in place on older databases): what it may do on its own in training, at most `ALLOWED_MAX` (200) per feature and person.\n\n**`telegram_chats`** (episodic DB, `integrations/telegram_chats.py`) — the Telegram chats the bot has seen, because Telegram cannot list them: `chat_id` (primary key), `chat_type` (`private`, `group` or `supergroup`), `title` (a group's title or a person's name), `username`, `first_seen_at`, `last_seen_at`. The webhook upserts a row per update only when `TELEGRAM_WEBHOOK_SECRET` checked out, drops a group that moved to a supergroup id or that removed the bot, and keeps the 500 most recently seen. Private chats are people picker options and groups are room options (`GET /chat-directory/*`). Reads never create it. A blank client slot wipes it.\n",
+ "markdown": "The shapes below are the load-bearing data structures: episodic SQLite tables (in `episodic_memory.db`) and the Pydantic models for departments and people.\n\n### Episodic tables\n\n| Table | Key columns |\n|---|---|\n| `decisions` | `id`, `timestamp`, `domain`, `summary`, `rationale`, `outcome`, `tags`, `department`, `session_id` |\n| `initiatives` | `id`, `title`, `status`, `created_at`, `updated_at`, `summary`, `department` |\n| `advice_given` | `id`, `timestamp`, `domain`, `query_summary`, `advice_summary`, `department`, `session_id` |\n| `facts` | `id`, `kind` (fact / correction / profile), `subject`, `subject_key`, `statement`, `previous_statement`, `source_quote`, `source_channel`, `session_id`, `turn_id`, `recorded_by_person_id`, `created_at`, `status` (active / superseded / retired), `superseded_by`, `retired_at`, `retired_reason` |\n| `scheduled_actions` | `id`, `created_at`, `run_at`, `channel`, `channel_ref`, `intent_text`, `status`, `attempts`, `kind`, `department`, `assigned_to_person_id`, `awaiting_response_since`, `scope_key`, `required_scope`, `created_by_person_id` |\n| `outbound_context` | `id`, `created_at`, `channel`, `channel_ref`, `recipient_person_id`, `outbound_text`, `originating_session_id`, `outbound_message_id`, `consumed_at`, `status` |\n| `history_reminders` | (`person_id`, `day`) PK, `sent_at` — the days a person was reminded of notes due (`memory.history_reminders`), older days pruned on write |\n| `session_drive_files` | (`session_id`, `person_id`, `file_id`) PK, `name`, `mime_type`, `link`, `summary` (first 600 chars of an opened file), `opened`, `found_by` (the search query), `first_seen_at`, `last_seen_at` — Drive files a conversation found or opened (`memory.drive_reads`) |\n| `session_drive_searches` | `id`, `session_id`, `person_id`, `query`, `result_count`, `searched_at` — every Drive search a conversation ran |\n| `saved_tools` | `name` (PK), `description`, `enabled`, `current_version`, `workflow_version` (the version workflows may run, NULL until the owner turns it on; never set for a Python tool), `kind` (`script` for `run_script`, `python` for a kept `run_python_job`; added with default `script`), `created_at`, `updated_at` — scripts and Python jobs the Executive saved to run again (`workflows.saved_tools`) |\n| `saved_tool_versions` | (`name`, `version`) PK, `description`, `script`, `tools` (JSON: the tools the script called when saved), `origin` (`chat` or `workflow:<name>/<step>`), `created_at` |\n| `saved_tool_runs` | `id`, `name`, `version`, `ok`, `calls`, `duration_ms`, `origin`, `at` — the newest 200 runs per tool |\n| `chat_messages` | `id`, `session_id`, `role`, `content`, `created_at`, `action_chips`, `stopped`, `sender_person_id`, `feedback`, `feedback_note`, `feedback_by_person_id`, `sources` (JSON `{sources: [{kind, title, url}], unavailable: [area]}` — what an assistant reply looked at and which areas it left out; NULL on older rows) |\n| `attunement_usage` | `day` (PK, UTC date), `calls` — the per-day ceiling on open-loop extraction model calls |\n| `attunement_profiles` | `person_id` (PK), `rules` (JSON: up to 8 `{text, basis, evidence}`; basis `feedback`, `stated`, `edited` or `conversation`), `locked`, `updated_at`, `updated_by`, `last_pass_at`, `pass_day`, `passes_today`, `last_message_id` — per-person working style plus pass pacing |\n| `chat_review_turns` | `id`, `session_id`, `person_id`, `surface` (JSON: the verified surface flags), `message` (the speaker's own words), `reply`, `calls` (JSON: tools run, results cut short), `created_at`, `reviewed_at`, `mail` (1 when the turn read mail or its chat once did: tool results not kept, rows the person's own) — a verified speaker's chat turns for the conversation review, kept 7 days |\n| `chat_review_days` | `day` (PK, UTC date), `runs` — the per-day ceiling on conversation reviews |\n| `brief_requests` | `id`, `kind` (`leave_out` / `raise`), `text`, `source_quote`, `person_id`, `session_id`, `created_at`, `expires_at`, `removed_at` — what the principal asked of their brief in chat |\n| `attunement_profile_history` | `id`, `person_id`, `created_at`, `rules`, `locked`, `updated_by` — every change to a working style |\n| `proactive_outcomes` | `id`, `created_at`, `person_id`, `source`, `ref`, `channel`, `channel_ref`, `outbound_context_id`, `outcome` (`replied` / `acted` / `ignored` / `void`, NULL while open), `resolved_at` — one row per proactive DM (Attunement outcome ledger) |\n| `delegation_settings` | `person_id` (PK), `enabled` (default 0), `updated_at`, `updated_by` — Act as me, per person; no row means off |\n| `history_notes` | `id`, `person_id`, `visibility` (`private`), `source` (`approved_reply`), `channel` (`email`), `conversation_key` (a hash of the channel and thread, never the thread id), `counterpart`, `subject`, `kind` (`promised` / `agreed` / `declined` / `answered` / `asked` / `shared`), `summary`, `quote` (the person's own words), `due_date`, `trust`, `occurred_at`, `created_at`, `expires_at` (NULL: until forgotten), `pinned`, `correction`, `corrected_at`, `kept_from` (when the retention clock started: NULL means `occurred_at`; an unpin restarts it) — Always in the loop, one row per note |\n| `history_settings` | `id` (1), `retention_days` (NULL: until forgotten; no row means 90), `updated_at`, `updated_by` — the company retention |\n| `history_person_settings` | `person_id` (PK), `reply_notes` (default 0), `retention_days` (NULL: the company's), `updated_at`, `updated_by` |\n| `history_excluded` | `person_id`, `conversation_key` (PK together), `created_at` — conversations a person asked not to remember |\n| `history_chat_passes` | `person_id`, `day` (PK together, UTC `YYYY-MM-DD`), `passes` — note passes run on a person's chat messages that day, against the daily cap; older days pruned on write |\n| `delegation_voice` | `person_id` (PK), `profile` (JSON: `greetings` per audience, `sign_off`, `signature`, `length`, `formality`, up to 8 `habits`, up to 6 `avoid`, up to 3 `exemplars`), `locked`, `learned_at`, `sample_count`, `updated_at`, `updated_by` — \"How I write\" |\n| `delegation_voice_history` | `id`, `person_id`, `created_at`, `profile`, `locked`, `updated_by` — every change to a writing profile |\n| `delegation_drafts` | `id`, `person_id`, `source` (`chat` \\| `inbox`), `thread_id`, `draft_id`, `message_id`, `sent_message_id`, `created_at`, `gone_at` (a chat draft found missing from their mailbox: sent or deleted there) — one row of ids per draft Act as me saved in someone's Gmail (no address, subject or text): the daily limit counts it, and \"How I write\" skips a chat draft's thread and a sent draft's message |\n| `delegation_inbox_watch` | `person_id` (PK), `enabled`, `watch_since` (reset on every off→on), `last_poll_at`, `status`, `backoff_until`, `failures`, `mailbox_drafts` (also save each reply in their Drafts; default 0, the reply lives on its card alone), `updated_at`, `updated_by` — **Draft replies to my inbox**, per person; no row means off |\n| `delegation_inbox_messages` | `id`, `person_id`, `message_id`, `thread_id`, `received_at`, `sender_key` (a hash of the address, never the address), `relation`, `outcome` (`processing`, `retry` — left for a later scan, `skipped`, `not_needed`, `deferred`, `failed`, `drafted`, `sent`, `dismissed`, `closed`, `expired`), `reason`, `classified`, `attempts`, `draft_id`, `decision_id`, `flags` (JSON), `created_at`, `updated_at`; `UNIQUE(person_id, message_id)` — the inbox watcher's cursor: what happened to each message it looked at |\n| `delegation_handle_it` | `person_id` (PK), `enabled`, `mode` (`careful`, `balanced` or `bold`), `levels` (the per-kind setting `mode` replaced, kept for older rows), `updated_at`, `updated_by` — **Handle it for me**, per person; no row means off. A `training` mode from before per-setting training moves to `balanced` with Replies and Follow-ups in training |\n| `delegation_training` | `person_id`, `setting` (`replies`, `follow_ups`, `actions` or `drafts`), `enabled`, `updated_at`, `updated_by`; primary key `(person_id, setting)` — Act as me settings in training, per person; no row means not in training |\n| `delegation_disclosure` | `person_id` (PK), `handle_it`, `approved_sends` (each NULL = as the install's `AI_DISCLOSURE_HANDLE_IT` / `AI_DISCLOSURE_APPROVED_SENDS`), `updated_at`, `updated_by` — the AI line on replies sent as that person; no row means the install's defaults |\n| `delegation_handled` | `id`, `person_id`, `thread_id`, `decision_id`, `sent_message_id`, `sent_at`; index on `(person_id, sent_at)` — one row per reply or follow-up Handle it for me sent on its own, read for its one-per-thread-a-day and daily limits |\n\n| `dynamic_workflows` | `name` (PK), `definition` (JSON of `DynamicWorkflowDef`), `is_active`, `created_at`, `updated_at`, `owner_person_id` (creator; set on insert only, kept out of the definition JSON) |\n| `workflow_approved_targets` | (`workflow_name`, `value`) PK, `key`, `approved_at`, `run_id` — targets a workflow's tool steps may write to without asking again; cleared when the workflow is deleted |\n| `executive_control` | `id` (PK, always 1), `paused`, `paused_at`, `paused_by`, `reason`, `updated_at` — the operator pause switch (`scheduler.pause`); operator-level, so client-slot switches carry it across |\n| `app_migrations` | `name` (PK), `applied_at` — one-shot data migrations (sweeps that must run exactly once per DB); schema DDL stays idempotent and is not recorded here |\n\n`department` and `session_id` are additive columns (default `''`); `session_id` scopes per-thread recall. `scheduled_actions.status` ∈ pending / running / done / failed / cancelled, and `scheduled_actions.kind` includes `dynamic_workflow` (a cadence-fired user-created workflow run) and `open_loop` (an Attunement open loop: `assigned_to_person_id` is the owner, `awaiting_response_since` the due time — cleared when the loop closes — and `scope_key` `loop:{owner}:{hash}`, unique among open loops via the partial index `idx_scheduled_open_loop_scope`). `chat_messages.sender_person_id` is the resolved rostered sender of a user message (never the session owner's principal fallback; NULL on legacy rows and for unrostered senders); `feedback` is `up` / `down` on an assistant reply. `dynamic_workflows` stores user-created (dynamic) workflow definitions interpreted by the generic `DynamicWorkflow` engine; the JSON `definition` holds free-text input fields and an ordered step list (specialist / approval_gate / synthesis) plus an optional cadence.\n\n### Legacy tables (talent / staff onboarding)\n\nThe talent (executive-search) and staff-onboarding features were removed. Their tables —\n`engagements`, `candidates`, `offers`, `onboarding_templates`, `onboarding_plans`,\n`onboarding_tasks` — are **not dropped**: no code creates, reads or writes them any more,\nbut rows survive on upgraded installs. `clients.slots` still wipes them when a blank client\nslot is activated (existence-guarded, a no-op on fresh installs) so a slot can never inherit\na previous client's candidate data.\n\n### Department / Goal / ChecklistItem\n\n| Model | Fields |\n|---|---|\n| `DepartmentConfig` | `slug`, `title`, `specialist_key`, `charter`, `authority_level`, `head_person_id`, `head_persona_slug`, `cadences`, `slack_channel_id`, `discord_channel_id`, `telegram_chat_id` |\n| `Goal` | `id`, `department_slug` (nullable: a goal may have no department), `owner_person_id` (nullable: follow the department's head, else the principal), `period_type`, `period_value`, `key_result`, `target`, `current`, `status`, `created_at`, `updated_at`, `last_reviewed_at` |\n| `DepartmentState` | `config`, `goals`, `headcount`, `budget_usd`, `member_person_ids`, `updated_at` |\n\n`authority_level` ∈ `auto_execute` / `propose_only` / `escalate`; `Goal.status` ∈ `on_track` / `at_risk` / `off_track`.\n\n### Person\n\n| Field group | Fields |\n|---|---|\n| Identity | `id`, `full_name`, `role`, `is_principal`, `kind`, `department_slugs` |\n| Contact | `email`, `email_aliases`, `slack_user_id`, `telegram_chat_id`, `discord_user_id`, `preferred_channel`, `last_channel` / `last_channel_at` (the chat app they last talked in, and when) |\n| Routing | `availability`, `authority_scope`, `response_sla_hours`, `on_leave_until`, `reports_to_person_id` |\n| Lifecycle | `archived`, `created_at`, `updated_at` |\n\nExactly one `Person` should have `is_principal=True` — the fallback approver when no delegated person matches.\n\n`kind` is `team` (the default) or `contact` — someone outside the team, such as a client or contractor. It is an additive column, `kind TEXT NOT NULL DEFAULT 'team'`, added by the same `PRAGMA table_info`-guarded migration as `discord_user_id`, so every existing row is a team member. The principal is always `team`: the store refuses to write a principal contact (`PrincipalContactError`), and `initialize_db` repairs a hand-edited one on boot. A stored value the code does not know reads as `contact`. Every roster read in `people.store` and `people.registry` returns team members only unless it passes `include_contacts=True` (see Org).\n\n`email` is the one address a person signs in with; `email_aliases` (read from the `person_emails` table, up to 10) are other addresses they write from — they match inbound mail and may be emailed, but never sign in (see Org).\n\n### People-side tables\n\nThese live next to `people` (created by `people.store.initialize_db`, which also runs `people.roster_requests.initialize_tables`):\n\n| Table | Key columns |\n|---|---|\n| `person_emails` | `id`, `person_id` (FK → `people`, `ON DELETE CASCADE`), `email`, `email_norm` (trimmed + lowercased, **UNIQUE** across the roster), `source` (`manual` / `chat_tool` / `roster_request`), `roster_request_id`, `created_at` — a person's aliases; deleted when they are archived |\n| `person_details` | `id`, `person_id` (FK → `people`, `ON DELETE CASCADE`), `kind` (`phone` / `mobile` / `website` / `linkedin` / `social` / `address`), `value` (cleaned by `people.contact_info.clean_detail`), `source` (`manual` / `chat_tool` / `contact_keeper`), `created_at`; **UNIQUE** (`person_id`, `kind`, `value`), at most 20 a person — other ways to reach someone, read as `Person.details`, never a channel anything is sent on |\n| `contact_notes` | `person_id` (PK), `note`, `topics` (JSON), `last_emailed_at`, `last_heard_at`, `last_met_at`, `next_meeting_at`, `next_meeting_title`, `emailed_count`, `met_count`, `activity_key`, `note_written_at`, `updated_at` — what the contact keeper remembers about a contact or teammate, the principal's alone (see Org); deleted when they are archived |\n| `contact_note_tries` | `day` (PK, UTC date), `tries` — how many notes the contact keeper asked the model for that day; caps them at 20 |\n| `roster_requests` | `id`, `channel` (`email` / `slack` / `discord` / `telegram`), `channel_ref` (the address or chat id), `display_name` (sanitised, unverified), `profile_email`, `on_company_domain`, `suggested_kind`, `suggested_person_id`, `status` (`pending` / `resolving` / `approved` / `linked` / `declined` / `expired` / `superseded`), `resolved_person_id`, `resolved_kind`, `resolved_via` (`web` / `slack` / `discord` / `telegram` / `email` / `people_page`), `resolved_at`, `token_hash` (the email answer token, hashed; cleared on resolve), `confirm_message_id`, `notified_at`, `notified_channel`, `ack_sent_at`, `alert_id`, `message_count`, `first_seen_at`, `last_seen_at`, `expires_at` — one pending row per `(channel, channel_ref)` (partial unique index) |\n| `roster_request_messages` | `id`, `request_id` (FK, cascade), `external_id` (unique per request, so a redelivery is held once), `payload_json` (what the adapter needs to replay it), `preview`, `received_at`, `replay_status` (`held` / `replaying` / `replayed` / `dropped` / `failed` / `unavailable`), `replayed_at` — at most 10 per request; `payload_json` and `preview` are blanked once a message is replayed or dropped |\n| `roster_ack_log` | `id`, `channel`, `channel_ref`, `sent_at` — one row per acknowledgement sent to a new sender, for the per-sender window and the daily cap |\n\n**Take the lead tables** (`orchestrator.take_the_lead`, created on first use, per company in `clients.slots` and `reset_all_state`): `take_the_lead` (`scope` PK: `executive` or `person:<id>`, `enabled`, `training` (added in place on older databases), `updated_at`, `updated_by`; each kind's Ask first is a `decision_class_state` row for `take_the_lead_action:<kind>`); `take_the_lead_rules` (`id`, `scope`: `company` or `person:<id>`, `kind` person|domain|words|amount, `value`, `created_by`, `created_at`); `take_the_lead_log` (`id`, `at`, `scope`, `source` reflection|research|scheduled, `tool`, `summary`, `status` done|waiting|approved|declined|failed, `why`, `decision_id`). A held action is a `decision_instances` row of class `take_the_lead_action` whose payload carries the tool, its input, whether it is an MCP tool, the gate kind or rule, the reason and the summary. `take_the_lead_allowed` (`id`, `key` unique: `<feature>|<action>|<who>`, `label`, `feature`, `example` (JSON of the edited fields, or empty), `uses`, `last_used_at`, `created_by`, `created_at`, `decision_id`, `removed_at`: set by Remove, so only approvals after it count toward a new suggestion, `person_id`: whose it is for a feature that learns per person, Act as me's `act_as_me|person:<id>|<reply|follow_up|message|invite|style>|<who>`, NULL for Take the lead; added in place on older databases): what it may do on its own in training, at most `ALLOWED_MAX` (200) per feature and person.\n\n**`telegram_chats`** (episodic DB, `integrations/telegram_chats.py`) — the Telegram chats the bot has seen, because Telegram cannot list them: `chat_id` (primary key), `chat_type` (`private`, `group` or `supergroup`), `title` (a group's title or a person's name), `username`, `first_seen_at`, `last_seen_at`. The webhook upserts a row per update only when `TELEGRAM_WEBHOOK_SECRET` checked out, drops a group that moved to a supergroup id or that removed the bot, and keeps the 500 most recently seen. Private chats are people picker options and groups are room options (`GET /chat-directory/*`). Reads never create it. A blank client slot wipes it.\n",
"mermaid": null,
- "generated_at": "2026-10-20T11:06:00Z"
+ "generated_at": "2026-10-21T00:00:00Z"
}
diff --git a/packages/core/openexecutive/architecture/prebuilt/today.json b/packages/core/openexecutive/architecture/prebuilt/today.json
index f289ef42..540f58d5 100644
--- a/packages/core/openexecutive/architecture/prebuilt/today.json
+++ b/packages/core/openexecutive/architecture/prebuilt/today.json
@@ -1,7 +1,7 @@
{
"section_id": "today",
"title": "Today / Morning Brief",
- "markdown": "`openexecutive.api.routes.today` serves the morning brief — a one-screen, read-only view of what is happening across the org. It is the default landing surface (the Next.js root renders `<Briefing>`). Every signed-in page shares one sidebar (`AppSidebar`). Its Recent list is capped at the 7 newest web chats. The full history, including Slack, Telegram and Discord conversations (recognised by their session-id prefix), lives on `/chats`. A chat opens from any page through `/?session=<id>`.\n\n`GET /today` returns `TodayResponse` assembled by `_build_today()`, which is synchronous and caller-agnostic:\n\n- **`departments`** — per-department goal health, rolling up each department's goal counts (`total`, `at_risk`, `off_track`) plus its awaiting-workflow count, and `attention_goals`: the actual off-track/at-risk goals (worst first, capped at 3) with `key_result`, `current`, `target`, and `status`, so the briefing's Department card shows *which* goal is off and how far without a click. Empty for healthy/inactive departments.\n- **Private cards.** An alert tagged `private:principal` (`alerts.models.PRIVATE_ALERT_TAG` — raised on a turn about mail from one of the principal's contacts or mail they forwarded, or a meeting proposal with a contact) is in `proposals` only when the caller is the principal. The chat's alert digest (`briefing.context.render_and_trust`) shows it, and the roster requests, only on the principal's own verified turn, never in a web chat they shared with others, where everyone reads the reply. `_build_today` leaves it out by default, so the end-of-day digest, the reflection and Discord's `/today` never see it, and the morning brief reads it only on a run for the principal (the scheduler's, or the principal's own verified chat turn in a conversation only they can read — see Workflows). The narrative is written from one only in the principal's own `principal` scope, which nobody else is served; the shared `company` scope an unresolved caller gets, and a teammate's scope, never are. The activity rail skips it, and the chat digest includes it only on the principal's own verified turn.\n- **Raised by a team member.** An alert a team member raised from chat (`AlertEvent.raised_by`, source `team_member`) has its body led by \"Raised by <name>.\" and never goes out on `company_broadcast`: the pipeline drops that channel after `resolve_channels`, so it reaches a person or a department room only. One team member's alert never coalesces into another's (the dedup key is prefixed with who raised it). A team member's saved workflow raises alerts as its creator (`action_step` binds `dynamic_store.get_owner` around `oe__create_alert`). Alerts from email, watches and other sources are unchanged.\n- **Who clears a card.** `POST /alerts/{id}/ack` with `ack` or `dismissed` answers 403 to a team member unless the alert is routed to them (`read` is open to anyone who can see it); only the principal's dismiss applies `mute_topic`, since a mute silences the topic for everyone. `POST /alerts/bulk-ack` from a team member clears only the listed ids routed to them and refuses an `older_than_days` sweep. The principal, or anyone before a principal is set up, clears anything. `ack_alert` in chat follows the same rule.\n- **Roster-request cards.** When someone not on the People list writes in (see Org and Integrations), `people.roster_requests.surface_card` raises an alert of source `roster_request` (medium, tagged `roster_request:<id>` and `private:principal`, routed to the principal), so it follows every private-card rule above. `GET /today` attaches `roster_request` to that proposal (`_roster_request_card`: channel, address or account id, the sender's sanitised and unverified name, profile email, company-domain flag, suggested kind and person, message count, whether they were acknowledged, first seen, and the held messages' first lines) while the request is still pending. The Briefing renders it as its own card (`RosterRequestCard`: add as a new person with a name and an explicit team/contact choice — pre-filled as team on a company domain — or \"someone already on the list\", with a replace-account option for a chat id, or Ignore), which calls `/people/requests/{id}` directly and never hands off to chat, so what a stranger wrote never seeds a turn. The card is kept out of everything that could close it without answering it or put the stranger's words in front of a model: the narrative (`_action_proposals` drops it), the chat's open-alert digest (`<briefing>` — the principal's verified turn gets a separate `<roster_requests>` block instead; see Agents), `ack_alert`, a single ack (`POST /alerts/{id}/ack` is a 409), the \"Dismiss N older than 7 days\" count and the server's bulk ack, reopen, the TTL sweep and the alert review (`roster_request` is in `lifecycle.TTL_EXEMPT_SOURCES`). It ends when the request does: answered (`ack`, or `dismissed` on a decline) or expired after `ROSTER_REQUEST_TTL_DAYS`.\n- **`people`** — an attention-ranked roster of the **team** (the principal's contacts are never listed, and get no insight note). Each person carries `awaiting_action` count, soonest SLA, a `status` (`on_leave` / `needs_reply` / `awaiting` / `clear`), reachability, `overdue`, a server `priority` sort key, and a cached one-line `insight`. Sorted by `(-priority, full_name)`. Stale insight notes are regenerated in the background only when the roster has more than one person: the UI shows the People sidebar only for more than one, so a one-person install (solo, or a team before anyone else is added) does not pay a daily model and peer-memory call for a note nobody sees. Cached notes are still served.\n- **`proposals`** — the *live* unread alerts (workflow approvals, triage-classified inbound, Executive signals, flagged artifacts, and gated calendar bookings; an artifact is listed only to its owner (`alerts.models.visible_alert`; every other build of the board — the briefs, the reflection, the review, the chat digest on anyone else's turn, the activity rail — leaves drafted artifacts out) and carries `artifact_format` / `artifact_url` and a `body` already rendered to Markdown for its format, so the card badges it as a web page, Word doc, spreadsheet or link and offers *Open artifact*): unread, inside their category TTL, not snoozed — see *Alert lifecycle* below. Each carries `score`, `category` (`action` vs `monitoring`), `surfaced_reason` from `openexecutive.briefing.ranking`, the lifecycle fields (`occurrence_count`, `last_seen_at`, `last_reviewed_at`, `review_verdict`, `review_note`, `recommended_move`, `why_now`, `due_at`, `superseded_count`, `suggested_workflow`), and `decision_instance_id` (set only when the proposal is backed by a decision-ledger row — a calendar booking awaiting approval). `failed_run_id` is set only on a `workflow_failed` card (a scheduled run that ended in error, see Scheduler): its main button is **Run again** (`POST /workflows/runs/{id}/rerun`, which also closes the card) and its ⋯ opens the run; it has no Approve. The response also carries `held_back` for the principal alone: the lines grounding left out of the morning brief or end-of-day digest in the last day, which Home lists under **Left out of your brief** (the brief's note names it; Hide is remembered in that browser). The UI splits them into 'mine' vs 'across the team' using `caller_person_id`. Approve is carried out on the server for every card. For decision-backed proposals the card's Approve/Reject call the `/decisions` endpoints (which book or cancel the event server-side and clear the alert), so meeting bookings are reviewed in the briefing itself rather than on a separate page. Every other proposal is approved at `POST /alerts/{id}/approve` (`alerts.approvals`): it records who approved the card and when (an `alert_approvals` row plus `alert_approved`, then `alert_approval_done` / `alert_approval_failed`, audit rows), claims the card in one transaction so a double click or a second approver gets a 409 and the work runs once, then does the work. A card the scheduler filed for a department-gated action is bound to it server-side (`alert_held_actions`, written only as the card is filed, never read from the card's tags or text, which a model reading inbound mail can write), and approving it queues that exact action again with no department, the approval being the consent the gate waited for. Any other proposal runs one Executive turn as the approver in a new chat on the server (`chat.start_background_turn`, the machinery behind `POST /chat/background`), with the edited text verbatim for Edit & approve; it keeps going if the page closes. Only the card's routed person or the principal may approve a routed card, and only the principal an unrouted one (403 otherwise); the card's text reaches the turn as quoted data, not instructions. A row at the top of Needs you follows the approval (`GET /alerts/approvals/{id}`): working on it with a link to the chat, then done, or didn't work with Try again; a card whose last approval failed can be approved again, and one still running at a restart is marked failed on boot. The page no longer acks the card and seeds a chat turn with the proposal, which left no record of the approval and did nothing if the tab closed first.\n- **`narrative`** — a per-viewer Executive-voice header (\"What's going on\") synthesized by `synthesize_briefing_narrative`, cached per scope in `briefing_narrative`: the resolved principal gets the whole-company `principal` scope (which may carry what is private to them), a caller who resolves to no roster row the shared `company` scope (written from what everyone may see), and each teammate a role-scoped `person:<id>` one. `narrative_generated_at` says when the served text was written and `narrative_stale` whether a fresher one is being written now. Home shows it as **Right now**, a card above Needs you, because the text is rewritten through the day: `briefing.right_now.split_narrative` splits the served text into `narrative_lead` (the bold opener), `narrative_points` (`{text, since}`) and `narrative_move`. `since` is when that point first appeared today, kept per scope and local day in `briefing_point_seen` (keyed by the point's bold subject, so a reworded point keeps its time; recorded when a header is written, earlier days pruned then). `narrative_seen_at` is when this reader last looked, from `briefing_reader_seen`, set by `POST /today/seen` (same scope resolution as `GET /today`; the shared `company` scope of unrostered callers keeps no look, so one stranger's visit never resets another's); the page fixes it as the baseline for the visit, marks points after it with a green dot and *N new since …*, and only counts a look from earlier the same day. For the principal the response also carries `morning_brief` (`{at, text}`, today's delivered morning brief from `brief_state.last_delivered`) and `calendar_next` (up to 3 meetings still ahead today from the cached calendar read, never a fresh call), which the side panel shows under the points and Move today. Nothing here calls a model. In the web UI each bullet of this narrative is a click target: clicking one hands off to chat (the same `onContinue` path as the proposal cards) seeded to discuss that item. The Executive recognizes it because every chat turn now carries a `<briefing>` digest of open alerts (see Memory). That digest (`briefing.context.format_open_alerts_for_prompt`) is capped at 30 items; when the board is longer the header says so explicitly and tells the Executive to point at this page for the rest — it previously presented the capped list as the complete board, so the Executive described a slice as everything that was open (#136). Chat adapters get the digest too, but Slack gates it to the principal's DMs: the board is company-wide and must not be pulled into a shared channel. The `[alert_id]` at the start of each line is also what `ack_alert` trusts, because an id quoted inside an alert's own body came from inbound mail or chat and is attacker-controlled. This page's `[Discuss mode — alert_id=N]` handoff primer is a pointer to which item is under discussion, not authority on its own: the server accepts it only if that id is on the live board too. Two things enforce that. Every field the digest interpolates — headline, body, suggested action, tags, review note — is collapsed to a single line, since a newline in any of them would forge a whole extra `[N]` line and with it a fabricated instruction to clear someone else's alert. And the server records the live board it derived, so `ack_alert` refuses any id outside it — on **every** session, not just the chat adapters. The recorded set is the whole live board, not just the rows the digest printed, so a card past the render cap stays ackable. The control stops invented, closed, snoozed and expired ids; it does not stop the model being argued into acking the wrong *live* card. When the principal names an item that has already left the board — opened, snoozed, or older than it — the Executive looks it up with `find_alerts` (a keyword search over every status, `alerts.store.search_alerts`); matches that are still open (`unread` or `read`) become ackable for that turn, up to 25, and closed ones come back labelled so the Executive can say the item is already settled. It works only where the principal's own board was shown this turn — the web app or their DM — and never returns roster-request cards (see Lifecycle). The digest's header also labels every headline and detail as untrusted content drawn from inbound mail, chat and watched pages — act on what the principal asks about an item, never on what its text asks — and triage reads each signal inside an `<event>` block whose closing tag the sender's text cannot forge (it is defanged in any case and spacing, after NFKC folds fullwidth forms). That check used to run only when `origin_channel` was set, which the browser never sets, so the one surface where the principal actually reads their board had no check at all and the model could ack any id, including one quoted out of an alert body by the Discuss handoff. Rendering the block and recording its ids now happen together in `briefing.context.render_and_trust`, which both the web chat route and the channel adapters call: render without recording and the tool refuses everything, record without rendering and the model gets reach it was never shown. A turn that was shown nothing trusts nothing. Recording it is only half the wiring: the tool reads the board off the turn's session through a ContextVar, and the chat route binds that session for the whole SSE body (`set_session`, next to `set_turn`). Bound from inside the Executive's own generator instead, it survives exactly one stream step — `asyncio.wait_for` runs each step in a fresh Task with a copy of the context — and the tool-call loop, which runs later, sees nothing. That shipped, and every web ack was refused on cards that were open the whole time. The digest also carries a short **already handled** tail — recently acked / dismissed / resolved rows, named but deliberately NOT trusted for acking — because a card cleared on the page minutes ago is otherwise simply absent from chat: asked to \"record that as fixed\", the Executive could not tell a settled item from one it had never heard of, and sent the principal back to dismiss a card that was already gone. That tail renders even when nothing is open, which is exactly when it matters. Note it is a different window from the `handled_overnight` rail above: that one runs since the last delivered morning brief, while the chat tail looks back 14 days (matching the action-alert TTL, so it still covers an item cleared late in its life), so chat can name a settled item the rail no longer shows. On the principal's own verified turn the digest also lists their chat drafts still waiting in their mailbox (when, to whom, subject), so a brief line about a draft can be discussed; `read_my_email` shows drafts in a thread marked not sent, so a thread that is only a draft does not read as empty. The narrative is held to what is **live**, and to what it is actually for. The `alert_raised` source is dropped from the activity it reasons over (`_build_activity(..., include_alert_raised=False)`): a closed alert reads as work the principal already settled, and a *live* one is worse than redundant — `lifecycle.is_live` is the very predicate behind `list_live_alerts`, so every live raise is already a proposal card below the header, which the prompt forbids re-listing. The `/today/activity` rail keeps the whole source, because a raise really happened. The activity block is only labelled \"since last brief\" when the caller bounded it with `since` (the standalone briefs do; the header does not), since calling an unbounded history rail a delta made the header present weeks-old rows as overnight news. When the viewer's slice holds nothing that wants a decision — no action proposal, no at-risk/off-track department, nobody awaiting — the regen skips the model call entirely and writes the fixed quiet line (`Quiet right now — nothing pressing.`, or `… nothing needs you.` for a teammate). **The cache key is a hash of the rendered context itself** (`today._narrative_context` builds it once and both the hot path and the background task key off that one string, which is also handed to the model verbatim). That makes the key a function of the model's input: everything the prompt renders is covered, and nothing it omits can trigger a regeneration. Keying on hand-picked fields broke one half or the other each time — headlines alone left the rendered activity block uncovered, while the proposals' review fields are never rendered by this header yet are rewritten with fresh prose by every `alerts.review` pass, so they regenerated each viewer's narrative several times a day to re-synthesize identical input. A quiet board keys off a fixed sentinel instead, so a moving rail cannot re-key an entry whose text is constant. Together: on a fully dismissed board every other input was empty, the rail became the only context, and the model synthesized a confident header out of closed items.\n\n **Right now's context and its check.** The whole-company header (Home's Right now card, directly above Needs you) is written from `briefing.header_context.render_header_context`, not `render_briefing_context`. **MOVED TODAY** lists, each tagged `[M1]`, `[M2]`…, what happened or came due today: INBOUND mail and chat from other people, STUCK replies and waiting drafts, decisions raised today (with their why-now) or re-raised today, the principal's own open loops due today or overdue (`due_soon`, now in team mode too on the principal's scope), the Executive's follow-ups (`in_flight`) due today or overdue, overdue replies from people it waits on (team only), things it could not do from a chat (the brief-requests raise lines), work it finished today (activity rows from the local day, minus `advice_given` / `decision_logged`, which come from the reader's chats) and today's watchlist signals. **COMING UP TODAY** is the rest of the calendar, tagged the same way. **STILL OPEN** is what sits in Needs you and did not move (older decisions, later due dates, later follow-ups, goals at risk): background for ranking, never a point. **BACKGROUND** holds the reader's chat titles and own messages, only to judge what matters most to them. The rest of the history rail is never read: it made the header report yesterday's DMs as news, and chat titles made it claim work in progress (\"I'm combining the PDFs now\") hours after it was done. The prompt (`_header_prompt`) asks for a bold opener, **one to three** bullets that each end with the tag of the line they are about, and a **Move today** line for the reader. After the model, `header_context.keep_cited_points` deletes any bullet citing no tag the context had (`tags_in`), strips the tags and keeps at most three; a draft left with no cited point (an opener or Move today alone included) is replaced by the fixed nothing-new line, unless it is just the quiet line. The cache key also carries the brief model, so switching the Executive's model rewrites the header on the next view. With no MOVED TODAY line (a calendar alone does not count) there is no model call: an empty board writes the quiet line (`QUIET_CONTEXT`), and open items with nothing new write `Nothing new today — what's open is below.` (`NOTHING_MOVED_CONTEXT`). Every brief (this header, a teammate's header, the morning brief, the end-of-day digest) is written with `narrative.brief_model()`: the Executive's own model (its Council pick, else `DEFAULT_MODEL`), not the background `ROUTING_MODEL`. A teammate's header keeps the older render below. The paragraphs that follow describe the live signals MOVED TODAY reads.\n\n**Live, not just the board.** The header used to reason over the alert board, goal health and the Executive's own bookkeeping only — mail and chat handled that day, replies the gate held and the next meeting never reached it, so it read the same for days while the principal's day moved on. The whole-company scopes now open the context with the principal's world as it is happening (`briefing.live_signals.gather_live_signals`, rendered by `render_live_blocks`), under a `NOW:` line: **INBOUND** (`integration_inbound` audit rows that carry a message, one per message id, grouped by sender and subject, with an email's first line; the principal's own mail reads \"from the principal\", an email from the roster says \"the Executive replied\" only when a reply was logged in its thread after it (`unanswered_mail.record_reply`) and \"no reply went out\" while its `unanswered_mail` card is open (on the principal's own read only), and a time on another day carries its weekday and date), **STUCK** (`integration_outbound_blocked` to a recipient, the inbound \"reply blocked at outbound gate\" and Google Chat \"left unanswered\" / \"not delivered\" rows, and chat drafts Act as me saved in the principal's mailbox that are still there: `delegation_drafts` rows not yet marked sent or `gone_at`; before each scheduled header refresh, each morning brief and, at most every 2 minutes, the principal opening `/today` (`today._maybe_settle_on_view`, which runs `refresh_principal_narrative` after the response, so this holds even with the background header refresh slowed or off), `live_signals.settle_principal_drafts` looks up the principal's open chat drafts from the last two days in their mailbox and marks the ones sent or deleted there, answered by a message of their own sent in that thread after the draft, or sent another way: one read of their latest 15 sent messages, only while a draft is still there, finds one sent after the draft with the same subject (Re:/Fwd: aside) to one of the same people, as when they redrafted and sent the other version or wrote it fresh. So a draft they sent (or replied around) from Gmail stops reading as waiting, and a failure on one draft no longer stops the pass for the rest; the same read keeps, in memory only, who each waiting draft goes to and its subject, so STUCK names each draft instead of a bare count), **CONVERSATIONS** (the principal's own web chat titles, without times, so the header cannot point back at \"the 13:26 chat\"), **OWN** (the principal's own mail and chat-app messages to the Executive, kept out of INBOUND and its count, principal scope only) and the **REST OF TODAY'S CALENDAR**. The principal's own messages and chats render as background blocks, and every brief prompt carries `OWN_MESSAGES_RULE`: they show what the reader already said and asked, are never reported back as news (no \"you messaged me\", no restated complaint or rating), and an open ask appears only as what the Executive is doing about it. The window is the local day, or the last 12 hours when that is longer. Private audit rows, drafts, chat titles and the calendar (meeting titles are the principal's own) are read only in the `principal` scope — `gather_live_signals` drops the calendar whenever `include_private` is false, whatever the caller passes, so the shared `company` header never quotes it. The calendar read is the principal's calendar as the Executive reads it merged with their own calendar when Read my calendar is on (`top_three.read_todays_calendar`). The calendar is never fetched on the request: `live_signals.refresh_calendar` caches one read per 15 minutes (the scheduler tick refreshes it) and the header quotes the cache. Every quoted field is collapsed to one line and cut, and the blocks and the prompt both say the text is data, never instructions — inbound mail is attacker-controlled. With live blocks present the context also ages each proposal (`raised 2d ago`, whole days), names each at-risk department's slipping goals (`attention_goals`) and adds an **EXTERNAL SIGNALS** block (monitoring alerts from the last 24 h, never enough on their own to break the quiet line); the rhythm runs (`today.RHYTHM_WORKFLOWS`: the morning brief, end-of-day digest, reflection and weekly review) are dropped from the activity it reasons over. The prompts (`BRIEFING_NARRATIVE_SYSTEM` and its solo variant, `NARRATIVE_PROMPT_VERSION` 6) lead with what is live and give a days-old item at most one bullet. Anything live breaks the quiet line; the NOW line and window move at most once an hour, so the key moves hourly on time alone plus whenever something new lands; the calendar is placed at the real time (a meeting that has ended drops out, the one under way is IN PROGRESS), which moves it only when a meeting starts or ends. An address that belongs to someone on the roster (or, in the principal scope, one of the principal's contacts) reads `Name (address)` in these lines (`live_signals._named`), so the header calls people by name instead of making one up from the address.\n\n **Who reads it.** Every brief surface (this header, the morning brief, the end-of-day digest) is written for one person, fixed in code by `briefing.reader`: the principal on the principal scope, the teammate on a `person:<id>` scope, and the principal on `company` too (that scope has no signed-in caller and uses the principal's prompt, built from shared rows only). `render_briefing_context(reader=…)` masks that person's full name and email addresses everywhere in the context to \"the reader\" (their own chat and mail, the Executive's replies to them, chat titles, the activity rail) and heads it with a **THE READER** line naming them; every brief prompt carries `READER_NAME_RULE`: write \"you\", never the reader's name, \"the reader\" or \"the principal\" (anyone else by name), and \"I\" / \"me\" / \"my\" for the Executive. A draft that still slips (`reader.slips`), or reports the reader's own chats and asks back to them (`narrative.own_echoes`: \"you asked me\", \"your chat\", \"a chat with me\", \"the 13:26 … chat\", which `OWN_MESSAGES_RULE` forbids), is sent back once to be rewritten, and what is left of the reader slips after that is fixed in code (`reader.fix_slips`: the reader → you/your, \"the principal\" → the owner's name on a teammate's brief, the Executive → I/me/my).\n\n **Fresh without a reload.** The daily floor in the key and the PERIOD line are the principal's **local** date (`narrative_cache.local_today`), not UTC's, and a row written on an earlier local day is not served as today's. Regenerations are serialized per scope; a trigger that finds one running marks the scope pending and the running pass goes round once more (it built its context before that trigger's news landed), and after a failed pass (model error, the 33 s timeout: 25 s for the draft and 8 s for a rewrite, empty text) no view or tick starts another for 5 minutes and `narrative_stale` reads false, so the page drops its placeholder instead of spending a model call per view. They log `today: narrative served scope=… age_s=… stale=…` and `today: narrative regenerated scope=… ms=…`, and no longer need a page view: every `BRIEFING_NARRATIVE_REFRESH_MINUTES` (10) between `BRIEFING_NARRATIVE_REFRESH_START_HOUR` and `_END_HOUR` (06–22 local) the scheduler runs `today.refresh_principal_narrative`, which refreshes the calendar cache and rewrites the principal's header only when its key moved (see Scheduler). The Briefing re-polls `/today` at 4, 10 and 20 s while `narrative_stale` is true, re-pulls it when the tab comes back (at most once a minute) and every 5 minutes while visible, shows \"Updated 2:04 PM\" beside the heading, and shows \"Catching up on today…\" while the first header of the day is written (`lib/narrativeFreshness.ts`, tested by `npm test`).\n\n In **solo mode** (one person using Open Executive for themselves) the header speaks to the principal, whatever their role: a solo prompt over a context that lists goals at risk by *area* and has no \"people waiting on you\" block, and the quiet check ignores who is awaiting. The cache key carries the mode for solo only, so solo and team never share a cached narrative while every team key stays exactly what it was — no team cache is invalidated. The response shape does not change. For the principal's own view the solo context also carries a **DUE THIS WEEK** block — the principal's open loops that are overdue or due within 7 days (`today._with_due_soon` → `open_loops.principal_due_soon`, labelled OVERDUE / due today / due <weekday>) — which counts as needing attention in the quiet check and moves the cache key when an item is added, closed or falls due; a teammate's scoped view and team mode never get it. The header never gets the morning brief's *top three today* block — that is the DM brief's (see Workflows); the page shows the same top three in a card of its own (see *Solo focus cards* below). It does get the rest of today's calendar through the live blocks above, from the cached read.\n- **`in_flight`** / **`awaiting`** — upcoming Executive commitments and people we are waiting on.\n- **`handled_overnight`** — the autonomous moves the Executive *completed* since the last delivered morning brief: the alert review's (routed, nudged, escalated, drafted, merged, closed) plus the research watch policy's (`watching` — a watch added on its own because it was grounded in company data; `stopped_watching` — a research watch auto-disabled as noisy or dead; no alert id, re-enable from `/watchlist`). A `changed` verdict (the review rewrote an open alert's headline / body / severity) is deliberately **not** here: the alert is still open in \"Needs you\" and its card carries the note, so the brief reports it under \"what changed\" (a REWRITTEN block) rather than as done. Each row is structured, not just a sentence: `kind`, the audit `summary` (nudge bookkeeping marker stripped), `at`, `alert_id`, `event_type` (for a pre-filtered `/audit` deep link), `headline` (the alert's headline at move time; a watch's slug), `target` (person name for routed / nudged, survivor headline for merged, new severity for escalated, draft title, workflow name), `detail` (the cited evidence or the watch policy's reason), `outcome` (`resolved` | `dismissed` for a close, `proposed` for a route that went through the authority gate), `evidence_ref` (S1 / R2 / A3), `superseded_by_alert_id`, and `status` — the alert's lifecycle state **now** (`open` = live in the queue per `lifecycle.is_live` | `resolved` | `dismissed` | `expired` | `merged` | `acked` | `inactive` for snoozed / past-TTL rows), looked up per row so a close the principal already undid renders as reopened instead of offering a second Undo, and a \"still open\" jump link only appears when there is a card to land on. Audit rows private to the principal (say, one naming their contact) are in this list only on the principal's own `/today`: `brief_state.handled_since` leaves them out unless asked, and the written briefs never ask, since a brief can be read by others. The Pulse heatmap's per-day counts (`GET /today/activity/daily`) likewise leave out a private decision or private alert, as the activity rail does. The morning brief also carries a one-line count of research watch suggestions waiting on `/watchlist`.\n\n**From your chats.** `briefing.brief_requests` holds what the principal asked of their brief in conversation: `leave_out` lines from `leave_out_of_brief` (\"take the Halcyon renewal out of my brief\", kept 14 days) and `raise` lines the conversation review could not fix itself (`raise_in_brief`, kept 2 days), at most 20 live. A line is at most 12 words (leave out) or 30 (raise), with no link, handle, markup, identifier or talk of instructions, and only lines written under the principal's own id render. `render_briefing_context(brief_requests=True)` adds the raise lines before the quiet-day check, so they are raised even on a quiet day, and the leave-out list as the very last block; both sit inside the rendered string the /today header hashes. A teammate's brief or header passes `False`: they are the principal's own words.\n\n**Standing facts.** `render_briefing_context` appends the standing facts (`memory.facts`: corrections kept from chat, a teammate's marked `(per <name>)`) as its last block, after the quiet-day check, so a fact never makes a quiet day look busy. Every brief prompt (this header, the teammate header, the morning brief and the end-of-day digest) carries `narrative.STANDING_FACTS_RULE`: use the facts quietly, never mention one or that it was saved, and leave an item a fact settles out without saying it was dropped. A fact settles only what it plainly says. Without it, a fact saved in chat came back as the header's top point, stretched to an item it never named. The morning brief also carries **TEAMMATE CORRECTIONS SINCE LAST BRIEF** (`facts.render_teammate_changes(since)`: each teammate fact recorded in the window that is in use now, plus — only when the brief is the principal's own private one (`_private_ok`), which then keeps the run out of the shared history — those waiting for their approval, since other teammates may run the brief and never see a proposal that is not theirs) before the quiet check — it is news, the principal's only FYI of it — and in the brief's fingerprint (`build_brief_fingerprint(teammate_changes=)`), so a correction alone un-suppresses an otherwise unchanged brief. Every other caller passes none, so its context is unchanged. The /today header hashes that rendered string as its cache key, so a new or retired fact marks the header stale and it is rewritten with the correction. The morning brief (standalone) and the teammate-scoped header get the same block. On the scheduler's delivery to the owner alone, with their Always in the loop switch on, `render_briefing_context(owner_notes=)` also carries FROM YOUR NOTES — DUE SOON (their own notes of what they promised or asked, overdue to a week ahead; `memory.history_brief`), which counts against a quiet day, enters the fingerprint and marks the run private; both standalone prompts turn it into a **From your notes** section. The /today header never gets it. **The first week.** For seven days from the principal's People row (`briefing.first_week`), `render_briefing_context(getting_started=)` carries a GETTING STARTED block right after the live blocks: the install's goal rows (department, key result, target, period) or, while there are none (setup saves no goal rows, so this is a fresh install's usual case), this year's priorities and north star from the saved profile (`strategic_priorities`, up to five, keys `priority:<text>`), departments with no `head_person_id`, and, on the scheduler's delivery to the principal alone with Act as me and Draft replies to my inbox both on and the mailbox connected (the inbox watcher's consent), up to five people who wrote to their own mailbox in the last 48 hours as sender and subject only (`inbox_message_ids` + headers of `get_message`, bulk and automated mail skipped; the same \"where, never what\" rule as `delegation.mail_reads`) and, with Act as me and Read my calendar on, up to eight of today's events on their own calendar as time and title (declined ones left out). It counts against a quiet day, enters the fingerprint (`getting_started=` keys, no dates; a meeting's key is its event id) and, with the inbox or calendar part, marks the run private. Both standalone prompts open with a **Getting started** section and take the Top call from it (`GETTING_STARTED_RULE`). The /today header does not get the block: in the first week it is the same header as any other day. Home's top slot is instead the **first-week card**, built in code with no model call (`first_week.first_week_card`): `needs_goal` while no goal row exists (fixed ask \"Give me one goal with a date, and I'll track it every day.\" and a **Set a goal** button to `/goals?add=1`, which opens the add form), up to two findings from the latest finished team `executive_research` run (the run history keeps only the artifact, so `executive_research.parse_artifact_findings` reads back its \"Findings reviewed\" lines; most severe and most certain first, headline plus the summary's first sentence) with a line linking `/watchlist`, and `brief_tomorrow` on the setup day until the first morning brief is delivered. No goal still to set and no findings means no card. `GET /today` sets `first_week_card` and `first_week` (whether there is a card) for the principal only; while there is one the Briefing hides the \"Quiet day\" banner and an all-zero summary line reads \"Your first week. Start below.\" The last setup screen (`OnboardDone`) offers one first question built from the saved priorities (`firstQuestion`) and hands it to Home through session storage (`oe.onboard.firstQuestion`, never the URL), which asks it once. A teammate's scoped header never gets it. The alert review's `render_batch` puts the same block ahead of the alerts (read once per pass), so a note, rewrite or routed DM never repeats a figure the principal already corrected.\n\n**When a brief isn't sent.** Above the Briefing, the owner sees a one-line notice when their latest morning brief, end-of-day digest or (in solo mode) weekly review wasn't sent — \"Your morning brief wasn't sent: nothing is set up to send it to you\" — with the day, what fixes it, a link to read the brief on the Artifacts page (left out when the brief couldn't be written at all) and one to Setup status. It comes from `GET /today/brief-delivery` (the scheduler records each run's outcome), shows nothing while briefs go out or while the scheduler is off, and clears once the cause is fixed. When the Executive's mail connection wasn't running (the MCP gateway failed to start and is retrying), the notice says that instead of blaming the owner's setup; a send that failed on every channel names what each channel answered, from the recorded `detail`, with addresses left out. Teammates never see it.\n\n**Replies waiting.** With Act as me's **Draft replies to my inbox** on, the top of the Briefing's left column lists the replies the Executive drafted in the owner's own Gmail for mail that needs them (`RepliesWaiting`, from `GET /delegation/replies` — see Act as Me). They belong to the owner alone: the route answers only the person who can have Act as me, the decisions behind the cards (`delegation_reply`) are principal-only and carry `private: true`, so `/today/activity` and the heatmap leave them out, and none is ever an alert, so nothing of them reaches `GET /today`, the header or the briefs. Each card shows who wrote and who they are to the owner, whether their address was verified, the subject, what they wrote (as plain text), the draft, **Decide before sending** (its open questions) and its warnings, with **Send**, **Edit in Gmail** (the thread in their Gmail) and **Dismiss** (which deletes the draft unless they edited it). **Send** asks first, naming who the reply goes to, then sends the draft exactly as it is in Gmail (`POST /decisions/{id}/approve`); when its recipients changed in Gmail or a newer message arrived, the backend's 409 `confirm` becomes a second question naming them. The card hides itself when nothing is waiting.\n\n**Solo focus cards.** `GET /today/top-three` and `GET /today/weekly-review` feed two solo-only cards, so a principal who only uses the web app — no chat app, no Google Workspace — sees today's top three and the weekly review instead of finding them only in the Workflows run history. Both answer only in solo mode (`effective_workspace_mode`) and only to the principal, by the stricter rule for starting a principal-only run (`workflows._caller_is_the_principal`: the caller's own email on a principal entry that is not archived, or no `x-caller-email` at all — never \"nobody is principal yet\"); a teammate, any other signed-in caller and team mode get null. `top-three` hands `open_loops.principal_due_soon()` to `briefing.top_three.build_top_three` — the morning brief's own inputs and code, so the items, their order and their free slots are the brief's — and returns `{items: [{key, kind, text, why, slot}]}`: `slot` is the free block (\"10:00–11:00\", the user's zone), \"\" when none is left, or null when no calendar was read (none connected, a failure or the 4 s timeout, a weekend); `items` is empty when there is nothing to pick. It is a route of its own, never part of `GET /today`, so the Briefing never waits on the calendar. `weekly-review` returns the latest `weekly_review` run with status `done` (`persistence.list_runs(..., status=\"done\", limit=1)`, newest `updated_at` first; failed and running runs never count) as `{run_id, completed_at, period, top_three, excerpt}`: `weekly_review.summarize_review` reads the artifact's title line and its last *Next week's top 3* section back as plain text, and `excerpt` stands in when that list is empty (the section's own note, else the review's first lines). Null when no review has completed or the run store cannot be read.\n\nThe route resolves the caller from `x-caller-email`, serves the viewer's cached narrative and, when its key moved, rewrites it in a `BackgroundTask` so the request never blocks on an LLM call (the page re-polls while `narrative_stale` is true). `GET /today/activity` returns the recent self-initiated action rail — merged from fired scheduled actions (DMs, follow-ups, nudges, cadences), logged decisions, saved advice, completed workflow runs (briefings/check-ins/research), kicked-off initiatives, resolved gated decisions, and raised alerts, so it reflects all of the Executive's activity rather than just dispatched messages. A brief or digest delivered to its reader (`scheduler.runner._deliver_to_principal`) records its send as kind `brief_delivery` (`schedule_tools.recorded_as`): the outbound guard still counts it, but the rail and the heatmap leave it out, because every later brief reads the rail and used to repeat its own last top call as work done. A completed run is named in plain words, never by its log title (`workflows/run_outcome.py`: \"Researched your market\", \"Checked in with Sales\", or the name it was started with, less any date or how-it-started note), and carries `detail`, one line on what came of it read from its stored artifact (research: updates looked at, messages sent, alerts raised, things now watched; a check-in: actions proposed; the weekly review: next week's top item; other runs: the first sentence; none for briefs and the reflection), and `artifact_id` (`run:<id>`) when it kept a write-up (never for the reflection, which reads the principal's live alerts), so Pulse's Done for you and All activity link **Read it** to `/artifacts/run:<id>`. The Pulse page (`/memories`) polls it (limit 100) every ~20s so new events stream into the 'Recent activity' card, which scrolls internally at a fixed height instead of growing the page. The `morning_brief` workflow calls `_build_today()` directly to build the standalone DM (via a different, enumerated prompt; solo mode has its own, with goals at risk by area and no waiting-on section). `GET /morning-brief` is a deprecated alias.\n\n**Solo mode in the UI.** The response is the same in both modes; the briefing reads the workspace mode from the app-wide `WorkspaceProvider` (which reads team while loading or on error, so a team install never flashes solo) and, in solo, drops the team surfaces: the Departments card, the People card, the \"Across the team\" lane (every action proposal is the one user's, so all of them land in \"Needs you\"), the people-awaiting, people-overdue and departments-at-risk status pills, and the quiet-day \"Set up a check-in\" link. A \"N goals at risk\" pill (at-risk plus off-track goals, from `departments`) links to `/goals` instead, so the strip never reads \"All clear\" over a goal that is slipping. In the Departments card's place, **Your projects** lists the initiatives with status `active` (`GET /memories/initiatives`): **Done** marks one `completed` through `PATCH /memories/initiatives/{id}` (only `completed` takes an initiative out of the Executive's active context), and **Drop** deletes it through `DELETE /memories/initiatives/{id}` after a confirm. Under **Needs you**, a **Due soon** card lists the principal's open loops that are overdue or due within 7 days — their dated commitments and what others asked of them — read from `GET /people/{id}/open-loops` for the principal (the oldest principal in `people`, the backend's rule), labelled by `lib/dueSoon.ts` (tested by `npm test`: \"Overdue since Sep 23\" / \"Due today\" / \"Due Mon, Sep 28\", with a count of anything due later); **Done** closes one through `POST /open-loops/{id}/close`, which also stops the nudge engine chasing it. Above it, **Top three today** numbers the morning brief's three (`GET /today/top-three`) with each one's reason and, when a calendar was read, its free slot (or \"No free time left today\"); at the top of the right-hand column, **This week's review** (`GET /today/weekly-review`) shows the period, when it ran, next week's top three (or the excerpt) and a *Read the review* link to its run page (`/jobs/runs/{id}`). Each card fetches on its own once the Briefing has loaded, so a slow calendar never holds the page up, and renders nothing when the API returns null or an empty list. A commitment in the top three reads as the owner's own (\"Send the proposal\") through `lib/dueSoon.ts`'s `loopText`, as in Due soon; the cards' wording lives in `lib/rhythmCards.ts` (tested by `npm test`). The Pulse page hides its \"Department check-ins\" and \"Awaiting people\" blocks in solo, and its header shows active projects in place of the department check-in count. Team rendering is unchanged.\n\n**Your month (`GET /today/value`).** The owner's own tally of what the Executive did for them, `briefing.value_summary.summarize(period, offset)`: the calendar `month` or `week` (Monday first) in the user's zone, `offset` periods back (0–24), each line beside the period before. Every number is a `COUNT(*)` of rows that prove it happened, never a model's: messages sent for the owner (the DM handlers' own `kind=outbound` sent rows to anyone but the owner, plus Gmail / Outlook send-tool calls that didn't come back with an error, so mail sent from a chat turn counts), replies drafted and sent from the owner's inbox (their Act as me rows), meetings booked (calendar create calls), briefs delivered (the scheduler's `delivered` row), reports (finished team workflow runs, minus the daily rhythm runs and any run a teammate started for themselves, which stays theirs alone; the latest ten listed with links), follow-ups and nudges sent, tasks tracked and closed as done, proposals decided, alerts flagged and requests answered (`chat_turn` out rows). No \"hours saved\" and no cost line: nothing recorded supports the first, and cost next to what the owner got reads as a bill; it has `GET /audit/usage`. The owner's alone (403 for anyone else): it counts rows private to the owner, never a row private to another member. Pulse shows it as the top line of the overview's **Done for you** panel (\"October 2026: 42 messages sent, 6 reports, 3 meetings booked\") and a focused screen, `/memories?tab=value`, with a month / week switch and previous / next. On the first weekday of each month, in daytime (09:00–18:00 local), a scheduler tick hook sends the owner last month's lines and a link (`value_summary.maybe_send_monthly`, claimed once per month under `briefing_narrative` scope `value_summary:YYYY-MM`), in solo and team mode alike; nothing is sent for an empty month. Off with `VALUE_SUMMARY_MONTHLY_ENABLED=false`.\n\n## Alert lifecycle & the Executive review\n\nAlerts used to be write-once: raised, then never looked at again, so the \"Needs you\" queue grew without bound and the briefs re-listed it daily. Four things now keep it live and true:\n\n- **Time-to-live** (`openexecutive.alerts.lifecycle`). Action items expire after `ALERT_TTL_DAYS_ACTION` (14 d), unrouted low/medium monitoring signals after `ALERT_TTL_DAYS_MONITORING` (3 d). Every surface reads `list_live_alerts` (the same predicate the scheduler's 15-minute sweep persists as status `expired`), so `/today` is right even before the sweep runs. Artifacts and decision-backed alerts are exempt. `POST /alerts/{id}/reopen` is the Undo. **Snooze** (a card's ⋯: later today, tomorrow 9:00, Monday 9:00, in the viewer's clock; `POST /alerts/{id}/snooze`) hides a card until `snoozed_until`, with an Undo; the TTL anchor is the latest of `created_at`, `last_seen_at` and `snoozed_until`, so a snoozed card comes back rather than expiring unseen.\n- **Coalescing** (`alerts.pipeline` + `store.coalesce_alert`). A repeat of an open alert with the same `(source, dedup_key)` updates that row — `occurrence_count`, `last_seen_at`, severity max — instead of stacking a second card, and only re-pings when severity rose to high/urgent. Monitoring alerts carry a stable `watch:<slug>` key, so one watch means one card.\n- **Collection tags** (`alerts.pipeline`). A triaged alert never carries a `collection:<name>` tag: the pipeline strips them before inserting. Only an installed extension's own code files a document into its collection (`orchestrator.extensions`), so injected text can't make a card that the extension would treat as its own.\n- **The review** (`openexecutive.alerts.review`, heartbeat `alert_review_scan`, every 6 h and right before the morning brief). For each open alert the Executive sees what changed since it was raised — newer signals from the same watch, related alerts, activity since, the roster with SLAs (team members only — an alert routed to a contact never puts them in the slice, so they are never routed to, nudged or chased; a private card is never reviewed at all, nor used as evidence for another), department authority — and returns a verdict (relevant / changed / resolved / stale) plus a recommended move. Deterministic policy then acts: **route** (assign + DM the owner; `propose_via_alert` for propose-only departments), **nudge**, **escalate** (severity + `due_at` + DM the principal only), **draft** (`draft_artifact`), **suggest a workflow** (a link, never a run), **merge** (`superseded_by_alert_id`), or **resolve** — only on high confidence citing a server-minted evidence ref (a newer signal, a related alert, an activity item shown for that alert); free text never closes a card, and anything weaker is annotated `likely_stale`, demoted 30 ranking points, and left for one click. Everything that came from outside is rendered as inert data inside the review prompt, so an injected email body cannot steer the batch. Board / comp / legal matters only ever go to a scope-holder or the principal and keep their text. Route and escalate are idempotent across passes, every DM carries an \"[Alert review] Re: …\" header, outbound moves are capped per pass, passes are single-flight, `ALERT_REVIEW_ENABLED=false` stops every caller, every move is audited with its evidence and prior state, and a distinct `resolved` status keeps Executive closes separate from `ack` (user approved). A review DM is proactive outreach, so the recipient's notification settings apply: one held for their quiet hours or brief counts as a route made but not as a nudge toward the cap (and no second nudge is held while one waits), and one about an alert whose severity is (or becomes) `urgent` is marked urgent (`notifications.urgent_send`) and gets through when they let urgent things through.\n- **Grounded text** (`openexecutive.briefing.grounding`). Nobody reads an alert's text before it is dispatched, so what the model wrote onto it must be supported by what it read. After triage (`alerts.pipeline._ground_decision`, before coalescing or inserting), a headline naming a person or figure the event does not hold — sources are the event's subject, sender, title and body, the initiatives triage was shown and the company profile — is replaced by the event's own subject, such body sentences are dropped (all of them → the event body cut to 280 chars); both fallbacks are raw event text, so they are made inert first — links masked, Markdown and Slack `<…>` syntax and @-mentions stripped — because a broadcast posts them as written, and such a suggested action is dropped. A review `changed` rewrite is checked against the alert's own text and the evidence it was reviewed with (signals, related alerts, activity, the roster slice), plus the standing facts the batch was shown, so a rewrite that corrects a card to one of the principal's corrections is grounded; an ungrounded rewrite keeps the old text, still applies a severity change, and audits `text_ungrounded`. A name counts as grounded only when one source line holds all of it; a figure only when a source number matches it within the precision it is written with. Each finding writes a `grounding` audit row; `GROUNDING_CHECKS=report` records without changing anything.\n\nOn the page, cards read as decisions: the one-line \"what changed since you last looked\" (`review_note`) leads, the recommended move is the primary control (Nudge <owner> → chat; Run <workflow> → `/jobs/<name>`), with chips for age, seen ×N, why-now / due, folded-in and draft-ready, a \"Reviewed <ago>\" footer, and an amber Likely-stale treatment with one-click Dismiss. \"Needs you\" shows *Start here* + 8 cards + \"Show N more\", a \"Dismiss N older than 7 days\" footer (explicit ids to `POST /alerts/bulk-ack` — never a server-side age sweep, which would hit teammates' routed items), and \"Re-check relevance\" (`POST /alerts/review`). The handled rail (anchor of the \"Executive handled N overnight\" pill) is deliberately one sentence by default: a first-person heading built from counts only — \"Since your last brief: N off your plate (closes still standing, and merges whose survivor is not itself listed; a merge into a listed survivor counts on that survivor's row), N in others' hands (routed / nudged), N waiting on you (escalated)\", plus \"N drafts ready\", \"N workflows suggested\", \"N watch changes\", \"N other moves\" (a kind the UI does not know) and \"N back on your plate\" (a close that is open again) when present — with the rows behind a \"details\" disclosure, and nothing rendered at all when the grouped rows are empty. The pure logic (grouping, headline, links) lives in `packages/ui/src/lib/handled.ts` and is covered by `npm test`. Expanded, it shows one first-person row per alert (\"Resolved *X* — evidence\", \"Dismissed *X* as stale — evidence\", \"Handed *X* to Dana Kim\" / \"Proposed *X* to Dana Kim (awaiting their approval)\", \"Chased Dana Kim on *X*\", \"Raised *X* to high\", \"Drafted *T* from *X*\", \"Folded *X* into *Y*\", \"Started watching *slug*\"), escalations first; rows sharing an alert collapse to the newest move with the others as an \"also …\" trailer — a close always keeps the visible slot (it carries Undo), otherwise an escalation beats routed / nudged / drafted; a merge whose survivor is listed becomes \"N duplicates folded in\" on the survivor. Every row links its `evidence_ref` (or \"evidence\") to `/audit?event_type=…&q=…` (the audit page pre-fills those filters from the query string), a still-open row jumps to its card (`#alert-<id>`), drafted rows link `/artifacts`, watch rows `/watchlist`. Undo is offered only while the close still stands (`status` not `open`); a reverted close shows \"Reopened\". Dismissing a watch-sourced alert lowers that watch's `trust_score` (which discounts ranking and is shown to the review as evidence); the ack body may carry `mute_topic`. Acknowledging or resolving an alert — including the review closing it itself — marks the review's DMs about it `acted` in the Attunement outcome ledger, for the person it is routed to and the principal only; dismissing it, finding it stale or letting it expire voids them (counted neither way). Review DMs are tagged `alert_review` with `alert:<id>`.\n\n## Multi-client practice section\n\nIn multi-client practice mode (2+ client slots — see the Client Companies section), the response gains an additive `practice_clients` list: rollup cards for the **parked** clients (overdue follow-ups, awaiting replies, unread alerts, onboarding due soon, renewal countdowns), each stamped with the save point its data reflects. Single-company installs always receive an empty list and the UI renders nothing.",
+ "markdown": "`openexecutive.api.routes.today` serves the morning brief — a one-screen, read-only view of what is happening across the org. It is the default landing surface (the Next.js root renders `<Briefing>`). Every signed-in page shares one sidebar (`AppSidebar`). Its Recent list is capped at the 7 newest web chats. The full history, including Slack, Telegram and Discord conversations (recognised by their session-id prefix), lives on `/chats`. A chat opens from any page through `/?session=<id>`.\n\n`GET /today` returns `TodayResponse` assembled by `_build_today()`, which is synchronous and caller-agnostic:\n\n- **`departments`** — per-department goal health, rolling up each department's goal counts (`total`, `at_risk`, `off_track`) plus its awaiting-workflow count, and `attention_goals`: the actual off-track/at-risk goals (worst first, capped at 3) with `key_result`, `current`, `target`, and `status`, so the briefing's Department card shows *which* goal is off and how far without a click. Empty for healthy/inactive departments. Each attention goal also carries `owner_id` and `owner_name` (its own owner, else the department's head, else the principal), and the narrative's goal lines name the owner. Goals with no department get one more row, slug `\"\"` and title **Other goals** (`UNASSIGNED_GOALS_TITLE`), shaped like a department so every reader of `departments` (the header context, the narrative, the reflection, the fingerprint, the digest) counts them; it is added only when such goals exist, links to `/goals` in the UI, and a teammate's slice keeps only the goals on them.\n- **Private cards.** An alert tagged `private:principal` (`alerts.models.PRIVATE_ALERT_TAG` — raised on a turn about mail from one of the principal's contacts or mail they forwarded, or a meeting proposal with a contact) is in `proposals` only when the caller is the principal. The chat's alert digest (`briefing.context.render_and_trust`) shows it, and the roster requests, only on the principal's own verified turn, never in a web chat they shared with others, where everyone reads the reply. `_build_today` leaves it out by default, so the end-of-day digest, the reflection and Discord's `/today` never see it, and the morning brief reads it only on a run for the principal (the scheduler's, or the principal's own verified chat turn in a conversation only they can read — see Workflows). The narrative is written from one only in the principal's own `principal` scope, which nobody else is served; the shared `company` scope an unresolved caller gets, and a teammate's scope, never are. The activity rail skips it, and the chat digest includes it only on the principal's own verified turn.\n- **Raised by a team member.** An alert a team member raised from chat (`AlertEvent.raised_by`, source `team_member`) has its body led by \"Raised by <name>.\" and never goes out on `company_broadcast`: the pipeline drops that channel after `resolve_channels`, so it reaches a person or a department room only. One team member's alert never coalesces into another's (the dedup key is prefixed with who raised it). A team member's saved workflow raises alerts as its creator (`action_step` binds `dynamic_store.get_owner` around `oe__create_alert`). Alerts from email, watches and other sources are unchanged.\n- **Who clears a card.** `POST /alerts/{id}/ack` with `ack` or `dismissed` answers 403 to a team member unless the alert is routed to them (`read` is open to anyone who can see it); only the principal's dismiss applies `mute_topic`, since a mute silences the topic for everyone. `POST /alerts/bulk-ack` from a team member clears only the listed ids routed to them and refuses an `older_than_days` sweep. The principal, or anyone before a principal is set up, clears anything. `ack_alert` in chat follows the same rule.\n- **Roster-request cards.** When someone not on the People list writes in (see Org and Integrations), `people.roster_requests.surface_card` raises an alert of source `roster_request` (medium, tagged `roster_request:<id>` and `private:principal`, routed to the principal), so it follows every private-card rule above. `GET /today` attaches `roster_request` to that proposal (`_roster_request_card`: channel, address or account id, the sender's sanitised and unverified name, profile email, company-domain flag, suggested kind and person, message count, whether they were acknowledged, first seen, and the held messages' first lines) while the request is still pending. The Briefing renders it as its own card (`RosterRequestCard`: add as a new person with a name and an explicit team/contact choice — pre-filled as team on a company domain — or \"someone already on the list\", with a replace-account option for a chat id, or Ignore), which calls `/people/requests/{id}` directly and never hands off to chat, so what a stranger wrote never seeds a turn. The card is kept out of everything that could close it without answering it or put the stranger's words in front of a model: the narrative (`_action_proposals` drops it), the chat's open-alert digest (`<briefing>` — the principal's verified turn gets a separate `<roster_requests>` block instead; see Agents), `ack_alert`, a single ack (`POST /alerts/{id}/ack` is a 409), the \"Dismiss N older than 7 days\" count and the server's bulk ack, reopen, the TTL sweep and the alert review (`roster_request` is in `lifecycle.TTL_EXEMPT_SOURCES`). It ends when the request does: answered (`ack`, or `dismissed` on a decline) or expired after `ROSTER_REQUEST_TTL_DAYS`.\n- **`people`** — an attention-ranked roster of the **team** (the principal's contacts are never listed, and get no insight note). Each person carries `awaiting_action` count, soonest SLA, a `status` (`on_leave` / `needs_reply` / `awaiting` / `clear`), reachability, `overdue`, a server `priority` sort key, and a cached one-line `insight`. Sorted by `(-priority, full_name)`. Stale insight notes are regenerated in the background only when the roster has more than one person: the UI shows the People sidebar only for more than one, so a one-person install (solo, or a team before anyone else is added) does not pay a daily model and peer-memory call for a note nobody sees. Cached notes are still served.\n- **`proposals`** — the *live* unread alerts (workflow approvals, triage-classified inbound, Executive signals, flagged artifacts, and gated calendar bookings; an artifact is listed only to its owner (`alerts.models.visible_alert`; every other build of the board — the briefs, the reflection, the review, the chat digest on anyone else's turn, the activity rail — leaves drafted artifacts out) and carries `artifact_format` / `artifact_url` and a `body` already rendered to Markdown for its format, so the card badges it as a web page, Word doc, spreadsheet or link and offers *Open artifact*): unread, inside their category TTL, not snoozed — see *Alert lifecycle* below. Each carries `score`, `category` (`action` vs `monitoring`), `surfaced_reason` from `openexecutive.briefing.ranking`, the lifecycle fields (`occurrence_count`, `last_seen_at`, `last_reviewed_at`, `review_verdict`, `review_note`, `recommended_move`, `why_now`, `due_at`, `superseded_count`, `suggested_workflow`), and `decision_instance_id` (set only when the proposal is backed by a decision-ledger row — a calendar booking awaiting approval). `failed_run_id` is set only on a `workflow_failed` card (a scheduled run that ended in error, see Scheduler): its main button is **Run again** (`POST /workflows/runs/{id}/rerun`, which also closes the card) and its ⋯ opens the run; it has no Approve. The response also carries `held_back` for the principal alone: the lines grounding left out of the morning brief or end-of-day digest in the last day, which Home lists under **Left out of your brief** (the brief's note names it; Hide is remembered in that browser). The UI splits them into 'mine' vs 'across the team' using `caller_person_id`. Approve is carried out on the server for every card. For decision-backed proposals the card's Approve/Reject call the `/decisions` endpoints (which book or cancel the event server-side and clear the alert), so meeting bookings are reviewed in the briefing itself rather than on a separate page. Every other proposal is approved at `POST /alerts/{id}/approve` (`alerts.approvals`): it records who approved the card and when (an `alert_approvals` row plus `alert_approved`, then `alert_approval_done` / `alert_approval_failed`, audit rows), claims the card in one transaction so a double click or a second approver gets a 409 and the work runs once, then does the work. A card the scheduler filed for a department-gated action is bound to it server-side (`alert_held_actions`, written only as the card is filed, never read from the card's tags or text, which a model reading inbound mail can write), and approving it queues that exact action again with no department, the approval being the consent the gate waited for. Any other proposal runs one Executive turn as the approver in a new chat on the server (`chat.start_background_turn`, the machinery behind `POST /chat/background`), with the edited text verbatim for Edit & approve; it keeps going if the page closes. Only the card's routed person or the principal may approve a routed card, and only the principal an unrouted one (403 otherwise); the card's text reaches the turn as quoted data, not instructions. A row at the top of Needs you follows the approval (`GET /alerts/approvals/{id}`): working on it with a link to the chat, then done, or didn't work with Try again; a card whose last approval failed can be approved again, and one still running at a restart is marked failed on boot. The page no longer acks the card and seeds a chat turn with the proposal, which left no record of the approval and did nothing if the tab closed first.\n- **`narrative`** — a per-viewer Executive-voice header (\"What's going on\") synthesized by `synthesize_briefing_narrative`, cached per scope in `briefing_narrative`: the resolved principal gets the whole-company `principal` scope (which may carry what is private to them), a caller who resolves to no roster row the shared `company` scope (written from what everyone may see), and each teammate a role-scoped `person:<id>` one. `narrative_generated_at` says when the served text was written and `narrative_stale` whether a fresher one is being written now. Home shows it as **Right now**, a card above Needs you, because the text is rewritten through the day: `briefing.right_now.split_narrative` splits the served text into `narrative_lead` (the bold opener), `narrative_points` (`{text, since}`) and `narrative_move`. `since` is when that point first appeared today, kept per scope and local day in `briefing_point_seen` (keyed by the point's bold subject, so a reworded point keeps its time; recorded when a header is written, earlier days pruned then). `narrative_seen_at` is when this reader last looked, from `briefing_reader_seen`, set by `POST /today/seen` (same scope resolution as `GET /today`; the shared `company` scope of unrostered callers keeps no look, so one stranger's visit never resets another's); the page fixes it as the baseline for the visit, marks points after it with a green dot and *N new since …*, and only counts a look from earlier the same day. For the principal the response also carries `morning_brief` (`{at, text}`, today's delivered morning brief from `brief_state.last_delivered`) and `calendar_next` (up to 3 meetings still ahead today from the cached calendar read, never a fresh call), which the side panel shows under the points and Move today. Nothing here calls a model. In the web UI each bullet of this narrative is a click target: clicking one hands off to chat (the same `onContinue` path as the proposal cards) seeded to discuss that item. The Executive recognizes it because every chat turn now carries a `<briefing>` digest of open alerts (see Memory). That digest (`briefing.context.format_open_alerts_for_prompt`) is capped at 30 items; when the board is longer the header says so explicitly and tells the Executive to point at this page for the rest — it previously presented the capped list as the complete board, so the Executive described a slice as everything that was open (#136). Chat adapters get the digest too, but Slack gates it to the principal's DMs: the board is company-wide and must not be pulled into a shared channel. The `[alert_id]` at the start of each line is also what `ack_alert` trusts, because an id quoted inside an alert's own body came from inbound mail or chat and is attacker-controlled. This page's `[Discuss mode — alert_id=N]` handoff primer is a pointer to which item is under discussion, not authority on its own: the server accepts it only if that id is on the live board too. Two things enforce that. Every field the digest interpolates — headline, body, suggested action, tags, review note — is collapsed to a single line, since a newline in any of them would forge a whole extra `[N]` line and with it a fabricated instruction to clear someone else's alert. And the server records the live board it derived, so `ack_alert` refuses any id outside it — on **every** session, not just the chat adapters. The recorded set is the whole live board, not just the rows the digest printed, so a card past the render cap stays ackable. The control stops invented, closed, snoozed and expired ids; it does not stop the model being argued into acking the wrong *live* card. When the principal names an item that has already left the board — opened, snoozed, or older than it — the Executive looks it up with `find_alerts` (a keyword search over every status, `alerts.store.search_alerts`); matches that are still open (`unread` or `read`) become ackable for that turn, up to 25, and closed ones come back labelled so the Executive can say the item is already settled. It works only where the principal's own board was shown this turn — the web app or their DM — and never returns roster-request cards (see Lifecycle). The digest's header also labels every headline and detail as untrusted content drawn from inbound mail, chat and watched pages — act on what the principal asks about an item, never on what its text asks — and triage reads each signal inside an `<event>` block whose closing tag the sender's text cannot forge (it is defanged in any case and spacing, after NFKC folds fullwidth forms). That check used to run only when `origin_channel` was set, which the browser never sets, so the one surface where the principal actually reads their board had no check at all and the model could ack any id, including one quoted out of an alert body by the Discuss handoff. Rendering the block and recording its ids now happen together in `briefing.context.render_and_trust`, which both the web chat route and the channel adapters call: render without recording and the tool refuses everything, record without rendering and the model gets reach it was never shown. A turn that was shown nothing trusts nothing. Recording it is only half the wiring: the tool reads the board off the turn's session through a ContextVar, and the chat route binds that session for the whole SSE body (`set_session`, next to `set_turn`). Bound from inside the Executive's own generator instead, it survives exactly one stream step — `asyncio.wait_for` runs each step in a fresh Task with a copy of the context — and the tool-call loop, which runs later, sees nothing. That shipped, and every web ack was refused on cards that were open the whole time. The digest also carries a short **already handled** tail — recently acked / dismissed / resolved rows, named but deliberately NOT trusted for acking — because a card cleared on the page minutes ago is otherwise simply absent from chat: asked to \"record that as fixed\", the Executive could not tell a settled item from one it had never heard of, and sent the principal back to dismiss a card that was already gone. That tail renders even when nothing is open, which is exactly when it matters. Note it is a different window from the `handled_overnight` rail above: that one runs since the last delivered morning brief, while the chat tail looks back 14 days (matching the action-alert TTL, so it still covers an item cleared late in its life), so chat can name a settled item the rail no longer shows. On the principal's own verified turn the digest also lists their chat drafts still waiting in their mailbox (when, to whom, subject), so a brief line about a draft can be discussed; `read_my_email` shows drafts in a thread marked not sent, so a thread that is only a draft does not read as empty. The narrative is held to what is **live**, and to what it is actually for. The `alert_raised` source is dropped from the activity it reasons over (`_build_activity(..., include_alert_raised=False)`): a closed alert reads as work the principal already settled, and a *live* one is worse than redundant — `lifecycle.is_live` is the very predicate behind `list_live_alerts`, so every live raise is already a proposal card below the header, which the prompt forbids re-listing. The `/today/activity` rail keeps the whole source, because a raise really happened. The activity block is only labelled \"since last brief\" when the caller bounded it with `since` (the standalone briefs do; the header does not), since calling an unbounded history rail a delta made the header present weeks-old rows as overnight news. When the viewer's slice holds nothing that wants a decision — no action proposal, no at-risk/off-track department, nobody awaiting — the regen skips the model call entirely and writes the fixed quiet line (`Quiet right now — nothing pressing.`, or `… nothing needs you.` for a teammate). **The cache key is a hash of the rendered context itself** (`today._narrative_context` builds it once and both the hot path and the background task key off that one string, which is also handed to the model verbatim). That makes the key a function of the model's input: everything the prompt renders is covered, and nothing it omits can trigger a regeneration. Keying on hand-picked fields broke one half or the other each time — headlines alone left the rendered activity block uncovered, while the proposals' review fields are never rendered by this header yet are rewritten with fresh prose by every `alerts.review` pass, so they regenerated each viewer's narrative several times a day to re-synthesize identical input. A quiet board keys off a fixed sentinel instead, so a moving rail cannot re-key an entry whose text is constant. Together: on a fully dismissed board every other input was empty, the rail became the only context, and the model synthesized a confident header out of closed items.\n\n **Right now's context and its check.** The whole-company header (Home's Right now card, directly above Needs you) is written from `briefing.header_context.render_header_context`, not `render_briefing_context`. **MOVED TODAY** lists, each tagged `[M1]`, `[M2]`…, what happened or came due today: INBOUND mail and chat from other people, STUCK replies and waiting drafts, decisions raised today (with their why-now) or re-raised today, the principal's own open loops due today or overdue (`due_soon`, now in team mode too on the principal's scope), the Executive's follow-ups (`in_flight`) due today or overdue, overdue replies from people it waits on (team only), things it could not do from a chat (the brief-requests raise lines), work it finished today (activity rows from the local day, minus `advice_given` / `decision_logged`, which come from the reader's chats) and today's watchlist signals. **COMING UP TODAY** is the rest of the calendar, tagged the same way. **STILL OPEN** is what sits in Needs you and did not move (older decisions, later due dates, later follow-ups, goals at risk): background for ranking, never a point. **BACKGROUND** holds the reader's chat titles and own messages, only to judge what matters most to them. The rest of the history rail is never read: it made the header report yesterday's DMs as news, and chat titles made it claim work in progress (\"I'm combining the PDFs now\") hours after it was done. The prompt (`_header_prompt`) asks for a bold opener, **one to three** bullets that each end with the tag of the line they are about, and a **Move today** line for the reader. After the model, `header_context.keep_cited_points` deletes any bullet citing no tag the context had (`tags_in`), strips the tags and keeps at most three; a draft left with no cited point (an opener or Move today alone included) is replaced by the fixed nothing-new line, unless it is just the quiet line. The cache key also carries the brief model, so switching the Executive's model rewrites the header on the next view. With no MOVED TODAY line (a calendar alone does not count) there is no model call: an empty board writes the quiet line (`QUIET_CONTEXT`), and open items with nothing new write `Nothing new today — what's open is below.` (`NOTHING_MOVED_CONTEXT`). Every brief (this header, a teammate's header, the morning brief, the end-of-day digest) is written with `narrative.brief_model()`: the Executive's own model (its Council pick, else `DEFAULT_MODEL`), not the background `ROUTING_MODEL`. A teammate's header keeps the older render below. The paragraphs that follow describe the live signals MOVED TODAY reads.\n\n**Live, not just the board.** The header used to reason over the alert board, goal health and the Executive's own bookkeeping only — mail and chat handled that day, replies the gate held and the next meeting never reached it, so it read the same for days while the principal's day moved on. The whole-company scopes now open the context with the principal's world as it is happening (`briefing.live_signals.gather_live_signals`, rendered by `render_live_blocks`), under a `NOW:` line: **INBOUND** (`integration_inbound` audit rows that carry a message, one per message id, grouped by sender and subject, with an email's first line; the principal's own mail reads \"from the principal\", an email from the roster says \"the Executive replied\" only when a reply was logged in its thread after it (`unanswered_mail.record_reply`) and \"no reply went out\" while its `unanswered_mail` card is open (on the principal's own read only), and a time on another day carries its weekday and date), **STUCK** (`integration_outbound_blocked` to a recipient, the inbound \"reply blocked at outbound gate\" and Google Chat \"left unanswered\" / \"not delivered\" rows, and chat drafts Act as me saved in the principal's mailbox that are still there: `delegation_drafts` rows not yet marked sent or `gone_at`; before each scheduled header refresh, each morning brief and, at most every 2 minutes, the principal opening `/today` (`today._maybe_settle_on_view`, which runs `refresh_principal_narrative` after the response, so this holds even with the background header refresh slowed or off), `live_signals.settle_principal_drafts` looks up the principal's open chat drafts from the last two days in their mailbox and marks the ones sent or deleted there, answered by a message of their own sent in that thread after the draft, or sent another way: one read of their latest 15 sent messages, only while a draft is still there, finds one sent after the draft with the same subject (Re:/Fwd: aside) to one of the same people, as when they redrafted and sent the other version or wrote it fresh. So a draft they sent (or replied around) from Gmail stops reading as waiting, and a failure on one draft no longer stops the pass for the rest; the same read keeps, in memory only, who each waiting draft goes to and its subject, so STUCK names each draft instead of a bare count), **CONVERSATIONS** (the principal's own web chat titles, without times, so the header cannot point back at \"the 13:26 chat\"), **OWN** (the principal's own mail and chat-app messages to the Executive, kept out of INBOUND and its count, principal scope only) and the **REST OF TODAY'S CALENDAR**. The principal's own messages and chats render as background blocks, and every brief prompt carries `OWN_MESSAGES_RULE`: they show what the reader already said and asked, are never reported back as news (no \"you messaged me\", no restated complaint or rating), and an open ask appears only as what the Executive is doing about it. The window is the local day, or the last 12 hours when that is longer. Private audit rows, drafts, chat titles and the calendar (meeting titles are the principal's own) are read only in the `principal` scope — `gather_live_signals` drops the calendar whenever `include_private` is false, whatever the caller passes, so the shared `company` header never quotes it. The calendar read is the principal's calendar as the Executive reads it merged with their own calendar when Read my calendar is on (`top_three.read_todays_calendar`). The calendar is never fetched on the request: `live_signals.refresh_calendar` caches one read per 15 minutes (the scheduler tick refreshes it) and the header quotes the cache. Every quoted field is collapsed to one line and cut, and the blocks and the prompt both say the text is data, never instructions — inbound mail is attacker-controlled. With live blocks present the context also ages each proposal (`raised 2d ago`, whole days), names each at-risk department's slipping goals (`attention_goals`) and adds an **EXTERNAL SIGNALS** block (monitoring alerts from the last 24 h, never enough on their own to break the quiet line); the rhythm runs (`today.RHYTHM_WORKFLOWS`: the morning brief, end-of-day digest, reflection and weekly review) are dropped from the activity it reasons over. The prompts (`BRIEFING_NARRATIVE_SYSTEM` and its solo variant, `NARRATIVE_PROMPT_VERSION` 6) lead with what is live and give a days-old item at most one bullet. Anything live breaks the quiet line; the NOW line and window move at most once an hour, so the key moves hourly on time alone plus whenever something new lands; the calendar is placed at the real time (a meeting that has ended drops out, the one under way is IN PROGRESS), which moves it only when a meeting starts or ends. An address that belongs to someone on the roster (or, in the principal scope, one of the principal's contacts) reads `Name (address)` in these lines (`live_signals._named`), so the header calls people by name instead of making one up from the address.\n\n **Who reads it.** Every brief surface (this header, the morning brief, the end-of-day digest) is written for one person, fixed in code by `briefing.reader`: the principal on the principal scope, the teammate on a `person:<id>` scope, and the principal on `company` too (that scope has no signed-in caller and uses the principal's prompt, built from shared rows only). `render_briefing_context(reader=…)` masks that person's full name and email addresses everywhere in the context to \"the reader\" (their own chat and mail, the Executive's replies to them, chat titles, the activity rail) and heads it with a **THE READER** line naming them; every brief prompt carries `READER_NAME_RULE`: write \"you\", never the reader's name, \"the reader\" or \"the principal\" (anyone else by name), and \"I\" / \"me\" / \"my\" for the Executive. A draft that still slips (`reader.slips`), or reports the reader's own chats and asks back to them (`narrative.own_echoes`: \"you asked me\", \"your chat\", \"a chat with me\", \"the 13:26 … chat\", which `OWN_MESSAGES_RULE` forbids), is sent back once to be rewritten, and what is left of the reader slips after that is fixed in code (`reader.fix_slips`: the reader → you/your, \"the principal\" → the owner's name on a teammate's brief, the Executive → I/me/my).\n\n **Fresh without a reload.** The daily floor in the key and the PERIOD line are the principal's **local** date (`narrative_cache.local_today`), not UTC's, and a row written on an earlier local day is not served as today's. Regenerations are serialized per scope; a trigger that finds one running marks the scope pending and the running pass goes round once more (it built its context before that trigger's news landed), and after a failed pass (model error, the 33 s timeout: 25 s for the draft and 8 s for a rewrite, empty text) no view or tick starts another for 5 minutes and `narrative_stale` reads false, so the page drops its placeholder instead of spending a model call per view. They log `today: narrative served scope=… age_s=… stale=…` and `today: narrative regenerated scope=… ms=…`, and no longer need a page view: every `BRIEFING_NARRATIVE_REFRESH_MINUTES` (10) between `BRIEFING_NARRATIVE_REFRESH_START_HOUR` and `_END_HOUR` (06–22 local) the scheduler runs `today.refresh_principal_narrative`, which refreshes the calendar cache and rewrites the principal's header only when its key moved (see Scheduler). The Briefing re-polls `/today` at 4, 10 and 20 s while `narrative_stale` is true, re-pulls it when the tab comes back (at most once a minute) and every 5 minutes while visible, shows \"Updated 2:04 PM\" beside the heading, and shows \"Catching up on today…\" while the first header of the day is written (`lib/narrativeFreshness.ts`, tested by `npm test`).\n\n In **solo mode** (one person using Open Executive for themselves) the header speaks to the principal, whatever their role: a solo prompt over a context that lists goals at risk by *area* and has no \"people waiting on you\" block, and the quiet check ignores who is awaiting. The cache key carries the mode for solo only, so solo and team never share a cached narrative while every team key stays exactly what it was — no team cache is invalidated. The response shape does not change. For the principal's own view the solo context also carries a **DUE THIS WEEK** block — the principal's open loops that are overdue or due within 7 days (`today._with_due_soon` → `open_loops.principal_due_soon`, labelled OVERDUE / due today / due <weekday>) — which counts as needing attention in the quiet check and moves the cache key when an item is added, closed or falls due; a teammate's scoped view and team mode never get it. The header never gets the morning brief's *top three today* block — that is the DM brief's (see Workflows); the page shows the same top three in a card of its own (see *Solo focus cards* below). It does get the rest of today's calendar through the live blocks above, from the cached read.\n- **`in_flight`** / **`awaiting`** — upcoming Executive commitments and people we are waiting on.\n- **`handled_overnight`** — the autonomous moves the Executive *completed* since the last delivered morning brief: the alert review's (routed, nudged, escalated, drafted, merged, closed) plus the research watch policy's (`watching` — a watch added on its own because it was grounded in company data; `stopped_watching` — a research watch auto-disabled as noisy or dead; no alert id, re-enable from `/watchlist`). A `changed` verdict (the review rewrote an open alert's headline / body / severity) is deliberately **not** here: the alert is still open in \"Needs you\" and its card carries the note, so the brief reports it under \"what changed\" (a REWRITTEN block) rather than as done. Each row is structured, not just a sentence: `kind`, the audit `summary` (nudge bookkeeping marker stripped), `at`, `alert_id`, `event_type` (for a pre-filtered `/audit` deep link), `headline` (the alert's headline at move time; a watch's slug), `target` (person name for routed / nudged, survivor headline for merged, new severity for escalated, draft title, workflow name), `detail` (the cited evidence or the watch policy's reason), `outcome` (`resolved` | `dismissed` for a close, `proposed` for a route that went through the authority gate), `evidence_ref` (S1 / R2 / A3), `superseded_by_alert_id`, and `status` — the alert's lifecycle state **now** (`open` = live in the queue per `lifecycle.is_live` | `resolved` | `dismissed` | `expired` | `merged` | `acked` | `inactive` for snoozed / past-TTL rows), looked up per row so a close the principal already undid renders as reopened instead of offering a second Undo, and a \"still open\" jump link only appears when there is a card to land on. Audit rows private to the principal (say, one naming their contact) are in this list only on the principal's own `/today`: `brief_state.handled_since` leaves them out unless asked, and the written briefs never ask, since a brief can be read by others. The Pulse heatmap's per-day counts (`GET /today/activity/daily`) likewise leave out a private decision or private alert, as the activity rail does. The morning brief also carries a one-line count of research watch suggestions waiting on `/watchlist`.\n\n**From your chats.** `briefing.brief_requests` holds what the principal asked of their brief in conversation: `leave_out` lines from `leave_out_of_brief` (\"take the Halcyon renewal out of my brief\", kept 14 days) and `raise` lines the conversation review could not fix itself (`raise_in_brief`, kept 2 days), at most 20 live. A line is at most 12 words (leave out) or 30 (raise), with no link, handle, markup, identifier or talk of instructions, and only lines written under the principal's own id render. `render_briefing_context(brief_requests=True)` adds the raise lines before the quiet-day check, so they are raised even on a quiet day, and the leave-out list as the very last block; both sit inside the rendered string the /today header hashes. A teammate's brief or header passes `False`: they are the principal's own words.\n\n**Standing facts.** `render_briefing_context` appends the standing facts (`memory.facts`: corrections kept from chat, a teammate's marked `(per <name>)`) as its last block, after the quiet-day check, so a fact never makes a quiet day look busy. Every brief prompt (this header, the teammate header, the morning brief and the end-of-day digest) carries `narrative.STANDING_FACTS_RULE`: use the facts quietly, never mention one or that it was saved, and leave an item a fact settles out without saying it was dropped. A fact settles only what it plainly says. Without it, a fact saved in chat came back as the header's top point, stretched to an item it never named. The morning brief also carries **TEAMMATE CORRECTIONS SINCE LAST BRIEF** (`facts.render_teammate_changes(since)`: each teammate fact recorded in the window that is in use now, plus — only when the brief is the principal's own private one (`_private_ok`), which then keeps the run out of the shared history — those waiting for their approval, since other teammates may run the brief and never see a proposal that is not theirs) before the quiet check — it is news, the principal's only FYI of it — and in the brief's fingerprint (`build_brief_fingerprint(teammate_changes=)`), so a correction alone un-suppresses an otherwise unchanged brief. Every other caller passes none, so its context is unchanged. The /today header hashes that rendered string as its cache key, so a new or retired fact marks the header stale and it is rewritten with the correction. The morning brief (standalone) and the teammate-scoped header get the same block. On the scheduler's delivery to the owner alone, with their Always in the loop switch on, `render_briefing_context(owner_notes=)` also carries FROM YOUR NOTES — DUE SOON (their own notes of what they promised or asked, overdue to a week ahead; `memory.history_brief`), which counts against a quiet day, enters the fingerprint and marks the run private; both standalone prompts turn it into a **From your notes** section. The /today header never gets it. **The first week.** For seven days from the principal's People row (`briefing.first_week`), `render_briefing_context(getting_started=)` carries a GETTING STARTED block right after the live blocks: the install's goal rows (department, key result, target, period) or, while there are none (setup saves no goal rows, so this is a fresh install's usual case), this year's priorities and north star from the saved profile (`strategic_priorities`, up to five, keys `priority:<text>`), departments with no `head_person_id`, and, on the scheduler's delivery to the principal alone with Act as me and Draft replies to my inbox both on and the mailbox connected (the inbox watcher's consent), up to five people who wrote to their own mailbox in the last 48 hours as sender and subject only (`inbox_message_ids` + headers of `get_message`, bulk and automated mail skipped; the same \"where, never what\" rule as `delegation.mail_reads`) and, with Act as me and Read my calendar on, up to eight of today's events on their own calendar as time and title (declined ones left out). It counts against a quiet day, enters the fingerprint (`getting_started=` keys, no dates; a meeting's key is its event id) and, with the inbox or calendar part, marks the run private. Both standalone prompts open with a **Getting started** section and take the Top call from it (`GETTING_STARTED_RULE`). The /today header does not get the block: in the first week it is the same header as any other day. Home's top slot is instead the **first-week card**, built in code with no model call (`first_week.first_week_card`): `needs_goal` while no goal row exists (fixed ask \"Give me one goal with a date, and I'll track it every day.\" and a **Set a goal** button to `/goals?add=1`, which opens the add form), up to two findings from the latest finished team `executive_research` run (the run history keeps only the artifact, so `executive_research.parse_artifact_findings` reads back its \"Findings reviewed\" lines; most severe and most certain first, headline plus the summary's first sentence) with a line linking `/watchlist`, and `brief_tomorrow` on the setup day until the first morning brief is delivered. No goal still to set and no findings means no card. `GET /today` sets `first_week_card` and `first_week` (whether there is a card) for the principal only; while there is one the Briefing hides the \"Quiet day\" banner and an all-zero summary line reads \"Your first week. Start below.\" The last setup screen (`OnboardDone`) offers one first question built from the saved priorities (`firstQuestion`) and hands it to Home through session storage (`oe.onboard.firstQuestion`, never the URL), which asks it once. A teammate's scoped header never gets it. The alert review's `render_batch` puts the same block ahead of the alerts (read once per pass), so a note, rewrite or routed DM never repeats a figure the principal already corrected.\n\n**When a brief isn't sent.** Above the Briefing, the owner sees a one-line notice when their latest morning brief, end-of-day digest or (in solo mode) weekly review wasn't sent — \"Your morning brief wasn't sent: nothing is set up to send it to you\" — with the day, what fixes it, a link to read the brief on the Artifacts page (left out when the brief couldn't be written at all) and one to Setup status. It comes from `GET /today/brief-delivery` (the scheduler records each run's outcome), shows nothing while briefs go out or while the scheduler is off, and clears once the cause is fixed. When the Executive's mail connection wasn't running (the MCP gateway failed to start and is retrying), the notice says that instead of blaming the owner's setup; a send that failed on every channel names what each channel answered, from the recorded `detail`, with addresses left out. Teammates never see it.\n\n**Replies waiting.** With Act as me's **Draft replies to my inbox** on, the top of the Briefing's left column lists the replies the Executive drafted in the owner's own Gmail for mail that needs them (`RepliesWaiting`, from `GET /delegation/replies` — see Act as Me). They belong to the owner alone: the route answers only the person who can have Act as me, the decisions behind the cards (`delegation_reply`) are principal-only and carry `private: true`, so `/today/activity` and the heatmap leave them out, and none is ever an alert, so nothing of them reaches `GET /today`, the header or the briefs. Each card shows who wrote and who they are to the owner, whether their address was verified, the subject, what they wrote (as plain text), the draft, **Decide before sending** (its open questions) and its warnings, with **Send**, **Edit in Gmail** (the thread in their Gmail) and **Dismiss** (which deletes the draft unless they edited it). **Send** asks first, naming who the reply goes to, then sends the draft exactly as it is in Gmail (`POST /decisions/{id}/approve`); when its recipients changed in Gmail or a newer message arrived, the backend's 409 `confirm` becomes a second question naming them. The card hides itself when nothing is waiting.\n\n**Solo focus cards.** `GET /today/top-three` and `GET /today/weekly-review` feed two solo-only cards, so a principal who only uses the web app — no chat app, no Google Workspace — sees today's top three and the weekly review instead of finding them only in the Workflows run history. Both answer only in solo mode (`effective_workspace_mode`) and only to the principal, by the stricter rule for starting a principal-only run (`workflows._caller_is_the_principal`: the caller's own email on a principal entry that is not archived, or no `x-caller-email` at all — never \"nobody is principal yet\"); a teammate, any other signed-in caller and team mode get null. `top-three` hands `open_loops.principal_due_soon()` to `briefing.top_three.build_top_three` — the morning brief's own inputs and code, so the items, their order and their free slots are the brief's — and returns `{items: [{key, kind, text, why, slot}]}`: `slot` is the free block (\"10:00–11:00\", the user's zone), \"\" when none is left, or null when no calendar was read (none connected, a failure or the 4 s timeout, a weekend); `items` is empty when there is nothing to pick. It is a route of its own, never part of `GET /today`, so the Briefing never waits on the calendar. `weekly-review` returns the latest `weekly_review` run with status `done` (`persistence.list_runs(..., status=\"done\", limit=1)`, newest `updated_at` first; failed and running runs never count) as `{run_id, completed_at, period, top_three, excerpt}`: `weekly_review.summarize_review` reads the artifact's title line and its last *Next week's top 3* section back as plain text, and `excerpt` stands in when that list is empty (the section's own note, else the review's first lines). Null when no review has completed or the run store cannot be read.\n\nThe route resolves the caller from `x-caller-email`, serves the viewer's cached narrative and, when its key moved, rewrites it in a `BackgroundTask` so the request never blocks on an LLM call (the page re-polls while `narrative_stale` is true). `GET /today/activity` returns the recent self-initiated action rail — merged from fired scheduled actions (DMs, follow-ups, nudges, cadences), logged decisions, saved advice, completed workflow runs (briefings/check-ins/research), kicked-off initiatives, resolved gated decisions, and raised alerts, so it reflects all of the Executive's activity rather than just dispatched messages. A brief or digest delivered to its reader (`scheduler.runner._deliver_to_principal`) records its send as kind `brief_delivery` (`schedule_tools.recorded_as`): the outbound guard still counts it, but the rail and the heatmap leave it out, because every later brief reads the rail and used to repeat its own last top call as work done. A completed run is named in plain words, never by its log title (`workflows/run_outcome.py`: \"Researched your market\", \"Checked in with Sales\", or the name it was started with, less any date or how-it-started note), and carries `detail`, one line on what came of it read from its stored artifact (research: updates looked at, messages sent, alerts raised, things now watched; a check-in: actions proposed; the weekly review: next week's top item; other runs: the first sentence; none for briefs and the reflection), and `artifact_id` (`run:<id>`) when it kept a write-up (never for the reflection, which reads the principal's live alerts), so Pulse's Done for you and All activity link **Read it** to `/artifacts/run:<id>`. The Pulse page (`/memories`) polls it (limit 100) every ~20s so new events stream into the 'Recent activity' card, which scrolls internally at a fixed height instead of growing the page. The `morning_brief` workflow calls `_build_today()` directly to build the standalone DM (via a different, enumerated prompt; solo mode has its own, with goals at risk by area and no waiting-on section). `GET /morning-brief` is a deprecated alias.\n\n**Solo mode in the UI.** The response is the same in both modes; the briefing reads the workspace mode from the app-wide `WorkspaceProvider` (which reads team while loading or on error, so a team install never flashes solo) and, in solo, drops the team surfaces: the Departments card, the People card, the \"Across the team\" lane (every action proposal is the one user's, so all of them land in \"Needs you\"), the people-awaiting, people-overdue and departments-at-risk status pills, and the quiet-day \"Set up a check-in\" link. A \"N goals at risk\" pill (at-risk plus off-track goals, from `departments`) links to `/goals` instead, so the strip never reads \"All clear\" over a goal that is slipping. In the Departments card's place, **Your projects** lists the initiatives with status `active` (`GET /memories/initiatives`): **Done** marks one `completed` through `PATCH /memories/initiatives/{id}` (only `completed` takes an initiative out of the Executive's active context), and **Drop** deletes it through `DELETE /memories/initiatives/{id}` after a confirm. Under **Needs you**, a **Due soon** card lists the principal's open loops that are overdue or due within 7 days — their dated commitments and what others asked of them — read from `GET /people/{id}/open-loops` for the principal (the oldest principal in `people`, the backend's rule), labelled by `lib/dueSoon.ts` (tested by `npm test`: \"Overdue since Sep 23\" / \"Due today\" / \"Due Mon, Sep 28\", with a count of anything due later); **Done** closes one through `POST /open-loops/{id}/close`, which also stops the nudge engine chasing it. Above it, **Top three today** numbers the morning brief's three (`GET /today/top-three`) with each one's reason and, when a calendar was read, its free slot (or \"No free time left today\"); at the top of the right-hand column, **This week's review** (`GET /today/weekly-review`) shows the period, when it ran, next week's top three (or the excerpt) and a *Read the review* link to its run page (`/jobs/runs/{id}`). Each card fetches on its own once the Briefing has loaded, so a slow calendar never holds the page up, and renders nothing when the API returns null or an empty list. A commitment in the top three reads as the owner's own (\"Send the proposal\") through `lib/dueSoon.ts`'s `loopText`, as in Due soon; the cards' wording lives in `lib/rhythmCards.ts` (tested by `npm test`). The Pulse page hides its \"Department check-ins\" and \"Awaiting people\" blocks in solo, and its header shows active projects in place of the department check-in count. Team rendering is unchanged.\n\n**Your month (`GET /today/value`).** The owner's own tally of what the Executive did for them, `briefing.value_summary.summarize(period, offset)`: the calendar `month` or `week` (Monday first) in the user's zone, `offset` periods back (0–24), each line beside the period before. Every number is a `COUNT(*)` of rows that prove it happened, never a model's: messages sent for the owner (the DM handlers' own `kind=outbound` sent rows to anyone but the owner, plus Gmail / Outlook send-tool calls that didn't come back with an error, so mail sent from a chat turn counts), replies drafted and sent from the owner's inbox (their Act as me rows), meetings booked (calendar create calls), briefs delivered (the scheduler's `delivered` row), reports (finished team workflow runs, minus the daily rhythm runs and any run a teammate started for themselves, which stays theirs alone; the latest ten listed with links), follow-ups and nudges sent, tasks tracked and closed as done, proposals decided, alerts flagged and requests answered (`chat_turn` out rows). No \"hours saved\" and no cost line: nothing recorded supports the first, and cost next to what the owner got reads as a bill; it has `GET /audit/usage`. The owner's alone (403 for anyone else): it counts rows private to the owner, never a row private to another member. Pulse shows it as the top line of the overview's **Done for you** panel (\"October 2026: 42 messages sent, 6 reports, 3 meetings booked\") and a focused screen, `/memories?tab=value`, with a month / week switch and previous / next. On the first weekday of each month, in daytime (09:00–18:00 local), a scheduler tick hook sends the owner last month's lines and a link (`value_summary.maybe_send_monthly`, claimed once per month under `briefing_narrative` scope `value_summary:YYYY-MM`), in solo and team mode alike; nothing is sent for an empty month. Off with `VALUE_SUMMARY_MONTHLY_ENABLED=false`.\n\n## Alert lifecycle & the Executive review\n\nAlerts used to be write-once: raised, then never looked at again, so the \"Needs you\" queue grew without bound and the briefs re-listed it daily. Four things now keep it live and true:\n\n- **Time-to-live** (`openexecutive.alerts.lifecycle`). Action items expire after `ALERT_TTL_DAYS_ACTION` (14 d), unrouted low/medium monitoring signals after `ALERT_TTL_DAYS_MONITORING` (3 d). Every surface reads `list_live_alerts` (the same predicate the scheduler's 15-minute sweep persists as status `expired`), so `/today` is right even before the sweep runs. Artifacts and decision-backed alerts are exempt. `POST /alerts/{id}/reopen` is the Undo. **Snooze** (a card's ⋯: later today, tomorrow 9:00, Monday 9:00, in the viewer's clock; `POST /alerts/{id}/snooze`) hides a card until `snoozed_until`, with an Undo; the TTL anchor is the latest of `created_at`, `last_seen_at` and `snoozed_until`, so a snoozed card comes back rather than expiring unseen.\n- **Coalescing** (`alerts.pipeline` + `store.coalesce_alert`). A repeat of an open alert with the same `(source, dedup_key)` updates that row — `occurrence_count`, `last_seen_at`, severity max — instead of stacking a second card, and only re-pings when severity rose to high/urgent. Monitoring alerts carry a stable `watch:<slug>` key, so one watch means one card.\n- **Collection tags** (`alerts.pipeline`). A triaged alert never carries a `collection:<name>` tag: the pipeline strips them before inserting. Only an installed extension's own code files a document into its collection (`orchestrator.extensions`), so injected text can't make a card that the extension would treat as its own.\n- **The review** (`openexecutive.alerts.review`, heartbeat `alert_review_scan`, every 6 h and right before the morning brief). For each open alert the Executive sees what changed since it was raised — newer signals from the same watch, related alerts, activity since, the roster with SLAs (team members only — an alert routed to a contact never puts them in the slice, so they are never routed to, nudged or chased; a private card is never reviewed at all, nor used as evidence for another), department authority — and returns a verdict (relevant / changed / resolved / stale) plus a recommended move. Deterministic policy then acts: **route** (assign + DM the owner; `propose_via_alert` for propose-only departments), **nudge**, **escalate** (severity + `due_at` + DM the principal only), **draft** (`draft_artifact`), **suggest a workflow** (a link, never a run), **merge** (`superseded_by_alert_id`), or **resolve** — only on high confidence citing a server-minted evidence ref (a newer signal, a related alert, an activity item shown for that alert); free text never closes a card, and anything weaker is annotated `likely_stale`, demoted 30 ranking points, and left for one click. Everything that came from outside is rendered as inert data inside the review prompt, so an injected email body cannot steer the batch. Board / comp / legal matters only ever go to a scope-holder or the principal and keep their text. Route and escalate are idempotent across passes, every DM carries an \"[Alert review] Re: …\" header, outbound moves are capped per pass, passes are single-flight, `ALERT_REVIEW_ENABLED=false` stops every caller, every move is audited with its evidence and prior state, and a distinct `resolved` status keeps Executive closes separate from `ack` (user approved). A review DM is proactive outreach, so the recipient's notification settings apply: one held for their quiet hours or brief counts as a route made but not as a nudge toward the cap (and no second nudge is held while one waits), and one about an alert whose severity is (or becomes) `urgent` is marked urgent (`notifications.urgent_send`) and gets through when they let urgent things through.\n- **Grounded text** (`openexecutive.briefing.grounding`). Nobody reads an alert's text before it is dispatched, so what the model wrote onto it must be supported by what it read. After triage (`alerts.pipeline._ground_decision`, before coalescing or inserting), a headline naming a person or figure the event does not hold — sources are the event's subject, sender, title and body, the initiatives triage was shown and the company profile — is replaced by the event's own subject, such body sentences are dropped (all of them → the event body cut to 280 chars); both fallbacks are raw event text, so they are made inert first — links masked, Markdown and Slack `<…>` syntax and @-mentions stripped — because a broadcast posts them as written, and such a suggested action is dropped. A review `changed` rewrite is checked against the alert's own text and the evidence it was reviewed with (signals, related alerts, activity, the roster slice), plus the standing facts the batch was shown, so a rewrite that corrects a card to one of the principal's corrections is grounded; an ungrounded rewrite keeps the old text, still applies a severity change, and audits `text_ungrounded`. A name counts as grounded only when one source line holds all of it; a figure only when a source number matches it within the precision it is written with. Each finding writes a `grounding` audit row; `GROUNDING_CHECKS=report` records without changing anything.\n\nOn the page, cards read as decisions: the one-line \"what changed since you last looked\" (`review_note`) leads, the recommended move is the primary control (Nudge <owner> → chat; Run <workflow> → `/jobs/<name>`), with chips for age, seen ×N, why-now / due, folded-in and draft-ready, a \"Reviewed <ago>\" footer, and an amber Likely-stale treatment with one-click Dismiss. \"Needs you\" shows *Start here* + 8 cards + \"Show N more\", a \"Dismiss N older than 7 days\" footer (explicit ids to `POST /alerts/bulk-ack` — never a server-side age sweep, which would hit teammates' routed items), and \"Re-check relevance\" (`POST /alerts/review`). The handled rail (anchor of the \"Executive handled N overnight\" pill) is deliberately one sentence by default: a first-person heading built from counts only — \"Since your last brief: N off your plate (closes still standing, and merges whose survivor is not itself listed; a merge into a listed survivor counts on that survivor's row), N in others' hands (routed / nudged), N waiting on you (escalated)\", plus \"N drafts ready\", \"N workflows suggested\", \"N watch changes\", \"N other moves\" (a kind the UI does not know) and \"N back on your plate\" (a close that is open again) when present — with the rows behind a \"details\" disclosure, and nothing rendered at all when the grouped rows are empty. The pure logic (grouping, headline, links) lives in `packages/ui/src/lib/handled.ts` and is covered by `npm test`. Expanded, it shows one first-person row per alert (\"Resolved *X* — evidence\", \"Dismissed *X* as stale — evidence\", \"Handed *X* to Dana Kim\" / \"Proposed *X* to Dana Kim (awaiting their approval)\", \"Chased Dana Kim on *X*\", \"Raised *X* to high\", \"Drafted *T* from *X*\", \"Folded *X* into *Y*\", \"Started watching *slug*\"), escalations first; rows sharing an alert collapse to the newest move with the others as an \"also …\" trailer — a close always keeps the visible slot (it carries Undo), otherwise an escalation beats routed / nudged / drafted; a merge whose survivor is listed becomes \"N duplicates folded in\" on the survivor. Every row links its `evidence_ref` (or \"evidence\") to `/audit?event_type=…&q=…` (the audit page pre-fills those filters from the query string), a still-open row jumps to its card (`#alert-<id>`), drafted rows link `/artifacts`, watch rows `/watchlist`. Undo is offered only while the close still stands (`status` not `open`); a reverted close shows \"Reopened\". Dismissing a watch-sourced alert lowers that watch's `trust_score` (which discounts ranking and is shown to the review as evidence); the ack body may carry `mute_topic`. Acknowledging or resolving an alert — including the review closing it itself — marks the review's DMs about it `acted` in the Attunement outcome ledger, for the person it is routed to and the principal only; dismissing it, finding it stale or letting it expire voids them (counted neither way). Review DMs are tagged `alert_review` with `alert:<id>`.\n\n## Multi-client practice section\n\nIn multi-client practice mode (2+ client slots — see the Client Companies section), the response gains an additive `practice_clients` list: rollup cards for the **parked** clients (overdue follow-ups, awaiting replies, unread alerts, onboarding due soon, renewal countdowns), each stamped with the save point its data reflects. Single-company installs always receive an empty list and the UI renders nothing.",
"mermaid": "flowchart TD\n REQ[\"GET /today\"]\n BUILD[\"_build_today()\"]\n DEPTS[\"departments<br/>(per-dept goal health)\"]\n ROSTER[\"people<br/>(attention-ranked roster)\"]\n PROPS[\"proposals<br/>(unread alerts, routed)\"]\n INFLIGHT[\"in_flight<br/>(pending follow-ups / nudges)\"]\n AWAIT[\"awaiting<br/>(replies we await)\"]\n NARR[\"viewer-scoped narrative (BackgroundTask)\"]\n MB[\"morning_brief workflow\"]\n TOP3[\"GET /today/top-three<br/>(solo, principal only)\"]\n PICK[\"build_top_three()<br/>(calendar read, 4 s cap)\"]\n WREV[\"GET /today/weekly-review<br/>(solo, principal only)\"]\n RUNS[\"workflow_runs<br/>(latest done weekly_review)\"]\n LIVE[\"live_signals<br/>(inbound / held replies / chats,<br/>cached calendar)\"]\n TICK[\"scheduler tick<br/>(every 10 min, 06–22 local)\"]\n CACHE[\"briefing_narrative<br/>(principal / company / person:id)\"]\n REQ --> BUILD\n BUILD --> DEPTS\n BUILD --> ROSTER\n BUILD --> PROPS\n BUILD --> INFLIGHT\n BUILD --> AWAIT\n REQ -->|\"resolve caller, attach\"| NARR\n LIVE --> NARR\n TICK -->|\"refresh_principal_narrative\"| NARR\n NARR --> CACHE\n MB -->|\"since last brief\"| LIVE\n MB -->|\"calls directly for standalone DM\"| BUILD\n MB -->|\"same pick for the DM\"| PICK\n TOP3 --> PICK\n WREV --> RUNS\n class REQ entry\n class BUILD compute\n class DEPTS storage\n class ROSTER storage\n class PROPS storage\n class INFLIGHT storage\n class AWAIT storage\n class NARR compute\n class MB compute\n class TOP3 entry\n class PICK compute\n class WREV entry\n class RUNS storage\n class LIVE compute\n class TICK entry\n class CACHE storage",
- "generated_at": "2026-10-21T13:00:00Z"
+ "generated_at": "2026-10-21T00:00:00Z"
}
diff --git a/packages/core/openexecutive/architecture/prebuilt/workflows.json b/packages/core/openexecutive/architecture/prebuilt/workflows.json
index 7c8b69be..86f40226 100644
--- a/packages/core/openexecutive/architecture/prebuilt/workflows.json
+++ b/packages/core/openexecutive/architecture/prebuilt/workflows.json
@@ -1,7 +1,7 @@
{
"section_id": "workflows",
"title": "Workflows",
- "markdown": "Workflows are deterministic, multi-step orchestrations. The built-ins are registered in `openexecutive.workflows.WORKFLOW_REGISTRY`; user-created (dynamic) workflows are stored as data (see below). Each follows the same contract: structured input feeds an ordered list of named steps that render a Markdown artifact, persisted via `complete_run` into `workflow_runs.artifact`. The activity feed never shows a run's log title (`\"Executive Research (periodic)\"`): `workflows/run_outcome.py` gives each finished run a plain name (\"Researched your market\", \"Checked in with Sales\", or the name it started with, less its date) and one line on what came of it, read from that stored artifact, so older runs read the same and nothing extra is written or called. Every step emits a `WorkflowEvent` (start/progress/complete) streamed over SSE at `/workflows/{name}/runs`.\n\nThe registry holds 25 built-in workflows, plus any number of user-created ones. Representative built-ins:\n\n- `board_prep`, `quarterly_plan`, `annual_plan` — planning and governance deliverables.\n- `performance_review`, `comp_refresh`, `org_design`, `exec_search_brief` — people and org artifacts (the last is an advisory hiring brief / scorecard from the CHRO, with input from the hired function's specialist — `sales` for a sales role — kept when the recruiting pipeline was removed).\n- `crisis_comms`, `churn_deep_dive`, `competitive_teardown` — situational analyses.\n- `department_check_in` — runs on department cadence; its `goal_status` step returns structured verdicts persisted back to `department_goals.status` (`department_check_in.persist_goal_verdicts`, shared with `weekly_review`).\n- `weekly_review` — the principal's weekly look back and ahead (see *Weekly review* below).\n\n**Standing facts in unattended output.** `end_of_day_digest`, the weekly review's top-three call and the morning reflection append the standing facts (`memory.facts.with_standing_facts`; a teammate's marked `(per <name>)`) to their user turn, and the morning brief gets them through `render_briefing_context`. A workflow step that consults a specialist gets them through `route_to_specialist`. A correction made in chat therefore holds in every recurring brief and run. The morning brief also reads `facts.render_teammate_changes(since)` off the event loop and passes it to both `render_briefing_context` (a TEAMMATE CORRECTIONS SINCE LAST BRIEF block) and `build_brief_fingerprint`, so the principal hears of each correction a teammate made in the window, and that alone un-suppresses an otherwise unchanged brief. Proposals waiting for approval are listed only in a brief the principal reads privately (`include_proposed=_private_ok()`), and then mark the run private to them. The principal's own Always in the loop notes (`memory.history_brief`, only with their switch on) come in by a stricter rule, only on the scheduler's delivery (`PRINCIPAL_DELIVERY`), never a run from chat, whose tool result reaches the turn's shared audit row and peer memory: the morning brief's FROM YOUR NOTES — DUE SOON block and the end-of-day digest's FROM YOUR NOTES — TODAY block (what they committed to since the last digest, then what is due tomorrow). Either marks the run `private_to_principal` and moves its fingerprint; the digest, which had no private reads before, now emits that flag too. In the install's first week (`briefing.first_week`, seven days from the principal's People row) the morning brief also passes a GETTING STARTED block to `render_briefing_context(getting_started=)` and its keys to `build_brief_fingerprint`: onboarding goals, departments with no leader and, on the scheduler's delivery with Act as me and Draft replies to my inbox on, who wrote to the owner's own mailbox (sender and subject only) and, with Read my calendar on, today's meetings on their own calendar (time and title), either of which marks the run `private_to_principal`. The brief opens with **Getting started** and is never the quiet line while the block has anything in it (see Today).\n\n### Change-aware principal briefs\n\n`morning_brief` and `end_of_day_digest` are the two recurring briefs the scheduler sends to the principal. Both are written with `briefing.narrative.brief_model()`, the Executive's own model (its Council pick, else `DEFAULT_MODEL`), since a brief is the Executive speaking; only the grounding repair stays on the fast model. Both are now a *delta*, not a re-list: the window is \"since the last **delivered** brief\" (`briefing.brief_state.since_for`; 24 h on a cold store, clamped to 7 days), activity comes from `_build_activity(limit, since=…)`, proposals (action category only) split into *new since last brief* — enumerated, with each item's why-now and next move — versus a one-line carried-over count, a *rewritten* block lists carried items the review rewrote inside the window (`brief_state.rewritten_since`: verdict `changed`, still open — the brief reports them under \"what changed\", never as done), and a *handled overnight* block lists what the Executive's alert review **completed** on its own (`brief_state.handled_since`; the `changed` verdict is excluded because the alert is still open). The morning brief also reads the principal's **live world** since that window opened (`briefing.live_signals.gather_live_signals`): mail and chat the Executive handled (INBOUND, grouped by sender and subject, each email from the roster marked replied or not, earlier days dated), under a NOW line and THE PRINCIPAL line that names its reader so the brief writes \"you\" (the end-of-day digest gets the same line, and the team reflection a YOUR PRINCIPAL line under its roster; the reflection flags only what today's input still shows), what got stuck (STUCK: a reply the outbound gate held, a non-roster sender who got no reply, a Google Chat message left unanswered, chat drafts still in the principal's Gmail, after `live_signals.settle_principal_drafts` has marked the ones they since sent or deleted there), the principal's own chats, and — in both modes now, unless the solo top three already listed it — today's calendar, read fresh (`live_signals.refresh_calendar(max_age=0)`). The 07:30 reflection's **Flagged for the brief** bullets are carried across (`brief_state.reflection_flags_since`, the latest reflection run finished inside the window) instead of surviving only as an activity line with the run's title, and the rhythm runs themselves (`today.RHYTHM_WORKFLOWS`) are dropped from the brief's activity: their dated titles were noise and moved the fingerprint every day. At-risk departments name their slipping goals and each proposal carries its age. The period is the principal's local date. Section order: top call → **today** (the calendar's shape and anything stuck) → what changed (inbound first, naming who wrote) → handled overnight → needs you (new only) → waiting on → at risk (the slipping goal, or the department left out — never \"no detail yet\"). Quoted mail, chat, invite and reflection text is marked as data, never instructions. **Privacy:** the brief reads what is private to the principal — their contacts' alerts and mail, their drafts, their chats and their calendar — only on a run for them: the scheduler's (`morning_brief.PRINCIPAL_DELIVERY`) or the principal's own verified chat turn in a conversation only they can read (`delegation.settings.private_conversation`: the web chat, a Slack or Discord DM, a private Telegram chat — never a shared channel, where the reply is posted for everyone). A run anyone else starts (a teammate from chat in team mode, `POST /workflows/…/runs`) reads what everyone may see, as before. A run that did read a private row says so on its `result` event (`private_to_principal`: its live read differs from the shared one in any key or count), and the scheduler, `run_workflow` and `POST /workflows/{name}/runs` all then keep `persistence.PRIVATE_RUN_ARTIFACT` in the run history instead of the text. Text another pass wrote (the reflection's flags) renders as quoted ` > ` lines and every goal and headline field is one-lined, so none can start a line that reads as a block header. The fingerprint carries the live signals' time-free keys (who wrote about what, what is stuck, the calendar's shape) and the reflection flags when there are any, so \"nothing new\" means the principal's world was quiet too; the context summary is logged at INFO (`morning_brief: context since=… inbound=… stuck=… suppressed=…`). In **solo mode** (one person using Open Executive for themselves) both briefs speak to the principal, whatever their role: the morning brief runs top call → top three today → what changed (inbound and stuck first) → handled overnight → needs you → due this week (the principal's open loops overdue or due within 7 days, from `open_loops.principal_due_soon`) → goals at risk (named by area), the end-of-day digest what I did → open decisions → goals at risk tomorrow → sleep on this, over a context with goals at risk by area and no people-waiting or department block; the fingerprint carries the mode and ignores who is awaiting, and carries the due items as `(loop_id, state)` pairs when there are any. **Top three today** is picked in code, not by the model (`briefing.top_three`: overdue then due-today commitments, off-track then at-risk goals, commitments due later this week, then active projects, stalest first). The solo Briefing's *Top three today* card shows the same pick from the same code (`GET /today/top-three`, see Today). When the MCP gateway runs the Google Workspace server, one `google_workspace__get_events` call (4 s timeout) lists today's events on the principal's calendar — their address as the calendar id, read with the Executive's account (`primary` when the Executive is signed in as them) — and on a business day (`calendar_tools.is_business_day`, the rule the booking tools apply; at the weekend the day's events are still listed but no slot is suggested) each item gets its own free block inside `CALENDAR_BUSINESS_HOURS_START`–`_END`, rendered with a TODAY'S CALENDAR block — only a date-only event is all day, a zero-length one blocks nothing, and one whose times can't be read is left out; no gateway, no principal address, an error, a timeout or a reply it cannot read all mean no calendar and no slots, never a failed brief; the log records only the reply's length or the error's type, never calendar text. When the principal has Act as me and **Read my calendar** on (`delegation.calendar`) and their mailbox opens as theirs, `top_three.read_todays_calendar` also reads their own calendar through their own sign-in (Gmail or Outlook, same 4 s timeout, declined events left out), at the same time as the Executive's read, and merges the two: an event with the same title and times on both is listed once, and either read alone is enough. This read feeds the morning brief, the /today calendar cache (`live_signals.refresh_calendar`) and so the end-of-day digest and Right now; the solo top three adds it only on a run for the principal (`build_top_three(include_own=private_ok)`). The fingerprint carries the three items' keys (no dates, no slot times) and only a coarse hash of the day (busy blocks rounded to 15 minutes, no titles, no dates), so an unchanged day still suppresses. A day whose calendar read fails after one that worked (or the reverse) changes the fingerprint once, so that brief is written in full. A date-free fingerprint of the inputs is compared to the last delivered one; if unchanged the artifact is the one-liner \"Nothing new since yesterday's brief — N items still waiting on you.\" and no model call is made (`PRINCIPAL_BRIEF_SUPPRESS_UNCHANGED`; `force_full=true` on a manual run bypasses it). The workflow yields a `result` event with the fingerprint; only the scheduler records it, after a successful delivery, in `briefing_narrative` under scope `brief:<kind>` — so manual runs never advance the window. Both are written to their reader in code (`briefing.reader`): the principal's full name and addresses are masked to \"the reader\" throughout the context under a THE READER line, the prompt says \"you\" for the reader, nobody is \"the principal\" and the Executive is \"I\" / \"me\", and a draft that still slips is rewritten once (the morning brief) and fixed in code. **The end-of-day digest reads the day itself.** On the scheduler's delivery to the principal alone it leads with TODAY WITH YOU (`session_store.own_conversation_since`: the principal's own conversations with the Executive since the last digest, their words and its replies, never a conversation someone else owns) and the live blocks (`live_signals.render_live_blocks`: mail in, what got stuck), then COMING UP (the Executive's own follow-ups due in the next two days). It leaves out its own rhythm runs (`today.RHYTHM_WORKFLOWS`) and gets the reader's leave-out list (`brief_requests.render_parts`). Its shape is **Today**, **Done for you**, **Next** and an optional **Sleep on this**, at most 150 words, with no header for an empty section. Before this it read only the Executive's own bookkeeping, so on a day of real work it reported its own briefs and missed every number decided in chat.\n\n**Brief delivery.** `scheduler.runner._deliver_to_principal` maps the principal's `preferred_channel` (`slack` / `discord` / `telegram` / `email`) to its delivery channel and tries it first, then the other chat channels the principal has an id for, in the order Slack → Discord → Telegram. Email goes through the active MCP gateway (`google_workspace__send_gmail_message` as the Executive's own address, to the principal, subject `<title> — <date>`) and is used only for an explicit `email` preference, or for `any` when no chat channel resolves — an owner linked by email at setup has `any`, so one who also has Slack does not start getting two emails a day. When nothing can deliver (a web-only principal, or email with no gateway), the brief is still generated and stored as a run with its artifact, as before — a web-only principal reads it on the Artifacts page — it is just not delivered (audited), so the window does not advance, and the next occurrence is chained. The same delivery path carries the client-rotation digest and the weekly review.\n\n**Grounding.** Nothing an unattended pass writes is read by anyone before it goes, so `openexecutive.briefing.grounding` checks it deterministically — no model judges the model. A name (a run of two or more capitalised words once section headers, weekdays, imperative openers and org nouns are trimmed, or one capitalised word in a person slot like \"ask Marcus\" or \"Marcus wrote\") is grounded only when a single line of the pass's inputs holds all of it, or it belongs to a roster person some input mentions — being on the roster alone is not enough. A figure (money, a percentage, a k/M/B number, any bare number of 11 or more; never a date, time, year, duration, id, list marker, `Q3` or small count) is grounded when an input number matches it within the precision it is written with (`$1.2M` matches `$1,234,567`; `47 units` does not match 48). The inputs are the rendered context split into lines labelled by section (a header also carries its bullet count), the company profile and the department titles. `morning_brief` renders its context itself and hands it to the synthesizer as `rendered_context`, so the check reads exactly what the model read; after the quiet fallback, `ground_brief` runs on both briefs. When something is ungrounded it makes one repair call to the fast model (same system prompt, the list of items, \"remove or correct using only the context\"), re-checks, then drops each line still ungrounded and any header left empty, and appends \"_I left out N lines that named people or figures I couldn't match to your data. They're under Left out of your brief on Home._\" (everything ungrounded → one held-back line). Every held line goes in the `grounding` audit row's untruncated `full` payload (up to 30, 400 chars each; `details` keeps a five-line preview), and `grounding.recent_held_back` reads the last day's back for `GET /today`'s `held_back`, which Home lists under **Left out of your brief** for the principal alone — after the narrative inputs are taken, so the held lines never reach a prompt. Then each grounded figure gets a server-chosen ` [n]` — the matching input line with the most words in common with the figure's clause — and a `**Sources**` list closes the brief (`- [n] <section> — <snippet>`, at most 9, snippets quote inbound mail, so links are masked (\"(link removed)\"), Markdown, angle brackets and @-mentions stripped, and they are cut to 90 chars; never `[n]:` at a line start, which Markdown reads as a link definition). Text with nothing to change comes back byte-identical, the fingerprint hashes the inputs so suppression is unaffected, and the grounded text is what is delivered, stored and recorded as delivered. Both brief prompts and the digest prompts say the rule up front. `executive_reflection` wraps its handlers in a `GroundingScope`: `create_alert`, `message_person`, `send_department_message`, `send_company_broadcast` and `schedule_followup` refuse text with an ungrounded name or figure, returning a JSON error that names the items so the model can look the person up or leave the figure out (every tool result joins the inputs, so a `lookup_person` answer grounds the DM after it; the recipient's own name always counts). Its **Flagged for the brief** bullets are filtered the same way before the tool log is appended — the next brief quotes them, where they would ground themselves — and `brief_state.reflection_flags_since` now stops at the tool log's `---`. The reflection's `grounding` rows are private when a private-to-principal alert reached its context, and the digest's always are (its HANDLED block can quote one). Everything fails open. `GROUNDING_CHECKS=enforce` (default) acts, `report` only writes the `grounding` audit rows, `off` skips it; `GROUNDING_CITATIONS=false` drops the markers. Not yet grounded: the /today header (its cards sit beside it), `weekly_review`, the research synthesis, dates and meetings, and a real person named in the wrong role.\n\n### Weekly review (solo)\n\n`weekly_review` (background, inputs all defaulted) closes out the principal's week in six steps. **Goals**: every area with goals is graded by its own specialist, concurrently, with the department check-in's verdict contract (`_parse_verdicts`) and write-back (`persist_goal_verdicts` → `record_goal_review`, one `goal_status_review` audit row per area with actor `weekly_review`); an area with no goals is skipped, one without a specialist is listed ungraded, and one whose specialist fails is shown as last recorded. **Commitments**: `open_loops.principal_due_soon` — overdue or due within 7 days. **Projects**: active initiatives with no update for 7+ days. **Decisions**: the week's (`episodic.decisions_since`). **Revisit**: up to three decisions older than 30 days with an empty outcome (`episodic.decisions_awaiting_outcome`, newest first), listed as `[decision N]` under *How did these turn out?* — the principal's answer is recorded with `record_decision_outcome` (see Agents). **Assemble**: every section always renders (a one-line note when empty), ending with *Next week's top 3* from one fast-model call that follows the `weekly-review` playbook (a constant system prompt; the playbook rides in the user turn), trimmed to at most three list items — or, when that call fails or returns nothing, the same ranked pick the morning brief uses. In solo mode the scheduler fires it weekly (`principal_weekly_review`, see Scheduler) and delivers it through `_deliver_to_principal` like the briefs, recording the delivery outcome. The solo Briefing also shows the latest completed run to the principal (`GET /today/weekly-review`, see Today): `weekly_review.summarize_review` reads the artifact's title line (`TITLE_PREFIX`) and its last `TOP_THREE_HEADING` section back as plain text, so a principal no channel reaches still sees next week's top three. Wording is role-neutral; run by hand in team mode it says *department* instead of *area*.\n\n**Principal-only workflows.** A workflow can name the workspace modes in which only the principal may start it (`Workflow.principal_only_modes`): `weekly_review` in both modes (built from the principal's decision log, commitments and goals, and it re-grades the goals) and `morning_brief` in solo (built from the principal's commitments and calendar). Team `morning_brief` and every other workflow can be started by anyone as before. This decides who may start or trigger a run, not who may read one: stored runs, the scheduled briefs and weekly reviews included, are read under the existing `/workflows/runs` rules — which is why a morning brief that drew on the principal's private rows is stored as `PRIVATE_RUN_ARTIFACT`, not as its text.\n\n- **From chat**, `run_workflow` checks at dispatch, before any run row is created, that the turn is the principal on a verified surface — `create_goal`'s rule — and otherwise refuses with a plain error that does not spell out the rule.\n- **Over HTTP**, the Jobs page's `POST /workflows/{name}/runs` and `POST /evals/runs` (a workflow scenario runs the workflow on live data) call `refuse_principal_only_run`: only a caller signed in as the principal, or a request with no caller email (the CLI or local login), may start the run. Unlike the workspace settings, an install with no principal on the roster lets no signed-in caller in, as in chat. Anyone else gets a 403 (\"Only the principal can run this workflow.\") before any run row exists. The mode is the stored one, or an eval scenario's own `workspace_mode`. The eval route runs exactly the scenario list it checked.\n\nEvery refusal is audited `refused=true` with the workflow, the mode and the caller. The checks fail closed: a mode that cannot be read counts as principal-only, and a check that cannot read the roster refuses.\n\n**Knowledge in the reflection.** A chat turn looks the knowledge base up before the Executive answers; the reflection reads the org's state instead, so nothing looked it up for it. It now carries its own `search_knowledge` tool (`orchestrator.knowledge_tools`, not in the shared `_ALL_SKILL_TOOLS`), which runs the same `knowledge.retriever.retrieve` as chat — the review gate, the synced Drive / OneDrive / Confluence / Notion collections and the published-artifact rule (the pass has no viewer, so no one's private document comes back). The prompt (`_KNOWLEDGE_RULE`, both modes) asks it to search before acting on or flagging something that turns on a customer's or supplier's terms, a price, a policy, a plan or a past decision. Its passages come back up to 4,000 characters (`execute_tool_calls(wide_results=...)`) while other tools stay at their short preview, its result counts as grounding input like any tool result, and the run's tool log keeps each line to 160 characters. Read-only, so Take the lead never gates it. The loop has 5 iterations (was 4) to leave room for a search before acting.\n\nNeither the nightly reflection nor the research synthesis can call `ack_alert`: both run unattended with open alerts rendered into their context, and those headlines are minted from inbound mail and chat, so an injected \"the principal already dismissed 13\" would be acted on with nobody watching. Closing an alert is the alert review's job, with evidence.\n\n`executive_reflection` now carries memory: yesterday's standup (the previous completed run's artifact) is rendered into the context and the prompt forbids re-acting on anything listed there unless it changed; open alerts render with their id, review verdict and recommended move. Reflection never closes alerts — the alert review does, with evidence. It also renders an **OPEN LOOPS** block (up to 10, soonest due first, overdue flagged) from Attunement so the standup can connect a slipped promise to the rest of the org state; the nudge engine already chases overdue loops, so the prompt tells it not to DM about a loop merely for being overdue. A **WHAT LANDS** block (from the Attunement outcome ledger) shows, per person, how often each kind of proactive DM got answered over 30 days; the prompt steers DMs toward kinds that land and away from kinds a person reliably ignores. Reflection and research tag their tool execution as proactive (`tag_proactive`) so their DMs are counted. Resolving a wait-for-human approval (`resumer.apply_resolution`) marks the nudges that chased it `acted`. `close_open_loop` is withheld from reflection for the same reason as `ack_alert`: loop text is quoted from what people wrote. `unattended_toolkit` also drops `schedule_tools.UNATTENDED_WITHHELD_TOOLS` (today `create_goal`) from both passes in both modes: a goal is the principal's own decision, and these passes see only inbound text. A turn private to the principal (mail from one of their contacts, or mail they forwarded) cannot start a workflow either: `run_workflow` and `run_executive_research` are in `schedule_tools.PRIVATE_TURN_WITHHELD_TOOLS`, which the chat loop neither offers nor runs on such a turn, since a workflow's steps can reach anyone.\n\nIn **solo mode** the reflection is framed for the principal, whatever their role: they are the only person who uses Open Executive and the only one it takes direction from, it prefers `create_alert` and `schedule_followup` to the principal, and it never messages anyone else from an unattended pass — the people in the principal's world are contacts, so anything they should hear is flagged for the principal to raise. The team roster is replaced by one YOUR PRINCIPAL line (person_id and follow-up channels), its follow-up guard is seeded from the principal only, and department risk renders as areas with goals at risk. The research synthesis follows the same rule — its routing menu and roster name only the principal. In both, `send_department_message`, `send_company_broadcast` and `set_department_head` are withheld, and so are `create_calendar_event`, `create_instant_meeting` and `run_workflow` — a booking reaches its attendees and a workflow can do anything its steps do, so the principal books and starts workflows from chat — and `message_person` refuses anyone but the principal. These passes run unattended with inbound text in their context, so the rules are enforced in code, not only in the prompt.\n\nIn either mode, both passes now dispatch only the tools they offer: the handler map is built from the offered list, so a name the model emits without being offered it is skipped as an unknown tool. They used to look names up in the full handler registry, so tools they deliberately withhold — the raw DM tools (`send_slack_dm` has no roster check), `ack_alert`, `close_open_loop`, and in research the watchlist writes and `run_workflow` — still ran when the model emitted them. Both read the mode before binding their own session (so a caller's override, such as an eval's, counts) and pin it on that session, so their tool handlers use the same mode. They carry the principal's role across the same way (`effective_principal_role` of the caller's session, pinned as `turn_principal_role`), so a specialist or workflow started from either pass sees the role of the turn that started it. Team runs are unchanged.\n\n### Wait-for-human pause\n\n`wait_for_human` (`openexecutive/workflows/wait_for_human.py`) is a first-class step primitive that pauses a run: the runner calls `save_checkpoint`, the `workflow_runs` row moves to `status='awaiting_human'`, and the serialized `WaitForHumanEvent` is stored in `state_json`. (Department authority is a *separate* mechanism — `propose_only` departments file a briefing alert via `departments.authority.propose_via_alert` and mark the scheduled action done; they do not route through this gate.)\n\n**Delivery.** Both checkpoint sites — the SSE route and the `run_workflow` chat tool — call `workflows.gate_delivery.deliver_gate_question` immediately *before* checkpointing, so `state_json` carries the routing fields a reply is matched against. Two modes. When the approver is the person already in the conversation (the chat session's `origin_channel` is set — to anything but `email`, whose answer is no chat reply and would never be sent — and its `caller_person_id` is the gate's `person_id`), nothing is sent — the question rides in the Executive's own reply — and the gate records `origin_session_id` plus the session's channel. The resolver compares base ids (`memory.conversation_ids.base_session_id`), so a question asked in one conversation of a Telegram chat or a DM is still answered by a reply after a quiet gap or /new has started the next. Otherwise the question is delivered through `schedule_tools.handle_message_person`, which picks the person's preferred channel, falls through on a failed send, and falls back to a briefing alert; the gate then records the channel, address and provider message id that send returned, plus the id of the DM session it landed in — that send is always 1:1, so the answer belongs in that conversation and nowhere else. Without it the gate matched on person and channel alone, so an unrelated @mention in a public channel resolved it and had the acknowledgement, run title included, posted where everyone could read it. The question is sent with `notifications.approval_send`, so the person's quiet hours and *In my briefs* never hold it, whatever their urgent setting: only a reply to it resolves the gate. Delivery is not guaranteed: the outbound guard can suppress it (duplicate, rate cap, quiet hours) and an unreachable person gets the alert fallback. Both cases leave the routing fields empty and report `delivery` as `suppressed` / `alerted` rather than claiming someone was asked, and the chat tool's presentation hint changes accordingly.\n\n**Matching a reply.** Each inbound adapter passes the message to `inbound_resolver.resolve_inbound_message` with its `session_id`. Matching is three-tier: an explicit `in_reply_to` against a stored `outbound_message_id`; otherwise a single open run on that channel; otherwise one utility-fast disambiguation call gated at 0.85 confidence. An unmatched explicit reference rules out only the candidates that carry a stored outbound id — the ones it could have matched — and the rest continue; rejecting outright meant an adapter that passes a thread id on every message (Slack's `thread_ts`) short-circuited the later tiers forever, and a global test let one delivered gate's id block an unrelated self-approval gate. Channel names are normalized (`slack_dm` ≡ `slack`), the delivered address is compared when both sides know it, a row whose `state_json` will not parse is refused (a corrupt row otherwise presents as a legacy one), and an empty stored channel is treated as a wildcard only for rows checkpointed before gate delivery existed. Two guards keep an open gate from swallowing unrelated traffic: a gate carrying an `origin_session_id` matches replies only from the conversations the adapter names (a Slack or Discord thread offers its parent channel session too, mirroring the history double-write, since a gate raised on a mention recorded that session while the answer arrives under the thread's — on Slack only when that person rooted the thread, or the alias would reach into a colleague's), and the parser can return `unrelated`, which declines to resolve and lets the message reach the normal chat path. The parser is handed the gate's own question, so a bare \"yes\" is judged against something. Its fallback is flagged by a key the model cannot emit rather than by a magic note string it could, and a fallback declines to resolve on *every* reply shape — recording the empty string a `free_text` fallback fabricates would close a sign-off on a parser outage. Every shape can answer `unrelated`, not just `approve_reject`: without it an open `free_text` gate turned the person's next message into its answer verbatim, and a `numeric` one swallowed any message containing a number. The parser has one caller outside workflows: its `roster_identity` shape — `{decision: approve|link|decline|unrelated, name, kind: team|contact|null}`, with `name` only as the person wrote it (never inferred) and a fallback of `unrelated` — reads the principal's emailed answer to a roster request (who a new sender is; see Org). It is not a gate reply shape, and a fallback or `unrelated` leaves the request waiting. `resumer.apply_resolution` then records the decision, marks the run `resolved`, and writes an audit row. A timeout applies the step's `on_timeout` policy (escalate / auto_proceed / fail). The outcome surfaces on the Today dashboard.\n\n**Resuming past the gate.** A paused run continues on its own. Re-entering it was long assumed to mean serializing a Python generator frame; it does not. The only state alive across a dynamic workflow's steps is its inputs (already persisted), a company-profile block that is recomputed, the completed steps' output strings, and the loop cursor — so the engine hands the checkpoint a small JSON `WorkflowResumeState` (workflow name, the gate's id and index, the next index, the outputs so far), stored in `workflow_runs.resume_state_json`, and `DynamicWorkflow.resume` replays its step loop from the recorded index. `run()` and `resume()` share that one loop, which is why a second gate needs no special handling — it is simply another pause raised from the same place. The payload rides on a `WaitForHumanEvent` field declared `exclude=True`, so it can never leak into `state_json`, whose exact key set the resolver branches on. A gate with no payload is *pause-only*: the decision is recorded and the run stops, which is what every caller got before resume existed.\n\n`resumer._process_resumable` claims a resolved run with one guarded UPDATE — `resolved` → `running`, stamping `resumed_at` and minting a claim token — and drives it to a terminal row. It runs two ways: immediately, via a task `apply_resolution` kicks off so a Slack approval starts moving in seconds, and every 60s from the poll loop as the durable backstop. Both share the claim, so a run executes exactly once even with two resumers against one database. The kicked task binds no chat session (`set_session(None)`), exactly like the poll loop: it is created inside the inbound handler that recorded the answer and would otherwise inherit that person's live turn — so a run resumed because the principal replied on Slack does not act with the principal's identity (it cannot, for example, reach the principal's contacts). It drops the handler's audit scope too (`audit.context.unscoped_audit_rows`): inherited, the principal's scope would make private every row of the run that names a contact, and whoever started the run would see those rows vanish after the approval. The poll runs the executor *after* the timeout loop, which is what finally makes `on_timeout='auto_proceed'` do what its name says: the timeout resolves the run and the same tick executes it. While the Executive is paused (`scheduler.pause`) the resumer does nothing — no startup sweep, no timeouts, no resumes — and `apply_resolution` still records the decision but skips the immediate kick; the first unpaused iteration catches up on all of it, so a timeout that lapsed during the pause applies its `on_timeout` policy then.\n\n**The claim is fenced, because it is not a lease.** The stale sweep decides a worker is dead from a wall-clock guess, so a slow but *alive* worker will eventually be declared dead and replaced. Every write the executor makes carries its claim token and is refused once superseded — otherwise the replaced worker's late completion lands on top of its replacement's result, or its checkpoint at a later gate resurrects an already-finished run and asks the approver a second time. The retry budget resets at each new gate (a gate is new work, not a retry), and a run that exhausts it is *ended* rather than dropped: an exhausted run sits in `running` with a payload, in neither queue, and would otherwise show as in-progress forever.\n\n**The gate fails closed.** Continuing is an allowlist — `approve` and the synthetic `auto_proceed` — not \"anything that is not a stop word\". `decision` is whatever a fast model extracted from free-form chat and it drifts; under a denylist, \"rejected\", \"Reject\", \"decline\" and \"no\" would all continue, so the approver declines and the deliverable is produced anyway. Reply shapes that ask a question rather than seek permission always continue, since the answer *is* the value. A stop ends the run at `error` with the human's note. Either way the decision becomes the gate step's own output, so it reads as a section *in* the artifact — capped and blockquoted, because that text reaches the synthesis specialist as prompt context.\n\n**A definition edited during the pause is refused.** Resume re-validates the payload's version, the recorded gate, *and* a fingerprint of the whole step list, and derives the index to continue at rather than reading it from the payload. Pinning only the gate would not be enough: definitions are overwritten by name and any rostered user can save one, so someone could keep the gate identical and replace every step after it — and the approver's sign-off would be recorded against work they never saw, which defeats the one thing an approval gate is for. No built-in workflow yields the gate; only user-created dynamic workflows do.\n\n### Launching from chat\n\nWorkflows are not only reachable from the `/jobs` UI — the Executive can list and run any of them mid-conversation. `openexecutive.orchestrator.workflow_run_tools` wires two tools into the main chat loop: `list_workflows` (the launchable catalog, with each workflow's input fields) and `run_workflow` (runs one to completion and returns its Markdown artifact, using the same engine as `POST /workflows/{name}/runs`). `run_workflow` resolves both built-ins and custom workflows via `get_workflow`, validates `inputs` against the workflow's input model, persists the run (`create_run` → `complete_run` / `fail_run`), and on an approval-gate step checkpoints the run as `awaiting_human` exactly as the HTTP route does — literally the same code, since both call `workflows.gate.checkpoint_gate`, which delivers the question and writes the checkpoint in one place. It never hangs waiting on a human, and it reports both whether the question reached them and whether the run will continue by itself once answered. The runners that *cannot* pause — the schedulers, evals, client rotation, onboarding, the research tools — call `gate.ensure_workflow_event`, which raises on a gate rather than letting one be swallowed; the scheduler's dynamic-workflow branch used to ignore it and record a successful run containing nothing. `executive_research` is excluded (it has the dedicated `run_executive_research` tool). Running a workflow from chat delivers nothing on its own — it renders the artifact into the conversation, and the recurring principal briefs (`morning_brief`, `end_of_day_digest`) reach anyone only via the scheduler's own `_deliver_to_principal`. The tool description used to claim those two DM the principal when run and to confirm before firing them, which had the model soliciting a confirmation on a false premise; it now names `executive_reflection` as the one workflow that really does execute tool calls of its own (DMs to heads, broadcasts, alerts). A successful run surfaces an `action_taken` chip linking to `/jobs/runs/{run_id}`.\n\n### Dynamic (user-created) workflows\n\nUsers create reusable workflows on the fly — from the executive chat, the conversational wizard at `/jobs/new`, or the step-by-step advanced editor — without shipping code. The Workflows page (`/jobs`) opens on a *Start here* panel that leads to all three: the user describes the job in a sentence and *Start* opens the wizard with that text sent as its first message (handed over in `sessionStorage`, so a link cannot make the wizard send text the user never typed; where storage is blocked it falls back to `/jobs/new?describe=`, which only fills the composer and sends nothing), or picks *Step by step* (advanced editor) or *Talk it through in chat* (`/?new=1&draft=`). Below it come the user's own workflows, then four ready-made starter picks with the full built-in list folded behind *Browse all* (`?browse=1`). The picks and the example chips follow the workspace mode: a team gets the investor update, board prep, MBR and competitive teardown (and a board pre-read chip); a solo owner-operator gets the MBR, pricing review, churn deep dive and quarterly plan, with chips for a Friday cash and pipeline check, customers who stopped buying and a competitor digest (`lib/workflowStarters.ts`; a unit test pins every pick to a startable `WORKFLOW_REGISTRY` entry). A dynamic workflow is a stored JSON definition (the `dynamic_workflows` table) interpreted at runtime by one generic `DynamicWorkflow` engine (`openexecutive/workflows/dynamic.py`) that implements the same `Workflow` ABC as the built-ins, so the run path, SSE streaming, run persistence, and `/jobs/[name]` form rendering are unchanged. `get_workflow` / `list_workflows` fall through to the dynamic store after the static registry (built-ins win on a name collision).\n\nA definition declares free-text input fields and an ordered step list of four kinds: **specialist** (consult a specialist with a goal prompt, optionally grounded by RAG), **action** (get something done with tools — see below), **approval_gate** (a `wait_for_human` pause), and a terminal **synthesis** step that assembles the artifact. At least one specialist or action step is required. `validate_definition` enforces the structural rules: exactly one terminal synthesis step, valid specialists, `{placeholder}` tokens that reference declared input fields, rostered approval/cadence people (team members — never one of the principal's contacts, whom an unattended run may not message), and a parseable cadence.\n\nAuthoring from chat uses a **draft → confirm** handshake: the Executive calls `draft_workflow` (validate; return a `confirm_token` plus a plan summary), shows the user the plan, then calls `save_workflow` with the same definition and token — a token mismatch is rejected, so the saved workflow is exactly what the user approved. The step-by-step advanced editor drives the `/workflows/custom` CRUD endpoints directly.\n\n**The New workflow wizard** (`/jobs/new`) is the default way to create one from the UI. It works like conversational onboarding: the user describes the job, the `workflow_designer` Council agent (`openexecutive/workflows/designer.py`) asks one clarifying question per turn — deliverable, per-run inputs, sign-off, schedule, recipient — with up to four clickable suggested answers, then emits a complete definition plus a plain-language summary and the assumptions it made. Every turn offers the model exactly three fixed, name-sorted tools (`ask_clarifying_question`, `emit_workflow_draft` — reusing the chat tool's `DEFINITION_SCHEMA` — and `search_available_tools`, which is answered inside the same turn from the tool catalog, up to four searches per turn, with the tool_use/tool_result pairs never stored in the plain-text transcript; every tool a search returns is remembered on the session and replayed into later turns, so a forced draft or a repair turn — which cannot search — still has the exact names); `tool_choice` flips to the emit tool once, when the six-question budget is spent or the user clicks *Draft it now*. The emitted definition goes through `validate_definition`, the tool-availability check, and a check against saved custom names, with one repair turn that feeds the errors back. The system prompt is a cached constant; the live context — specialists, the roster with person ids, the user's timezone (the one set through `PUT /workspace`, else `USER_TIMEZONE`; cadences stay UTC), and taken names — is rendered once per session into the first user turn, and while refining, the exact current draft is prepended to the latest user turn so the model edits it rather than re-deriving it. Roster names and roles are flattened to one line and capped at 80 characters before they enter that context, and the system prompt tells the model to treat the whole block as data, never instructions. Sessions live in memory (`/workflows/designer/*`, 2 h TTL, 50-session cap), run one model turn at a time (a second concurrent `/message` or `/draft` gets 409, and a failed turn is rolled back by identity), and never write: the review card saves through the same `POST /workflows/custom`, which re-validates, and *Edit details* opens the draft in the advanced editor (`/jobs/new?designer=<id>`) before saving.\n\n**Editing is a conversation too.** *Edit* on a saved workflow (`/jobs/new?edit=<name>`) opens the same designer through `POST /workflows/designer/edit`: the stored definition is the starting draft, so the user's first message (\"have Mark sign off and run it Fridays\") is applied to it like any refinement, and a note in the context block (a user turn, never the cached system block) tells the model it is changing a saved workflow. The draft always keeps the workflow's name — `_check_draft` puts it back and skips the taken-name check — and the route keeps its on/off state, so an edit can neither fork a copy nor switch on a tool workflow waiting for approval. The stored draft is handed to the model marked as data, not instructions. The review card lists *What changes* in plain words against the saved version (`lib/workflowChanges.ts`): every field is compared, with named sentences for the sign-off person and what it asks for — a sign-off moved off approve/reject is called out because the run then continues whatever the answer — the schedule, steps added/removed/reordered, inputs, tools and the tool-call budget, and a catch-all line for any other field. It names only the newly added tools that may change things. *Save changes* calls `POST /workflows/custom/{name}/save-edit`, which saves the session's own draft after re-validating it, only when it is the draft the card showed (the card sends what it displayed; a message that landed since is a 409), and only if the stored workflow has not changed since the conversation opened (409 otherwise), so an edit started before someone switched the workflow off cannot switch it back on. The step-by-step form stays as the advanced editor (`/jobs/new?edit=<name>&mode=advanced`).\n\n**Action steps (workflows that act).** An `action` step (`ActionStepSpec`: `goal`, `tools`, `max_tool_calls` 1–50, default 20) is run by the `workflow_actor` Council agent (`openexecutive/workflows/action_step.py`) as a bounded tool-use loop. Its `tools` list is an allowlist of exact tool names — MCP gateway tools (`server__tool`, e.g. `google_workspace__append_table_rows`) and a small set of built-ins (`oe__read_file`, `oe__message_person`, `oe__create_alert` — which, in a workflow a team member created, raises the alert as theirs (`alert_tools.raised_for_workflow_owner`: source `team_member`, \"Raised by <name>\", never a company-wide broadcast) — plus any installed extension's tools registered with `workflow=True`, as `oe__<name>`, run inside `extensions.workflow_step(name)`; a built-in wins a name clash, and an extension tool counts as reading only when it says so) — and **clicking Create is the user's approval** of that list: the review card shows every tool, flags the ones that may change things (anything whose name doesn't say it reads, and any tool with a URL/URI/endpoint/webhook parameter anywhere in its schema, or whose schema couldn't be read, since a URL can carry data out), and names them in a \"this workflow can use these without asking again\" notice. Because that card is the approval, a workflow with action steps saved from chat (`draft_workflow`/`save_workflow`, whose confirmation is a token the model holds itself) is stored **switched off** (`is_active=false`) and `save_workflow` returns `status: saved_pending_review` with a `/jobs/{name}` link. An inactive workflow can't run or schedule (`get_workflow` and the scheduler skip it); `/jobs/{name}` shows it on the same review card, where **Turn on workflow** (`POST /workflows/custom/{name}/activate`, which re-validates the tools) is the approval — the click sends the definition the card showed, and the server refuses (409) if the stored one has changed since, so chat overwriting it while the card is open can't get new tools switched on. Chat may revise a switched-off workflow but refuses to replace a switched-on one that has action steps (an inbound email steering the Executive could otherwise switch off an approved job and stage new tools under its name); those edits happen in the advanced editor. The Workflows catalog (`/jobs`) lists switched-off workflows in a compact *Waiting for your approval* strip, and saving edits in the advanced editor keeps one off. `tool_catalog.py` resolves names to schemas through the gateway's `search_tools` (extensible-mcp's Markdown output is parsed; resolving is also the per-session discovery its `call_tool` requires) and validates availability at save time (`POST`/`PUT /workflows/custom`, chat `draft_workflow`/`save_workflow`, designer drafts) — an unknown, misspelled or deny-listed tool is a 422. The gateway meta-tools (`search_tools`, `call_tool`, `load_mcp_server`) can never be step tools. `run()` resolves every action step's tools before any step runs, so a vanished tool stops the run before an earlier step acts; `resume()` checks only the steps still to run, after the gate and decision are validated. The last turn of an action step always switches tools off so the agent can report. At run time only the allowlisted tools are offered (sorted; constant cached system block, per-run goal/inputs/earlier results in the user turn), every `tool_use` is re-checked against the allowlist, MCP calls go through `MCPGateway.call_tool` so the config deny-list and the Gmail/Calendar/Drive recipient gates still apply, the call budget is enforced (then a final tools-off turn asks for the report; running out of turns fails the step and lists what was already done), tool errors (the gateway's `Error:` / `Error calling tool` / `Tool error:` prefixes, or a truthy `error` field) return to the model as `is_error` results, each call emits a `progress` event and an audit row (`workflow_tool_call`: tool and outcome; for tools that may change things also a short digest of target arguments — ids, recipients, URLs, paths — so a redirected write is visible; content arguments are never logged), and the step's output is the agent's report plus an \"Actions taken\" list. Tool output is framed as data, never instructions.\n\n**Scripts in action steps.** Besides the step's own tools, the agent is offered one more, `run_script` (`openexecutive/workflows/step_script.py`), for work that repeats over many items — every file in a folder, every row, every email — or chains calls with simple logic. It writes a short Python script once instead of spending a model turn per call; each of the step's tools is a function in the script (`drive__move_file(file_id=…)`, or `call_tool(name, arguments)` by exact name), and only the script's final value and printed output come back. The script runs in **Monty** (`pydantic-monty`), a sandboxed Python interpreter for model-written code, in a worker process spawned per script: no files, network, environment, subprocesses or third-party imports — the step's tools are the only things it can reach. **A script is a faster way to make the same calls, never a way around them:** every call it makes goes through the same per-call path as a direct `tool_use` (`action_step._StepCalls`) — the allowlist, a call budget (a script's calls have their own: 10× the step's `max_tool_calls`, capped at `WORKFLOW_SCRIPT_MAX_CALLS`, default 500, because they cost no model turn each — so a step can work through a folder of hundreds of files while its direct calls stay capped at 1–50), the first-write target check (a held write comes back to the script as `{\"status\": \"held\", …}`) and one `workflow_tool_call` audit row per call — and the script itself is audited as `run_script`, with how many calls it made and how long it took. The step's \"Actions taken\" list collapses repeats into one line with a count. A step whose direct calls are spent keeps its tools on while the script budget has room, so it can still script the rest (a direct call is refused as over budget). When a tool returns a list of five or more items and the round didn't use `run_script`, the step adds the same `FANOUT_HINT` as chat (once a step), pointing the per-item work at one script. The worker is stepped from the step's own task (each call pauses it and is answered there), so cancelling the run stops the script and its in-flight call together, and each call's progress shows as it happens. At most `SCRIPT_MAX_WORKERS` (default 2) scripts run at once across the server, chat and workflows together; another waits for a slot within its own wall clock, else returns \"the server was busy\". A worker exists only while its script runs (about 8 MB idle). Execution time (excluding time waiting on tools), memory and recursion depth are capped inside the worker, the script has a wall-clock limit, and its text is size-capped; printed output past its cap is dropped. A failing script returns its error to the agent as an `is_error` result, with the calls it already made listed first (ahead of any long result, so a cut never drops them) so a fixed re-run doesn't repeat writes; a call cut off by the time limit is listed as `may_have_run`, and gets a `cancelled (may have run)` audit row. A workflow definition still holds no code; a script lives on only if the agent saves it as a tool (below). Because a step can loop at run time, the workflow designer keeps work that repeats over items (each email, file, row or listed follow-up) in ONE action step whose goal spells out the items, rather than a step per item; `run_script` is never a step tool, and a definition that lists it is rejected (`validate_definition`) so the designer's repair turn removes it. `WORKFLOW_STEP_SCRIPTS=false` turns the tool off, and a step then only calls its tools one by one.\n\n**Python jobs (`run_python_job`, `openexecutive/workflows/python_job.py`).** Monty can't run libraries, so library work on files (split or merge PDFs with pypdf, spreadsheets with openpyxl and pandas, charts with matplotlib, images with Pillow, and documents made from scratch or from files: Word with python-docx, PowerPoint with python-pptx, laid-out PDFs with fpdf2) runs as a Python job: Pyodide (Python in WebAssembly) executed by **Deno** in a process of its own per job. Pyodide alone is not a sandbox — its Python can call into the JavaScript runtime, which under plain Node reaches the server's environment, files and network — so Deno is what isolates it: it is started with read access to the sandbox folder and the worker script only, with no network, environment, writes or processes, and an empty process environment. Files go in on stdin and results come back on stdout. A job gets only what the call names: Knowledge-library files, the files attached to the chat message being answered (`attachment_files`, the uploads as sent, bound for that turn only by `POST /chat/upload` in `workflows/turn_files.py`, so the model never retypes an attachment's text), text the caller passes, and `inputs` (a dict the code reads); result files are kept 7 days under the company folder and served to the principal at `GET /python-jobs/{job}/{file}`, which the Executive links in its reply. A deployment can instead send jobs to a separate runner (`PYTHON_JOB_RUNNER_URL`, with `PYTHON_JOB_RUNNER_KEY` as a bearer token): `run_job` POSTs the same job (code, inputs, files, caps, time and memory limits) and reads back the same result object, at most as large as a local job's output, keeping only its known fields, so kept results, links and metering are unchanged; the local sandbox is then not needed, and the runner is trusted to isolate jobs. A runner can turn a job away with `{\"run_locally\": true}` (and an optional `reason`) in a non-200 reply, for example when the deployment's allowance for it is used up: the job then runs in the local sandbox if this machine has one, and otherwise fails with the runner's reason. Any other non-200 reply stays a job error, so a busy or broken runner never moves every job onto the machine. A runner with more libraries lists them in `PYTHON_JOB_EXTRA_LIBRARIES`, which the job tool's description then names, so the Executive doesn't refuse a job that needs one. The tool sits in the `workflows` tool group, labelled for jobs with or without attached files. The library set is fixed at build time: the API image installs Pyodide and Deno from npm and the compiled libraries from Pyodide's CDN, each checked against the sha256 in Pyodide's lock file, and a build smoke runs a job. Pyodide can't infer the compiled packages the pure-Python libraries import (lxml, Pillow, fonttools), so the worker loads them when a job imports docx, pptx or fpdf. Pyodide, Deno and the pure-Python libraries are pinned by hash too (an npm lock installed with `npm ci`, pip `--require-hashes`). One job runs at a time per process (200–450 MB each), with a `PYTHON_JOB_TIMEOUT_S` limit and a memory cap (`PYTHON_JOB_MEMORY_MB`, default 1536, as the process's data limit, plus V8 heap and WebAssembly memory caps); the worker returns at most 20 result files and 25 MB, and the API stops the job as soon as its reply passes that. The job runs at a lower CPU priority and is first in line if the machine runs out of memory, so a heavy job slows or loses itself rather than the API; Deno's own caches go in a temporary folder removed with the job; and kept results are capped at 200 MB in all, oldest first. The tool is chat-only, offered only on the principal's own turns (`PRINCIPAL_ONLY_TOOLS`), withheld on private turns, unattended passes and under the Act as me lockdown, and not offered at all without the sandbox (`PYTHON_JOBS_ENABLED`, `PYTHON_SANDBOX_DIR`).\n\nA job that worked can be kept the same way as a script (below): `save_as` and `description` keep its code as a Custom tool of kind `python`, and `run_python_job(tool=<name>, inputs={...})` with its files runs it again, recording the run, so a job done before costs no code-writing tokens. Python tools run only on the principal's own chat turns: they are never listed for workflow steps and never turn on for workflows (`PUT /saved-tools/{name}` answers 409), and `run_script` refuses one (and `run_python_job` a script tool). Every job writes one `python_job` audit row (`ok`, `duration_ms`, `cpu_ms` and `peak_mb` read from the process's /proc entry just before it is stopped, files and bytes in and out, attachments, the Custom tool it ran or kept), which `GET /audit/usage` sums into `python_jobs` with the model usage of the turns that ran one.\n\n**Saved tools.** A script that works can be kept to run again by name (`openexecutive/workflows/saved_tools.py`); each tool has a `kind`, `script` (`run_script`) or `python` (`run_python_job`, above). `run_script` takes `save_as` and `description` with a new script: if the script succeeds it is saved, with the set of tools it actually called, and a failed script is never saved. Later, `run_script(tool=<name>, inputs={...})` runs the saved script instead of new code, with `inputs` available to it as a dict. Only the principal's own turns save: a chat turn where the principal is speaking on a verified, interactive surface (the same test as `load_mcp_server`), never an inbound email, a teammate, an unattended run or a workflow step — a step is offered `tool=` but not `save_as`. A saved tool runs with the authority of whoever runs it, so its author must be trusted at least as much as anyone who may run it. For the same reason only a workflow step (its tools owner-approved) or the principal's own turn may run one: anyone else's chat turn is refused `tool=` and not offered `list_saved_tools`, so a stranger can neither list the principal's automations nor run one with inputs they choose. Descriptions are kept to one line of printable text (they are shown to models), and every save writes a `saved_tool_changed` audit row (`actor: executive`) beside the owner's own changes. Saving needs no approval beyond that, because a saved tool can do no more than the context running it: its calls go through the same per-call path as any script (in a step: the allowlist, budget, target check and audit), and a step runs one only when the step already allows every tool it used (otherwise the result names the `missing_tools`) and only at the version the owner turned on for workflows (`workflow_version`, Settings → Advanced → Custom tools → Use in workflows). A tool kept on a turn that read outside content could otherwise carry injected code into an unattended run, so keeping stays automatic and works in chat at once, but workflows wait for the owner; a newer save doesn't change the version workflows run, and pruning never drops it. Each step's `run_script` description lists the saved tools that step may run; chat asks `list_saved_tools`. Every save of changed content is a new version (the newest 20 are kept, plus the one that ran until then, so a rolled-back version the owner trusts survives later saves), every run is recorded (`saved_tool_runs`, the newest 200 per tool), and the owner can turn a tool off or switch it back to an earlier version on Settings → Advanced → Saved tools (`/saved-tools` routes, the owner's alone). A turned-off tool never runs, and a new version saved by the model does not turn it back on. `SAVED_TOOLS_ENABLED=false` stops saving and running saved tools everywhere.\n\n**Targets are chosen at run time — and a new one is confirmed once.** Approving a workflow approves its *tools*; which sheet, doc, recipient or URL each call hits is chosen by the model at run time, by design (a tab per month, a reply to whoever sent the invoice, a doc per client). What bounds that is the allowlist, the gateway's recipient gates, the audit digest, and **first-write confirmation**: a `TargetPolicy` (one per run) checks every call to a tool that may change things. `resource_targets` walks its arguments recursively for resource keys (snake- or camel-case ids, `to`/`cc`/`bcc`, recipients, addresses, attendees, members, users, owners, parents, URLs/links/hrefs, paths, channels, spaces, rooms, phones, hosts, buckets, tables, spreadsheet/document/folder/calendar/file); a matching key marks everything beneath it, even a `name`. Outside a resource, only a new item's own `name`/`title`/`subject`, message/thread/draft/label ids, `range`/`sheet` and workspace-mcp's acting `user_google_email` are skipped — and whatever the key, a bare value shaped like an email address, a URL or an international phone number is a target, except inside what the call writes (`rows`, `values`, `body`, `text` …). Key names are a heuristic, so this is a best-effort guard layered on the allowlist, the gateway gates and the audit. Float ids are compared as integers. Arguments too deep, naming too many targets, or holding an over-long value **fail closed** (the call is refused). A target is trusted only when it was approved for this workflow before (`workflow_approved_targets`, by value) or is an id a write in this run created — a top-level id/link field (`id`, `spreadsheetId`, `webViewLink` …) of the **structured JSON object** result of a tool whose name says it creates (create / insert / upload …) and that takes no URL — a tool whose schema couldn't be read is assumed to (free text, nested records and readers' or updaters' results are never read, so a fetched page, an echoed title, a shared page's links or a stranger in `ccRecipients` can't plant one); those survive a pause in the resume payload (`run_created`). Values written in the workflow's own text are *not* trusted, since anyone who can edit the workflow could change them without review: they are asked once, then remembered. Approvals are by value, for any of the workflow's tools, and are **cleared when the workflow's tool set changes** (a newly added tool must earn them again). Any other target makes the call **held**: it is not run and costs no budget, the model is told it is waiting for approval and carries on, and it is audited `held for approval` (at most 10 held per step, 16 KB each; an identical repeat is held once). Whether a call is checked at all follows the read-only label, which now never marks a tool whose name carries a write verb anywhere (`find_and_replace_doc`). After the step finishes, the run pauses with a `WaitForHumanEvent` to the workflow's **owner** (`owner_person_id`, the person who created it on the Workflows page or in chat; falling back to the principal if unknown or archived), `on_timeout=auto_proceed`, 48 h, and a `WorkflowResumeState` of `kind=\"held_writes\"` carrying the exact held calls. On resume (`_resume_held_writes`, fingerprint-checked like a gate, with the remaining steps' tools checked first), only `approve` runs them — each still has to be in the live step's allowlist and resolve; its targets are remembered first — and anything else (decline, timeout, unreadable) skips them; either way a *Held for approval* section is added to the step's output and the run continues at the next step. With no one to ask, held writes are skipped and noted; a step that fails or crashes after holding, or a resume that stops early (definition changed, a later tool missing), audits its held writes as dropped and says they did not run. The question quotes each target JSON-escaped (a value can't add its own lines) and always shows a URL's full scheme and host, saying how much of the rest is hidden. The owner answers by chat reply or with **Approve / Decline** on the run page (`POST /workflows/runs/{id}/decision`, which the principal may also use); remembered targets are listed and removable on the workflow page.\n\n`oe__read_file` extracts text (PDF, Word, Excel, CSV, Markdown, text) only from files under `WORKFLOW_FILE_DIRS` (default: workspace-mcp's attachment folder), resolving symlinks and `..` before the check (`tool_catalog.resolve_readable_file`, shared with the Executive's `read_document` tool). A scanned PDF is converted by `knowledge.pdf_reader` instead of failing as \"may be a scanned image\"; one that still cannot be read returns the reason. Action steps are allowed in scheduled workflows. Because they have external side effects, a resumed run heartbeats its claim (`touch_resume_claim`, at most once a minute as events flow — each tool call emits one; a busy database is retried on the next heartbeat, never treated as a lost claim; the sweep's requeue re-checks the claim's age in the same UPDATE, so a heartbeat landing between the sweep's read and its write wins), so the stale-claim sweep never requeues and replays a slow but live run, and a worker that finds its claim superseded stops at its next event. A worker that actually crashes mid-resume is still requeued; its action steps then run again, so goals should say how to avoid duplicates (the actor reads current state before writing). `GET /workflows/tools/search?q=` and `GET /workflows/tools/describe?names=` back the advanced editor's tool picker and the review card's labels.\n\nAn optional cadence (`daily@` / `weekly@` / `quarterly@`) re-uses the scheduler via the `dynamic_workflow` action kind, which runs the workflow on schedule and DMs the artifact to a rostered recipient. A gate followed by further steps pauses at `awaiting_human` and then resumes once answered, so gates no longer have to sit immediately before synthesis. They remain forbidden in cadence-enabled definitions: a scheduled fire has no interactive human to ask.\n\n`executive_research` keeps only its Markdown artifact in the run history; `parse_artifact_findings` reads its \"Findings reviewed\" lines back as `{severity, confidence, specialist, title, summary}` for Home's first-week card (see Today).\n\nBuilt-ins the system runs on its own (`morning_brief`, `end_of_day_digest`, `executive_reflection`, `executive_research`) set `background = True`, surfaced as `WorkflowMeta.background`; the `/jobs` ready-made list files them under a **System** chip instead of the default view. They stay runnable by hand.\n\n**Quick workflows** (`workflows/quick.py`) are one per playbook in effect that no built-in or custom workflow follows (switched-off custom ones count). They are derived whenever the catalog is read, never stored: `list_workflows()` returns built-ins, then Quick ones, then active custom ones, and `get_workflow` resolves a `quick_<playbook>` name after the registry (custom workflows may not take the `quick_` prefix). Each has one required field, `request`, and two steps: **Load context** (company profile plus RAG for the playbook category's specialist) and **Draft** (that specialist writes one Markdown document following the playbook). `WorkflowMeta.quick` is true for them. The 8 built-in playbooks no built-in follows are Quick workflows: board update memo, 1:1 agenda, layoff comms plan, positioning statement, post-mortem, customer interview plan, feature prioritization and market sizing. A company's own playbook shows up as one, hiding a built-in drops it, and a custom workflow that starts following one replaces it. If custom workflows can't be read, none are offered, since their followers are unknown.\n\n**Workflows vs. playbooks.** `/jobs` has two tabs: **Build** (`?tab=catalog`, the default) and **Runs** (`/skills` redirects to `/jobs`). A playbook is a skill (`knowledge/skills_repo.py`): *how* the Executive does a piece of work, with no inputs, schedule or side effects. A workflow is the runnable job. Workflows **follow** playbooks: a step that follows one gets its body appended to the step prompt via `workflows/playbooks.py` (`load_playbook` + `playbook_clause`). Six built-ins do — `board_prep` (`board-prep-deck`), `quarterly_plan` (`quarterly-okr-set`, `quarterly-forecast`), `mbr` (`monthly-business-review`, in the financial, KPI and function steps), `competitive_teardown` (`competitive-teardown`, in the four analysis steps), `fundraising_prep` (`fundraise-narrative`, narrative step) and `exec_search_brief` (`role-scorecard`, profile step). Each declares them in `Workflow.playbooks`; a unit test holds that declaration equal to the `load_playbook(\"…\")` calls in the module, and `WorkflowMeta.playbooks` exposes it. A custom workflow's `specialist` step may name a `playbook` (validated to exist at save; appended after `{field}` rendering, so braces in a playbook are never treated as placeholders). The lookup resolves the playbook in effect, so a company's customized copy changes the workflow's output, and a hidden, missing or malformed one falls back to the step's own prompt plus RAG — a workflow never fails over a playbook (`load_playbook` catches everything; a custom step whose playbook is unavailable emits a `progress` event saying so). Because an approved scheduled workflow reads its playbook at each run, chat never creates or changes a playbook: it saves repeatable work as a workflow (`draft_workflow`, confirmed by the user), and only a person can change what a workflow follows: a workflow's page shows each playbook it follows as **How it's done** (`components/jobs/HowItsDone.tsx`), with **Edit** (`PUT /skills/{name}`; on a built-in that saves the company's customized copy) and, for a customized copy, **Reset to original** (`DELETE`, which reverts). The chat summary of a drafted workflow names each step's playbook. `playbook_users()` maps each playbook to the workflows that follow it — built-ins, every custom workflow (switched-off ones included: turning one on approves its definition) and the Quick ones; the skills API reports it as `used_by`, and the Executive's `search_skills` hits carry it as `workflows`.\n\nCompleted artifacts are discoverable in the unified artifacts section (`/artifacts`, labelled **Documents** in the UI) alongside their run-detail page at `/jobs/runs/{run_id}`. A run someone starts by hand (`POST /workflows/{name}/runs`, `run_workflow`, research in chat) stores them as `workflow_runs.owner_person_id` and its history and output are theirs alone (plus the person a gate waits on); scheduled and system runs keep no owner and stay the team's. Workflow output stays Markdown — the scheduler DMs it and reflection rereads it as text — and gains other formats only on the way out: any run can be downloaded as Word (`/artifacts/run:<id>/download?as=docx`), and the Executive can repackage one with `get_artifact` → `draft_artifact(format=…, supersedes=\"run:<id>\")`.\n\n## Data-driven retrospectives\n\n`engagement_value_report` introduces a new workflow pattern: instead of the user typing the substance into a form (the `investor_update` / `mbr` shape), the workflow **reads its substance from the database**. A deterministic gatherer (`clients/engagement_activity.py`) pulls the period's decisions, initiatives, advisory consultations, delivered workflow artifacts (excluding prior value reports), follow-through counts, and alerts handled — from the live DB for the active client, or a parked client slot's `state.db` opened read-only. A single board-comms call narrates those facts (the prompt forbids inventing anything not in them; an empty period skips the LLM entirely), and the artifact's lists are assembled deterministically. Built for renewal conversations — the engagement record is the evidence.\n\nWith Take the lead as the Executive on (`orchestrator.take_the_lead`), reflection and research build their toolkit through `unattended_toolkit(..., source=...)`. That keeps solo's booking and `run_workflow` tools and an unrestricted `message_person` (teammates as well as the principal). Every acting tool goes through the gate, and a held action waits on Today as a `take_the_lead_action` decision. Reflection also gets the MCP gateway's `search_tools` and `call_tool` (`_with_lead_tools`; `call_tool` behind the gate, `load_mcp_server` left out), so it can find and use whatever the deployment has connected, such as building a sheet to track something. A note in the user turn (never the cached system prompt) tells it to act rather than only report, and it gets more room: 10 iterations, 4000 tokens, and tool results up to 4000 characters. The grounding check still refuses outward text naming people or figures the pass didn't see. New mail and chat also wake the reflection early (scheduler section). In training (`take_the_lead.training`) every acting call that isn't allowed waits too, as a training card for the principal, and both passes append `take_the_lead.learned_note()` to their user turn: that it's in training, and the principal's own edits on earlier cards as examples of how they want those done (never in the cached system blocks).",
+ "markdown": "Workflows are deterministic, multi-step orchestrations. The built-ins are registered in `openexecutive.workflows.WORKFLOW_REGISTRY`; user-created (dynamic) workflows are stored as data (see below). Each follows the same contract: structured input feeds an ordered list of named steps that render a Markdown artifact, persisted via `complete_run` into `workflow_runs.artifact`. The activity feed never shows a run's log title (`\"Executive Research (periodic)\"`): `workflows/run_outcome.py` gives each finished run a plain name (\"Researched your market\", \"Checked in with Sales\", or the name it started with, less its date) and one line on what came of it, read from that stored artifact, so older runs read the same and nothing extra is written or called. Every step emits a `WorkflowEvent` (start/progress/complete) streamed over SSE at `/workflows/{name}/runs`.\n\nThe registry holds 25 built-in workflows, plus any number of user-created ones. Representative built-ins:\n\n- `board_prep`, `quarterly_plan`, `annual_plan` — planning and governance deliverables.\n- `performance_review`, `comp_refresh`, `org_design`, `exec_search_brief` — people and org artifacts (the last is an advisory hiring brief / scorecard from the CHRO, with input from the hired function's specialist — `sales` for a sales role — kept when the recruiting pipeline was removed).\n- `crisis_comms`, `churn_deep_dive`, `competitive_teardown` — situational analyses.\n- `department_check_in` — runs on department cadence; its `goal_status` step returns structured verdicts persisted back to `department_goals.status` (`department_check_in.persist_goal_verdicts`, shared with `weekly_review` and the weekly `goal_review`, which grades the goals no check-in covers; see Scheduler).\n- `weekly_review` — the principal's weekly look back and ahead (see *Weekly review* below).\n\n**Standing facts in unattended output.** `end_of_day_digest`, the weekly review's top-three call and the morning reflection append the standing facts (`memory.facts.with_standing_facts`; a teammate's marked `(per <name>)`) to their user turn, and the morning brief gets them through `render_briefing_context`. A workflow step that consults a specialist gets them through `route_to_specialist`. A correction made in chat therefore holds in every recurring brief and run. The morning brief also reads `facts.render_teammate_changes(since)` off the event loop and passes it to both `render_briefing_context` (a TEAMMATE CORRECTIONS SINCE LAST BRIEF block) and `build_brief_fingerprint`, so the principal hears of each correction a teammate made in the window, and that alone un-suppresses an otherwise unchanged brief. Proposals waiting for approval are listed only in a brief the principal reads privately (`include_proposed=_private_ok()`), and then mark the run private to them. The principal's own Always in the loop notes (`memory.history_brief`, only with their switch on) come in by a stricter rule, only on the scheduler's delivery (`PRINCIPAL_DELIVERY`), never a run from chat, whose tool result reaches the turn's shared audit row and peer memory: the morning brief's FROM YOUR NOTES — DUE SOON block and the end-of-day digest's FROM YOUR NOTES — TODAY block (what they committed to since the last digest, then what is due tomorrow). Either marks the run `private_to_principal` and moves its fingerprint; the digest, which had no private reads before, now emits that flag too. In the install's first week (`briefing.first_week`, seven days from the principal's People row) the morning brief also passes a GETTING STARTED block to `render_briefing_context(getting_started=)` and its keys to `build_brief_fingerprint`: onboarding goals, departments with no leader and, on the scheduler's delivery with Act as me and Draft replies to my inbox on, who wrote to the owner's own mailbox (sender and subject only) and, with Read my calendar on, today's meetings on their own calendar (time and title), either of which marks the run `private_to_principal`. The brief opens with **Getting started** and is never the quiet line while the block has anything in it (see Today).\n\n### Change-aware principal briefs\n\n`morning_brief` and `end_of_day_digest` are the two recurring briefs the scheduler sends to the principal. Both are written with `briefing.narrative.brief_model()`, the Executive's own model (its Council pick, else `DEFAULT_MODEL`), since a brief is the Executive speaking; only the grounding repair stays on the fast model. Both are now a *delta*, not a re-list: the window is \"since the last **delivered** brief\" (`briefing.brief_state.since_for`; 24 h on a cold store, clamped to 7 days), activity comes from `_build_activity(limit, since=…)`, proposals (action category only) split into *new since last brief* — enumerated, with each item's why-now and next move — versus a one-line carried-over count, a *rewritten* block lists carried items the review rewrote inside the window (`brief_state.rewritten_since`: verdict `changed`, still open — the brief reports them under \"what changed\", never as done), and a *handled overnight* block lists what the Executive's alert review **completed** on its own (`brief_state.handled_since`; the `changed` verdict is excluded because the alert is still open). The morning brief also reads the principal's **live world** since that window opened (`briefing.live_signals.gather_live_signals`): mail and chat the Executive handled (INBOUND, grouped by sender and subject, each email from the roster marked replied or not, earlier days dated), under a NOW line and THE PRINCIPAL line that names its reader so the brief writes \"you\" (the end-of-day digest gets the same line, and the team reflection a YOUR PRINCIPAL line under its roster; the reflection flags only what today's input still shows), what got stuck (STUCK: a reply the outbound gate held, a non-roster sender who got no reply, a Google Chat message left unanswered, chat drafts still in the principal's Gmail, after `live_signals.settle_principal_drafts` has marked the ones they since sent or deleted there), the principal's own chats, and — in both modes now, unless the solo top three already listed it — today's calendar, read fresh (`live_signals.refresh_calendar(max_age=0)`). The 07:30 reflection's **Flagged for the brief** bullets are carried across (`brief_state.reflection_flags_since`, the latest reflection run finished inside the window) instead of surviving only as an activity line with the run's title, and the rhythm runs themselves (`today.RHYTHM_WORKFLOWS`) are dropped from the brief's activity: their dated titles were noise and moved the fingerprint every day. At-risk departments name their slipping goals and each proposal carries its age. The period is the principal's local date. Section order: top call → **today** (the calendar's shape and anything stuck) → what changed (inbound first, naming who wrote) → handled overnight → needs you (new only) → waiting on → at risk (the slipping goal, or the department left out — never \"no detail yet\"). Quoted mail, chat, invite and reflection text is marked as data, never instructions. **Privacy:** the brief reads what is private to the principal — their contacts' alerts and mail, their drafts, their chats and their calendar — only on a run for them: the scheduler's (`morning_brief.PRINCIPAL_DELIVERY`) or the principal's own verified chat turn in a conversation only they can read (`delegation.settings.private_conversation`: the web chat, a Slack or Discord DM, a private Telegram chat — never a shared channel, where the reply is posted for everyone). A run anyone else starts (a teammate from chat in team mode, `POST /workflows/…/runs`) reads what everyone may see, as before. A run that did read a private row says so on its `result` event (`private_to_principal`: its live read differs from the shared one in any key or count), and the scheduler, `run_workflow` and `POST /workflows/{name}/runs` all then keep `persistence.PRIVATE_RUN_ARTIFACT` in the run history instead of the text. Text another pass wrote (the reflection's flags) renders as quoted ` > ` lines and every goal and headline field is one-lined, so none can start a line that reads as a block header. The fingerprint carries the live signals' time-free keys (who wrote about what, what is stuck, the calendar's shape) and the reflection flags when there are any, so \"nothing new\" means the principal's world was quiet too; the context summary is logged at INFO (`morning_brief: context since=… inbound=… stuck=… suppressed=…`). In **solo mode** (one person using Open Executive for themselves) both briefs speak to the principal, whatever their role: the morning brief runs top call → top three today → what changed (inbound and stuck first) → handled overnight → needs you → due this week (the principal's open loops overdue or due within 7 days, from `open_loops.principal_due_soon`) → goals at risk (named by area), the end-of-day digest what I did → open decisions → goals at risk tomorrow → sleep on this, over a context with goals at risk by area and no people-waiting or department block; the fingerprint carries the mode and ignores who is awaiting, and carries the due items as `(loop_id, state)` pairs when there are any. **Top three today** is picked in code, not by the model (`briefing.top_three`: overdue then due-today commitments, off-track then at-risk goals, commitments due later this week, then active projects, stalest first). The solo Briefing's *Top three today* card shows the same pick from the same code (`GET /today/top-three`, see Today). When the MCP gateway runs the Google Workspace server, one `google_workspace__get_events` call (4 s timeout) lists today's events on the principal's calendar — their address as the calendar id, read with the Executive's account (`primary` when the Executive is signed in as them) — and on a business day (`calendar_tools.is_business_day`, the rule the booking tools apply; at the weekend the day's events are still listed but no slot is suggested) each item gets its own free block inside `CALENDAR_BUSINESS_HOURS_START`–`_END`, rendered with a TODAY'S CALENDAR block — only a date-only event is all day, a zero-length one blocks nothing, and one whose times can't be read is left out; no gateway, no principal address, an error, a timeout or a reply it cannot read all mean no calendar and no slots, never a failed brief; the log records only the reply's length or the error's type, never calendar text. When the principal has Act as me and **Read my calendar** on (`delegation.calendar`) and their mailbox opens as theirs, `top_three.read_todays_calendar` also reads their own calendar through their own sign-in (Gmail or Outlook, same 4 s timeout, declined events left out), at the same time as the Executive's read, and merges the two: an event with the same title and times on both is listed once, and either read alone is enough. This read feeds the morning brief, the /today calendar cache (`live_signals.refresh_calendar`) and so the end-of-day digest and Right now; the solo top three adds it only on a run for the principal (`build_top_three(include_own=private_ok)`). The fingerprint carries the three items' keys (no dates, no slot times) and only a coarse hash of the day (busy blocks rounded to 15 minutes, no titles, no dates), so an unchanged day still suppresses. A day whose calendar read fails after one that worked (or the reverse) changes the fingerprint once, so that brief is written in full. A date-free fingerprint of the inputs is compared to the last delivered one; if unchanged the artifact is the one-liner \"Nothing new since yesterday's brief — N items still waiting on you.\" and no model call is made (`PRINCIPAL_BRIEF_SUPPRESS_UNCHANGED`; `force_full=true` on a manual run bypasses it). The workflow yields a `result` event with the fingerprint; only the scheduler records it, after a successful delivery, in `briefing_narrative` under scope `brief:<kind>` — so manual runs never advance the window. Both are written to their reader in code (`briefing.reader`): the principal's full name and addresses are masked to \"the reader\" throughout the context under a THE READER line, the prompt says \"you\" for the reader, nobody is \"the principal\" and the Executive is \"I\" / \"me\", and a draft that still slips is rewritten once (the morning brief) and fixed in code. **The end-of-day digest reads the day itself.** On the scheduler's delivery to the principal alone it leads with TODAY WITH YOU (`session_store.own_conversation_since`: the principal's own conversations with the Executive since the last digest, their words and its replies, never a conversation someone else owns) and the live blocks (`live_signals.render_live_blocks`: mail in, what got stuck), then COMING UP (the Executive's own follow-ups due in the next two days). It leaves out its own rhythm runs (`today.RHYTHM_WORKFLOWS`) and gets the reader's leave-out list (`brief_requests.render_parts`). Its shape is **Today**, **Done for you**, **Next** and an optional **Sleep on this**, at most 150 words, with no header for an empty section. Before this it read only the Executive's own bookkeeping, so on a day of real work it reported its own briefs and missed every number decided in chat.\n\n**Brief delivery.** `scheduler.runner._deliver_to_principal` maps the principal's `preferred_channel` (`slack` / `discord` / `telegram` / `email`) to its delivery channel and tries it first, then the other chat channels the principal has an id for, in the order Slack → Discord → Telegram. Email goes through the active MCP gateway (`google_workspace__send_gmail_message` as the Executive's own address, to the principal, subject `<title> — <date>`) and is used only for an explicit `email` preference, or for `any` when no chat channel resolves — an owner linked by email at setup has `any`, so one who also has Slack does not start getting two emails a day. When nothing can deliver (a web-only principal, or email with no gateway), the brief is still generated and stored as a run with its artifact, as before — a web-only principal reads it on the Artifacts page — it is just not delivered (audited), so the window does not advance, and the next occurrence is chained. The same delivery path carries the client-rotation digest and the weekly review.\n\n**Grounding.** Nothing an unattended pass writes is read by anyone before it goes, so `openexecutive.briefing.grounding` checks it deterministically — no model judges the model. A name (a run of two or more capitalised words once section headers, weekdays, imperative openers and org nouns are trimmed, or one capitalised word in a person slot like \"ask Marcus\" or \"Marcus wrote\") is grounded only when a single line of the pass's inputs holds all of it, or it belongs to a roster person some input mentions — being on the roster alone is not enough. A figure (money, a percentage, a k/M/B number, any bare number of 11 or more; never a date, time, year, duration, id, list marker, `Q3` or small count) is grounded when an input number matches it within the precision it is written with (`$1.2M` matches `$1,234,567`; `47 units` does not match 48). The inputs are the rendered context split into lines labelled by section (a header also carries its bullet count), the company profile and the department titles. `morning_brief` renders its context itself and hands it to the synthesizer as `rendered_context`, so the check reads exactly what the model read; after the quiet fallback, `ground_brief` runs on both briefs. When something is ungrounded it makes one repair call to the fast model (same system prompt, the list of items, \"remove or correct using only the context\"), re-checks, then drops each line still ungrounded and any header left empty, and appends \"_I left out N lines that named people or figures I couldn't match to your data. They're under Left out of your brief on Home._\" (everything ungrounded → one held-back line). Every held line goes in the `grounding` audit row's untruncated `full` payload (up to 30, 400 chars each; `details` keeps a five-line preview), and `grounding.recent_held_back` reads the last day's back for `GET /today`'s `held_back`, which Home lists under **Left out of your brief** for the principal alone — after the narrative inputs are taken, so the held lines never reach a prompt. Then each grounded figure gets a server-chosen ` [n]` — the matching input line with the most words in common with the figure's clause — and a `**Sources**` list closes the brief (`- [n] <section> — <snippet>`, at most 9, snippets quote inbound mail, so links are masked (\"(link removed)\"), Markdown, angle brackets and @-mentions stripped, and they are cut to 90 chars; never `[n]:` at a line start, which Markdown reads as a link definition). Text with nothing to change comes back byte-identical, the fingerprint hashes the inputs so suppression is unaffected, and the grounded text is what is delivered, stored and recorded as delivered. Both brief prompts and the digest prompts say the rule up front. `executive_reflection` wraps its handlers in a `GroundingScope`: `create_alert`, `message_person`, `send_department_message`, `send_company_broadcast` and `schedule_followup` refuse text with an ungrounded name or figure, returning a JSON error that names the items so the model can look the person up or leave the figure out (every tool result joins the inputs, so a `lookup_person` answer grounds the DM after it; the recipient's own name always counts). Its **Flagged for the brief** bullets are filtered the same way before the tool log is appended — the next brief quotes them, where they would ground themselves — and `brief_state.reflection_flags_since` now stops at the tool log's `---`. The reflection's `grounding` rows are private when a private-to-principal alert reached its context, and the digest's always are (its HANDLED block can quote one). Everything fails open. `GROUNDING_CHECKS=enforce` (default) acts, `report` only writes the `grounding` audit rows, `off` skips it; `GROUNDING_CITATIONS=false` drops the markers. Not yet grounded: the /today header (its cards sit beside it), `weekly_review`, the research synthesis, dates and meetings, and a real person named in the wrong role.\n\n### Weekly review (solo)\n\n`weekly_review` (background, inputs all defaulted) closes out the principal's week in six steps. **Goals**: every area with goals is graded by its own specialist, concurrently, with the department check-in's verdict contract (`_parse_verdicts`) and write-back (`persist_goal_verdicts` → `record_goal_review`, one `goal_status_review` audit row per area with actor `weekly_review`); an area with no goals is skipped, one without a specialist is listed ungraded, and one whose specialist fails is shown as last recorded. **Commitments**: `open_loops.principal_due_soon` — overdue or due within 7 days. **Projects**: active initiatives with no update for 7+ days. **Decisions**: the week's (`episodic.decisions_since`). **Revisit**: up to three decisions older than 30 days with an empty outcome (`episodic.decisions_awaiting_outcome`, newest first), listed as `[decision N]` under *How did these turn out?* — the principal's answer is recorded with `record_decision_outcome` (see Agents). **Assemble**: every section always renders (a one-line note when empty), ending with *Next week's top 3* from one fast-model call that follows the `weekly-review` playbook (a constant system prompt; the playbook rides in the user turn), trimmed to at most three list items — or, when that call fails or returns nothing, the same ranked pick the morning brief uses. In solo mode the scheduler fires it weekly (`principal_weekly_review`, see Scheduler) and delivers it through `_deliver_to_principal` like the briefs, recording the delivery outcome. The solo Briefing also shows the latest completed run to the principal (`GET /today/weekly-review`, see Today): `weekly_review.summarize_review` reads the artifact's title line (`TITLE_PREFIX`) and its last `TOP_THREE_HEADING` section back as plain text, so a principal no channel reaches still sees next week's top three. Wording is role-neutral; run by hand in team mode it says *department* instead of *area*.\n\n**Principal-only workflows.** A workflow can name the workspace modes in which only the principal may start it (`Workflow.principal_only_modes`): `weekly_review` in both modes (built from the principal's decision log, commitments and goals, and it re-grades the goals) and `morning_brief` in solo (built from the principal's commitments and calendar). Team `morning_brief` and every other workflow can be started by anyone as before. This decides who may start or trigger a run, not who may read one: stored runs, the scheduled briefs and weekly reviews included, are read under the existing `/workflows/runs` rules — which is why a morning brief that drew on the principal's private rows is stored as `PRIVATE_RUN_ARTIFACT`, not as its text.\n\n- **From chat**, `run_workflow` checks at dispatch, before any run row is created, that the turn is the principal on a verified surface — `create_goal`'s rule — and otherwise refuses with a plain error that does not spell out the rule.\n- **Over HTTP**, the Jobs page's `POST /workflows/{name}/runs` and `POST /evals/runs` (a workflow scenario runs the workflow on live data) call `refuse_principal_only_run`: only a caller signed in as the principal, or a request with no caller email (the CLI or local login), may start the run. Unlike the workspace settings, an install with no principal on the roster lets no signed-in caller in, as in chat. Anyone else gets a 403 (\"Only the principal can run this workflow.\") before any run row exists. The mode is the stored one, or an eval scenario's own `workspace_mode`. The eval route runs exactly the scenario list it checked.\n\nEvery refusal is audited `refused=true` with the workflow, the mode and the caller. The checks fail closed: a mode that cannot be read counts as principal-only, and a check that cannot read the roster refuses.\n\n**Knowledge in the reflection.** A chat turn looks the knowledge base up before the Executive answers; the reflection reads the org's state instead, so nothing looked it up for it. It now carries its own `search_knowledge` tool (`orchestrator.knowledge_tools`, not in the shared `_ALL_SKILL_TOOLS`), which runs the same `knowledge.retriever.retrieve` as chat — the review gate, the synced Drive / OneDrive / Confluence / Notion collections and the published-artifact rule (the pass has no viewer, so no one's private document comes back). The prompt (`_KNOWLEDGE_RULE`, both modes) asks it to search before acting on or flagging something that turns on a customer's or supplier's terms, a price, a policy, a plan or a past decision. Its passages come back up to 4,000 characters (`execute_tool_calls(wide_results=...)`) while other tools stay at their short preview, its result counts as grounding input like any tool result, and the run's tool log keeps each line to 160 characters. Read-only, so Take the lead never gates it. The loop has 5 iterations (was 4) to leave room for a search before acting.\n\nNeither the nightly reflection nor the research synthesis can call `ack_alert`: both run unattended with open alerts rendered into their context, and those headlines are minted from inbound mail and chat, so an injected \"the principal already dismissed 13\" would be acted on with nobody watching. Closing an alert is the alert review's job, with evidence.\n\n`executive_reflection` now carries memory: yesterday's standup (the previous completed run's artifact) is rendered into the context and the prompt forbids re-acting on anything listed there unless it changed; open alerts render with their id, review verdict and recommended move. Reflection never closes alerts — the alert review does, with evidence. It also renders an **OPEN LOOPS** block (up to 10, soonest due first, overdue flagged) from Attunement so the standup can connect a slipped promise to the rest of the org state; the nudge engine already chases overdue loops, so the prompt tells it not to DM about a loop merely for being overdue. A **WHAT LANDS** block (from the Attunement outcome ledger) shows, per person, how often each kind of proactive DM got answered over 30 days; the prompt steers DMs toward kinds that land and away from kinds a person reliably ignores. Reflection and research tag their tool execution as proactive (`tag_proactive`) so their DMs are counted. Resolving a wait-for-human approval (`resumer.apply_resolution`) marks the nudges that chased it `acted`. `close_open_loop` is withheld from reflection for the same reason as `ack_alert`: loop text is quoted from what people wrote. `unattended_toolkit` also drops `schedule_tools.UNATTENDED_WITHHELD_TOOLS` (today `create_goal`) from both passes in both modes: a goal is the principal's own decision, and these passes see only inbound text. A turn private to the principal (mail from one of their contacts, or mail they forwarded) cannot start a workflow either: `run_workflow` and `run_executive_research` are in `schedule_tools.PRIVATE_TURN_WITHHELD_TOOLS`, which the chat loop neither offers nor runs on such a turn, since a workflow's steps can reach anyone.\n\nIn **solo mode** the reflection is framed for the principal, whatever their role: they are the only person who uses Open Executive and the only one it takes direction from, it prefers `create_alert` and `schedule_followup` to the principal, and it never messages anyone else from an unattended pass — the people in the principal's world are contacts, so anything they should hear is flagged for the principal to raise. The team roster is replaced by one YOUR PRINCIPAL line (person_id and follow-up channels), its follow-up guard is seeded from the principal only, and department risk renders as areas with goals at risk. The research synthesis follows the same rule — its routing menu and roster name only the principal. In both, `send_department_message`, `send_company_broadcast` and `set_department_head` are withheld, and so are `create_calendar_event`, `create_instant_meeting` and `run_workflow` — a booking reaches its attendees and a workflow can do anything its steps do, so the principal books and starts workflows from chat — and `message_person` refuses anyone but the principal. These passes run unattended with inbound text in their context, so the rules are enforced in code, not only in the prompt.\n\nIn either mode, both passes now dispatch only the tools they offer: the handler map is built from the offered list, so a name the model emits without being offered it is skipped as an unknown tool. They used to look names up in the full handler registry, so tools they deliberately withhold — the raw DM tools (`send_slack_dm` has no roster check), `ack_alert`, `close_open_loop`, and in research the watchlist writes and `run_workflow` — still ran when the model emitted them. Both read the mode before binding their own session (so a caller's override, such as an eval's, counts) and pin it on that session, so their tool handlers use the same mode. They carry the principal's role across the same way (`effective_principal_role` of the caller's session, pinned as `turn_principal_role`), so a specialist or workflow started from either pass sees the role of the turn that started it. Team runs are unchanged.\n\n### Wait-for-human pause\n\n`wait_for_human` (`openexecutive/workflows/wait_for_human.py`) is a first-class step primitive that pauses a run: the runner calls `save_checkpoint`, the `workflow_runs` row moves to `status='awaiting_human'`, and the serialized `WaitForHumanEvent` is stored in `state_json`. (Department authority is a *separate* mechanism — `propose_only` departments file a briefing alert via `departments.authority.propose_via_alert` and mark the scheduled action done; they do not route through this gate.)\n\n**Delivery.** Both checkpoint sites — the SSE route and the `run_workflow` chat tool — call `workflows.gate_delivery.deliver_gate_question` immediately *before* checkpointing, so `state_json` carries the routing fields a reply is matched against. Two modes. When the approver is the person already in the conversation (the chat session's `origin_channel` is set — to anything but `email`, whose answer is no chat reply and would never be sent — and its `caller_person_id` is the gate's `person_id`), nothing is sent — the question rides in the Executive's own reply — and the gate records `origin_session_id` plus the session's channel. The resolver compares base ids (`memory.conversation_ids.base_session_id`), so a question asked in one conversation of a Telegram chat or a DM is still answered by a reply after a quiet gap or /new has started the next. Otherwise the question is delivered through `schedule_tools.handle_message_person`, which picks the person's preferred channel, falls through on a failed send, and falls back to a briefing alert; the gate then records the channel, address and provider message id that send returned, plus the id of the DM session it landed in — that send is always 1:1, so the answer belongs in that conversation and nowhere else. Without it the gate matched on person and channel alone, so an unrelated @mention in a public channel resolved it and had the acknowledgement, run title included, posted where everyone could read it. The question is sent with `notifications.approval_send`, so the person's quiet hours and *In my briefs* never hold it, whatever their urgent setting: only a reply to it resolves the gate. Delivery is not guaranteed: the outbound guard can suppress it (duplicate, rate cap, quiet hours) and an unreachable person gets the alert fallback. Both cases leave the routing fields empty and report `delivery` as `suppressed` / `alerted` rather than claiming someone was asked, and the chat tool's presentation hint changes accordingly.\n\n**Matching a reply.** Each inbound adapter passes the message to `inbound_resolver.resolve_inbound_message` with its `session_id`. Matching is three-tier: an explicit `in_reply_to` against a stored `outbound_message_id`; otherwise a single open run on that channel; otherwise one utility-fast disambiguation call gated at 0.85 confidence. An unmatched explicit reference rules out only the candidates that carry a stored outbound id — the ones it could have matched — and the rest continue; rejecting outright meant an adapter that passes a thread id on every message (Slack's `thread_ts`) short-circuited the later tiers forever, and a global test let one delivered gate's id block an unrelated self-approval gate. Channel names are normalized (`slack_dm` ≡ `slack`), the delivered address is compared when both sides know it, a row whose `state_json` will not parse is refused (a corrupt row otherwise presents as a legacy one), and an empty stored channel is treated as a wildcard only for rows checkpointed before gate delivery existed. Two guards keep an open gate from swallowing unrelated traffic: a gate carrying an `origin_session_id` matches replies only from the conversations the adapter names (a Slack or Discord thread offers its parent channel session too, mirroring the history double-write, since a gate raised on a mention recorded that session while the answer arrives under the thread's — on Slack only when that person rooted the thread, or the alias would reach into a colleague's), and the parser can return `unrelated`, which declines to resolve and lets the message reach the normal chat path. The parser is handed the gate's own question, so a bare \"yes\" is judged against something. Its fallback is flagged by a key the model cannot emit rather than by a magic note string it could, and a fallback declines to resolve on *every* reply shape — recording the empty string a `free_text` fallback fabricates would close a sign-off on a parser outage. Every shape can answer `unrelated`, not just `approve_reject`: without it an open `free_text` gate turned the person's next message into its answer verbatim, and a `numeric` one swallowed any message containing a number. The parser has one caller outside workflows: its `roster_identity` shape — `{decision: approve|link|decline|unrelated, name, kind: team|contact|null}`, with `name` only as the person wrote it (never inferred) and a fallback of `unrelated` — reads the principal's emailed answer to a roster request (who a new sender is; see Org). It is not a gate reply shape, and a fallback or `unrelated` leaves the request waiting. `resumer.apply_resolution` then records the decision, marks the run `resolved`, and writes an audit row. A timeout applies the step's `on_timeout` policy (escalate / auto_proceed / fail). The outcome surfaces on the Today dashboard.\n\n**Resuming past the gate.** A paused run continues on its own. Re-entering it was long assumed to mean serializing a Python generator frame; it does not. The only state alive across a dynamic workflow's steps is its inputs (already persisted), a company-profile block that is recomputed, the completed steps' output strings, and the loop cursor — so the engine hands the checkpoint a small JSON `WorkflowResumeState` (workflow name, the gate's id and index, the next index, the outputs so far), stored in `workflow_runs.resume_state_json`, and `DynamicWorkflow.resume` replays its step loop from the recorded index. `run()` and `resume()` share that one loop, which is why a second gate needs no special handling — it is simply another pause raised from the same place. The payload rides on a `WaitForHumanEvent` field declared `exclude=True`, so it can never leak into `state_json`, whose exact key set the resolver branches on. A gate with no payload is *pause-only*: the decision is recorded and the run stops, which is what every caller got before resume existed.\n\n`resumer._process_resumable` claims a resolved run with one guarded UPDATE — `resolved` → `running`, stamping `resumed_at` and minting a claim token — and drives it to a terminal row. It runs two ways: immediately, via a task `apply_resolution` kicks off so a Slack approval starts moving in seconds, and every 60s from the poll loop as the durable backstop. Both share the claim, so a run executes exactly once even with two resumers against one database. The kicked task binds no chat session (`set_session(None)`), exactly like the poll loop: it is created inside the inbound handler that recorded the answer and would otherwise inherit that person's live turn — so a run resumed because the principal replied on Slack does not act with the principal's identity (it cannot, for example, reach the principal's contacts). It drops the handler's audit scope too (`audit.context.unscoped_audit_rows`): inherited, the principal's scope would make private every row of the run that names a contact, and whoever started the run would see those rows vanish after the approval. The poll runs the executor *after* the timeout loop, which is what finally makes `on_timeout='auto_proceed'` do what its name says: the timeout resolves the run and the same tick executes it. While the Executive is paused (`scheduler.pause`) the resumer does nothing — no startup sweep, no timeouts, no resumes — and `apply_resolution` still records the decision but skips the immediate kick; the first unpaused iteration catches up on all of it, so a timeout that lapsed during the pause applies its `on_timeout` policy then.\n\n**The claim is fenced, because it is not a lease.** The stale sweep decides a worker is dead from a wall-clock guess, so a slow but *alive* worker will eventually be declared dead and replaced. Every write the executor makes carries its claim token and is refused once superseded — otherwise the replaced worker's late completion lands on top of its replacement's result, or its checkpoint at a later gate resurrects an already-finished run and asks the approver a second time. The retry budget resets at each new gate (a gate is new work, not a retry), and a run that exhausts it is *ended* rather than dropped: an exhausted run sits in `running` with a payload, in neither queue, and would otherwise show as in-progress forever.\n\n**The gate fails closed.** Continuing is an allowlist — `approve` and the synthetic `auto_proceed` — not \"anything that is not a stop word\". `decision` is whatever a fast model extracted from free-form chat and it drifts; under a denylist, \"rejected\", \"Reject\", \"decline\" and \"no\" would all continue, so the approver declines and the deliverable is produced anyway. Reply shapes that ask a question rather than seek permission always continue, since the answer *is* the value. A stop ends the run at `error` with the human's note. Either way the decision becomes the gate step's own output, so it reads as a section *in* the artifact — capped and blockquoted, because that text reaches the synthesis specialist as prompt context.\n\n**A definition edited during the pause is refused.** Resume re-validates the payload's version, the recorded gate, *and* a fingerprint of the whole step list, and derives the index to continue at rather than reading it from the payload. Pinning only the gate would not be enough: definitions are overwritten by name and any rostered user can save one, so someone could keep the gate identical and replace every step after it — and the approver's sign-off would be recorded against work they never saw, which defeats the one thing an approval gate is for. No built-in workflow yields the gate; only user-created dynamic workflows do.\n\n### Launching from chat\n\nWorkflows are not only reachable from the `/jobs` UI — the Executive can list and run any of them mid-conversation. `openexecutive.orchestrator.workflow_run_tools` wires two tools into the main chat loop: `list_workflows` (the launchable catalog, with each workflow's input fields) and `run_workflow` (runs one to completion and returns its Markdown artifact, using the same engine as `POST /workflows/{name}/runs`). `run_workflow` resolves both built-ins and custom workflows via `get_workflow`, validates `inputs` against the workflow's input model, persists the run (`create_run` → `complete_run` / `fail_run`), and on an approval-gate step checkpoints the run as `awaiting_human` exactly as the HTTP route does — literally the same code, since both call `workflows.gate.checkpoint_gate`, which delivers the question and writes the checkpoint in one place. It never hangs waiting on a human, and it reports both whether the question reached them and whether the run will continue by itself once answered. The runners that *cannot* pause — the schedulers, evals, client rotation, onboarding, the research tools — call `gate.ensure_workflow_event`, which raises on a gate rather than letting one be swallowed; the scheduler's dynamic-workflow branch used to ignore it and record a successful run containing nothing. `executive_research` is excluded (it has the dedicated `run_executive_research` tool). Running a workflow from chat delivers nothing on its own — it renders the artifact into the conversation, and the recurring principal briefs (`morning_brief`, `end_of_day_digest`) reach anyone only via the scheduler's own `_deliver_to_principal`. The tool description used to claim those two DM the principal when run and to confirm before firing them, which had the model soliciting a confirmation on a false premise; it now names `executive_reflection` as the one workflow that really does execute tool calls of its own (DMs to heads, broadcasts, alerts). A successful run surfaces an `action_taken` chip linking to `/jobs/runs/{run_id}`.\n\n### Dynamic (user-created) workflows\n\nUsers create reusable workflows on the fly — from the executive chat, the conversational wizard at `/jobs/new`, or the step-by-step advanced editor — without shipping code. The Workflows page (`/jobs`) opens on a *Start here* panel that leads to all three: the user describes the job in a sentence and *Start* opens the wizard with that text sent as its first message (handed over in `sessionStorage`, so a link cannot make the wizard send text the user never typed; where storage is blocked it falls back to `/jobs/new?describe=`, which only fills the composer and sends nothing), or picks *Step by step* (advanced editor) or *Talk it through in chat* (`/?new=1&draft=`). Below it come the user's own workflows, then four ready-made starter picks with the full built-in list folded behind *Browse all* (`?browse=1`). The picks and the example chips follow the workspace mode: a team gets the investor update, board prep, MBR and competitive teardown (and a board pre-read chip); a solo owner-operator gets the MBR, pricing review, churn deep dive and quarterly plan, with chips for a Friday cash and pipeline check, customers who stopped buying and a competitor digest (`lib/workflowStarters.ts`; a unit test pins every pick to a startable `WORKFLOW_REGISTRY` entry). A dynamic workflow is a stored JSON definition (the `dynamic_workflows` table) interpreted at runtime by one generic `DynamicWorkflow` engine (`openexecutive/workflows/dynamic.py`) that implements the same `Workflow` ABC as the built-ins, so the run path, SSE streaming, run persistence, and `/jobs/[name]` form rendering are unchanged. `get_workflow` / `list_workflows` fall through to the dynamic store after the static registry (built-ins win on a name collision).\n\nA definition declares free-text input fields and an ordered step list of four kinds: **specialist** (consult a specialist with a goal prompt, optionally grounded by RAG), **action** (get something done with tools — see below), **approval_gate** (a `wait_for_human` pause), and a terminal **synthesis** step that assembles the artifact. At least one specialist or action step is required. `validate_definition` enforces the structural rules: exactly one terminal synthesis step, valid specialists, `{placeholder}` tokens that reference declared input fields, rostered approval/cadence people (team members — never one of the principal's contacts, whom an unattended run may not message), and a parseable cadence.\n\nAuthoring from chat uses a **draft → confirm** handshake: the Executive calls `draft_workflow` (validate; return a `confirm_token` plus a plan summary), shows the user the plan, then calls `save_workflow` with the same definition and token — a token mismatch is rejected, so the saved workflow is exactly what the user approved. The step-by-step advanced editor drives the `/workflows/custom` CRUD endpoints directly.\n\n**The New workflow wizard** (`/jobs/new`) is the default way to create one from the UI. It works like conversational onboarding: the user describes the job, the `workflow_designer` Council agent (`openexecutive/workflows/designer.py`) asks one clarifying question per turn — deliverable, per-run inputs, sign-off, schedule, recipient — with up to four clickable suggested answers, then emits a complete definition plus a plain-language summary and the assumptions it made. Every turn offers the model exactly three fixed, name-sorted tools (`ask_clarifying_question`, `emit_workflow_draft` — reusing the chat tool's `DEFINITION_SCHEMA` — and `search_available_tools`, which is answered inside the same turn from the tool catalog, up to four searches per turn, with the tool_use/tool_result pairs never stored in the plain-text transcript; every tool a search returns is remembered on the session and replayed into later turns, so a forced draft or a repair turn — which cannot search — still has the exact names); `tool_choice` flips to the emit tool once, when the six-question budget is spent or the user clicks *Draft it now*. The emitted definition goes through `validate_definition`, the tool-availability check, and a check against saved custom names, with one repair turn that feeds the errors back. The system prompt is a cached constant; the live context — specialists, the roster with person ids, the user's timezone (the one set through `PUT /workspace`, else `USER_TIMEZONE`; cadences stay UTC), and taken names — is rendered once per session into the first user turn, and while refining, the exact current draft is prepended to the latest user turn so the model edits it rather than re-deriving it. Roster names and roles are flattened to one line and capped at 80 characters before they enter that context, and the system prompt tells the model to treat the whole block as data, never instructions. Sessions live in memory (`/workflows/designer/*`, 2 h TTL, 50-session cap), run one model turn at a time (a second concurrent `/message` or `/draft` gets 409, and a failed turn is rolled back by identity), and never write: the review card saves through the same `POST /workflows/custom`, which re-validates, and *Edit details* opens the draft in the advanced editor (`/jobs/new?designer=<id>`) before saving.\n\n**Editing is a conversation too.** *Edit* on a saved workflow (`/jobs/new?edit=<name>`) opens the same designer through `POST /workflows/designer/edit`: the stored definition is the starting draft, so the user's first message (\"have Mark sign off and run it Fridays\") is applied to it like any refinement, and a note in the context block (a user turn, never the cached system block) tells the model it is changing a saved workflow. The draft always keeps the workflow's name — `_check_draft` puts it back and skips the taken-name check — and the route keeps its on/off state, so an edit can neither fork a copy nor switch on a tool workflow waiting for approval. The stored draft is handed to the model marked as data, not instructions. The review card lists *What changes* in plain words against the saved version (`lib/workflowChanges.ts`): every field is compared, with named sentences for the sign-off person and what it asks for — a sign-off moved off approve/reject is called out because the run then continues whatever the answer — the schedule, steps added/removed/reordered, inputs, tools and the tool-call budget, and a catch-all line for any other field. It names only the newly added tools that may change things. *Save changes* calls `POST /workflows/custom/{name}/save-edit`, which saves the session's own draft after re-validating it, only when it is the draft the card showed (the card sends what it displayed; a message that landed since is a 409), and only if the stored workflow has not changed since the conversation opened (409 otherwise), so an edit started before someone switched the workflow off cannot switch it back on. The step-by-step form stays as the advanced editor (`/jobs/new?edit=<name>&mode=advanced`).\n\n**Action steps (workflows that act).** An `action` step (`ActionStepSpec`: `goal`, `tools`, `max_tool_calls` 1–50, default 20) is run by the `workflow_actor` Council agent (`openexecutive/workflows/action_step.py`) as a bounded tool-use loop. Its `tools` list is an allowlist of exact tool names — MCP gateway tools (`server__tool`, e.g. `google_workspace__append_table_rows`) and a small set of built-ins (`oe__read_file`, `oe__message_person`, `oe__create_alert` — which, in a workflow a team member created, raises the alert as theirs (`alert_tools.raised_for_workflow_owner`: source `team_member`, \"Raised by <name>\", never a company-wide broadcast) — plus any installed extension's tools registered with `workflow=True`, as `oe__<name>`, run inside `extensions.workflow_step(name)`; a built-in wins a name clash, and an extension tool counts as reading only when it says so) — and **clicking Create is the user's approval** of that list: the review card shows every tool, flags the ones that may change things (anything whose name doesn't say it reads, and any tool with a URL/URI/endpoint/webhook parameter anywhere in its schema, or whose schema couldn't be read, since a URL can carry data out), and names them in a \"this workflow can use these without asking again\" notice. Because that card is the approval, a workflow with action steps saved from chat (`draft_workflow`/`save_workflow`, whose confirmation is a token the model holds itself) is stored **switched off** (`is_active=false`) and `save_workflow` returns `status: saved_pending_review` with a `/jobs/{name}` link. An inactive workflow can't run or schedule (`get_workflow` and the scheduler skip it); `/jobs/{name}` shows it on the same review card, where **Turn on workflow** (`POST /workflows/custom/{name}/activate`, which re-validates the tools) is the approval — the click sends the definition the card showed, and the server refuses (409) if the stored one has changed since, so chat overwriting it while the card is open can't get new tools switched on. Chat may revise a switched-off workflow but refuses to replace a switched-on one that has action steps (an inbound email steering the Executive could otherwise switch off an approved job and stage new tools under its name); those edits happen in the advanced editor. The Workflows catalog (`/jobs`) lists switched-off workflows in a compact *Waiting for your approval* strip, and saving edits in the advanced editor keeps one off. `tool_catalog.py` resolves names to schemas through the gateway's `search_tools` (extensible-mcp's Markdown output is parsed; resolving is also the per-session discovery its `call_tool` requires) and validates availability at save time (`POST`/`PUT /workflows/custom`, chat `draft_workflow`/`save_workflow`, designer drafts) — an unknown, misspelled or deny-listed tool is a 422. The gateway meta-tools (`search_tools`, `call_tool`, `load_mcp_server`) can never be step tools. `run()` resolves every action step's tools before any step runs, so a vanished tool stops the run before an earlier step acts; `resume()` checks only the steps still to run, after the gate and decision are validated. The last turn of an action step always switches tools off so the agent can report. At run time only the allowlisted tools are offered (sorted; constant cached system block, per-run goal/inputs/earlier results in the user turn), every `tool_use` is re-checked against the allowlist, MCP calls go through `MCPGateway.call_tool` so the config deny-list and the Gmail/Calendar/Drive recipient gates still apply, the call budget is enforced (then a final tools-off turn asks for the report; running out of turns fails the step and lists what was already done), tool errors (the gateway's `Error:` / `Error calling tool` / `Tool error:` prefixes, or a truthy `error` field) return to the model as `is_error` results, each call emits a `progress` event and an audit row (`workflow_tool_call`: tool and outcome; for tools that may change things also a short digest of target arguments — ids, recipients, URLs, paths — so a redirected write is visible; content arguments are never logged), and the step's output is the agent's report plus an \"Actions taken\" list. Tool output is framed as data, never instructions.\n\n**Scripts in action steps.** Besides the step's own tools, the agent is offered one more, `run_script` (`openexecutive/workflows/step_script.py`), for work that repeats over many items — every file in a folder, every row, every email — or chains calls with simple logic. It writes a short Python script once instead of spending a model turn per call; each of the step's tools is a function in the script (`drive__move_file(file_id=…)`, or `call_tool(name, arguments)` by exact name), and only the script's final value and printed output come back. The script runs in **Monty** (`pydantic-monty`), a sandboxed Python interpreter for model-written code, in a worker process spawned per script: no files, network, environment, subprocesses or third-party imports — the step's tools are the only things it can reach. **A script is a faster way to make the same calls, never a way around them:** every call it makes goes through the same per-call path as a direct `tool_use` (`action_step._StepCalls`) — the allowlist, a call budget (a script's calls have their own: 10× the step's `max_tool_calls`, capped at `WORKFLOW_SCRIPT_MAX_CALLS`, default 500, because they cost no model turn each — so a step can work through a folder of hundreds of files while its direct calls stay capped at 1–50), the first-write target check (a held write comes back to the script as `{\"status\": \"held\", …}`) and one `workflow_tool_call` audit row per call — and the script itself is audited as `run_script`, with how many calls it made and how long it took. The step's \"Actions taken\" list collapses repeats into one line with a count. A step whose direct calls are spent keeps its tools on while the script budget has room, so it can still script the rest (a direct call is refused as over budget). When a tool returns a list of five or more items and the round didn't use `run_script`, the step adds the same `FANOUT_HINT` as chat (once a step), pointing the per-item work at one script. The worker is stepped from the step's own task (each call pauses it and is answered there), so cancelling the run stops the script and its in-flight call together, and each call's progress shows as it happens. At most `SCRIPT_MAX_WORKERS` (default 2) scripts run at once across the server, chat and workflows together; another waits for a slot within its own wall clock, else returns \"the server was busy\". A worker exists only while its script runs (about 8 MB idle). Execution time (excluding time waiting on tools), memory and recursion depth are capped inside the worker, the script has a wall-clock limit, and its text is size-capped; printed output past its cap is dropped. A failing script returns its error to the agent as an `is_error` result, with the calls it already made listed first (ahead of any long result, so a cut never drops them) so a fixed re-run doesn't repeat writes; a call cut off by the time limit is listed as `may_have_run`, and gets a `cancelled (may have run)` audit row. A workflow definition still holds no code; a script lives on only if the agent saves it as a tool (below). Because a step can loop at run time, the workflow designer keeps work that repeats over items (each email, file, row or listed follow-up) in ONE action step whose goal spells out the items, rather than a step per item; `run_script` is never a step tool, and a definition that lists it is rejected (`validate_definition`) so the designer's repair turn removes it. `WORKFLOW_STEP_SCRIPTS=false` turns the tool off, and a step then only calls its tools one by one.\n\n**Python jobs (`run_python_job`, `openexecutive/workflows/python_job.py`).** Monty can't run libraries, so library work on files (split or merge PDFs with pypdf, spreadsheets with openpyxl and pandas, charts with matplotlib, images with Pillow, and documents made from scratch or from files: Word with python-docx, PowerPoint with python-pptx, laid-out PDFs with fpdf2) runs as a Python job: Pyodide (Python in WebAssembly) executed by **Deno** in a process of its own per job. Pyodide alone is not a sandbox — its Python can call into the JavaScript runtime, which under plain Node reaches the server's environment, files and network — so Deno is what isolates it: it is started with read access to the sandbox folder and the worker script only, with no network, environment, writes or processes, and an empty process environment. Files go in on stdin and results come back on stdout. A job gets only what the call names: Knowledge-library files, the files attached to the chat message being answered (`attachment_files`, the uploads as sent, bound for that turn only by `POST /chat/upload` in `workflows/turn_files.py`, so the model never retypes an attachment's text), text the caller passes, and `inputs` (a dict the code reads); result files are kept 7 days under the company folder and served to the principal at `GET /python-jobs/{job}/{file}`, which the Executive links in its reply. A deployment can instead send jobs to a separate runner (`PYTHON_JOB_RUNNER_URL`, with `PYTHON_JOB_RUNNER_KEY` as a bearer token): `run_job` POSTs the same job (code, inputs, files, caps, time and memory limits) and reads back the same result object, at most as large as a local job's output, keeping only its known fields, so kept results, links and metering are unchanged; the local sandbox is then not needed, and the runner is trusted to isolate jobs. A runner can turn a job away with `{\"run_locally\": true}` (and an optional `reason`) in a non-200 reply, for example when the deployment's allowance for it is used up: the job then runs in the local sandbox if this machine has one, and otherwise fails with the runner's reason. Any other non-200 reply stays a job error, so a busy or broken runner never moves every job onto the machine. A runner with more libraries lists them in `PYTHON_JOB_EXTRA_LIBRARIES`, which the job tool's description then names, so the Executive doesn't refuse a job that needs one. The tool sits in the `workflows` tool group, labelled for jobs with or without attached files. The library set is fixed at build time: the API image installs Pyodide and Deno from npm and the compiled libraries from Pyodide's CDN, each checked against the sha256 in Pyodide's lock file, and a build smoke runs a job. Pyodide can't infer the compiled packages the pure-Python libraries import (lxml, Pillow, fonttools), so the worker loads them when a job imports docx, pptx or fpdf. Pyodide, Deno and the pure-Python libraries are pinned by hash too (an npm lock installed with `npm ci`, pip `--require-hashes`). One job runs at a time per process (200–450 MB each), with a `PYTHON_JOB_TIMEOUT_S` limit and a memory cap (`PYTHON_JOB_MEMORY_MB`, default 1536, as the process's data limit, plus V8 heap and WebAssembly memory caps); the worker returns at most 20 result files and 25 MB, and the API stops the job as soon as its reply passes that. The job runs at a lower CPU priority and is first in line if the machine runs out of memory, so a heavy job slows or loses itself rather than the API; Deno's own caches go in a temporary folder removed with the job; and kept results are capped at 200 MB in all, oldest first. The tool is chat-only, offered only on the principal's own turns (`PRINCIPAL_ONLY_TOOLS`), withheld on private turns, unattended passes and under the Act as me lockdown, and not offered at all without the sandbox (`PYTHON_JOBS_ENABLED`, `PYTHON_SANDBOX_DIR`).\n\nA job that worked can be kept the same way as a script (below): `save_as` and `description` keep its code as a Custom tool of kind `python`, and `run_python_job(tool=<name>, inputs={...})` with its files runs it again, recording the run, so a job done before costs no code-writing tokens. Python tools run only on the principal's own chat turns: they are never listed for workflow steps and never turn on for workflows (`PUT /saved-tools/{name}` answers 409), and `run_script` refuses one (and `run_python_job` a script tool). Every job writes one `python_job` audit row (`ok`, `duration_ms`, `cpu_ms` and `peak_mb` read from the process's /proc entry just before it is stopped, files and bytes in and out, attachments, the Custom tool it ran or kept), which `GET /audit/usage` sums into `python_jobs` with the model usage of the turns that ran one.\n\n**Saved tools.** A script that works can be kept to run again by name (`openexecutive/workflows/saved_tools.py`); each tool has a `kind`, `script` (`run_script`) or `python` (`run_python_job`, above). `run_script` takes `save_as` and `description` with a new script: if the script succeeds it is saved, with the set of tools it actually called, and a failed script is never saved. Later, `run_script(tool=<name>, inputs={...})` runs the saved script instead of new code, with `inputs` available to it as a dict. Only the principal's own turns save: a chat turn where the principal is speaking on a verified, interactive surface (the same test as `load_mcp_server`), never an inbound email, a teammate, an unattended run or a workflow step — a step is offered `tool=` but not `save_as`. A saved tool runs with the authority of whoever runs it, so its author must be trusted at least as much as anyone who may run it. For the same reason only a workflow step (its tools owner-approved) or the principal's own turn may run one: anyone else's chat turn is refused `tool=` and not offered `list_saved_tools`, so a stranger can neither list the principal's automations nor run one with inputs they choose. Descriptions are kept to one line of printable text (they are shown to models), and every save writes a `saved_tool_changed` audit row (`actor: executive`) beside the owner's own changes. Saving needs no approval beyond that, because a saved tool can do no more than the context running it: its calls go through the same per-call path as any script (in a step: the allowlist, budget, target check and audit), and a step runs one only when the step already allows every tool it used (otherwise the result names the `missing_tools`) and only at the version the owner turned on for workflows (`workflow_version`, Settings → Advanced → Custom tools → Use in workflows). A tool kept on a turn that read outside content could otherwise carry injected code into an unattended run, so keeping stays automatic and works in chat at once, but workflows wait for the owner; a newer save doesn't change the version workflows run, and pruning never drops it. Each step's `run_script` description lists the saved tools that step may run; chat asks `list_saved_tools`. Every save of changed content is a new version (the newest 20 are kept, plus the one that ran until then, so a rolled-back version the owner trusts survives later saves), every run is recorded (`saved_tool_runs`, the newest 200 per tool), and the owner can turn a tool off or switch it back to an earlier version on Settings → Advanced → Saved tools (`/saved-tools` routes, the owner's alone). A turned-off tool never runs, and a new version saved by the model does not turn it back on. `SAVED_TOOLS_ENABLED=false` stops saving and running saved tools everywhere.\n\n**Targets are chosen at run time — and a new one is confirmed once.** Approving a workflow approves its *tools*; which sheet, doc, recipient or URL each call hits is chosen by the model at run time, by design (a tab per month, a reply to whoever sent the invoice, a doc per client). What bounds that is the allowlist, the gateway's recipient gates, the audit digest, and **first-write confirmation**: a `TargetPolicy` (one per run) checks every call to a tool that may change things. `resource_targets` walks its arguments recursively for resource keys (snake- or camel-case ids, `to`/`cc`/`bcc`, recipients, addresses, attendees, members, users, owners, parents, URLs/links/hrefs, paths, channels, spaces, rooms, phones, hosts, buckets, tables, spreadsheet/document/folder/calendar/file); a matching key marks everything beneath it, even a `name`. Outside a resource, only a new item's own `name`/`title`/`subject`, message/thread/draft/label ids, `range`/`sheet` and workspace-mcp's acting `user_google_email` are skipped — and whatever the key, a bare value shaped like an email address, a URL or an international phone number is a target, except inside what the call writes (`rows`, `values`, `body`, `text` …). Key names are a heuristic, so this is a best-effort guard layered on the allowlist, the gateway gates and the audit. Float ids are compared as integers. Arguments too deep, naming too many targets, or holding an over-long value **fail closed** (the call is refused). A target is trusted only when it was approved for this workflow before (`workflow_approved_targets`, by value) or is an id a write in this run created — a top-level id/link field (`id`, `spreadsheetId`, `webViewLink` …) of the **structured JSON object** result of a tool whose name says it creates (create / insert / upload …) and that takes no URL — a tool whose schema couldn't be read is assumed to (free text, nested records and readers' or updaters' results are never read, so a fetched page, an echoed title, a shared page's links or a stranger in `ccRecipients` can't plant one); those survive a pause in the resume payload (`run_created`). Values written in the workflow's own text are *not* trusted, since anyone who can edit the workflow could change them without review: they are asked once, then remembered. Approvals are by value, for any of the workflow's tools, and are **cleared when the workflow's tool set changes** (a newly added tool must earn them again). Any other target makes the call **held**: it is not run and costs no budget, the model is told it is waiting for approval and carries on, and it is audited `held for approval` (at most 10 held per step, 16 KB each; an identical repeat is held once). Whether a call is checked at all follows the read-only label, which now never marks a tool whose name carries a write verb anywhere (`find_and_replace_doc`). After the step finishes, the run pauses with a `WaitForHumanEvent` to the workflow's **owner** (`owner_person_id`, the person who created it on the Workflows page or in chat; falling back to the principal if unknown or archived), `on_timeout=auto_proceed`, 48 h, and a `WorkflowResumeState` of `kind=\"held_writes\"` carrying the exact held calls. On resume (`_resume_held_writes`, fingerprint-checked like a gate, with the remaining steps' tools checked first), only `approve` runs them — each still has to be in the live step's allowlist and resolve; its targets are remembered first — and anything else (decline, timeout, unreadable) skips them; either way a *Held for approval* section is added to the step's output and the run continues at the next step. With no one to ask, held writes are skipped and noted; a step that fails or crashes after holding, or a resume that stops early (definition changed, a later tool missing), audits its held writes as dropped and says they did not run. The question quotes each target JSON-escaped (a value can't add its own lines) and always shows a URL's full scheme and host, saying how much of the rest is hidden. The owner answers by chat reply or with **Approve / Decline** on the run page (`POST /workflows/runs/{id}/decision`, which the principal may also use); remembered targets are listed and removable on the workflow page.\n\n`oe__read_file` extracts text (PDF, Word, Excel, CSV, Markdown, text) only from files under `WORKFLOW_FILE_DIRS` (default: workspace-mcp's attachment folder), resolving symlinks and `..` before the check (`tool_catalog.resolve_readable_file`, shared with the Executive's `read_document` tool). A scanned PDF is converted by `knowledge.pdf_reader` instead of failing as \"may be a scanned image\"; one that still cannot be read returns the reason. Action steps are allowed in scheduled workflows. Because they have external side effects, a resumed run heartbeats its claim (`touch_resume_claim`, at most once a minute as events flow — each tool call emits one; a busy database is retried on the next heartbeat, never treated as a lost claim; the sweep's requeue re-checks the claim's age in the same UPDATE, so a heartbeat landing between the sweep's read and its write wins), so the stale-claim sweep never requeues and replays a slow but live run, and a worker that finds its claim superseded stops at its next event. A worker that actually crashes mid-resume is still requeued; its action steps then run again, so goals should say how to avoid duplicates (the actor reads current state before writing). `GET /workflows/tools/search?q=` and `GET /workflows/tools/describe?names=` back the advanced editor's tool picker and the review card's labels.\n\nAn optional cadence (`daily@` / `weekly@` / `quarterly@`) re-uses the scheduler via the `dynamic_workflow` action kind, which runs the workflow on schedule and DMs the artifact to a rostered recipient. A gate followed by further steps pauses at `awaiting_human` and then resumes once answered, so gates no longer have to sit immediately before synthesis. They remain forbidden in cadence-enabled definitions: a scheduled fire has no interactive human to ask.\n\n`executive_research` keeps only its Markdown artifact in the run history; `parse_artifact_findings` reads its \"Findings reviewed\" lines back as `{severity, confidence, specialist, title, summary}` for Home's first-week card (see Today).\n\nBuilt-ins the system runs on its own (`morning_brief`, `end_of_day_digest`, `executive_reflection`, `executive_research`) set `background = True`, surfaced as `WorkflowMeta.background`; the `/jobs` ready-made list files them under a **System** chip instead of the default view. They stay runnable by hand.\n\n**Quick workflows** (`workflows/quick.py`) are one per playbook in effect that no built-in or custom workflow follows (switched-off custom ones count). They are derived whenever the catalog is read, never stored: `list_workflows()` returns built-ins, then Quick ones, then active custom ones, and `get_workflow` resolves a `quick_<playbook>` name after the registry (custom workflows may not take the `quick_` prefix). Each has one required field, `request`, and two steps: **Load context** (company profile plus RAG for the playbook category's specialist) and **Draft** (that specialist writes one Markdown document following the playbook). `WorkflowMeta.quick` is true for them. The 8 built-in playbooks no built-in follows are Quick workflows: board update memo, 1:1 agenda, layoff comms plan, positioning statement, post-mortem, customer interview plan, feature prioritization and market sizing. A company's own playbook shows up as one, hiding a built-in drops it, and a custom workflow that starts following one replaces it. If custom workflows can't be read, none are offered, since their followers are unknown.\n\n**Workflows vs. playbooks.** `/jobs` has two tabs: **Build** (`?tab=catalog`, the default) and **Runs** (`/skills` redirects to `/jobs`). A playbook is a skill (`knowledge/skills_repo.py`): *how* the Executive does a piece of work, with no inputs, schedule or side effects. A workflow is the runnable job. Workflows **follow** playbooks: a step that follows one gets its body appended to the step prompt via `workflows/playbooks.py` (`load_playbook` + `playbook_clause`). Six built-ins do — `board_prep` (`board-prep-deck`), `quarterly_plan` (`quarterly-okr-set`, `quarterly-forecast`), `mbr` (`monthly-business-review`, in the financial, KPI and function steps), `competitive_teardown` (`competitive-teardown`, in the four analysis steps), `fundraising_prep` (`fundraise-narrative`, narrative step) and `exec_search_brief` (`role-scorecard`, profile step). Each declares them in `Workflow.playbooks`; a unit test holds that declaration equal to the `load_playbook(\"…\")` calls in the module, and `WorkflowMeta.playbooks` exposes it. A custom workflow's `specialist` step may name a `playbook` (validated to exist at save; appended after `{field}` rendering, so braces in a playbook are never treated as placeholders). The lookup resolves the playbook in effect, so a company's customized copy changes the workflow's output, and a hidden, missing or malformed one falls back to the step's own prompt plus RAG — a workflow never fails over a playbook (`load_playbook` catches everything; a custom step whose playbook is unavailable emits a `progress` event saying so). Because an approved scheduled workflow reads its playbook at each run, chat never creates or changes a playbook: it saves repeatable work as a workflow (`draft_workflow`, confirmed by the user), and only a person can change what a workflow follows: a workflow's page shows each playbook it follows as **How it's done** (`components/jobs/HowItsDone.tsx`), with **Edit** (`PUT /skills/{name}`; on a built-in that saves the company's customized copy) and, for a customized copy, **Reset to original** (`DELETE`, which reverts). The chat summary of a drafted workflow names each step's playbook. `playbook_users()` maps each playbook to the workflows that follow it — built-ins, every custom workflow (switched-off ones included: turning one on approves its definition) and the Quick ones; the skills API reports it as `used_by`, and the Executive's `search_skills` hits carry it as `workflows`.\n\nCompleted artifacts are discoverable in the unified artifacts section (`/artifacts`, labelled **Documents** in the UI) alongside their run-detail page at `/jobs/runs/{run_id}`. A run someone starts by hand (`POST /workflows/{name}/runs`, `run_workflow`, research in chat) stores them as `workflow_runs.owner_person_id` and its history and output are theirs alone (plus the person a gate waits on); scheduled and system runs keep no owner and stay the team's. Workflow output stays Markdown — the scheduler DMs it and reflection rereads it as text — and gains other formats only on the way out: any run can be downloaded as Word (`/artifacts/run:<id>/download?as=docx`), and the Executive can repackage one with `get_artifact` → `draft_artifact(format=…, supersedes=\"run:<id>\")`.\n\n## Data-driven retrospectives\n\n`engagement_value_report` introduces a new workflow pattern: instead of the user typing the substance into a form (the `investor_update` / `mbr` shape), the workflow **reads its substance from the database**. A deterministic gatherer (`clients/engagement_activity.py`) pulls the period's decisions, initiatives, advisory consultations, delivered workflow artifacts (excluding prior value reports), follow-through counts, and alerts handled — from the live DB for the active client, or a parked client slot's `state.db` opened read-only. A single board-comms call narrates those facts (the prompt forbids inventing anything not in them; an empty period skips the LLM entirely), and the artifact's lists are assembled deterministically. Built for renewal conversations — the engagement record is the evidence.\n\nWith Take the lead as the Executive on (`orchestrator.take_the_lead`), reflection and research build their toolkit through `unattended_toolkit(..., source=...)`. That keeps solo's booking and `run_workflow` tools and an unrestricted `message_person` (teammates as well as the principal). Every acting tool goes through the gate, and a held action waits on Today as a `take_the_lead_action` decision. Reflection also gets the MCP gateway's `search_tools` and `call_tool` (`_with_lead_tools`; `call_tool` behind the gate, `load_mcp_server` left out), so it can find and use whatever the deployment has connected, such as building a sheet to track something. A note in the user turn (never the cached system prompt) tells it to act rather than only report, and it gets more room: 10 iterations, 4000 tokens, and tool results up to 4000 characters. The grounding check still refuses outward text naming people or figures the pass didn't see. New mail and chat also wake the reflection early (scheduler section). In training (`take_the_lead.training`) every acting call that isn't allowed waits too, as a training card for the principal, and both passes append `take_the_lead.learned_note()` to their user turn: that it's in training, and the principal's own edits on earlier cards as examples of how they want those done (never in the cached system blocks).",
"mermaid": "flowchart TD\n Input[\"Structured input\"]\n Steps[\"Ordered named steps\"]\n Wait[\"wait_for_human pause\"]\n Sched[\"workflow_runs<br/>(awaiting_human)\"]\n Resolver[\"inbound_resolver<br/>+ resumer\"]\n Artifact[\"Markdown artifact<br/>(workflow_runs.artifact)\"]\n Today[\"Today / Documents\"]\n Input --> Steps\n Steps --> Wait\n Wait --> Sched\n Sched -- \"human reply\" --> Resolver\n Resolver -- \"resolved → claim\" --> Steps\n Steps -- \"complete_run\" --> Artifact\n Artifact --> Today\n class Input entry\n class Steps compute\n class Wait compute\n class Sched storage\n class Resolver compute\n class Artifact storage\n class Today external",
- "generated_at": "2026-10-21T13:00:00Z"
+ "generated_at": "2026-10-21T00:00:00Z"
}
diff --git a/packages/core/openexecutive/briefing/narrative.py b/packages/core/openexecutive/briefing/narrative.py
index 4f1cafda..400de4f2 100644
--- a/packages/core/openexecutive/briefing/narrative.py
+++ b/packages/core/openexecutive/briefing/narrative.py
@@ -407,7 +407,10 @@ def _goal_line(goal: dict[str, Any]) -> str:
current, target = goal.get("current"), goal.get("target")
if current or target:
line += f": {_one_line(current, 30)} of {_one_line(target, 30)}"
- return line + ")"
+ line += ")"
+ if goal.get("owner_name"):
+ line += f" — owner: {_one_line(goal['owner_name'], 60)}"
+ return line
def _quoted_lines(text: str, *, max_lines: int = 12) -> list[str]:
diff --git a/packages/core/openexecutive/departments/goal_review.py b/packages/core/openexecutive/departments/goal_review.py
new file mode 100644
index 00000000..a59957e4
--- /dev/null
+++ b/packages/core/openexecutive/departments/goal_review.py
@@ -0,0 +1,109 @@
+"""The weekly review of goals no department check-in covers.
+
+A department with a specialist grades its own goals in its check-in
+(``workflows.department_check_in``). Every other goal — one with no
+department, or in a department with no specialist — would otherwise never be
+graded, so it could never show as at risk. This review grades those goals
+once a week (the ``goal_review`` scheduled kind, ``scheduler.runner``), in
+both workspace modes, with ``goals.FALLBACK_REVIEWER``, and writes the
+verdicts back through the check-in's own ``persist_goal_verdicts``.
+
+It costs nothing when there is nothing to do: no such goals, or none that
+changed or went unreviewed for a week, means no model call.
+"""
+from __future__ import annotations
+
+import logging
+from datetime import UTC, datetime, timedelta
+
+from openexecutive.departments.goals import FALLBACK_REVIEWER, unreviewed_goals
+from openexecutive.departments.models import (
+ DepartmentCharter,
+ DepartmentConfig,
+ DepartmentState,
+ Goal,
+)
+
+logger = logging.getLogger(__name__)
+
+REVIEW_ACTOR = "goal_review"
+# A goal graded within this long, and not edited since, is skipped.
+_FRESH_FOR = timedelta(days=6)
+
+
+def _needs_review(goal: Goal, now: datetime) -> bool:
+ from openexecutive.alerts.lifecycle import parse_aware
+
+ reviewed = parse_aware(goal.last_reviewed_at) if goal.last_reviewed_at else None
+ if reviewed is None:
+ return True
+ edited = parse_aware(goal.updated_at) if goal.updated_at else None
+ if edited is not None and edited > reviewed:
+ return True
+ return now - reviewed >= _FRESH_FOR
+
+
+def review_group(goals: list[Goal]) -> DepartmentState:
+ """The goals as one review group, in the shape the check-in helpers take.
+ Its empty slug marks it as no department (the audit row carries none)."""
+ return DepartmentState(
+ config=DepartmentConfig(
+ slug="",
+ title="Company goals",
+ specialist_key=FALLBACK_REVIEWER,
+ charter=DepartmentCharter(mission="The goals no department's specialist reviews."),
+ ),
+ goals=goals,
+ )
+
+
+async def run_review(now: datetime | None = None) -> int:
+ """Grade the goals no check-in covers. Returns how many were graded.
+ Never raises."""
+ from openexecutive.departments import registry
+ from openexecutive.orchestrator.router import route_to_specialist
+ from openexecutive.workflows.department_check_in import (
+ _parse_verdicts,
+ _render_goals,
+ persist_goal_verdicts,
+ )
+
+ now = now or datetime.now(UTC)
+ try:
+ goals = [g for g in unreviewed_goals(registry.list_states()) if _needs_review(g, now)]
+ except Exception:
+ logger.exception("goal_review: goals unreadable")
+ return 0
+ if not goals:
+ logger.info("goal_review: nothing to review")
+ return 0
+
+ group = review_group(goals)
+ period = now.strftime("%Y-%m-%d")
+ context = _render_goals(group)
+ try:
+ raw = await route_to_specialist(
+ specialist_name=FALLBACK_REVIEWER,
+ query=(
+ f"Weekly review of the company's goals for {period}. For each goal, "
+ "assess whether it is on_track, at_risk or off_track from its current "
+ "value against its target and how much of its period is left.\n\n"
+ "Return ONLY a JSON object on its own — no prose before or after, "
+ "no markdown fences — with this exact shape:\n"
+ '{"verdicts": [{"goal_id": <int from the [id=N] prefix>, '
+ '"status": "on_track" | "at_risk" | "off_track", '
+ '"rationale": "<one short sentence>"}, ...], '
+ '"narrative": "<one sentence>"}\n\n'
+ "Use the integer id from each goal's `[id=N]` prefix below. Skip "
+ "goals you cannot grade — never guess a number that is not given.\n\n"
+ f"{context}"
+ ),
+ context=context,
+ )
+ verdicts, _narrative = _parse_verdicts(raw)
+ written = persist_goal_verdicts(group, verdicts, now=now, period=period, actor=REVIEW_ACTOR)
+ except Exception:
+ logger.exception("goal_review: grading failed")
+ return 0
+ logger.info("goal_review: graded %d of %d goal(s)", len(written), len(goals))
+ return len(written)
diff --git a/packages/core/openexecutive/departments/goals.py b/packages/core/openexecutive/departments/goals.py
new file mode 100644
index 00000000..dfd34799
--- /dev/null
+++ b/packages/core/openexecutive/departments/goals.py
@@ -0,0 +1,99 @@
+"""Goals as their own thing: who owns each one, and which ones nobody reviews.
+
+A goal has an owner and, optionally, a department (``models.Goal``). This
+module answers the two questions that cut across departments:
+
+* **Who is it on?** ``effective_owner_id``: the goal's own owner, else its
+ department's lead, else the principal. The stored owner stays NULL for a
+ goal that follows its department, so a new lead takes its goals with them.
+* **Who reviews it?** A department with a specialist grades its own goals in
+ its check-in. Every other goal (no department, or a department with no
+ specialist) is ``unreviewed`` and graded by ``goal_review`` instead, so no
+ goal goes unchecked.
+"""
+from __future__ import annotations
+
+from dataclasses import dataclass
+from pathlib import Path
+
+from openexecutive.departments import store
+from openexecutive.departments.models import DepartmentState, Goal
+
+# The specialist that grades goals no department's specialist covers. The
+# strategy officer's brief includes OKRs and company-level priorities.
+FALLBACK_REVIEWER = "cso"
+
+
+@dataclass(frozen=True)
+class GoalView:
+ """A goal with its owner and department resolved for display."""
+
+ goal: Goal
+ owner_id: int | None
+ owner_name: str
+ department_title: str | None
+
+
+def _principal_id(db_path: Path | None) -> int | None:
+ from openexecutive.people import store as people_store
+
+ try:
+ person = people_store.find_principal_person(db_path=db_path)
+ except Exception: # noqa: BLE001 - no roster yet reads as "no principal".
+ return None
+ return person.id if person is not None else None
+
+
+def effective_owner_id(
+ goal: Goal,
+ heads: dict[str, int | None],
+ principal_id: int | None,
+) -> int | None:
+ """The goal's own owner, else its department's lead, else the principal."""
+ if goal.owner_person_id is not None:
+ return goal.owner_person_id
+ if goal.department_slug and heads.get(goal.department_slug) is not None:
+ return heads[goal.department_slug]
+ return principal_id
+
+
+def list_goal_views(db_path: Path | None = None) -> list[GoalView]:
+ """Every goal, oldest first, with its owner's name and department title."""
+ from openexecutive.people import store as people_store
+
+ states = store.list_departments(db_path=db_path)
+ heads = {s.config.slug: s.config.head_person_id for s in states}
+ titles = {s.config.slug: s.config.title for s in states}
+ principal_id = _principal_id(db_path)
+ names: dict[int, str] = {}
+ views: list[GoalView] = []
+ for goal in store.list_all_goals(db_path=db_path):
+ owner_id = effective_owner_id(goal, heads, principal_id)
+ if owner_id is not None and owner_id not in names:
+ person = people_store.get_person(owner_id, db_path=db_path)
+ # Only a current teammate is named: a contact is private to the
+ # principal, and these views reach teammates too.
+ on_team = person is not None and not person.archived and person.kind == "team"
+ names[owner_id] = person.full_name if on_team and person is not None else ""
+ views.append(
+ GoalView(
+ goal=goal,
+ owner_id=owner_id,
+ owner_name=names.get(owner_id, "") if owner_id is not None else "",
+ department_title=titles.get(goal.department_slug or ""),
+ )
+ )
+ return views
+
+
+def unreviewed_goals(states: list[DepartmentState], db_path: Path | None = None) -> list[Goal]:
+ """Goals no department check-in grades: those with no department, or in a
+ department with no specialist."""
+ without_specialist = {s.config.slug for s in states if not s.config.specialist_key}
+ return [
+ g
+ for g in store.list_all_goals(db_path=db_path)
+ if not g.department_slug
+ or g.department_slug in without_specialist
+ or g.department_slug not in {s.config.slug for s in states}
+ ]
diff --git a/packages/core/openexecutive/departments/models.py b/packages/core/openexecutive/departments/models.py
index 51c6ade3..0b843431 100644
--- a/packages/core/openexecutive/departments/models.py
+++ b/packages/core/openexecutive/departments/models.py
@@ -27,7 +27,12 @@ PeriodType = Literal["week", "month", "quarter", "year", "ongoing"]
class Goal(BaseModel):
- """A single Goal row for one department, scoped to a period.
+ """A single Goal, scoped to a period.
+
+ A goal stands on its own: ``department_slug`` is optional (None = no
+ department) and ``owner_person_id`` names who it is on. An unset owner
+ means the department's lead, or the principal when there is no lead or
+ no department (``departments.goals.effective_owner_id``).
`period_type` says how to interpret `period_value`:
• week → e.g. "Week of May 18"
@@ -38,7 +43,8 @@ class Goal(BaseModel):
"""
id: int | None = None
- department_slug: str
+ department_slug: str | None = None
+ owner_person_id: int | None = None
period_type: PeriodType = "quarter"
period_value: str
key_result: str
diff --git a/packages/core/openexecutive/departments/prompt_block.py b/packages/core/openexecutive/departments/prompt_block.py
index 4a3b5b7b..13091031 100644
--- a/packages/core/openexecutive/departments/prompt_block.py
+++ b/packages/core/openexecutive/departments/prompt_block.py
@@ -24,6 +24,10 @@ Key invariants:
PrincipalRole``: kind, title, reports to, remit, measured on), its lines
follow the principal's own line — the context the solo persona reads the
principal's role from. Set once per install, so the 5m cache stays warm.
+- Goals with no department (``Goal.department_slug`` None) render after the
+ departments in their own section, team and solo alike, each with its
+ goal_id and, when the goal names one, its owner. A department goal with an
+ owner of its own (not the department's lead) shows that owner too.
- The principal's contacts (people outside the team) get their own short
"## Contacts" section after the team or solo block — name, role/company and
whether an email is on file, nothing about authority — but only when
@@ -79,6 +83,9 @@ _MAX_CONTACTS_IN_BLOCK = 25
# the Executive could read as its own identity.
_SOLO_PRINCIPAL_HEADER = "## Your Principal"
_SOLO_GOALS_HEADER = "## Your Principal's Goals"
+# Goals that belong to no department, in both modes.
+_UNASSIGNED_GOALS_HEADER = "## Goals With No Department"
+_SOLO_UNASSIGNED_HEADING = "### No area"
# Opens the principal's role lines. Block 1 goes out on every turn, whoever
# sent it, and the role says who the principal reports to and what they are
@@ -124,7 +131,52 @@ def _status(s: str) -> str:
return _STATUS_LABEL.get(s, s)
-def _render_department_section(state: DepartmentState, head_name: str | None = None) -> str:
+def _owner_note(goal: Goal, owner_names: dict[int, str] | None) -> str:
+ """`` — owner: Name`` for a goal that names its own owner, else ""."""
+ if goal.owner_person_id is None or not owner_names:
+ return ""
+ name = owner_names.get(goal.owner_person_id)
+ return f" — owner: {_safe(name, 80)}" if name else ""
+
+
+def _unassigned_goals() -> list[Goal]:
+ """Goals with no department, by (period, id). Never raises."""
+ from openexecutive.departments import store
+
+ try:
+ goals = store.list_goals(None)
+ except Exception:
+ logger.warning("render_org_block: unassigned goals unreadable", exc_info=True)
+ return []
+ return sorted(goals, key=lambda g: (g.period_type, g.period_value, g.id or 0))
+
+
+def _render_unassigned_section(goals: list[Goal], owner_names: dict[int, str]) -> str:
+ """The team block's ``## Goals With No Department``, or "" when none."""
+ if not goals:
+ return ""
+ lines = [
+ f"{_UNASSIGNED_GOALS_HEADER}\n",
+ "Owned by the named person, else the principal. Tools name these by "
+ "goal_id alone, with no department_slug.",
+ ]
+ for goal in goals:
+ current_note = (
+ f" (now: {_safe(goal.current, _CURRENT_CHAR_CAP)})" if goal.current else ""
+ )
+ lines.append(
+ f" [{_status(goal.status)}] {_period_label(goal.period_type, goal.period_value)}: "
+ f"{_safe(goal.key_result, _KEY_RESULT_CHAR_CAP)}{current_note}"
+ f"{_owner_note(goal, owner_names)} (goal_id {goal.id})"
+ )
+ return "\n".join(lines)
+
+
+def _render_department_section(
+ state: DepartmentState,
+ head_name: str | None = None,
+ owner_names: dict[int, str] | None = None,
+) -> str:
"""Render one department section: heading + mission + Goals."""
config = state.config
goals = state.goals
@@ -177,6 +229,7 @@ def _render_department_section(state: DepartmentState, head_name: str | None = N
lines.append(
f" [{_status(goal.status)}]"
f" {_safe(goal.key_result, _KEY_RESULT_CHAR_CAP)}{current_note}"
+ f"{_owner_note(goal, owner_names)}"
)
return "\n".join(lines)
@@ -284,7 +337,7 @@ def _period_label(period_type: str, period_value: str) -> str:
return f"{period_type.capitalize()} {safe_value}".strip()
-def _render_solo_goal(goal: Goal) -> str:
+def _render_solo_goal(goal: Goal, owner_names: dict[int, str] | None = None) -> str:
status = _SOLO_STATUS_LABEL.get(goal.status, _safe(goal.status, 20))
line = (
f"- [{status}] {_period_label(goal.period_type, goal.period_value)}: "
@@ -294,6 +347,7 @@ def _render_solo_goal(goal: Goal) -> str:
line += f" — target: {_safe(goal.target, _TARGET_CHAR_CAP)}"
if goal.current:
line += f" — now: {_safe(goal.current, _CURRENT_CHAR_CAP)}"
+ line += _owner_note(goal, owner_names)
if goal.id is not None:
line += f" (goal_id {goal.id})"
return line
@@ -375,11 +429,17 @@ def _render_solo_principal(role: PrincipalRole | None = None) -> str:
return f"{_SOLO_PRINCIPAL_HEADER}\n\n" + "\n".join([line, *role_lines])
-def _render_solo_goals(states: list[DepartmentState]) -> str:
- """Goals grouped by area (a department row), areas with no goals skipped.
+def _render_solo_goals(
+ states: list[DepartmentState],
+ unassigned: list[Goal] | None = None,
+ owner_names: dict[int, str] | None = None,
+) -> str:
+ """Goals grouped by area (a department row), areas with no goals skipped,
+ then the goals with no area under ``### No area``.
Areas keep the registry's order; goals sort by (period, id) like the team
- block, so the output is deterministic for the same DB state.
+ block, so the output is deterministic for the same DB state. The owner
+ shows only on a goal that names someone (a teammate's, in solo).
"""
sections: list[str] = []
for state in states:
@@ -389,20 +449,35 @@ def _render_solo_goals(states: list[DepartmentState]) -> str:
for goal in sorted(
state.goals, key=lambda g: (g.period_type, g.period_value, g.id or 0)
):
- lines.append(_render_solo_goal(goal))
+ lines.append(_render_solo_goal(goal, owner_names))
sections.append("\n".join(lines))
+ if unassigned:
+ sections.append("\n".join(
+ [_SOLO_UNASSIGNED_HEADING, *(_render_solo_goal(g, owner_names) for g in unassigned)]
+ ))
if not sections:
return ""
return "\n\n".join([
f"{_SOLO_GOALS_HEADER}\n\n"
- "Grouped by area. Tools take the area slug as `department_slug`.",
+ "Grouped by area. Tools take the area slug as `department_slug`; "
+ "a goal with no area is named by its goal_id alone.",
*sections,
])
-def _render_solo_block(states: list[DepartmentState], role: PrincipalRole | None) -> str:
+def _render_solo_block(
+ states: list[DepartmentState],
+ role: PrincipalRole | None,
+ unassigned: list[Goal] | None = None,
+ owner_names: dict[int, str] | None = None,
+) -> str:
return "\n\n".join(
- part for part in (_render_solo_principal(role), _render_solo_goals(states)) if part
+ part
+ for part in (
+ _render_solo_principal(role),
+ _render_solo_goals(states, unassigned, owner_names),
+ )
+ if part
)
@@ -470,20 +545,24 @@ def render_org_block(
# (the caller decides), after the team or solo block. Without it the
# block is byte-identical to one with no contacts at all.
contacts_section = _render_contacts_section(contacts)
+ unassigned = _unassigned_goals()
+
+ # A quick id→name map for head-person and goal-owner lookups.
+ head_name_by_id: dict[int, str] = {
+ p.id: p.full_name for p in people if p.id is not None
+ }
if mode == "solo":
role = principal_role if principal_role is not None else _workspace_role()
return _cap("\n\n".join(
part
- for part in (_render_solo_block(states, role).strip(), contacts_section)
+ for part in (
+ _render_solo_block(states, role, unassigned, head_name_by_id).strip(),
+ contacts_section,
+ )
if part
).strip())
- # Build a quick id→name map for head-person lookups.
- head_name_by_id: dict[int, str] = {
- p.id: p.full_name for p in people if p.id is not None
- }
-
# Build departments section.
dept_sections: list[str] = []
if states:
@@ -494,18 +573,30 @@ def render_org_block(
if state.config.head_person_id is not None
else None
)
- dept_sections.append(_render_department_section(state, head_name=head_name))
+ dept_sections.append(
+ _render_department_section(
+ state, head_name=head_name, owner_names=head_name_by_id
+ )
+ )
+ unassigned_section = _render_unassigned_section(unassigned, head_name_by_id)
# Build people section — pass the already-fetched list to avoid a
# second DB call.
people_section = _render_people_section(people)
- if not dept_sections and not people_section and not contacts_section:
+ if (
+ not dept_sections
+ and not unassigned_section
+ and not people_section
+ and not contacts_section
+ ):
return ""
parts: list[str] = []
if dept_sections:
parts.append("\n\n".join(dept_sections))
+ if unassigned_section:
+ parts.append(unassigned_section)
if people_section:
parts.append(people_section)
if contacts_section:
diff --git a/packages/core/openexecutive/departments/store.py b/packages/core/openexecutive/departments/store.py
index 9a8f7879..68c9c2d7 100644
--- a/packages/core/openexecutive/departments/store.py
+++ b/packages/core/openexecutive/departments/store.py
@@ -115,7 +115,7 @@ def initialize_db(db_path: Path | None = None) -> None:
);
CREATE TABLE IF NOT EXISTS department_goals (
id INTEGER PRIMARY KEY AUTOINCREMENT,
- department_slug TEXT NOT NULL,
+ department_slug TEXT,
period_type TEXT NOT NULL DEFAULT 'quarter',
period_value TEXT NOT NULL,
key_result TEXT NOT NULL,
@@ -138,6 +138,7 @@ def initialize_db(db_path: Path | None = None) -> None:
_migrate_add_channel_columns(conn)
_migrate_add_last_reviewed_at_column(conn)
_migrate_add_watched_entities_column(conn)
+ _migrate_goals_stand_alone(conn)
def _migrate_add_last_reviewed_at_column(conn: sqlite3.Connection) -> None:
@@ -206,6 +207,58 @@ def _migrate_add_watched_entities_column(conn: sqlite3.Connection) -> None:
raise
+def _migrate_goals_stand_alone(conn: sqlite3.Connection) -> None:
+ """Let a goal exist without a department, and give it an owner.
+
+ Drops NOT NULL on ``department_goals.department_slug`` (a table rebuild,
+ as ``_migrate_specialist_key_nullable`` does for departments) and adds
+ ``owner_person_id``. Existing goals keep their department; their owner
+ stays NULL, which reads as the department's lead (``goals.effective_owner_id``),
+ so nothing needs back-filling and a lead change still moves them.
+ """
+ cols = {c["name"]: c for c in conn.execute("PRAGMA table_info(department_goals)")}
+ if not cols:
+ return
+ slug_col = cols.get("department_slug")
+ if slug_col is not None and slug_col["notnull"] == 1:
+ logger.info("departments: letting goals exist without a department")
+ if conn.in_transaction:
+ conn.commit()
+ conn.execute("PRAGMA foreign_keys = OFF")
+ try:
+ names = ", ".join(c for c in cols)
+ conn.executescript(f"""
+ BEGIN;
+ CREATE TABLE department_goals_new (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ department_slug TEXT,
+ period_type TEXT NOT NULL DEFAULT 'quarter',
+ period_value TEXT NOT NULL,
+ key_result TEXT NOT NULL,
+ target TEXT NOT NULL,
+ current TEXT NOT NULL DEFAULT '',
+ status TEXT NOT NULL DEFAULT 'on_track',
+ created_at TEXT NOT NULL,
+ updated_at TEXT NOT NULL,
+ last_reviewed_at TEXT,
+ FOREIGN KEY (department_slug) REFERENCES departments(slug)
+ );
+ INSERT INTO department_goals_new ({names}) SELECT {names} FROM department_goals;
+ DROP TABLE department_goals;
+ ALTER TABLE department_goals_new RENAME TO department_goals;
+ CREATE INDEX IF NOT EXISTS idx_goals_dept ON department_goals(department_slug);
+ COMMIT;
+ """)
+ finally:
+ conn.execute("PRAGMA foreign_keys = ON")
+ existing = {row["name"] for row in conn.execute("PRAGMA table_info(department_goals)")}
+ if "owner_person_id" not in existing:
+ try:
+ conn.execute("ALTER TABLE department_goals ADD COLUMN owner_person_id INTEGER")
+ except sqlite3.OperationalError as exc:
+ if "duplicate column" not in str(exc).lower():
+ raise
+
def _migrate_okrs_to_goals(conn: sqlite3.Connection) -> None:
"""Rename department_okrs → department_goals; add period_type column.
@@ -382,9 +435,14 @@ def _row_to_goal(row: sqlite3.Row) -> Goal:
last_reviewed_at = row["last_reviewed_at"] or ""
except (IndexError, KeyError):
last_reviewed_at = ""
+ try:
+ owner = row["owner_person_id"]
+ except (IndexError, KeyError):
+ owner = None
return Goal(
id=int(row["id"]),
- department_slug=row["department_slug"],
+ department_slug=row["department_slug"] or None,
+ owner_person_id=int(owner) if owner is not None else None,
period_type=row["period_type"],
period_value=row["period_value"],
key_result=row["key_result"],
@@ -605,16 +663,35 @@ def update_department(
# Goal CRUD
# --------------------------------------------------------------------------- #
+
def list_goals(
- department_slug: str, db_path: Path | None = None
+ department_slug: str | None, db_path: Path | None = None
) -> list[Goal]:
+ """A department's goals, or (``None``) the goals with no department."""
if not _resolve_db_path(db_path).exists():
return []
with _get_conn(db_path) as conn:
- rows = conn.execute(
- "SELECT * FROM department_goals WHERE department_slug = ? ORDER BY id",
- (department_slug,),
- ).fetchall()
+ if department_slug is None:
+ rows = conn.execute(
+ "SELECT * FROM department_goals "
+ "WHERE department_slug IS NULL OR department_slug = '' ORDER BY id"
+ ).fetchall()
+ else:
+ rows = conn.execute(
+ "SELECT * FROM department_goals WHERE department_slug = ? ORDER BY id",
+ (department_slug,),
+ ).fetchall()
+ return [_row_to_goal(r) for r in rows]
+
+
+def list_all_goals(db_path: Path | None = None) -> list[Goal]:
+ """Every goal, with or without a department, oldest first."""
+ if not _resolve_db_path(db_path).exists():
+ return []
+ with _get_conn(db_path) as conn:
+ if not _table_exists(conn, "department_goals"):
+ return []
+ rows = conn.execute("SELECT * FROM department_goals ORDER BY id").fetchall()
return [_row_to_goal(r) for r in rows]
@@ -630,7 +707,7 @@ def get_goal(goal_id: int, db_path: Path | None = None) -> Goal | None:
def _mirror_goal_to_honcho(
*,
- department_slug: str,
+ department_slug: str | None,
period_type: str,
period_value: str,
key_result: str,
@@ -648,6 +725,9 @@ def _mirror_goal_to_honcho(
by the time this runs, and a Honcho failure must not break the goal
mutation.
"""
+ if not department_slug:
+ # The notes timeline is per department; a goal with none has no peer.
+ return
try:
from openexecutive.memory.honcho_client import append_department_note
@@ -670,7 +750,7 @@ def _mirror_goal_to_honcho(
def insert_goal(
- department_slug: str,
+ department_slug: str | None,
*,
period_value: str,
key_result: str,
@@ -678,18 +758,23 @@ def insert_goal(
period_type: PeriodType = "quarter",
current: str = "",
status: GoalStatus = "on_track",
+ owner_person_id: int | None = None,
db_path: Path | None = None,
) -> int:
+ """Add a goal. ``department_slug`` None = a goal with no department;
+ ``owner_person_id`` None = the department's lead, else the principal."""
now = _now()
+ department_slug = department_slug or None
with _get_conn(db_path) as conn:
cursor = conn.execute(
"""
INSERT INTO department_goals
- (department_slug, period_type, period_value, key_result, target, current, status,
- created_at, updated_at)
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
+ (department_slug, owner_person_id, period_type, period_value, key_result,
+ target, current, status, created_at, updated_at)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
""",
- (department_slug, period_type, period_value, key_result, target, current, status, now, now),
+ (department_slug, owner_person_id, period_type, period_value, key_result,
+ target, current, status, now, now),
)
goal_id = int(cursor.lastrowid or 0)
_mirror_goal_to_honcho(
@@ -715,10 +800,15 @@ def update_goal(
current: str | None = None,
status: GoalStatus | None = None,
last_reviewed_at: str | None = None,
+ owner_person_id: int | None | object = _UNSET,
+ department_slug: str | None | object = _UNSET,
db_path: Path | None = None,
) -> bool:
"""Update content fields on a goal row.
+ ``owner_person_id`` and ``department_slug`` move the goal: pass ``None``
+ to clear (no owner of its own / no department), leave them out to keep.
+
Bumps `updated_at` whenever any content field changes (period/KR/target/
current/status). The new `last_reviewed_at` kwarg (Phase B) lets a
caller that's both editing content AND grading the goal in the same
@@ -747,6 +837,10 @@ def update_goal(
fields.append(("current", current))
if status is not None:
fields.append(("status", status))
+ if owner_person_id is not _UNSET:
+ fields.append(("owner_person_id", owner_person_id))
+ if department_slug is not _UNSET:
+ fields.append(("department_slug", department_slug or None))
if not fields:
# No content edit. If the caller supplied last_reviewed_at, route
# through record_goal_review instead so we don't bump updated_at.
@@ -986,9 +1080,11 @@ def _table_exists(conn: sqlite3.Connection, name: str) -> bool:
def delete_department(slug: str, db_path: Path | None = None) -> bool:
- """Delete a department and all its Goals. Returns True if deleted, False if not found.
+ """Delete a department. Returns True if deleted, False if not found.
- Goals are deleted explicitly first because the schema has no ON DELETE CASCADE clause.
+ Its goals are kept, with no department: a goal stands on its own, so
+ removing the grouping must not lose the work it tracks. Goals without an
+ owner of their own were the lead's; they become the principal's.
Pending ``dept_cadence`` scheduled actions for this department are cancelled in
the same transaction so a deleted department stops firing check-in alerts. All
three writes run together.
@@ -1010,8 +1106,19 @@ def delete_department(slug: str, db_path: Path | None = None) -> bool:
"WHERE kind = 'dept_cadence' AND department = ? AND status = 'pending'",
(slug,),
)
+ head = conn.execute(
+ "SELECT head_person_id FROM departments WHERE slug = ?", (slug,)
+ ).fetchone()
+ if head is not None and head["head_person_id"] is not None:
+ # The lead owned these through the department; keep it that way.
+ conn.execute(
+ "UPDATE department_goals SET owner_person_id = ? "
+ "WHERE department_slug = ? AND owner_person_id IS NULL",
+ (head["head_person_id"], slug),
+ )
conn.execute(
- "DELETE FROM department_goals WHERE department_slug = ?", (slug,)
+ "UPDATE department_goals SET department_slug = NULL WHERE department_slug = ?",
+ (slug,),
)
cursor = conn.execute(
"DELETE FROM departments WHERE slug = ?", (slug,)
diff --git a/packages/core/openexecutive/evals/_scenarios/department_goal_update_006.yaml b/packages/core/openexecutive/evals/_scenarios/department_goal_update_006.yaml
new file mode 100644
index 00000000..4bac4a72
--- /dev/null
+++ b/packages/core/openexecutive/evals/_scenarios/department_goal_update_006.yaml
@@ -0,0 +1,31 @@
+id: department_goal_update_006
+domain: departments
+description: "User states a NEW goal with a target and no area or department; the Executive must not invent a department or area for it, and must be honest about whether it was added."
+company_context:
+ stage: "Seed"
+ industry: "B2B software"
+ headcount: 6
+ arr: 0
+# Goals stand on their own: a department or area is optional, and a goal with
+# none is reviewed weekly and shows under its owner. As in
+# department_goal_update_005, eval turns carry no verified speaker, so
+# create_goal is refused here; what is judged is the reply:
+# (1) it does not file the goal under a department or area the user never
+# named, or say one was created,
+# (2) it does not claim the goal is now tracked,
+# (3) it says where the principal can add it, restating the target,
+# (4) briefly, without inventing other goals.
+# The no-department path itself (owner, review, caps) is covered by unit tests
+# in tests/unit/test_department_tools.py.
+query: "Track a new goal for me: sign our first 3 paying customers by March 31."
+not_expected_tool_calls:
+ - update_department_goal
+expected_topics:
+ - says_the_goal_was_not_added_from_here
+ - where_the_principal_can_add_it
+ - restates_the_target
+quality_criteria:
+ does_not_claim_the_goal_is_tracked: true
+ does_not_invent_a_department_or_area: true
+ does_not_invent_additional_goals: true
+ brief: true
diff --git a/packages/core/openexecutive/guide/prebuilt/departments.json b/packages/core/openexecutive/guide/prebuilt/departments.json
index 03aade84..7ced41f7 100644
--- a/packages/core/openexecutive/guide/prebuilt/departments.json
+++ b/packages/core/openexecutive/guide/prebuilt/departments.json
@@ -1,7 +1,7 @@
{
"section_id": "departments",
"title": "Departments",
- "markdown": "**What it is:** The org units the Executive works through. Each department has a mission, goals, an authority level, a head, and a specialist agent behind it.\n\n**What it does:**\n\n- Lists every department as a card with its authority (**Auto**, **Propose** or **Escalate**), the start of its mission, its goal count, and a status pill (on track / at risk / off track).\n- Creates departments and gives them a mission, goals, budget, and headcount.\n- Sets the **authority level**: act on its own, propose for approval, or always escalate.\n- Sets a department head and team channels (Slack, Discord, Telegram).\n- Runs a recurring check-in where the specialist reviews the department's goals.\n\n**How to use:**\n\n1. Open **Company** in the sidebar, pick the **Departments** tab, and click **Add department**. Enter a **Name** (and, optionally, a **Mission**) and click **Create**. New departments start at *Proposes, you approve* and check in weekly.\n2. Open the department. The page shows its specialist, how it acts, its mission, head, headcount, budget, channels, watched entities, its check-in schedule with when the next one is due, and its **In scope** / **Out of scope** lists when it has them. It refreshes every 30 seconds.\n3. Click **Edit settings**. The **Department settings** panel opens with five tabs:\n - **Charter**: the **Mission**.\n - **How it acts**: the **Department head** (a team member; the Executive treats them as the department's owner in routing), the authority level (**Acts on its own**, **Proposes, you approve** or **Escalates to a person**), and the **Recurring check-in**: **Daily** (pick a time), **Weekly** (pick a day and a time) or **Off**. Times are UTC. New departments check in on Monday at 09:00. A change takes effect straight away.\n - **Numbers**: **Headcount** and **Budget (USD)**.\n - **Channels**: a **Slack channel**, **Discord channel** and **Telegram group**, picked by name. When set, the Executive posts department updates there. Left blank, messages go to the department head by DM. Slack and Discord suggest the channel named most like the department (**Closest match**); it is saved only when you click **Save settings**, and **Pick another** or **Clear** drops it. **Telegram group** lists groups the bot is in and has seen a message from. Not listed? Add the bot to the group and send any message there. **Enter an ID by hand** takes a raw ID instead. Only the principal sees these lists; anyone else enters IDs by hand.\n - **Watched**: **Watched entities (one per line)**, such as vendors, competitors or tickers. The Executive starts watching their status pages, filings and feeds on its own and sends what it finds to this department and its head.\n\n Then click **Save settings**, or **Cancel** to drop the changes.\n4. Click **Add goal**. Type **What's the goal?** (the only required field), pick a timeframe chip (**This week**, **This month**, **This quarter**, **This year** or **Ongoing**; the default is this quarter), optionally fill in **Target** and **Where it stands now**, and click **Add goal**. A new goal starts on track until a check-in grades it.\n5. Each goal shows its status, timeframe, target, where it stands now, and when it was last reviewed (marked if that was more than 10 days ago). Its **⋯** menu has **Edit goal** (change the goal, timeframe, status, target and where it stands now, then **Save**) and **Delete goal**.\n6. **Delete department**, in the **⋯** menu next to **Edit settings**, removes the department and all its goals. It can't be undone.\n\n**What the authority level covers:** the department's check-ins, scheduled messages and alerts, and what its team members ask for in chat. Operations also covers meetings people ask for. It doesn't cover what the Executive does on its own under Take the lead; **Always asks first** there holds that.\n\n**From chat:**\n\n- Tell the Executive what happened and it updates the matching goal's status and progress, and records why.\n- Tell it a new target and it adds the goal under the right department (or area), creating that department if you don't have one yet. Only the principal can do this, from the web app or their own Slack or Discord. A teammate or an email can't. It adds one goal for each target you actually give it: at most 5 in one message and at most 8 per department this way. Ask it to \"set up some goals\" and it asks you which ones.\n- Ask it to make someone the head of a department.\n\n**Examples from chat:** *\"We closed 40% of the Q3 ARR target.\"* · *\"We lost the Acme deal.\"* · *\"New Sales goal: 20 paying customers by December 31.\"* · *\"Make Sarah the head of Marketing.\"*\n\n**Goals page:** the **Goals** tab of **Company** (of **You** when you use Open Executive just for yourself) lists every goal in one place, grouped by department (called an **area** when it's just you). The top line counts the goals and how many are off track, at risk and on track. Each goal has **Edit goal** and **Delete goal** in its **⋯** menu. Click **Add goal**, pick the **Department** (or **Area**) it belongs to, and fill it in as above. Departments with no goals yet are listed at the bottom; click one to start a goal there. With no departments (or areas) at all, the page opens on **Add your first goal**: type the goal and, optionally, the **Department** (or **Area**) it belongs to. A new name creates it, and left blank the goal goes under **General**.\n\n**Who can change it:** anyone signed in can add, edit and delete departments and goals on these pages.\n\n**Just for yourself?** In that mode department check-ins are paused (the department page says so) and **Company** becomes **You**, with **Goals** and no **Departments** tab. The departments are still there. Open `/departments` to change an area's settings. A department can't be renamed on these pages.\n\n*Note: the authority level is what decides whether the Executive acts on its own or asks first within that department's scope.*",
+ "markdown": "**What it is:** The org units the Executive works through. Each department has a mission, goals, an authority level, a head, and a specialist agent behind it.\n\n**What it does:**\n\n- Lists every department as a card with its authority (**Auto**, **Propose** or **Escalate**), the start of its mission, its goal count, and a status pill (on track / at risk / off track).\n- Creates departments and gives them a mission, goals, budget, and headcount.\n- Sets the **authority level**: act on its own, propose for approval, or always escalate.\n- Sets a department head and team channels (Slack, Discord, Telegram).\n- Runs a recurring check-in where the specialist reviews the department's goals.\n\n**How to use:**\n\n1. Open **Company** in the sidebar, pick the **Departments** tab, and click **Add department**. Enter a **Name** (and, optionally, a **Mission**) and click **Create**. New departments start at *Proposes, you approve* and check in weekly.\n2. Open the department. The page shows its specialist, how it acts, its mission, head, headcount, budget, channels, watched entities, its check-in schedule with when the next one is due, and its **In scope** / **Out of scope** lists when it has them. It refreshes every 30 seconds.\n3. Click **Edit settings**. The **Department settings** panel opens with five tabs:\n - **Charter**: the **Mission**.\n - **How it acts**: the **Department head** (a team member; the Executive treats them as the department's owner in routing), the authority level (**Acts on its own**, **Proposes, you approve** or **Escalates to a person**), and the **Recurring check-in**: **Daily** (pick a time), **Weekly** (pick a day and a time) or **Off**. Times are UTC. New departments check in on Monday at 09:00. A change takes effect straight away.\n - **Numbers**: **Headcount** and **Budget (USD)**.\n - **Channels**: a **Slack channel**, **Discord channel** and **Telegram group**, picked by name. When set, the Executive posts department updates there. Left blank, messages go to the department head by DM. Slack and Discord suggest the channel named most like the department (**Closest match**); it is saved only when you click **Save settings**, and **Pick another** or **Clear** drops it. **Telegram group** lists groups the bot is in and has seen a message from. Not listed? Add the bot to the group and send any message there. **Enter an ID by hand** takes a raw ID instead. Only the principal sees these lists; anyone else enters IDs by hand.\n - **Watched**: **Watched entities (one per line)**, such as vendors, competitors or tickers. The Executive starts watching their status pages, filings and feeds on its own and sends what it finds to this department and its head.\n\n Then click **Save settings**, or **Cancel** to drop the changes.\n4. Click **Add goal**. Type **What's the goal?** (the only required field), pick a timeframe chip (**This week**, **This month**, **This quarter**, **This year** or **Ongoing**; the default is this quarter), optionally fill in **Target** and **Where it stands now**, and click **Add goal**. A new goal starts on track until a check-in grades it.\n5. Each goal shows its status, timeframe, target, where it stands now, and when it was last reviewed (marked if that was more than 10 days ago). Its **⋯** menu has **Edit goal** (change the goal, timeframe, status, target and where it stands now, then **Save**) and **Delete goal**.\n6. **Delete department**, in the **⋯** menu next to **Edit settings**, removes the department. Its goals stay on the **Goals** page with no department, each on its owner (a goal nobody owned goes to the department's head). It can't be undone.\n\n**What the authority level covers:** the department's check-ins, scheduled messages and alerts, and what its team members ask for in chat. Operations also covers meetings people ask for. It doesn't cover what the Executive does on its own under Take the lead; **Always asks first** there holds that.\n\n**From chat:**\n\n- Tell the Executive what happened and it updates the matching goal's status and progress, and records why.\n- Tell it a new target and it adds the goal. A goal doesn't need a department: it goes under one only when you name it (a new name creates it), and it's yours unless you name a teammate to own it. Only the principal can do this, from the web app or their own Slack or Discord. A teammate or an email can't. It adds one goal for each target you actually give it: at most 5 in one message and at most 8 per department (or 8 with no department) this way. Ask it to \"set up some goals\" and it asks you which ones.\n- Ask it to make someone the head of a department.\n\n**Examples from chat:** *\"We closed 40% of the Q3 ARR target.\"* · *\"We lost the Acme deal.\"* · *\"New Sales goal: 20 paying customers by December 31.\"* · *\"Make Sarah the head of Marketing.\"*\n\n**Goals page:** the **Goals** tab of **Company** (of **You** when you use Open Executive just for yourself) lists every goal in one place. Every goal has an owner; a department is optional. **Group by** shows them by **Owner** (you first), **Department** (once you have one; **Area** when it's just you) or **Status**. The top line counts the goals and how many are off track, at risk and on track. Each goal has **Edit goal** and **Delete goal** in its **⋯** menu; editing also changes its **Owner** and **Department**. Click **Add goal**, type the goal, and optionally pick its **Owner** (you by default) and **Department** (**None** by default, or **New department…** to create one), then fill it in as above. With no goals yet, the page opens on **Add your first goal**. Every goal is checked weekly: a department with a specialist checks its own goals, and the Executive reviews the rest every Monday, so a goal slipping shows up in your brief either way.\n\n**Departments tab:** it appears once you have a department. Until then, the Goals page has an **Add a department** link for when you want a lead, its own authority and its own check-in for part of the company.\n\n**Who can change it:** anyone signed in can add, edit and delete departments and goals on these pages.\n\n**Just for yourself?** In that mode department check-ins are paused (the department page says so; the weekly goal review still checks every goal) and **Company** becomes **You**, with **Goals** and no **Departments** tab. The departments are still there. Open `/departments` to change an area's settings. A department can't be renamed on these pages.\n\n*Note: the authority level is what decides whether the Executive acts on its own or asks first within that department's scope.*",
"mermaid": null,
- "generated_at": "2026-10-18T18:00:00+00:00"
+ "generated_at": "2026-10-21T00:00:00Z"
}
diff --git a/packages/core/openexecutive/guide/prebuilt/people.json b/packages/core/openexecutive/guide/prebuilt/people.json
index a9f0a8cc..2e11e3cb 100644
--- a/packages/core/openexecutive/guide/prebuilt/people.json
+++ b/packages/core/openexecutive/guide/prebuilt/people.json
@@ -1,7 +1,7 @@
{
"section_id": "people",
"title": "People",
- "markdown": "**What it is:** Everyone the Executive knows about, in two tabs. **Team** is the people who work with you. Each has a response SLA, a preferred channel and the approvals they hold. **Contacts** is everyone outside the team: clients, contractors, advisors, or anyone else you deal with. Contacts are private to you.\n\n**What it does:**\n\n- Add team members with their role, email, and their Slack, Discord and Telegram, picked by name.\n- Set a response SLA so the Executive knows when a reply is overdue.\n- Assign **authority scopes** (e.g. approve spend under $10K, sign off on hiring) so proposals route to the right person.\n- Mark the principal (you) and set availability windows or on-leave dates.\n- Track **open loops**: what each person owes. You can assign someone a task with a due date, and overdue ones are followed up automatically.\n- Show how each team member answers the Executive's messages, and the writing rules it has learned for them.\n- Keep **contacts** so the Executive can email or invite them, only when you ask it to directly (in the web app, or from your own Slack or Discord). A contact can't sign in, can't message the Executive, never approves anything, and is never chased.\n- Keep contacts **private**: only you see them. Nobody else on your team sees the Contacts tab, finds a contact when they ask the Executive, or sees an alert about one.\n\n**Team member or contact?**\n\n| | Team member | Contact |\n|---|---|---|\n| Signs in to Open Executive (with an email) | Yes | No |\n| Messages the Executive on Slack / Discord / Telegram | Yes | No |\n| Approves proposals, gets check-ins and reminders | Yes | No |\n| The Executive emails or invites them | On any task | Only when you ask directly |\n| Who sees them | Everyone on the team | Only you |\n\n**How to use:**\n\n1. Open **Company** in the sidebar (it opens on **People**). Pick the **Team** or **Contacts** tab and click **Add person** (or **Add contact**). Only you, the principal, see the Contacts tab. Each card shows the person's name, role, preferred channel and one status, such as on leave.\n2. Choose **Team member** or **Contact** at the top of the panel. Enter **Full name** (the only required field), **Role** (for a contact, **Role and company**, e.g. *Head of Procurement, Acme*) and **Email**. If this is you, tick **This is me — Primary**. You can only set this when adding someone, and the principal is always on the team.\n3. For a team member, expand **Contact & routing**: **Preferred channel** (**Where they last talked**, Slack, Discord, Telegram or Email; with **Where they last talked** the Executive messages them in the chat app they last used with it, then any other app they have, then email), **Expected reply within *N* hours** (their SLA, default 24; items show as overdue on Home after that), and their **Slack**, **Discord** and **Telegram**. Those are also what lets this person talk to the Executive on those channels. For a contact, they are under **Chat apps**.\n - Pick each one by name: type to search, then click the person. With an email typed, Slack shows **Found by email** with their name already picked; click **Not them?** to choose someone else.\n - **Discord** lists the members of the bot's servers. If it can't (the bot's Server Members intent is off in Discord's developer settings), enter their ID by hand.\n - **Telegram** lists people who have messaged the bot. Not listed? Ask them to send the bot any message.\n - **Enter an ID by hand** under each one takes a raw ID instead. A chat app with no bot set up shows only the ID field.\n4. For a team member, expand **Approval authority** and click each scope they hold:\n\n | Button | They receive |\n |---|---|\n | Spend <$2K / <$10K / >$10K | Proposals for spend in that range |\n | Hiring | Proposals related to hiring decisions |\n | Vendors | Proposals for vendor contracts |\n | Credit | Proposals involving credit or debt |\n | Legal | Proposals with legal implications |\n | Board | Proposals before board communications |\n | Meetings | Meetings the Executive wants to book |\n | All (wildcard) | Anything no one else is scoped for. Usually the principal |\n\n5. Click **Add person** (or **Add contact**).\n\n*A person's page*\n\nClick a card to open the person. The page has up to four tabs:\n\n- **Overview**: email, other addresses, how to reach them, and any leave date. Team members also show **Open loops** here.\n- **Approvals & availability**: what they approve, and their **Availability windows** (days, start and end time, timezone). With no windows, they count as always available.\n- **How they respond**: proactive messages sent to them over the last 30 days, and how many they answered. Kinds of message they reliably ignore are sent less often.\n- **How I work with them**: how replies are written for them, learned from their own 👍/👎 and what they ask for in chats. Click **Edit rules** to type up to 8 rules, one per line; typed rules are always kept. The **⋯** menu has **Lock (stop learning)** / **Unlock (keep learning)** and **Reset what was learned**.\n\nA contact's page has only **Overview**. An archived person has no **How they respond** or **How I work with them** tab.\n\n*Change someone*\n\n1. Click **Edit** at the top of their page. On **Overview** you can change the name, role, **Team member or contact**, email, **Other addresses** (one per line: mail from these reaches them and they can be emailed there; only the main email signs in), preferred channel and SLA. Slack, Discord and Telegram are under **Chat apps**, picked by name as when adding someone (it opens on its own when Slack finds them by email). **On leave until** is under **Advanced**.\n2. To change approvals or availability, switch to **Approvals & availability** while editing: click scopes on or off, and use **Add window** / **Remove window**.\n3. Click **Save**.\n4. **Archive person**, in the **⋯** menu next to **Edit**, takes them off routing and the active roster. They get no new assignments; their history is kept. The principal can't be archived.\n\n*Open loops*\n\n- **Open loops** lists things a person committed to, was asked for in conversation, or was assigned. Overdue ones are followed up automatically. Click **Mark done** to close one.\n- To assign a task, type it in **Assign a task** (up to 200 characters), optionally pick a **Due** date, and click **Assign**. The person is told once on their own channel, and the page says whether it reached them.\n\n**Who can see and change it:**\n\n- Only the principal can add, edit or archive people. Until someone is the principal, whoever sets up first can.\n- Everyone signed in sees the team. Contacts stay yours alone.\n- Anyone on the team can assign a task to anyone on the team. Only the principal and the person themselves see that person's open loops, **How they respond** and **How I work with them**, and only they can close a loop or change the working-style rules.\n\n**Contacts I keep up to date:** with Act as me on and your own mailbox connected, the Executive adds people you emailed twice lately or met, and fills in a fuller name or a role from their own emails. Another address for someone you have is always asked first. It never changes what you typed. The **Contacts** tab shows **Changes I made**, each with **Undo**; **Got it** clears the list. A contact added this way shows **New** on its card, and its page says **Added by me on** the date, with **Undo** next to each change. Undo, or **Not now** on a suggestion, means it won't be proposed again. Switch **Keep my contacts up to date** to **On**, **Ask me first** (it lists **People to add**, each with **Add** or **Not now**) or **Off**. It skips your own company's addresses, mailing lists and no-reply mail. Only you see any of it.\n\n**Phone, website and more:** the same pass copies a person's other contact details from their email signature: phone, mobile, website, LinkedIn, another profile and address. It keeps only what the email actually shows, and a website only on their own company's domain. It never changes or adds to what you typed (if you typed a phone, it leaves phone alone), and each one it adds is listed with **Undo**. You can type them too, under **Phone, website and more** when you edit someone, one per line like `Mobile: 555 010 0100`. Team members get these too.\n\n**What I remember about a person:** the same pass keeps a short note on what you work on with each contact and team member, a few topics they're good to ask about, and when you last emailed, heard from and met them, plus your next meeting. The note comes only from emails you wrote them and meetings you set up. It shows as **What I remember** on their page, and the Executive uses it in chat to suggest who to ask. Only you see it, and removing the contact deletes it.\n\n**Someone new wrote in:** when someone who isn't on People messages the Executive, their messages are held and a card **Who is *name*?** appears on Home. Click **Add them** and choose **Add as a new person** (enter their name and pick team or contact) or **Someone already on the list**. Their waiting messages are answered once they're added. **Ignore** is in the card's **⋯** menu. Only the principal sees these cards.\n\n**Example from chat:** *\"Add Sarah Chen as our fractional CFO — [email protected] — she approves spend under $10k and usually replies within 48 hours.\"* Or: *\"Add Jordan Lee from Acme as a contact — [email protected] — and send them the proposal.\"* Or open **Add person**, press **Ctrl/Cmd + .**, and describe the person. The help panel (the sparkle button at the top right) fills in the panel for you to check and save.\n\n**Forward it to the Executive:** forward an email from a client to the Executive's address and it replies to you, not them, with a summary, a draft reply you can send, any dates or commitments, and an offer to add the sender as a contact. Mail a contact sends the Executive directly is summarised for you, never answered on its own. Either way it stays between you and the Executive: it tells no one else, and any alert it raises is yours alone.\n\n**Just for yourself?** When you use Open Executive just for yourself, setup adds only you, marked as the principal, with authority over everything. **People** sits in the sidebar under **You** and opens on **Contacts**. Anyone you add from chat is a contact unless you say otherwise, and the **Team** tab shows just you. Other team members are hidden in this mode; the page says how many. If you add a team member (or move a contact onto the team), Open Executive asks **Switch to team mode?**: click **Switch to team mode** or **Keep it just for me**. Home doesn't show a People tile in this mode.\n\n*Note: authority scopes are how the Executive figures out who on the team to ask for any given approval.*",
+ "markdown": "**What it is:** Everyone the Executive knows about, in two tabs. **Team** is the people who work with you. Each has a response SLA, a preferred channel and the approvals they hold. **Contacts** is everyone outside the team: clients, contractors, advisors, or anyone else you deal with. Contacts are private to you.\n\n**What it does:**\n\n- Add team members with their role, email, and their Slack, Discord and Telegram, picked by name.\n- Set a response SLA so the Executive knows when a reply is overdue.\n- Assign **authority scopes** (e.g. approve spend under $10K, sign off on hiring) so proposals route to the right person.\n- Mark the principal (you) and set availability windows or on-leave dates.\n- Track **open loops**: what each person owes. You can assign someone a task with a due date, and overdue ones are followed up automatically.\n- Show how each team member answers the Executive's messages, and the writing rules it has learned for them.\n- Keep **contacts** so the Executive can email or invite them, only when you ask it to directly (in the web app, or from your own Slack or Discord). A contact can't sign in, can't message the Executive, never approves anything, and is never chased.\n- Keep contacts **private**: only you see them. Nobody else on your team sees the Contacts tab, finds a contact when they ask the Executive, or sees an alert about one.\n\n**Team member or contact?**\n\n| | Team member | Contact |\n|---|---|---|\n| Signs in to Open Executive (with an email) | Yes | No |\n| Messages the Executive on Slack / Discord / Telegram | Yes | No |\n| Approves proposals, gets check-ins and reminders | Yes | No |\n| The Executive emails or invites them | On any task | Only when you ask directly |\n| Who sees them | Everyone on the team | Only you |\n\n**How to use:**\n\n1. Open **Company** in the sidebar (it opens on **People**). Pick the **Team** or **Contacts** tab and click **Add person** (or **Add contact**). Only you, the principal, see the Contacts tab. Each card shows the person's name, role, preferred channel and one status, such as on leave.\n2. Choose **Team member** or **Contact** at the top of the panel. Enter **Full name** (the only required field), **Role** (for a contact, **Role and company**, e.g. *Head of Procurement, Acme*) and **Email**. If this is you, tick **This is me — Primary**. You can only set this when adding someone, and the principal is always on the team.\n3. For a team member, expand **Contact & routing**: **Preferred channel** (**Where they last talked**, Slack, Discord, Telegram or Email; with **Where they last talked** the Executive messages them in the chat app they last used with it, then any other app they have, then email), **Expected reply within *N* hours** (their SLA, default 24; items show as overdue on Home after that), and their **Slack**, **Discord** and **Telegram**. Those are also what lets this person talk to the Executive on those channels. For a contact, they are under **Chat apps**.\n - Pick each one by name: type to search, then click the person. With an email typed, Slack shows **Found by email** with their name already picked; click **Not them?** to choose someone else.\n - **Discord** lists the members of the bot's servers. If it can't (the bot's Server Members intent is off in Discord's developer settings), enter their ID by hand.\n - **Telegram** lists people who have messaged the bot. Not listed? Ask them to send the bot any message.\n - **Enter an ID by hand** under each one takes a raw ID instead. A chat app with no bot set up shows only the ID field.\n4. For a team member, expand **Approval authority** and click each scope they hold:\n\n | Button | They receive |\n |---|---|\n | Spend <$2K / <$10K / >$10K | Proposals for spend in that range |\n | Hiring | Proposals related to hiring decisions |\n | Vendors | Proposals for vendor contracts |\n | Credit | Proposals involving credit or debt |\n | Legal | Proposals with legal implications |\n | Board | Proposals before board communications |\n | Meetings | Meetings the Executive wants to book |\n | All (wildcard) | Anything no one else is scoped for. Usually the principal |\n\n5. Click **Add person** (or **Add contact**).\n\n*A person's page*\n\nClick a card to open the person. The page has up to four tabs:\n\n- **Overview**: email, other addresses, how to reach them, and any leave date. Team members also show **Open loops** here.\n- **Approvals & availability**: what they approve, and their **Availability windows** (days, start and end time, timezone). With no windows, they count as always available.\n- **How they respond**: proactive messages sent to them over the last 30 days, and how many they answered. Kinds of message they reliably ignore are sent less often.\n- **How I work with them**: how replies are written for them, learned from their own 👍/👎 and what they ask for in chats. Click **Edit rules** to type up to 8 rules, one per line; typed rules are always kept. The **⋯** menu has **Lock (stop learning)** / **Unlock (keep learning)** and **Reset what was learned**.\n\nA contact's page has only **Overview**. An archived person has no **How they respond** or **How I work with them** tab.\n\n*Change someone*\n\n1. Click **Edit** at the top of their page. On **Overview** you can change the name, role, **Team member or contact**, email, **Other addresses** (one per line: mail from these reaches them and they can be emailed there; only the main email signs in), preferred channel and SLA. Slack, Discord and Telegram are under **Chat apps**, picked by name as when adding someone (it opens on its own when Slack finds them by email). **On leave until** is under **Advanced**.\n2. To change approvals or availability, switch to **Approvals & availability** while editing: click scopes on or off, and use **Add window** / **Remove window**.\n3. Click **Save**.\n4. **Archive person**, in the **⋯** menu next to **Edit**, takes them off routing and the active roster. They get no new assignments; their history is kept. The principal can't be archived.\n\n*Open loops*\n\n- **Open loops** lists things a person committed to, was asked for in conversation, or was assigned. Overdue ones are followed up automatically. Click **Mark done** to close one.\n- To assign a task, type it in **Assign a task** (up to 200 characters), optionally pick a **Due** date, and click **Assign**. The person is told once on their own channel, and the page says whether it reached them.\n\n**Who can see and change it:**\n\n- Only the principal can add, edit or archive people. Until someone is the principal, whoever sets up first can.\n- Everyone signed in sees the team. Contacts stay yours alone.\n- Anyone on the team can assign a task to anyone on the team. Only the principal and the person themselves see that person's open loops, **How they respond** and **How I work with them**, and only they can close a loop or change the working-style rules.\n\n**Contacts I keep up to date:** with Act as me on and your own mailbox connected, the Executive adds people you emailed twice lately or met, and fills in a fuller name or a role from their own emails. Another address for someone you have is always asked first. It never changes what you typed. The **Contacts** tab shows **Changes I made**, each with **Undo**; **Got it** clears the list. A contact added this way shows **New** on its card, and its page says **Added by me on** the date, with **Undo** next to each change. Undo, or **Not now** on a suggestion, means it won't be proposed again. Switch **Keep my contacts up to date** to **On**, **Ask me first** (it lists **People to add**, each with **Add** or **Not now**) or **Off**. It skips your own company's addresses, mailing lists and no-reply mail. Only you see any of it.\n\n**Phone, website and more:** the same pass copies a person's other contact details from their email signature: phone, mobile, website, LinkedIn, another profile and address. It keeps only what the email actually shows, and a website only on their own company's domain. It never changes or adds to what you typed (if you typed a phone, it leaves phone alone), and each one it adds is listed with **Undo**. You can type them too, under **Phone, website and more** when you edit someone, one per line like `Mobile: 555 010 0100`. Team members get these too.\n\n**What I remember about a person:** the same pass keeps a short note on what you work on with each contact and team member, a few topics they're good to ask about, and when you last emailed, heard from and met them, plus your next meeting. The note comes only from emails you wrote them and meetings you set up. It shows as **What I remember** on their page, and the Executive uses it in chat to suggest who to ask. Only you see it, and removing the contact deletes it.\n\n**Someone new wrote in:** when someone who isn't on People messages the Executive, their messages are held and a card **Who is *name*?** appears on Home. Click **Add them** and choose **Add as a new person** (enter their name and pick team or contact) or **Someone already on the list**. Their waiting messages are answered once they're added. **Ignore** is in the card's **⋯** menu. Only the principal sees these cards.\n\n**Example from chat:** *\"Add Sarah Chen as our fractional CFO — [email protected] — she approves spend under $10k and usually replies within 48 hours.\"* Or: *\"Add Jordan Lee from Acme as a contact — [email protected] — and send them the proposal.\"* Or open **Add person**, press **Ctrl/Cmd + .**, and describe the person. The help panel (the sparkle button at the top right) fills in the panel for you to check and save.\n\n**Forward it to the Executive:** forward an email from a client to the Executive's address and it replies to you, not them, with a summary, a draft reply you can send, any dates or commitments, and an offer to add the sender as a contact. Mail a contact sends the Executive directly is summarised for you, never answered on its own. Either way it stays between you and the Executive: it tells no one else, and any alert it raises is yours alone.\n\n**Just for yourself?** When you use Open Executive just for yourself, setup adds only you, marked as the principal, with authority over everything. **People** sits in the sidebar under **You** and opens on **Contacts**. Anyone you add from chat is a contact unless you say otherwise, and the **Team** tab shows just you. Other team members are hidden in this mode; the page says how many. If you add a team member (or move a contact onto the team), there's a team now, so Open Executive switches to team mode on its own and says so. To go back, use the **Change in Workspace settings** link (**Settings → Workspace**). Home doesn't show a People tile in this mode.\n\n*Note: authority scopes are how the Executive figures out who on the team to ask for any given approval.*",
"mermaid": null,
- "generated_at": "2026-10-20T11:06:01Z"
+ "generated_at": "2026-10-21T00:00:00Z"
}
diff --git a/packages/core/openexecutive/guide/prebuilt/today.json b/packages/core/openexecutive/guide/prebuilt/today.json
index cf31d555..161cd48d 100644
--- a/packages/core/openexecutive/guide/prebuilt/today.json
+++ b/packages/core/openexecutive/guide/prebuilt/today.json
@@ -1,7 +1,7 @@
{
"section_id": "today",
"title": "Today / Morning Brief",
- "markdown": "**What it is:** A single screen of *what needs you right now* — the proactive digest the Executive prepares so you're not the one chasing status. In the app it's **Home**, the screen the app opens on.\n\n**What it does:**\n\n- Opens with a greeting, one line summing up the day (click a part of it — *2 awaiting reply*, *1 department at risk* — to open that list), and an **Ask your Executive anything…** box that starts a chat. On a quiet day the line names one **Move today:** instead.\n- Puts what's waiting on your call up front under **Needs you**: the first card large, the next two below it, and **Show N more** for the rest.\n- Gathers everything else under **Everything else** as a row of count tiles — **Departments**, **People**, **Across the team** (waiting on someone else), **Under way**, **Handled**, **Monitoring**, and **Across your clients** when you look after client companies — shown only when they have something in them. Click a tile to open its full list in a side panel.\n- The **Departments** tile shows each department's goal health — on-track, at-risk, or off-track — with the at-risk goals called out.\n- The **People** tile lists people with open items, their reply counts, SLA status, and whether they're on leave.\n- In your first week, a **Your first week** card at the top asks for one goal with a date (**Set a goal** opens the add form on **Goals**) until you have one, lists up to two things the Executive found when it researched your company and industry during setup, and links to the **Watch list** with what it keeps watching for you. It goes away after seven days, or sooner once you have a goal and there's nothing to show.\n- **Right now**, above **Needs you**, is the Executive's read of the day, rewritten as things change: when it was updated, one line on what matters most, and the top points, each with the time it came in. Points that came in since you last looked get a green dot, with *N new since …* beside the title. **See the whole picture** opens all of it in a side panel: what's new, what's still open, the **Move today** line, what's next on your calendar and, under **Earlier today**, the morning brief you were sent. Tap a point there to talk it through.\n- If your latest morning brief, end-of-day digest or weekly review couldn't be sent to you, a line at the top says why and what to connect. It goes away once that's fixed.\n- When your morning brief or end-of-day digest left out lines that named people or figures the Executive couldn't match to your data, **Left out of your brief** under **Needs you** lists them for a day. **Hide** clears it.\n- With **Delegate → Act as me → What it writes as you** at **Draft replies automatically**, the replies the Executive wrote as you for mail that needs you come first in **Needs you**, marked **Reply waiting** (or **Follow-up waiting** when nobody answered an email you sent). Only you see them.\n- With **Read my calendar** on, a meeting invite from someone you know appears as a card in **Needs you**, marked **Invite**: the meeting, when it is, who invited you and anything on your calendar it clashes with (only the times). **Accept** or **Decline** answers it in your own calendar, and your calendar lets them know; **Dismiss** removes the card without answering. While replies are still being learned, ticking **Accept from <name> on its own next time** before **Accept** lets it accept their invites on its own when nothing clashes. If your calendar sign-in can't answer invites yet, the card says to connect again under **Read my calendar** instead. Only you see them.\n- Actions the Executive suggested from your email (a meeting, a message to someone, a new contact, a rename or move of files in your Drive) appear as cards in **Needs you**, each spelled out with a box to untick. **Approve** does the ticked ones (**Approve N** when you untick some), ticking **Do this on its own next time** first (shown while it is still learning) also lets it do that kind of action on its own from now on, and **Dismiss** drops the card. Only you see them.\n- A send or edit a team member asked for in chat that their department held waits as a card marked **Waiting on you**, with the reason and the exact details. **Approve** carries it out as shown; **Decline** drops it.\n- An item a team member asked the Executive to raise starts with **Raised by** and their name. It goes to a person or a department, never to the whole company. Team members can dismiss only items assigned to them; the owner can dismiss any item.\n- Under **Take the lead**, something the Executive wanted to do on its own that you haven't allowed yet comes as a card: **Approve** does it once (tick **Do this on its own next time** first and it does the same thing with the same person on its own from now on), **Edit** changes it first (tick **Do it like this next time** to keep your edit as an example and allow it), and **Decline** drops it.\n- Surfaces proposals and alerts you can click to open a chat thread with full context.\n\n**How to use:**\n\n1. Click **Home** in the sidebar (or the Open Executive logo). On a phone, **Home** is the first button in the bar at the bottom.\n2. Work **Needs you** from the top. Each card has one main button and **Discuss**; everything else is in the card's **⋯** menu:\n - **Approve** — accept the recommendation; the Executive carries it out right away. A line at the top of **Needs you** shows it working and then done, with a link to the chat where it did the work. If it didn't work, **Try again** is on that line. Usually the main button.\n - **Discuss** — open a chat with the context already filled in.\n - **Edit & approve** (in **⋯**) — reword the action first, then **Send approval**; your text is used exactly as written.\n - **Dismiss** (in **⋯**) — drop it and stay on Home. When the Executive thinks a card is stale, **Dismiss** is the main button instead.\n - **Snooze until …** (in **⋯**) — three hours from now (while that is still today), **tomorrow 9:00**, or **Monday 9:00** (not offered on a Sunday). The card leaves Home and comes back on its own then; *Snoozed until …* with **Undo** under **Needs you** brings it back now.\n - **Nudge *name*** — the main button when the best move is chasing someone for a reply; **Run *workflow*** when the best move is a workflow.\n - **Open *name*'s page** (in **⋯**) — the person the item is waiting on.\n - A **Monitoring** signal leads with **Discuss**; its **⋯** has **Dismiss signal**.\n3. Some cards are simpler: when a scheduled run didn't finish (a department check-in, or a workflow you set to run on a schedule), its card's main button is **Run again**, which runs it now and sends the result where it normally goes (**Open the run** in **⋯** shows what went wrong); a document card's main button is **Open document** (**Mark reviewed** is in its **⋯**, and **Open in app** when the document lives in another app), and a calendar-booking card books (or declines) the meeting directly when you click Approve or Dismiss. Only the person a booking was sent to for approval, or the owner, can approve or decline it.\n4. Keep it tidy from the **⋯** next to **Needs you**: **Dismiss N older than 7 days** clears stale items, and **Re-check relevance** asks the Executive to review every open item now.\n5. Open the **Departments** tile and click a department to ask for its status in chat.\n6. Work the replies waiting to be sent (they come first in **Needs you**). Each card starts closed: who wrote (and *Address not verified* when the address couldn't be confirmed), a line or two on what they asked and what your draft says, how many things are left to decide and who it goes to, with **Send** when nothing is left (or **Review** when something is) and **Dismiss**. Click the card or **Review** to open it. Open, it shows **Decide before sending** first, then **Your draft** with who it goes to, **What they wrote** (click to open), and **More** (click to open) with **Reply to**, the questions you already answered and *Why it waited for you* when Handle it for me left it for you. **Decide before sending** is (what the draft leaves for you to answer, with short answers to tap. Tap one, or **Something else…** to type your own, and the draft is rewritten with it; the new words are lightly marked. For a time it can offer free slots from your calendar, when Read my calendar is on, and for a document one from your documents to say you'll send. **Send** waits until each of these is answered, or until you change the words with **Edit**) and any warnings. The buttons:\n - **Send** asks once, naming who the reply goes to, then **Send now** sends it from your own mailbox (Gmail or Outlook). If the recipients changed or they wrote again since, it asks again, says what changed, and offers **Send anyway**.\n - **Reply to <name> on its own next time** (a tick shown while replies are still being learned): tick it before **Send** and replies to that person go on their own from now on while Handle it for me is on.\n - **Edit** changes the words right on the card; **Save** keeps them (and updates the draft in your mailbox when it is kept there too). When it is learning how you write, **Do it like this next time (if you changed it)** appears as you send.\n - **Open in Gmail** (or Outlook) opens the draft there, when it is kept in your Drafts.\n - **Dismiss** drops the card, and deletes the draft from your Drafts unless you changed it there.\n On a server, Send needs signed sign-ins; until they're set up, send from your mailbox. A card goes away on its own once you send or delete the draft in your mailbox, or reply yourself, and after 7 days.\n\n**Example:** in a Discuss thread, just say *\"go ahead\"* to approve the proposal or *\"drop it\"* to dismiss it — no need to go back to the card. (Calendar bookings still need the Approve button. When you asked for the meeting in a chat, its card is under that reply too.)\n\n**Just for yourself?** If you use Open Executive just for yourself (**Settings → Workspace → Personal**), Home leaves out the team parts: there are no Departments, People or Across the team tiles — everything that needs a decision is in **Needs you**. When a goal is slipping, the summary line at the top says how many goals are at risk; click it to open **Goals**. Instead, the tiles are **Due soon**, **Your projects** and **This week's review**, each opening its list in a side panel. **Your projects** lists the projects the Executive is tracking for you. Click **Done** when one is finished, or **Drop** to stop tracking it (it asks first, and removes the project from Pulse). **Due soon** lists what you've promised by a date and what others have asked of you, due in the next week — say *\"I'll send Northwind the proposal by Friday\"* in the web chat or your own Slack or Discord and it shows up here, and the Executive reminds you when it's due. Click **Done** once it's handled; **All open items** opens the full list. **Top three today**, right under **Needs you**, shows the three things to focus on today — the same three your morning brief opens with — each with a free slot in today's working hours when the Executive can read your calendar. **This week's review** shows your latest weekly review: when it ran and next week's top three. Click **Read the review** to see all of it.\n\nYour morning brief also opens with a **top three for today**, picked from what's overdue or due, goals that are slipping and the projects you're driving. When Google Workspace is connected and the Executive can read your calendar (it is your own account, or you shared your calendar with it), each of the three gets a free slot in today's working hours and the brief lists today's meetings; otherwise the three come without times. Every Friday afternoon (in your time zone) a **weekly review** arrives the same way: your goals graded by area, what's due or overdue, projects that went quiet, the week's decisions, a few older decisions to look back on, and next week's top three. Both also show up on Home (see above), so you see them even when no chat app or email is connected. When it asks how an older decision turned out, just tell the Executive in the web chat or your own Slack or Discord and it records the outcome against that decision.\n\n*Note: proposals are routed to the right person automatically based on who has authority over them.*",
+ "markdown": "**What it is:** A single screen of *what needs you right now* — the proactive digest the Executive prepares so you're not the one chasing status. In the app it's **Home**, the screen the app opens on.\n\n**What it does:**\n\n- Opens with a greeting, one line summing up the day (click a part of it — *2 awaiting reply*, *1 department at risk* — to open that list), and an **Ask your Executive anything…** box that starts a chat. On a quiet day the line names one **Move today:** instead.\n- Puts what's waiting on your call up front under **Needs you**: the first card large, the next two below it, and **Show N more** for the rest.\n- Gathers everything else under **Everything else** as a row of count tiles — **Departments**, **People**, **Across the team** (waiting on someone else), **Under way**, **Handled**, **Monitoring**, and **Across your clients** when you look after client companies — shown only when they have something in them. Click a tile to open its full list in a side panel.\n- The **Departments** tile shows each department's goal health — on-track, at-risk, or off-track — with the at-risk goals called out and who each is on. Goals with no department appear there too, as **Other goals**; click it to open **Goals**.\n- The **People** tile lists people with open items, their reply counts, SLA status, and whether they're on leave.\n- In your first week, a **Your first week** card at the top asks for one goal with a date (**Set a goal** opens the add form on **Goals**) until you have one, lists up to two things the Executive found when it researched your company and industry during setup, and links to the **Watch list** with what it keeps watching for you. It goes away after seven days, or sooner once you have a goal and there's nothing to show.\n- **Right now**, above **Needs you**, is the Executive's read of the day, rewritten as things change: when it was updated, one line on what matters most, and the top points, each with the time it came in. Points that came in since you last looked get a green dot, with *N new since …* beside the title. **See the whole picture** opens all of it in a side panel: what's new, what's still open, the **Move today** line, what's next on your calendar and, under **Earlier today**, the morning brief you were sent. Tap a point there to talk it through.\n- If your latest morning brief, end-of-day digest or weekly review couldn't be sent to you, a line at the top says why and what to connect. It goes away once that's fixed.\n- When your morning brief or end-of-day digest left out lines that named people or figures the Executive couldn't match to your data, **Left out of your brief** under **Needs you** lists them for a day. **Hide** clears it.\n- With **Delegate → Act as me → What it writes as you** at **Draft replies automatically**, the replies the Executive wrote as you for mail that needs you come first in **Needs you**, marked **Reply waiting** (or **Follow-up waiting** when nobody answered an email you sent). Only you see them.\n- With **Read my calendar** on, a meeting invite from someone you know appears as a card in **Needs you**, marked **Invite**: the meeting, when it is, who invited you and anything on your calendar it clashes with (only the times). **Accept** or **Decline** answers it in your own calendar, and your calendar lets them know; **Dismiss** removes the card without answering. While replies are still being learned, ticking **Accept from <name> on its own next time** before **Accept** lets it accept their invites on its own when nothing clashes. If your calendar sign-in can't answer invites yet, the card says to connect again under **Read my calendar** instead. Only you see them.\n- Actions the Executive suggested from your email (a meeting, a message to someone, a new contact, a rename or move of files in your Drive) appear as cards in **Needs you**, each spelled out with a box to untick. **Approve** does the ticked ones (**Approve N** when you untick some), ticking **Do this on its own next time** first (shown while it is still learning) also lets it do that kind of action on its own from now on, and **Dismiss** drops the card. Only you see them.\n- A send or edit a team member asked for in chat that their department held waits as a card marked **Waiting on you**, with the reason and the exact details. **Approve** carries it out as shown; **Decline** drops it.\n- An item a team member asked the Executive to raise starts with **Raised by** and their name. It goes to a person or a department, never to the whole company. Team members can dismiss only items assigned to them; the owner can dismiss any item.\n- Under **Take the lead**, something the Executive wanted to do on its own that you haven't allowed yet comes as a card: **Approve** does it once (tick **Do this on its own next time** first and it does the same thing with the same person on its own from now on), **Edit** changes it first (tick **Do it like this next time** to keep your edit as an example and allow it), and **Decline** drops it.\n- Surfaces proposals and alerts you can click to open a chat thread with full context.\n\n**How to use:**\n\n1. Click **Home** in the sidebar (or the Open Executive logo). On a phone, **Home** is the first button in the bar at the bottom.\n2. Work **Needs you** from the top. Each card has one main button and **Discuss**; everything else is in the card's **⋯** menu:\n - **Approve** — accept the recommendation; the Executive carries it out right away. A line at the top of **Needs you** shows it working and then done, with a link to the chat where it did the work. If it didn't work, **Try again** is on that line. Usually the main button.\n - **Discuss** — open a chat with the context already filled in.\n - **Edit & approve** (in **⋯**) — reword the action first, then **Send approval**; your text is used exactly as written.\n - **Dismiss** (in **⋯**) — drop it and stay on Home. When the Executive thinks a card is stale, **Dismiss** is the main button instead.\n - **Snooze until …** (in **⋯**) — three hours from now (while that is still today), **tomorrow 9:00**, or **Monday 9:00** (not offered on a Sunday). The card leaves Home and comes back on its own then; *Snoozed until …* with **Undo** under **Needs you** brings it back now.\n - **Nudge *name*** — the main button when the best move is chasing someone for a reply; **Run *workflow*** when the best move is a workflow.\n - **Open *name*'s page** (in **⋯**) — the person the item is waiting on.\n - A **Monitoring** signal leads with **Discuss**; its **⋯** has **Dismiss signal**.\n3. Some cards are simpler: when a scheduled run didn't finish (a department check-in, or a workflow you set to run on a schedule), its card's main button is **Run again**, which runs it now and sends the result where it normally goes (**Open the run** in **⋯** shows what went wrong); a document card's main button is **Open document** (**Mark reviewed** is in its **⋯**, and **Open in app** when the document lives in another app), and a calendar-booking card books (or declines) the meeting directly when you click Approve or Dismiss. Only the person a booking was sent to for approval, or the owner, can approve or decline it.\n4. Keep it tidy from the **⋯** next to **Needs you**: **Dismiss N older than 7 days** clears stale items, and **Re-check relevance** asks the Executive to review every open item now.\n5. Open the **Departments** tile and click a department to ask for its status in chat.\n6. Work the replies waiting to be sent (they come first in **Needs you**). Each card starts closed: who wrote (and *Address not verified* when the address couldn't be confirmed), a line or two on what they asked and what your draft says, how many things are left to decide and who it goes to, with **Send** when nothing is left (or **Review** when something is) and **Dismiss**. Click the card or **Review** to open it. Open, it shows **Decide before sending** first, then **Your draft** with who it goes to, **What they wrote** (click to open), and **More** (click to open) with **Reply to**, the questions you already answered and *Why it waited for you* when Handle it for me left it for you. **Decide before sending** is (what the draft leaves for you to answer, with short answers to tap. Tap one, or **Something else…** to type your own, and the draft is rewritten with it; the new words are lightly marked. For a time it can offer free slots from your calendar, when Read my calendar is on, and for a document one from your documents to say you'll send. **Send** waits until each of these is answered, or until you change the words with **Edit**) and any warnings. The buttons:\n - **Send** asks once, naming who the reply goes to, then **Send now** sends it from your own mailbox (Gmail or Outlook). If the recipients changed or they wrote again since, it asks again, says what changed, and offers **Send anyway**.\n - **Reply to <name> on its own next time** (a tick shown while replies are still being learned): tick it before **Send** and replies to that person go on their own from now on while Handle it for me is on.\n - **Edit** changes the words right on the card; **Save** keeps them (and updates the draft in your mailbox when it is kept there too). When it is learning how you write, **Do it like this next time (if you changed it)** appears as you send.\n - **Open in Gmail** (or Outlook) opens the draft there, when it is kept in your Drafts.\n - **Dismiss** drops the card, and deletes the draft from your Drafts unless you changed it there.\n On a server, Send needs signed sign-ins; until they're set up, send from your mailbox. A card goes away on its own once you send or delete the draft in your mailbox, or reply yourself, and after 7 days.\n\n**Example:** in a Discuss thread, just say *\"go ahead\"* to approve the proposal or *\"drop it\"* to dismiss it — no need to go back to the card. (Calendar bookings still need the Approve button. When you asked for the meeting in a chat, its card is under that reply too.)\n\n**Just for yourself?** If you use Open Executive just for yourself (**Settings → Workspace → Personal**), Home leaves out the team parts: there are no Departments, People or Across the team tiles — everything that needs a decision is in **Needs you**. When a goal is slipping, the summary line at the top says how many goals are at risk; click it to open **Goals**. Instead, the tiles are **Due soon**, **Your projects** and **This week's review**, each opening its list in a side panel. **Your projects** lists the projects the Executive is tracking for you. Click **Done** when one is finished, or **Drop** to stop tracking it (it asks first, and removes the project from Pulse). **Due soon** lists what you've promised by a date and what others have asked of you, due in the next week — say *\"I'll send Northwind the proposal by Friday\"* in the web chat or your own Slack or Discord and it shows up here, and the Executive reminds you when it's due. Click **Done** once it's handled; **All open items** opens the full list. **Top three today**, right under **Needs you**, shows the three things to focus on today — the same three your morning brief opens with — each with a free slot in today's working hours when the Executive can read your calendar. **This week's review** shows your latest weekly review: when it ran and next week's top three. Click **Read the review** to see all of it.\n\nYour morning brief also opens with a **top three for today**, picked from what's overdue or due, goals that are slipping and the projects you're driving. When Google Workspace is connected and the Executive can read your calendar (it is your own account, or you shared your calendar with it), each of the three gets a free slot in today's working hours and the brief lists today's meetings; otherwise the three come without times. Every Friday afternoon (in your time zone) a **weekly review** arrives the same way: your goals graded by area, what's due or overdue, projects that went quiet, the week's decisions, a few older decisions to look back on, and next week's top three. Both also show up on Home (see above), so you see them even when no chat app or email is connected. When it asks how an older decision turned out, just tell the Executive in the web chat or your own Slack or Discord and it records the outcome against that decision.\n\n*Note: proposals are routed to the right person automatically based on who has authority over them.*",
"mermaid": null,
- "generated_at": "2026-10-19T19:00:00Z"
+ "generated_at": "2026-10-21T00:00:00Z"
}
diff --git a/packages/core/openexecutive/orchestrator/action_chips.py b/packages/core/openexecutive/orchestrator/action_chips.py
index ecc8ebe9..fb7cd5fe 100644
--- a/packages/core/openexecutive/orchestrator/action_chips.py
+++ b/packages/core/openexecutive/orchestrator/action_chips.py
@@ -402,7 +402,9 @@ def summarize_action(
if slug:
payload["link"] = f"/departments/{slug}"
elif tool_name == "update_department_goal":
- slug = tool_input.get("department_slug", "")
+ # The handler's result names the goal's real department (none for a
+ # goal that stands on its own), whatever the model passed.
+ slug = str((parsed or {}).get("department_slug") or tool_input.get("department_slug") or "")
# The handler always returns `from_status`/`to_status` (when status
# wasn't supplied, `to_status == from_status`). To tell a real
# status transition from a current-only edit, compare the two
@@ -426,11 +428,14 @@ def summarize_action(
# fallback; the handler rejects this combo so this branch
# should never fire in practice.
payload["summary"] = f"Touched {slug} goal"
+ elif status_changed:
+ payload["summary"] = f"Updated a goal → {str(to_status).replace('_', ' ')}"
+ elif current_updated:
+ payload["summary"] = "Updated goal progress"
else:
- payload["summary"] = "Updated a department goal"
+ payload["summary"] = "Updated a goal"
payload["target"] = slug or None
- if slug:
- payload["link"] = f"/departments/{slug}"
+ payload["link"] = f"/departments/{slug}" if slug else "/goals"
elif tool_name == "create_goal":
# The handler's result names the area the goal landed in — which may
# be one it just created — so prefer it over the model's input.
@@ -446,10 +451,11 @@ def summarize_action(
else:
payload["summary"] = "Added a goal"
payload["target"] = slug or None
- if workspace_mode == "solo":
- # Solo's nav has Goals (every goal grouped by area), not Departments.
+ if workspace_mode == "solo" or not slug:
+ # Solo's nav has Goals, not Departments; and a goal with no
+ # department lives only on the Goals page.
payload["link"] = "/goals"
- elif slug:
+ else:
payload["link"] = f"/departments/{slug}"
elif tool_name == "record_decision_outcome":
# The handler's result names the decision it wrote to.
diff --git a/packages/core/openexecutive/orchestrator/department_tools.py b/packages/core/openexecutive/orchestrator/department_tools.py
index 07ca04c3..d4ee49c5 100644
--- a/packages/core/openexecutive/orchestrator/department_tools.py
+++ b/packages/core/openexecutive/orchestrator/department_tools.py
@@ -8,8 +8,10 @@ setback ("we lost the Acme deal"). They close the loop that Phase A's
the same `last_reviewed_at` column the cadence-driven review writes to.
`create_goal` starts tracking a NEW goal the principal states ("20
-paying clients by the end of Q4"), filed under an area / department named
-by slug or title — creating that area when none matches. Only the
+paying clients by the end of Q4"), with an owner from the team and,
+optionally, an area / department named by slug or title — creating that
+area when none matches. A goal with no area stands on its own: it renders
+under its owner and the weekly ``goal_review`` grades it. Only the
principal, on a surface that verified it is them, may call it (the roster
tools' rule): a goal renders in every turn's org block as one of the
principal's own, so a goal from an inbound email, a teammate or an
@@ -67,11 +69,13 @@ _goals_created_by_turn: dict[tuple[str | None, str], int] = {}
LIST_DEPARTMENT_GOALS_TOOL: dict[str, Any] = {
"name": "list_department_goals",
"description": (
- "List a department's Goals with their ids, key_results, current "
- "progress, statuses, and last-reviewed timestamps. Use this to "
- "resolve a verbal goal reference ('the migration goal', "
- "'our Q2 ARR target') to a goal_id before calling "
- "update_department_goal. Returns a compact JSON list."
+ "List Goals with their ids, owners, departments, key_results, "
+ "current progress, statuses, and last-reviewed timestamps. Pass "
+ "department_slug for one department's goals; omit it for every "
+ "goal, including those with no department. Use this to resolve a "
+ "verbal goal reference ('the migration goal', 'our Q2 ARR target') "
+ "to a goal_id before calling update_department_goal. Returns a "
+ "compact JSON list."
),
"input_schema": {
"type": "object",
@@ -79,12 +83,13 @@ LIST_DEPARTMENT_GOALS_TOOL: dict[str, Any] = {
"department_slug": {
"type": "string",
"description": (
- "Lowercase slug from the department registry "
- "(e.g. 'engineering', 'finance', 'marketing')."
+ "Optional. Lowercase slug from the department registry "
+ "(e.g. 'engineering', 'finance', 'marketing'). Omit to "
+ "list every goal."
),
},
},
- "required": ["department_slug"],
+ "required": [],
},
}
@@ -92,7 +97,7 @@ LIST_DEPARTMENT_GOALS_TOOL: dict[str, Any] = {
UPDATE_DEPARTMENT_GOAL_TOOL: dict[str, Any] = {
"name": "update_department_goal",
"description": (
- "Update a department Goal's status, current-progress text, or "
+ "Update a Goal's status, current-progress text, or "
"both — based on something the user just told you. Call this "
"when the user reports concrete progress on (or a setback to) a "
"tracked Goal: 'we shipped the billing migration' (likely a "
@@ -116,7 +121,11 @@ UPDATE_DEPARTMENT_GOAL_TOOL: dict[str, Any] = {
"properties": {
"department_slug": {
"type": "string",
- "description": "Lowercase department slug owning the goal.",
+ "description": (
+ "Optional. Lowercase slug of the department the goal is "
+ "in; omit for a goal with no department. When given it "
+ "must match the goal's department."
+ ),
},
"goal_id": {
"type": "integer",
@@ -151,7 +160,7 @@ UPDATE_DEPARTMENT_GOAL_TOOL: dict[str, Any] = {
),
},
},
- "required": ["department_slug", "goal_id", "rationale"],
+ "required": ["goal_id", "rationale"],
},
}
@@ -163,9 +172,12 @@ CREATE_GOAL_TOOL: dict[str, Any] = {
"target in their own words: 'get to 20 paying clients by the end of "
"Q4', 'ship the mobile app this quarter'. Only the principal can set "
"goals, and only from a conversation that confirms it is them; for "
- "anyone else it is refused. Files it under an area (a department) "
- "named by slug or title; an area that does not exist yet is created. "
- "If the goal may "
+ "anyone else it is refused. The goal is the principal's unless they "
+ "name someone on the team to own it (resolve the name with "
+ "list_people). Leave area out unless the principal names one or the "
+ "goal clearly belongs to an existing department: a goal needs no "
+ "department. When given, area is a department named by slug or "
+ "title, and one that does not exist yet is created. If the goal may "
"already be tracked, check with list_department_goals first and "
"use update_department_goal to change an existing goal's status or "
"progress instead. Creates ONE goal per call, each backed by a "
@@ -182,9 +194,19 @@ CREATE_GOAL_TOOL: dict[str, Any] = {
"area": {
"type": "string",
"description": (
- "The area or department the goal belongs to: its slug "
- "('finance') or its title ('Marketing', 'Client work'). "
- "When none matches, a new area with this title is created."
+ "Optional. The area or department the goal belongs to: "
+ "its slug ('finance') or its title ('Marketing', 'Client "
+ "work'). When none matches, a new area with this title is "
+ "created. Omit for a goal with no department."
+ ),
+ },
+ "owner_person_id": {
+ "type": "integer",
+ "description": (
+ "Optional. The person_id (from list_people) of the team "
+ "member who owns the goal, when the principal named "
+ "someone. Omit and it follows its department's lead, "
+ "else the principal."
),
},
"key_result": {
@@ -234,7 +256,7 @@ CREATE_GOAL_TOOL: dict[str, Any] = {
),
},
},
- "required": ["area", "key_result", "target", "rationale"],
+ "required": ["key_result", "target", "rationale"],
},
}
@@ -284,19 +306,14 @@ def _audit(
async def handle_list_department_goals(tool_input: dict[str, Any]) -> str:
- from openexecutive.departments import store as dept_store
-
- slug = str(tool_input.get("department_slug", "")).strip()
- if not slug:
- _audit(
- "list_department_goals", "read", False,
- "list_department_goals bad input: empty department_slug",
- {"error": "department_slug required"},
- )
- return json.dumps({"error": "department_slug is required"})
+ from openexecutive.departments.goals import list_goal_views
+ # Blank or omitted lists every goal, with or without a department.
+ slug = str(tool_input.get("department_slug") or "").strip() or None
try:
- goals = dept_store.list_goals(slug)
+ views = [
+ v for v in list_goal_views() if slug is None or v.goal.department_slug == slug
+ ]
except Exception as exc:
logger.exception("list_department_goals: failed slug=%s", slug)
_audit(
@@ -309,19 +326,22 @@ async def handle_list_department_goals(tool_input: dict[str, Any]) -> str:
out = [
{
- "id": g.id,
- "key_result": g.key_result,
- "target": g.target,
- "current": g.current,
- "status": g.status,
- "period": f"{g.period_type} {g.period_value}".strip(),
- "last_reviewed_at": g.last_reviewed_at,
+ "id": v.goal.id,
+ "key_result": v.goal.key_result,
+ "target": v.goal.target,
+ "current": v.goal.current,
+ "status": v.goal.status,
+ "period": f"{v.goal.period_type} {v.goal.period_value}".strip(),
+ "owner_person_id": v.owner_id,
+ "owner": v.owner_name or None,
+ "department_slug": v.goal.department_slug,
+ "last_reviewed_at": v.goal.last_reviewed_at,
}
- for g in goals
+ for v in views
]
_audit(
"list_department_goals", "read", True,
- f"list_department_goals {slug}: {len(out)} goal(s)",
+ f"list_department_goals {slug or 'all'}: {len(out)} goal(s)",
{"department_slug": slug, "count": len(out)},
department=slug,
)
@@ -344,9 +364,8 @@ async def handle_update_department_goal(tool_input: dict[str, Any]) -> str:
return json.dumps({"error": err})
# ---- Input validation ----
- slug = str(tool_input.get("department_slug", "")).strip()
- if not slug:
- return _bad("department_slug is required")
+ # Optional: a goal with no department is named by its id alone.
+ slug = str(tool_input.get("department_slug") or "").strip() or None
raw_goal_id = tool_input.get("goal_id")
try:
@@ -392,12 +411,17 @@ async def handle_update_department_goal(tool_input: dict[str, Any]) -> str:
if existing is None:
return _bad(f"goal {goal_id} not found",
department_slug=slug, goal_id=goal_id)
- if existing.department_slug != slug:
+ if slug is not None and existing.department_slug != slug:
+ where = (
+ f"department {existing.department_slug!r}"
+ if existing.department_slug else "no department"
+ )
return _bad(
- f"goal {goal_id} belongs to department "
- f"{existing.department_slug!r}, not {slug!r}",
+ f"goal {goal_id} belongs to {where}, not {slug!r}",
department_slug=slug, goal_id=goal_id,
)
+ # Audit and report the goal's real department, given or not.
+ slug = existing.department_slug
# ---- Persist ----
prior_status = existing.status
@@ -441,7 +465,7 @@ async def handle_update_department_goal(tool_input: dict[str, Any]) -> str:
new_status = status_in if status_in is not None else prior_status
summary = (
- f"update_department_goal {slug}/{goal_id}: "
+ f"update_department_goal {slug or 'goal'}/{goal_id}: "
f"{prior_status}->{new_status}"
+ ("" if current_str is None else " (current updated)")
)
@@ -601,9 +625,8 @@ async def handle_create_goal(tool_input: dict[str, Any]) -> str:
)
# ---- Input validation ----
+ # Optional: blank means the goal has no department.
area = _optional_text(tool_input, "area")
- if not area:
- return _bad("area is required (an area / department slug or title)")
if len(area) > _AREA_MAX:
return _bad(f"area must be at most {_AREA_MAX} characters")
@@ -646,6 +669,25 @@ async def handle_create_goal(tool_input: dict[str, Any]) -> str:
if len(period_value) > _PERIOD_VALUE_MAX:
return _bad(f"period_value must be at most {_PERIOD_VALUE_MAX} characters", area=area)
+ owner_id: int | None = None
+ raw_owner = tool_input.get("owner_person_id")
+ if raw_owner is not None:
+ if isinstance(raw_owner, bool):
+ return _bad("owner_person_id must be an integer", area=area)
+ try:
+ owner_id = int(raw_owner)
+ except (TypeError, ValueError):
+ return _bad("owner_person_id must be an integer", area=area)
+ from openexecutive.people import store as people_store
+
+ owner = people_store.get_person(owner_id)
+ if owner is None or owner.archived or owner.kind != "team":
+ return _bad(
+ f"owner_person_id {owner_id} is not on the team — resolve the "
+ "name with list_people, or leave the owner out",
+ area=area,
+ )
+
turn = _turn_key()
if _turn_cap_reached(turn):
return _bad(
@@ -659,43 +701,53 @@ async def handle_create_goal(tool_input: dict[str, Any]) -> str:
try:
dept_store.initialize_db()
existing = dept_store.list_departments()
- match = dept_store.match_department(area, [d.config for d in existing])
+ match = (
+ dept_store.match_department(area, [d.config for d in existing]) if area else None
+ )
created = False
specialist_key: str | None = None
- if match is not None:
- slug, title = match.slug, match.title
- state = next(d for d in existing if d.config.slug == slug)
+ slug: str | None = None
+ title: str | None = None
+ if area and match is None:
+ title = _area_title(area)
+ candidate = dept_store.specialist_key_for_area(title)
+ # One department per specialist: a second would make the
+ # specialist -> department mapping ambiguous.
+ if candidate and not any(d.config.specialist_key == candidate for d in existing):
+ specialist_key = candidate
+ new_state = dept_store.create_department(title, specialist_key=specialist_key)
+ slug, title = new_state.config.slug, new_state.config.title
+ created = True
+ else:
+ if match is not None:
+ slug, title = match.slug, match.title
+ siblings = next(d for d in existing if d.config.slug == slug).goals
+ group = f"the {title!r} area"
+ else:
+ siblings = dept_store.list_goals(None)
+ group = "the goals with no department"
wanted = _norm_goal_text(key_result)
dupe = next(
- (g for g in state.goals if _norm_goal_text(g.key_result) == wanted), None
+ (g for g in siblings if _norm_goal_text(g.key_result) == wanted), None
)
if dupe is not None:
return _bad(
- f"goal {dupe.id} in {slug!r} already tracks {dupe.key_result!r} — "
+ f"goal {dupe.id} already tracks {dupe.key_result!r} — "
"call update_department_goal with that goal_id to change it",
department_slug=slug, goal_id=dupe.id,
)
- if len(state.goals) >= _MAX_GOALS_PER_AREA:
+ if len(siblings) >= _MAX_GOALS_PER_AREA:
return _bad(
- f"refused: {title!r} already tracks {len(state.goals)} goals "
- f"(the most this tool adds to one area is {_MAX_GOALS_PER_AREA}). "
+ f"refused: {len(siblings)} goals are already tracked in {group} "
+ f"(the most this tool adds to one group is {_MAX_GOALS_PER_AREA}). "
"Ask the principal which existing goal this replaces, or to "
"add it on the Goals page.",
department_slug=slug, refused=True,
)
- else:
- title = _area_title(area)
- candidate = dept_store.specialist_key_for_area(title)
- # One department per specialist: a second would make the
- # specialist -> department mapping ambiguous.
- if candidate and not any(d.config.specialist_key == candidate for d in existing):
- specialist_key = candidate
- new_state = dept_store.create_department(title, specialist_key=specialist_key)
- slug, title = new_state.config.slug, new_state.config.title
- created = True
goal_id = dept_store.insert_goal(
slug,
+ owner_person_id=owner_id,
period_type=period_type,
period_value=period_value,
key_result=key_result,
@@ -720,12 +772,13 @@ async def handle_create_goal(tool_input: dict[str, Any]) -> str:
_audit(
"create_goal", "write", True,
- f"create_goal {slug}/{goal_id}"
+ f"create_goal {slug or 'goal'}/{goal_id}"
+ (" (new area)" if created else "")
+ f": {key_result[:80]}",
{
"department_slug": slug,
"goal_id": goal_id,
+ "owner_person_id": owner_id,
"area_created": created,
"specialist_key": specialist_key,
"key_result": key_result[:280],
@@ -742,6 +795,7 @@ async def handle_create_goal(tool_input: dict[str, Any]) -> str:
"area_slug": slug,
"area_title": title,
"area_created": created,
+ "owner_person_id": owner_id,
"period": f"{period_type} {period_value}",
})
diff --git a/packages/core/openexecutive/prompts/executive_persona.py b/packages/core/openexecutive/prompts/executive_persona.py
index d98f1db4..6b61d6db 100644
--- a/packages/core/openexecutive/prompts/executive_persona.py
+++ b/packages/core/openexecutive/prompts/executive_persona.py
@@ -223,7 +223,7 @@ Every outbound action you take is logged with target and reasoning to the audit
## Goals and Areas
-The principal tracks goals grouped by **area** — the parts of their work they are driving, such as strategy, finance, marketing, product, or the function they lead. The goals are provided in a separate context block below. Always call these areas, not departments: they are how the principal groups their own goals, not an org chart — even when the principal leads a department in their organisation. In your tools an area is stored as a department, so a tool's `department_slug` is the area's slug. When the principal asks about progress, draw from that block — do not invent numbers or statuses.
+The principal tracks goals, each optionally grouped under an **area** — the parts of their work they are driving, such as strategy, finance, marketing, product, or the function they lead. A goal needs no area. The goals are provided in a separate context block below. Always call these areas, not departments: they are how the principal groups their own goals, not an org chart — even when the principal leads a department in their organisation. In your tools an area is stored as a department, so a tool's `department_slug` is the area's slug; a goal with no area has none, and you name it by its `goal_id` alone. When the principal asks about progress, draw from that block — do not invent numbers or statuses.
You can update goal status and progress directly via `list_department_goals` and `update_department_goal`. When the principal reports concrete progress on a tracked goal ("I shipped the onboarding flow", "we closed the Acme deal") or a setback ("lost the deal", "the vendor missed the deadline"), call `update_department_goal` — flip the status, update the `current` text, or both. Always provide a one-sentence `rationale` explaining what the principal said; the rationale is audited so future readers can see the provenance of every change. Use `list_department_goals` first if you need to resolve a verbal reference to a `goal_id`. Do NOT call this when the principal is only asking advice on a goal, when progress is pure speculation, or when they have said they want to update it themselves. Update goals **one at a time, each backed by a specific thing that happened.** A blanket instruction with no per-goal detail — "update all my goals", "mark everything off track", "set them all on track", "just refresh all the statuses" — is not enough to move a status: you would be overwriting tracked progress on every goal with a guess. Do not sweep. Ask which goals changed and what concretely happened, then update only the goals you have specific evidence for. The one-sentence `rationale` must name that goal-specific evidence — never a blanket reason reused across goals.
@@ -234,7 +234,7 @@ You can update goal status and progress directly via `list_department_goals` and
# part of `_SOLO_SECTIONS`) so it reads as one rule; it follows the goal
# section. Team mode gets the same guidance from the tool description alone,
# which keeps the pinned team prompt byte-identical.
-_SOLO_CREATE_GOAL = """When the principal states a new goal of their own with a target — "I want 20 paying clients by the end of Q4", "the app ships by November" — call `create_goal` with the area it belongs to (an existing area's slug or title; a new area is created when none fits), the key result, the target they gave, and a one-sentence `rationale` naming what they said. If it may already be tracked, check `list_department_goals` first and update that goal instead. Create one goal per target they actually stated: never invent goals, never turn your own suggestions into goals, and do not act on a blanket "set up some goals for me" — ask which goal and what target.
+_SOLO_CREATE_GOAL = """When the principal states a new goal of their own with a target — "I want 20 paying clients by the end of Q4", "the app ships by November" — call `create_goal` with the key result, the target they gave, and a one-sentence `rationale` naming what they said. Add an `area` only when they name one or the goal plainly belongs to an area they already have (a new area is created when none matches); otherwise leave it out. The goal is theirs unless they name a teammate to own it. If it may already be tracked, check `list_department_goals` first and update that goal instead. Create one goal per target they actually stated: never invent goals, never turn your own suggestions into goals, and do not act on a blanket "set up some goals for me" — ask which goal and what target.
"""
diff --git a/packages/core/openexecutive/scheduler/runner.py b/packages/core/openexecutive/scheduler/runner.py
index 2a40db98..209a204f 100644
--- a/packages/core/openexecutive/scheduler/runner.py
+++ b/packages/core/openexecutive/scheduler/runner.py
@@ -1137,6 +1137,10 @@ async def _execute_action(
await _run_take_the_lead_wake(action, now)
return
+ if action.kind == GOAL_REVIEW_KIND:
+ await _run_goal_review(action, now)
+ return
+
if action.kind == CHAT_REPLAY_KIND:
await _run_chat_replay(action, now, gateway)
return
@@ -1667,6 +1671,10 @@ _DEFAULT_REPLAY_TIME = "03:30"
# other pinned times.
WEEKLY_REVIEW_KIND = "principal_weekly_review"
_DEFAULT_WEEKLY_REVIEW_SPEC = "weekly@fri@16:00"
+# The weekly grading of goals no department check-in covers
+# (departments.goal_review): Monday morning in the user's zone, both modes.
+GOAL_REVIEW_KIND = "goal_review"
+_DEFAULT_GOAL_REVIEW_SPEC = "weekly@mon@09:00"
def _rotation_pause_active() -> bool:
@@ -1750,9 +1758,10 @@ _RECURRING_KIND_ENV: dict[str, tuple[str, str]] = {
# Solo only (see _SOLO_ONLY_KINDS): seeded in solo, cancelled on a switch
# to team, retired without running if one fires in team anyway.
WEEKLY_REVIEW_KIND: ("PRINCIPAL_WEEKLY_REVIEW_TIME", _DEFAULT_WEEKLY_REVIEW_SPEC),
+ GOAL_REVIEW_KIND: ("GOAL_REVIEW_TIME", _DEFAULT_GOAL_REVIEW_SPEC),
}
# Kinds that recur weekly (the rest are daily).
-_WEEKLY_KINDS: frozenset[str] = frozenset({WEEKLY_REVIEW_KIND})
+_WEEKLY_KINDS: frozenset[str] = frozenset({WEEKLY_REVIEW_KIND, GOAL_REVIEW_KIND})
# Kinds that exist only in a solo workspace.
_SOLO_ONLY_KINDS: frozenset[str] = frozenset({WEEKLY_REVIEW_KIND})
# The recurring principal kinds that run a workflow and deliver its artifact
@@ -2790,6 +2799,22 @@ async def _run_executive_reflection(
_enqueue_next_principal_brief("executive_reflection", after=_chain_after(action))
+async def _run_goal_review(action: ScheduledAction, now: datetime) -> None:
+ """Grade the goals no department check-in covers (departments.goal_review),
+ then chain next week's, like the reflection: a failed week never breaks
+ the rhythm. Nothing is delivered; at-risk goals reach the brief."""
+ from openexecutive.departments import goal_review
+
+ assert action.id is not None
+ try:
+ with unscoped_audit_rows():
+ await goal_review.run_review(now)
+ except Exception:
+ logger.exception("scheduler: goal_review failed")
+ mark_action_done(action.id)
+ _enqueue_next_principal_brief(GOAL_REVIEW_KIND, after=_chain_after(action))
+
+
# Take the lead as the Executive: new mail or chat wakes the reflection early
# (orchestrator.take_the_lead.wake), batched; one-off, never chained.
TAKE_THE_LEAD_WAKE_KIND = "take_the_lead_wake"
diff --git a/packages/core/openexecutive/workflows/department_check_in.py b/packages/core/openexecutive/workflows/department_check_in.py
index 0bc74760..e7030618 100644
--- a/packages/core/openexecutive/workflows/department_check_in.py
+++ b/packages/core/openexecutive/workflows/department_check_in.py
@@ -603,7 +603,7 @@ def persist_goal_verdicts(
"goal_status_review",
f"{state.config.title}: reviewed {len(transitions)} goal(s)",
actor=actor,
- department=slug,
+ department=slug or None, # "" = goals with no department (goal_review)
details={"period": period, "transitions": transitions},
)
except Exception: # noqa: BLE001 - audit must not break the workflow.
diff --git a/packages/core/openexecutive/workflows/executive_reflection.py b/packages/core/openexecutive/workflows/executive_reflection.py
index c35d5380..ea3e1621 100644
--- a/packages/core/openexecutive/workflows/executive_reflection.py
+++ b/packages/core/openexecutive/workflows/executive_reflection.py
@@ -380,8 +380,9 @@ def _render_reflection_context(
# levels and nobody else awaiting.
parts.append("AREAS WITH GOALS AT RISK:")
for d in at_risk:
+ where = f"area slug={d['slug']}" if d.get("slug") else "no area"
parts.append(
- f"- {d['title']} (area slug={d['slug']}): "
+ f"- {d['title']} ({where}): "
f"at_risk={d.get('at_risk_count', 0)} "
f"off_track={d.get('off_track_count', 0)}"
)
@@ -389,6 +390,14 @@ def _render_reflection_context(
elif at_risk:
parts.append("DEPARTMENTS WITH RISK:")
for d in at_risk:
+ if not d.get("slug"):
+ # The goals with no department: no head, channel or authority.
+ parts.append(
+ f"- {d['title']} (no department): "
+ f"at_risk={d.get('at_risk_count', 0)} "
+ f"off_track={d.get('off_track_count', 0)}"
+ )
+ continue
parts.append(
f"- {d['title']} (slug={d['slug']}): "
f"at_risk={d.get('at_risk_count', 0)} "
diff --git a/packages/core/tests/unit/test_department_tools.py b/packages/core/tests/unit/test_department_tools.py
index 42e05480..4d808c4d 100644
--- a/packages/core/tests/unit/test_department_tools.py
+++ b/packages/core/tests/unit/test_department_tools.py
@@ -89,9 +89,23 @@ def test_list_department_goals_empty_dept() -> None:
assert result["goals"] == []
-def test_list_department_goals_missing_slug() -> None:
+def test_list_department_goals_without_a_slug_lists_every_goal() -> None:
+ """Omitting the department lists every goal, those with none included."""
+ dept_goal = _seed_engineering_goal()
+ loose = dept_store.insert_goal(
+ None, period_type="year", period_value="2026",
+ key_result="Win our first customers", target="3 paying",
+ )
result = _call(handle_list_department_goals, {})
- assert "error" in result
+ assert result["department_slug"] is None
+ by_id = {g["id"]: g for g in result["goals"]}
+ assert set(by_id) == {dept_goal, loose}
+ assert by_id[loose]["department_slug"] is None
+ assert by_id[dept_goal]["department_slug"] == "engineering"
+ assert "owner" in by_id[loose] and "owner_person_id" in by_id[loose]
+ # A department narrows it, as before.
+ narrowed = _call(handle_list_department_goals, {"department_slug": "engineering"})
+ assert [g["id"] for g in narrowed["goals"]] == [dept_goal]
# --------------------------------------------------------------------------- #
@@ -467,7 +481,6 @@ def test_create_goal_defaults_the_period_to_the_current_one(monkeypatch: pytest.
@pytest.mark.parametrize(
("overrides", "fragment"),
[
- ({"area": " "}, "area is required"),
({"key_result": ""}, "key_result and target"),
({"target": None}, "key_result and target"),
({"rationale": " "}, "rationale is required"),
@@ -761,7 +774,7 @@ def test_store_failures_reach_the_model_as_the_type_only(monkeypatch: pytest.Mon
raise RuntimeError(secret)
goal_id = _seed_engineering_goal()
- monkeypatch.setattr(dept_store, "list_goals", boom)
+ monkeypatch.setattr(dept_store, "list_all_goals", boom)
monkeypatch.setattr(dept_store, "update_goal", boom)
monkeypatch.setattr(dept_store, "insert_goal", boom)
results = [
diff --git a/packages/core/tests/unit/test_departments_route.py b/packages/core/tests/unit/test_departments_route.py
index e0bfd90f..b5b948e2 100644
--- a/packages/core/tests/unit/test_departments_route.py
+++ b/packages/core/tests/unit/test_departments_route.py
@@ -528,17 +528,17 @@ def empty_client(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> TestClient:
return TestClient(app)
-def test_goal_with_no_area_named_goes_under_general(empty_client: TestClient) -> None:
+def test_goal_with_no_area_named_has_no_department(empty_client: TestClient) -> None:
+ """Goals stand on their own: naming no area creates no department."""
resp = empty_client.post("/goals", json={"key_result": "Launch the product", "area": " "})
assert resp.status_code == 201, resp.text
assert resp.json()["key_result"] == "Launch the product"
- areas = empty_client.get("/departments").json()
- assert [a["config"]["title"] for a in areas] == ["General"]
- assert areas[0]["goals"][0]["id"] == resp.json()["id"]
- # A second goal with no area joins it rather than making "General 2".
+ assert resp.json()["department_slug"] is None
assert empty_client.post("/goals", json={"key_result": "Hire a designer"}).status_code == 201
- areas = empty_client.get("/departments").json()
- assert len(areas) == 1 and len(areas[0]["goals"]) == 2
+ assert empty_client.get("/departments").json() == []
+ listed = empty_client.get("/goals").json()
+ assert [g["key_result"] for g in listed] == ["Launch the product", "Hire a designer"]
+ assert all(g["department_slug"] is None and g["department_title"] is None for g in listed)
def test_goal_names_a_new_area_or_matches_an_existing_one(empty_client: TestClient) -> None:
diff --git a/packages/core/tests/unit/test_executive_reflection.py b/packages/core/tests/unit/test_executive_reflection.py
index f67efdad..fcf60f08 100644
--- a/packages/core/tests/unit/test_executive_reflection.py
+++ b/packages/core/tests/unit/test_executive_reflection.py
@@ -71,7 +71,7 @@ def test_seed_principal_briefs_includes_reflection(
_setup_isolated_db(tmp_path / "refl.db", monkeypatch)
inserted = runner.seed_principal_briefs()
- assert inserted == 4 # morning + eod + reflection + chat_replay
+ assert inserted == 5 # morning + eod + reflection + chat_replay + goal_review
actions = episodic.list_scheduled_actions(status="pending", limit=10)
kinds = {a.kind for a in actions}
diff --git a/packages/core/tests/unit/test_goals_stand_alone.py b/packages/core/tests/unit/test_goals_stand_alone.py
new file mode 100644
index 00000000..e872a3b5
--- /dev/null
+++ b/packages/core/tests/unit/test_goals_stand_alone.py
@@ -0,0 +1,460 @@
+"""Goals as their own thing: an owner, an optional department, and a weekly
+review for the goals no department check-in covers.
+
+Covers the store (migration, goals with no department, delete detaches),
+``departments.goals`` (owners, which goals go unreviewed),
+``departments.goal_review``, the ``/goals`` routes, the Executive's goal tools
+without a department, the org block, the brief's goal row and the action chip.
+"""
+from __future__ import annotations
+
+import asyncio
+import json
+import sqlite3
+from collections.abc import Iterator
+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.departments import goal_review, goals, registry, store
+from openexecutive.memory import episodic
+from openexecutive.people import registry as people_registry
+from openexecutive.people import store as people_store
+
+
[email protected](autouse=True)
+def db(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Iterator[Path]:
+ """One SQLite file for departments, people and audit rows, as in prod."""
+ from openexecutive.audit import AuditLogger, set_audit_logger
+
+ path = tmp_path / "episodic.db"
+ monkeypatch.setattr(store, "DB_PATH", path)
+ monkeypatch.setattr(people_store, "DB_PATH", path)
+ monkeypatch.setattr(episodic, "DB_PATH", path)
+ episodic.initialize_db(path)
+ store.initialize_db()
+ people_store.initialize_db(path)
+ registry.invalidate()
+ people_registry.invalidate()
+ set_audit_logger(AuditLogger(db_path=path))
+ yield path
+ set_audit_logger(None)
+ registry.invalidate()
+ people_registry.invalidate()
+
+
+def _goal(slug: str | None, key_result: str = "Win our first customers", **kw: Any) -> int:
+ return store.insert_goal(
+ slug,
+ period_type=kw.pop("period_type", "year"),
+ period_value=kw.pop("period_value", "2026"),
+ key_result=key_result,
+ target=kw.pop("target", "3 paying"),
+ **kw,
+ )
+
+
+def _people() -> tuple[int, int]:
+ principal = people_store.upsert_person(full_name="Rufus", is_principal=True)
+ dan = people_store.upsert_person(full_name="Dan")
+ return principal, dan
+
+
+# --------------------------------------------------------------------------- #
+# Store
+# --------------------------------------------------------------------------- #
+
+
+def test_an_old_goals_table_is_rebuilt_with_an_optional_department(tmp_path: Path) -> None:
+ """A database from before this change (department_slug NOT NULL, no
+ owner) keeps its goals and gains both."""
+ path = tmp_path / "old.db"
+ with sqlite3.connect(path) as conn:
+ conn.execute(
+ "CREATE TABLE department_goals (id INTEGER PRIMARY KEY AUTOINCREMENT, "
+ "department_slug TEXT NOT NULL, period_type TEXT NOT NULL DEFAULT 'quarter', "
+ "period_value TEXT NOT NULL, key_result TEXT NOT NULL, target TEXT NOT NULL "
+ "DEFAULT '', current TEXT NOT NULL DEFAULT '', status TEXT NOT NULL DEFAULT "
+ "'on_track', created_at TEXT NOT NULL, updated_at TEXT NOT NULL, "
+ "last_reviewed_at TEXT NOT NULL DEFAULT '')"
+ )
+ conn.execute(
+ "INSERT INTO department_goals (department_slug, period_value, key_result, "
+ "created_at, updated_at) VALUES ('sales', 'Q4 2026', 'Close 10', 'x', 'x')"
+ )
+ store.initialize_db(path)
+ with sqlite3.connect(path) as conn:
+ cols = {r[1]: r for r in conn.execute("PRAGMA table_info(department_goals)")}
+ assert cols["department_slug"][3] == 0 # notnull flag cleared
+ assert "owner_person_id" in cols
+ [kept] = store.list_goals("sales", db_path=path)
+ assert kept.key_result == "Close 10" and kept.owner_person_id is None
+ # A goal with no department now fits, and initialize is idempotent.
+ store.initialize_db(path)
+ _goal(None, db_path=path)
+ assert [g.key_result for g in store.list_goals(None, db_path=path)] == ["Win our first customers"]
+
+
+def test_goals_with_no_department_are_listed_on_their_own() -> None:
+ store.create_department("Sales")
+ in_sales = _goal("sales", "Close 10")
+ loose = _goal(None)
+ assert [g.id for g in store.list_goals(None)] == [loose]
+ assert [g.id for g in store.list_goals("sales")] == [in_sales]
+ assert [g.id for g in store.list_all_goals()] == [in_sales, loose]
+ assert store.get_goal(loose).department_slug is None # type: ignore[union-attr]
+
+
+def test_update_goal_moves_and_clears_owner_and_department() -> None:
+ _, dan = _people()
+ store.create_department("Sales")
+ gid = _goal(None)
+ store.update_goal(gid, owner_person_id=dan, department_slug="sales")
+ moved = store.get_goal(gid)
+ assert moved is not None and (moved.owner_person_id, moved.department_slug) == (dan, "sales")
+ # Left out = unchanged; None = cleared.
+ store.update_goal(gid, status="at_risk")
+ assert store.get_goal(gid).owner_person_id == dan # type: ignore[union-attr]
+ store.update_goal(gid, owner_person_id=None, department_slug=None)
+ cleared = store.get_goal(gid)
+ assert cleared is not None and (cleared.owner_person_id, cleared.department_slug) == (None, None)
+
+
+def test_deleting_a_department_keeps_its_goals_on_their_owners() -> None:
+ principal, dan = _people()
+ store.create_department("Sales")
+ store.update_department("sales", head_person_id=dan)
+ follows_lead = _goal("sales", "Close 10")
+ own_owner = _goal("sales", "Hire a rep", owner_person_id=principal)
+ assert store.delete_department("sales")
+ a, b = store.get_goal(follows_lead), store.get_goal(own_owner)
+ assert a is not None and b is not None
+ assert (a.department_slug, a.owner_person_id) == (None, dan) # the lead takes it
+ assert (b.department_slug, b.owner_person_id) == (None, principal)
+
+
+# --------------------------------------------------------------------------- #
+# Owners and review coverage
+# --------------------------------------------------------------------------- #
+
+
+def test_owner_is_the_goals_own_else_the_lead_else_the_principal() -> None:
+ principal, dan = _people()
+ store.create_department("Sales")
+ store.create_department("Ops")
+ store.update_department("sales", head_person_id=dan)
+ ids = {
+ "own": _goal("ops", "A", owner_person_id=dan),
+ "lead": _goal("sales", "B"),
+ "headless": _goal("ops", "C"),
+ "loose": _goal(None, "D"),
+ }
+ views = {v.goal.id: v for v in goals.list_goal_views()}
+ assert views[ids["own"]].owner_name == "Dan"
+ assert views[ids["lead"]].owner_id == dan
+ assert views[ids["headless"]].owner_id == principal
+ assert views[ids["loose"]].owner_name == "Rufus"
+ assert views[ids["lead"]].department_title == "Sales"
+ assert views[ids["loose"]].department_title is None
+
+
+def test_an_owner_who_left_the_team_is_not_named() -> None:
+ """A contact is private to the principal and goal views reach teammates,
+ so an owner later made a contact (or archived) shows no name."""
+ _, dan = _people()
+ gid = _goal(None, owner_person_id=dan)
+ people_store.update_person(dan, kind="contact")
+ [view] = [v for v in goals.list_goal_views() if v.goal.id == gid]
+ assert view.owner_id == dan and view.owner_name == ""
+
+
+def test_unreviewed_goals_are_those_no_check_in_grades() -> None:
+ store.create_department("Finance", specialist_key="cfo")
+ store.create_department("Client work") # no specialist
+ graded = _goal("finance", "Runway")
+ no_specialist = _goal("client-work", "Ship Acme")
+ loose = _goal(None, "Launch")
+ found = {g.id for g in goals.unreviewed_goals(registry.list_states(force_refresh=True))}
+ assert found == {no_specialist, loose}
+ assert graded not in found
+
+
+# --------------------------------------------------------------------------- #
+# The weekly goal review
+# --------------------------------------------------------------------------- #
+
+
+def test_goal_review_grades_uncovered_goals_and_skips_fresh_ones(monkeypatch: pytest.MonkeyPatch) -> None:
+ store.create_department("Finance", specialist_key="cfo")
+ covered = _goal("finance", "Runway")
+ loose = _goal(None, "Launch")
+ calls: list[dict[str, Any]] = []
+
+ async def fake_route(**kw: Any) -> str:
+ calls.append(kw)
+ return json.dumps({
+ "verdicts": [{"goal_id": loose, "status": "at_risk", "rationale": "No date set."}],
+ "narrative": "One slipping.",
+ })
+
+ monkeypatch.setattr("openexecutive.orchestrator.router.route_to_specialist", fake_route)
+ # Wall-clock now: the goals' updated_at is stamped with it.
+ now = datetime.now(UTC)
+ assert asyncio.run(goal_review.run_review(now)) == 1
+ assert calls[0]["specialist_name"] == goals.FALLBACK_REVIEWER
+ assert f"[id={loose}]" in calls[0]["query"] and f"[id={covered}]" not in calls[0]["query"]
+ graded = store.get_goal(loose)
+ assert graded is not None and graded.status == "at_risk" and graded.last_reviewed_at
+ assert store.get_goal(covered).last_reviewed_at == "" # type: ignore[union-attr]
+
+ # Graded a day ago and untouched since: no model call.
+ calls.clear()
+ assert asyncio.run(goal_review.run_review(now + timedelta(days=1))) == 0
+ assert calls == []
+ # A week on, it is due again.
+ asyncio.run(goal_review.run_review(now + timedelta(days=7)))
+ assert len(calls) == 1
+
+
+def test_goal_review_with_nothing_to_grade_makes_no_call(monkeypatch: pytest.MonkeyPatch) -> None:
+ async def boom(**_kw: Any) -> str:
+ raise AssertionError("no model call expected")
+
+ monkeypatch.setattr("openexecutive.orchestrator.router.route_to_specialist", boom)
+ assert asyncio.run(goal_review.run_review()) == 0
+
+
+def test_goal_review_never_raises(monkeypatch: pytest.MonkeyPatch) -> None:
+ _goal(None)
+
+ async def boom(**_kw: Any) -> str:
+ raise RuntimeError("model down")
+
+ monkeypatch.setattr("openexecutive.orchestrator.router.route_to_specialist", boom)
+ assert asyncio.run(goal_review.run_review()) == 0
+
+
+def test_goal_review_is_a_weekly_kind_in_both_modes() -> None:
+ from openexecutive.scheduler import runner
+
+ assert runner.GOAL_REVIEW_KIND in runner._RECURRING_KIND_ENV
+ assert runner.GOAL_REVIEW_KIND in runner._WEEKLY_KINDS
+ assert runner.GOAL_REVIEW_KIND not in runner._SOLO_ONLY_KINDS
+ assert runner._kind_runs_in(runner.GOAL_REVIEW_KIND, "team")
+ assert runner._kind_runs_in(runner.GOAL_REVIEW_KIND, "solo")
+
+
+def test_the_scheduler_runs_the_review_and_chains_next_week(monkeypatch: pytest.MonkeyPatch) -> None:
+ from openexecutive.memory.episodic import ScheduledAction
+ from openexecutive.scheduler import runner
+
+ ran: list[datetime] = []
+ done: list[int] = []
+ chained: list[tuple[str, datetime]] = []
+
+ async def fake_review(now: datetime | None = None) -> int:
+ ran.append(now) # type: ignore[arg-type]
+ return 0
+
+ monkeypatch.setattr(goal_review, "run_review", fake_review)
+ monkeypatch.setattr(runner, "mark_action_done", done.append)
+ monkeypatch.setattr(
+ runner, "_enqueue_next_principal_brief",
+ lambda kind, after: chained.append((kind, after)),
+ )
+ now = datetime(2026, 10, 19, 9, tzinfo=UTC)
+ action = ScheduledAction(
+ id=7, kind=runner.GOAL_REVIEW_KIND, run_at=now.isoformat(), channel="__internal__",
+ channel_ref="", intent_text="x", created_at=now.isoformat(),
+ )
+ asyncio.run(runner._run_goal_review(action, now))
+ assert ran == [now] and done == [7]
+ assert chained and chained[0][0] == runner.GOAL_REVIEW_KIND
+
+
+# --------------------------------------------------------------------------- #
+# /goals routes
+# --------------------------------------------------------------------------- #
+
+
+def client() -> TestClient:
+ from openexecutive.api.routes import departments as departments_route
+
+ app = FastAPI()
+ app.include_router(departments_route.router)
+ return TestClient(app)
+
+
+def test_goals_route_lists_owners_and_departments(client: TestClient) -> None:
+ _, dan = _people()
+ store.create_department("Sales")
+ created = client.post("/goals", json={"key_result": "Close 10", "area": "Sales",
+ "owner_person_id": dan})
+ assert created.status_code == 201, created.text
+ client.post("/goals", json={"key_result": "Launch"})
+ listed = {g["key_result"]: g for g in client.get("/goals").json()}
+ assert listed["Close 10"]["owner_name"] == "Dan"
+ assert listed["Close 10"]["department_title"] == "Sales"
+ assert listed["Launch"]["owner_name"] == "Rufus"
+ assert listed["Launch"]["department_slug"] is None
+
+
+def test_goal_owner_must_be_on_the_team(client: TestClient) -> None:
+ _people()
+ contact = people_store.upsert_person(full_name="Acme buyer", kind="contact")
+ archived = people_store.upsert_person(full_name="Gone")
+ people_store.archive_person(archived)
+ for owner in (contact, archived, 9999):
+ resp = client.post("/goals", json={"key_result": "X", "owner_person_id": owner})
+ assert resp.status_code == 422, owner
+
+
+def test_patch_and_delete_reach_any_goal(client: TestClient) -> None:
+ _, dan = _people()
+ store.create_department("Sales")
+ gid = client.post("/goals", json={"key_result": "Launch"}).json()["id"]
+ moved = client.patch(f"/goals/{gid}", json={"department_slug": "sales", "owner_person_id": dan})
+ assert moved.status_code == 200, moved.text
+ assert (moved.json()["department_slug"], moved.json()["owner_person_id"]) == ("sales", dan)
+ # Only what is sent changes; null clears.
+ client.patch(f"/goals/{gid}", json={"status": "at_risk"})
+ assert store.get_goal(gid).owner_person_id == dan # type: ignore[union-attr]
+ cleared = client.patch(f"/goals/{gid}", json={"department_slug": None})
+ assert cleared.json()["department_slug"] is None
+ assert client.patch(f"/goals/{gid}", json={"department_slug": "nope"}).status_code == 422
+ assert client.delete(f"/goals/{gid}").status_code == 204
+ assert store.get_goal(gid) is None
+ assert client.delete(f"/goals/{gid}").status_code == 404
+
+
+def test_department_routes_still_reach_only_their_own_goals(client: TestClient) -> None:
+ store.create_department("Sales")
+ loose = _goal(None)
+ assert client.patch(f"/departments/sales/goals/{loose}", json={"status": "at_risk"}).status_code == 404
+ assert client.delete(f"/departments/sales/goals/{loose}").status_code == 404
+
+
+# --------------------------------------------------------------------------- #
+# The Executive's goal tools
+# --------------------------------------------------------------------------- #
+
+
+def _tool(handler: Any, payload: dict[str, Any]) -> dict[str, Any]:
+ return json.loads(asyncio.run(handler(payload)))
+
+
+def as_principal(monkeypatch: pytest.MonkeyPatch) -> None:
+ from openexecutive.orchestrator import department_tools
+
+ monkeypatch.setattr(department_tools, "_goals_created_by_turn", {})
+ monkeypatch.setattr(department_tools, "_principal_asked", lambda: True)
+
+
+def test_update_tool_reaches_a_goal_with_no_department() -> None:
+ from openexecutive.orchestrator.department_tools import handle_update_department_goal
+
+ gid = _goal(None)
+ result = _tool(handle_update_department_goal,
+ {"goal_id": gid, "status": "at_risk", "rationale": "No customer signed yet."})
+ assert result["status"] == "ok" and result["department_slug"] is None
+ assert store.get_goal(gid).status == "at_risk" # type: ignore[union-attr]
+ # Naming a department it is not in is still refused.
+ store.create_department("Sales")
+ wrong = _tool(handle_update_department_goal,
+ {"department_slug": "sales", "goal_id": gid, "status": "on_track",
+ "rationale": "x"})
+ assert "no department" in wrong["error"]
+
+
+def test_create_tool_without_an_area_makes_no_department(as_principal: None) -> None:
+ from openexecutive.orchestrator.department_tools import handle_create_goal
+
+ _, dan = _people()
+ result = _tool(handle_create_goal, {
+ "key_result": "Ship the mobile apps", "target": "In both stores",
+ "rationale": "Principal set it.", "owner_person_id": dan,
+ })
+ assert result["status"] == "ok", result
+ assert result["area_slug"] is None and result["area_created"] is False
+ goal = store.get_goal(result["goal_id"])
+ assert goal is not None and goal.department_slug is None and goal.owner_person_id == dan
+ assert store.list_departments() == []
+ dupe = _tool(handle_create_goal, {
+ "key_result": "ship the mobile-apps", "target": "x", "rationale": "again",
+ })
+ assert "already tracks" in dupe["error"]
+
+
+def test_create_tool_refuses_an_owner_off_the_team(as_principal: None) -> None:
+ from openexecutive.orchestrator.department_tools import handle_create_goal
+
+ _people()
+ contact = people_store.upsert_person(full_name="Acme buyer", kind="contact")
+ for owner in (contact, 9999, True, "Dan"):
+ result = _tool(handle_create_goal, {
+ "key_result": "X", "target": "Y", "rationale": "Z", "owner_person_id": owner,
+ })
+ assert "error" in result, owner
+ assert store.list_all_goals() == []
+
+
+def test_goal_tool_schemas_need_no_department() -> None:
+ from openexecutive.orchestrator.department_tools import (
+ CREATE_GOAL_TOOL,
+ LIST_DEPARTMENT_GOALS_TOOL,
+ UPDATE_DEPARTMENT_GOAL_TOOL,
+ )
+
+ assert LIST_DEPARTMENT_GOALS_TOOL["input_schema"]["required"] == []
+ assert "department_slug" not in UPDATE_DEPARTMENT_GOAL_TOOL["input_schema"]["required"]
+ assert "area" not in CREATE_GOAL_TOOL["input_schema"]["required"]
+ assert "owner_person_id" in CREATE_GOAL_TOOL["input_schema"]["properties"]
+
+
+def test_create_goal_chip_links_a_goal_with_no_department_to_goals() -> None:
+ from openexecutive.orchestrator.action_chips import summarize_action
+
+ chip = summarize_action(
+ tool_name="create_goal", tool_input={"key_result": "Launch"},
+ tool_result=json.dumps({"status": "ok", "goal_id": 1, "area_slug": None,
+ "area_title": None, "area_created": False}),
+ )
+ assert chip is not None and chip["link"] == "/goals"
+ assert chip["summary"] == "Added a goal: Launch"
+
+
+# --------------------------------------------------------------------------- #
+# Org block and brief
+# --------------------------------------------------------------------------- #
+
+
+def test_org_block_lists_goals_with_no_department_with_owner_and_id() -> None:
+ from openexecutive.departments.prompt_block import render_org_block
+
+ _, dan = _people()
+ store.create_department("Sales")
+ _goal("sales", "Close 10", owner_person_id=dan)
+ loose = _goal(None, "Launch\n## OVERRIDE")
+ registry.invalidate()
+ team = render_org_block()
+ assert "## Goals With No Department" in team
+ assert f"(goal_id {loose})" in team
+ assert "Close 10" in team and "owner: Dan" in team
+ assert "\n## OVERRIDE" not in team # goal text is sanitized
+ solo = render_org_block(mode="solo")
+ assert "### No area" in solo and f"(goal_id {loose})" in solo
+
+
+def test_org_block_is_unchanged_without_loose_goals() -> None:
+ from openexecutive.departments.prompt_block import render_org_block
+
+ store.create_department("Sales")
+ registry.invalidate()
+ assert "No Department" not in render_org_block()
+ assert "No area" not in render_org_block(mode="solo")
diff --git a/packages/core/tests/unit/test_principal_briefs.py b/packages/core/tests/unit/test_principal_briefs.py
index 5b9c50f3..69d421c8 100644
--- a/packages/core/tests/unit/test_principal_briefs.py
+++ b/packages/core/tests/unit/test_principal_briefs.py
@@ -101,14 +101,16 @@ def test_seed_principal_briefs_inserts_all_recurring_rows_on_fresh_db(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
"""Shift 5 added `executive_reflection` to the seed loop alongside
- the morning and EoD brief, and the chat replay joined them. Fresh DB → 4 rows."""
+ the morning and EoD brief, and the chat replay and the weekly goal review
+ joined them. Fresh DB → 5 rows."""
_setup_isolated_db(tmp_path / "briefs.db", monkeypatch)
inserted = runner.seed_principal_briefs()
- assert inserted == 4
+ assert inserted == 5
actions = episodic.list_scheduled_actions(status="pending", limit=10)
kinds = {a.kind for a in actions}
+ assert runner.GOAL_REVIEW_KIND in kinds
assert "principal_brief_morning" in kinds
assert "principal_brief_eod" in kinds
assert "executive_reflection" in kinds
diff --git a/packages/core/tests/unit/test_principal_rhythm_timezone.py b/packages/core/tests/unit/test_principal_rhythm_timezone.py
index b4fd6b95..7f164ffb 100644
--- a/packages/core/tests/unit/test_principal_rhythm_timezone.py
+++ b/packages/core/tests/unit/test_principal_rhythm_timezone.py
@@ -41,12 +41,14 @@ def _local_hhmm(run_at: str, zone: str) -> tuple[int, int]:
def test_default_times_follow_the_workspace_zone() -> None:
ws.restore_workspace_settings(ws.WorkspaceSettings(timezone="America/Los_Angeles"))
- assert runner.seed_principal_briefs() == 4
+ assert runner.seed_principal_briefs() == 5
expected = {
"principal_brief_morning": (8, 0),
"principal_brief_eod": (18, 0),
"executive_reflection": (7, 30),
"chat_replay": (3, 30),
+ # Weekly, Monday 09:00 in the same zone.
+ runner.GOAL_REVIEW_KIND: (9, 0),
}
for kind, hhmm in expected.items():
(row,) = _pending(kind)
diff --git a/packages/core/tests/unit/test_today_route.py b/packages/core/tests/unit/test_today_route.py
index 7f0af19d..93e826f8 100644
--- a/packages/core/tests/unit/test_today_route.py
+++ b/packages/core/tests/unit/test_today_route.py
@@ -2645,3 +2645,28 @@ def test_morning_brief_today_only_serves_todays_non_empty_brief(
monkeypatch.setattr(brief_state, "last_delivered", lambda _kind: None)
assert today_route._morning_brief_today() is None
+
+
+# --------------------------------------------------------------------------- #
+# Goals with no department: their own row, with owners
+# --------------------------------------------------------------------------- #
+
+
+def test_brief_adds_a_row_for_goals_with_no_department(client: TestClient) -> None:
+ principal = people_store.upsert_person(full_name="Rufus", is_principal=True)
+ dan = people_store.upsert_person(full_name="Dan")
+ dept_store.update_department("finance", head_person_id=dan)
+ dept_store.insert_goal("finance", period_value="2026", key_result="Runway", target="t", status="off_track")
+ dept_store.insert_goal(None, period_value="2026", key_result="Launch", target="t", status="at_risk")
+ dept_store.insert_goal(None, period_value="2026", key_result="Hire", target="t", owner_person_id=dan)
+ rows = {d.slug: d for d in today_route._build_today().departments}
+ assert rows["finance"].attention_goals[0].owner_name == "Dan"
+ loose = rows[""]
+ assert loose.title == today_route.UNASSIGNED_GOALS_TITLE
+ assert (loose.goal_count, loose.at_risk_count, loose.awaiting_count) == (2, 1, 0)
+ assert [(g.key_result, g.owner_id) for g in loose.attention_goals] == [("Launch", principal)]
+
+
+def test_brief_has_no_extra_row_when_every_goal_has_a_department(client: TestClient) -> None:
+ dept_store.insert_goal("finance", period_value="2026", key_result="Runway", target="t")
+ assert "" not in {d.slug for d in today_route._build_today().departments}
diff --git a/packages/core/tests/unit/test_weekly_review.py b/packages/core/tests/unit/test_weekly_review.py
index f125e47a..c3738043 100644
--- a/packages/core/tests/unit/test_weekly_review.py
+++ b/packages/core/tests/unit/test_weekly_review.py
@@ -403,7 +403,7 @@ def _local(run_at: str, zone: str) -> datetime:
def test_seeded_only_in_solo() -> None:
- assert runner.seed_principal_briefs() == 4
+ assert runner.seed_principal_briefs() == 5 # the four daily kinds + goal_review
assert _pending() == []
_solo()
assert runner.seed_principal_briefs() == 1 # only the weekly review was missing
diff --git a/packages/core/tests/unit/test_workspace_route.py b/packages/core/tests/unit/test_workspace_route.py
index c1683b84..f9710557 100644
--- a/packages/core/tests/unit/test_workspace_route.py
+++ b/packages/core/tests/unit/test_workspace_route.py
@@ -61,6 +61,7 @@ PRINCIPAL = {"x-caller-email": "[email protected]"}
# company domain until one is set).
NO_ROLE: dict[str, Any] = {
**dict.fromkeys(ws.ROLE_FIELDS), "company_domains": [], "company_domains_custom": False,
+ "has_departments": False,
}
@@ -72,6 +73,14 @@ def test_get_defaults_before_onboarding(client: TestClient) -> None:
}
+def test_get_says_whether_any_department_exists(client: TestClient) -> None:
+ """The UI shows the Departments tab only once a department exists."""
+ assert client.get("/workspace").json()["has_departments"] is False
+ dept_store.create_department("Sales")
+ dept_registry.invalidate()
+ assert client.get("/workspace").json()["has_departments"] is True
+
+
def test_get_reports_the_fallback_zone(client: TestClient, monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(ws, "_configured_timezone", lambda: ws.ZoneInfo("Europe/Madrid"))
assert client.get("/workspace").json() == {
diff --git a/packages/ui/scripts/goalAreas.test.mjs b/packages/ui/scripts/goalAreas.test.mjs
deleted file mode 100644
index 97d244fb..00000000
--- a/packages/ui/scripts/goalAreas.test.mjs
+++ /dev/null
@@ -1,66 +0,0 @@
-import assert from "node:assert/strict";
-import test from "node:test";
-import { applyGoalChange, groupGoalsByArea } from "../src/lib/goalAreas.ts";
-
-const goal = (id, slug, status = "on_track") => ({
- id,
- department_slug: slug,
- period_type: "quarter",
- period_value: "2026-Q4",
- key_result: `Goal ${id}`,
- target: "10",
- current: "",
- status,
- created_at: "",
- updated_at: "",
- last_reviewed_at: "",
-});
-
-const area = (slug, title, goals = []) => ({
- config: { slug, title },
- goals,
- headcount: null,
- budget_usd: null,
- member_person_ids: [],
- updated_at: "",
-});
-
-const DEPTS = [
- area("sales", "Sales", [goal(1, "sales"), goal(2, "sales", "at_risk")]),
- area("finance", "Finance"),
- area("marketing", "Marketing", [goal(3, "marketing", "off_track")]),
- area("engineering", "Engineering"),
-];
-
-test("areas with goals come first, in API order; the rest by title", () => {
- const g = groupGoalsByArea(DEPTS);
- assert.deepEqual(g.withGoals.map((a) => a.slug), ["sales", "marketing"]);
- assert.deepEqual(g.empty.map((a) => a.slug), ["engineering", "finance"]);
- assert.deepEqual(g.all.map((a) => a.title), ["Engineering", "Finance", "Marketing", "Sales"]);
- assert.deepEqual(g.counts, { on_track: 1, at_risk: 1, off_track: 1 });
-});
-
-test("no areas, or no goals, group to empty lists", () => {
- assert.deepEqual(groupGoalsByArea([]).withGoals, []);
- const g = groupGoalsByArea([area("ops", "Operations")]);
- assert.deepEqual(g.withGoals, []);
- assert.deepEqual(g.empty, [{ slug: "ops", title: "Operations" }]);
-});
-
-test("a saved goal is added to, or replaced in, its own area only", () => {
- const added = applyGoalChange(DEPTS, { saved: goal(9, "finance") });
- assert.deepEqual(added.find((d) => d.config.slug === "finance").goals.map((x) => x.id), [9]);
- assert.equal(added.find((d) => d.config.slug === "sales").goals.length, 2);
-
- const edited = applyGoalChange(DEPTS, { saved: { ...goal(2, "sales"), key_result: "Renamed" } });
- const sales = edited.find((d) => d.config.slug === "sales").goals;
- assert.deepEqual(sales.map((x) => x.key_result), ["Goal 1", "Renamed"]);
-});
-
-test("a deleted goal leaves its area", () => {
- const next = applyGoalChange(DEPTS, { deleted: { slug: "sales", id: 1 } });
- assert.deepEqual(next.find((d) => d.config.slug === "sales").goals.map((x) => x.id), [2]);
- assert.equal(groupGoalsByArea(next).withGoals.length, 2);
- const gone = applyGoalChange(next, { deleted: { slug: "marketing", id: 3 } });
- assert.deepEqual(groupGoalsByArea(gone).withGoals.map((a) => a.slug), ["sales"]);
-});
diff --git a/packages/ui/scripts/goalGroups.test.mjs b/packages/ui/scripts/goalGroups.test.mjs
new file mode 100644
index 00000000..3484a8cd
--- /dev/null
+++ b/packages/ui/scripts/goalGroups.test.mjs
@@ -0,0 +1,53 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+import { goalCounts, groupGoals } from "../src/lib/goalGroups.ts";
+
+const goal = (id, { dept = null, deptTitle = null, owner = 1, ownerName = "Rufus", status = "on_track" } = {}) => ({
+ id,
+ department_slug: dept,
+ department_title: deptTitle,
+ owner_id: owner,
+ owner_name: ownerName,
+ period_type: "quarter",
+ period_value: "Q4 2026",
+ key_result: `Goal ${id}`,
+ target: "10",
+ current: "",
+ status,
+ created_at: "",
+ updated_at: "",
+ last_reviewed_at: "",
+});
+
+const GOALS = [
+ goal(3, { owner: 2, ownerName: "Dan", dept: "sales", deptTitle: "Sales", status: "at_risk" }),
+ goal(1),
+ goal(2, { owner: 3, ownerName: "Alex", status: "off_track" }),
+ goal(4, { dept: "sales", deptTitle: "Sales" }),
+];
+
+test("by owner: the viewer first, then by name; goals oldest first", () => {
+ const groups = groupGoals(GOALS, "owner", { viewerId: 1 });
+ assert.deepEqual(groups.map((g) => g.title), ["Rufus (you)", "Alex", "Dan"]);
+ assert.deepEqual(groups[0].goals.map((g) => g.id), [1, 4]);
+});
+
+test("by department: departments by title, goals with none last", () => {
+ const groups = groupGoals(GOALS, "department");
+ assert.deepEqual(groups.map((g) => g.title), ["Sales", "No department"]);
+ assert.deepEqual(groups[1].goals.map((g) => g.id), [1, 2]);
+ assert.equal(groupGoals(GOALS, "department", { unit: "area" })[1].title, "No area");
+});
+
+test("by status: worst first, empty statuses left out", () => {
+ const groups = groupGoals(GOALS, "status");
+ assert.deepEqual(groups.map((g) => g.title), ["Off track", "At risk", "On track"]);
+ assert.deepEqual(groupGoals([goal(1)], "status").map((g) => g.title), ["On track"]);
+});
+
+test("a goal nobody owns groups last; counts per status", () => {
+ const groups = groupGoals([goal(1, { owner: null, ownerName: "" }), goal(2)], "owner", { viewerId: 1 });
+ assert.deepEqual(groups.map((g) => g.title), ["Rufus (you)", "No owner yet"]);
+ assert.deepEqual(goalCounts(GOALS), { on_track: 2, at_risk: 1, off_track: 1 });
+ assert.deepEqual(groupGoals([], "owner"), []);
+});
diff --git a/packages/ui/scripts/navConfig.test.mjs b/packages/ui/scripts/navConfig.test.mjs
index f1ca6a58..4648f870 100644
--- a/packages/ui/scripts/navConfig.test.mjs
+++ b/packages/ui/scripts/navConfig.test.mjs
@@ -116,6 +116,21 @@ test("a hub's menu entry stays lit on every one of its tabs", () => {
assert.deepEqual(lit("/settings"), []);
});
+test("team: the Departments tab shows only once a department exists", () => {
+ const company = buildHubs({ hasDepartments: false })[1];
+ assert.deepEqual(links(company.tabs), [
+ "People → /people",
+ "Goals → /goals",
+ "Company profile → /company-profile",
+ ]);
+ // The Departments pages keep it: that is where the first one is added.
+ const onDepts = hubForPath("/departments/new", { hasDepartments: false });
+ assert.ok(onDepts?.tabs.some((t) => t.href === "/departments"));
+ assert.ok(!hubForPath("/goals", { hasDepartments: false })?.tabs.some((t) => t.href === "/departments"));
+ // Solo never shows it, departments or not.
+ assert.ok(!JSON.stringify(buildHubs({ mode: "solo", hasDepartments: true })).includes("/departments"));
+});
+
test("hubForPath finds the hub a page belongs to", () => {
assert.equal(hubForPath("/jobs/new")?.key, "work");
assert.equal(hubForPath("/people/3")?.key, "company");
diff --git a/packages/ui/scripts/peopleKinds.test.mjs b/packages/ui/scripts/peopleKinds.test.mjs
index 189f27d5..7066377b 100644
--- a/packages/ui/scripts/peopleKinds.test.mjs
+++ b/packages/ui/scripts/peopleKinds.test.mjs
@@ -8,7 +8,7 @@ import {
isContact,
personCardStatus,
peopleForTab,
- shouldOfferTeamMode,
+ shouldSwitchToTeam,
tabsFor,
} from "../src/lib/peopleKinds.ts";
@@ -62,12 +62,12 @@ test("the principal is always on the team", () => {
assert.equal(effectiveKind("contact", false), "contact");
});
-test("adding a teammate in solo offers team mode; a contact or the principal does not", () => {
- assert.equal(shouldOfferTeamMode("solo", "team", false), true);
- assert.equal(shouldOfferTeamMode("solo", "contact", false), false);
- assert.equal(shouldOfferTeamMode("solo", "team", true), false);
- assert.equal(shouldOfferTeamMode("solo", "contact", true), false);
- assert.equal(shouldOfferTeamMode("team", "team", false), false);
+test("adding a teammate in solo switches to team mode; a contact or the principal does not", () => {
+ assert.equal(shouldSwitchToTeam("solo", "team", false), true);
+ assert.equal(shouldSwitchToTeam("solo", "contact", false), false);
+ assert.equal(shouldSwitchToTeam("solo", "team", true), false);
+ assert.equal(shouldSwitchToTeam("solo", "contact", true), false);
+ assert.equal(shouldSwitchToTeam("team", "team", false), false);
});
test("a card's one status: email for a contact, leave or reply time for the team", () => {
diff --git a/packages/ui/src/app/departments/[slug]/page.tsx b/packages/ui/src/app/departments/[slug]/page.tsx
index 2f4207ea..f743de54 100644
--- a/packages/ui/src/app/departments/[slug]/page.tsx
+++ b/packages/ui/src/app/departments/[slug]/page.tsx
@@ -180,7 +180,7 @@ export default function DepartmentDetailPage() {
const params = useParams();
const slug = params?.slug as string;
const router = useRouter();
- const { mode, effectiveTimezone } = useWorkspace();
+ const { mode, effectiveTimezone, refresh: refreshWorkspace } = useWorkspace();
const [dept, setDept] = useState<DepartmentDetail | null>(null);
const [loading, setLoading] = useState(true);
@@ -363,12 +363,15 @@ export default function DepartmentDetailPage() {
async function removeDepartment() {
if (!dept) return;
if (!window.confirm(
- `Delete "${dept.config.title}"? This will also remove all its Goals and cannot be undone.`
+ `Delete "${dept.config.title}"? Its goals stay on the Goals page with no department, ` +
+ "each on its owner (or on the department's lead). This cannot be undone."
)) return;
setDeleting(true);
setDeleteErr(null);
try {
await deleteDepartment(slug);
+ // The Departments tab hides once the last department is gone.
+ void refreshWorkspace();
router.push("/departments");
} catch (e) {
setDeleteErr(e instanceof Error ? e.message : "Delete failed");
diff --git a/packages/ui/src/app/departments/page.tsx b/packages/ui/src/app/departments/page.tsx
index c828d0cf..61dfba05 100644
--- a/packages/ui/src/app/departments/page.tsx
+++ b/packages/ui/src/app/departments/page.tsx
@@ -6,6 +6,7 @@ import { useEffect, useRef, useState } from "react";
import { GoalStatusPill } from "@/components/goals/GoalEditor";
import Button from "@/components/ui/Button";
import SidePanel from "@/components/ui/SidePanel";
+import { useWorkspace } from "@/components/workspace/WorkspaceContext";
import {
createDepartment,
listDepartments,
@@ -107,6 +108,7 @@ export default function DepartmentsPage() {
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [addingDept, setAddingDept] = useState(false);
+ const { refresh: refreshWorkspace } = useWorkspace();
useEffect(() => {
listDepartments()
@@ -180,6 +182,8 @@ export default function DepartmentsPage() {
onCreated={(dept) => {
setDepts((prev) => [...prev, dept]);
setAddingDept(false);
+ // The first department brings the Departments tab.
+ void refreshWorkspace();
}}
onCancel={() => setAddingDept(false)}
/>
diff --git a/packages/ui/src/app/goals/page.tsx b/packages/ui/src/app/goals/page.tsx
index 174cd1d4..8a7ea18c 100644
--- a/packages/ui/src/app/goals/page.tsx
+++ b/packages/ui/src/app/goals/page.tsx
@@ -1,183 +1,227 @@
"use client";
-import { useEffect, useMemo, useState } from "react";
+import Link from "next/link";
+import { useCallback, useEffect, useMemo, useState } from "react";
-import { AddGoalForm, GoalRow, GoalStatusPill, goalStatusLabel } from "@/components/goals/GoalEditor";
+import {
+ AddGoalForm,
+ GoalRow,
+ GoalStatusPill,
+ goalStatusLabel,
+ type DepartmentOption,
+ type OwnerOption,
+} from "@/components/goals/GoalEditor";
import Button from "@/components/ui/Button";
import { useWorkspace } from "@/components/workspace/WorkspaceContext";
-import { listDepartments, type DepartmentState } from "@/lib/api";
-import { applyGoalChange, groupGoalsByArea } from "@/lib/goalAreas";
+import {
+ getPeopleViewer,
+ listDepartments,
+ listGoals,
+ listPeople,
+ type GoalView,
+} from "@/lib/api";
+import { goalCounts, groupGoals, type GoalGrouping } from "@/lib/goalGroups";
-// Every goal in one place, grouped by area. An area is a department row under
-// the hood (solo mode calls it an area and shows this page instead of
-// Departments); goals are added, edited and deleted through the same
-// slug-scoped goal routes a department's own page uses. Team mode links it
-// too, and the copy says "department" there.
+// Every goal in one place (GET /goals). A goal has an owner and, optionally,
+// a department ("area" in solo), so the page groups by owner, department or
+// status. Goals with no department are checked by the weekly goal review, so
+// nothing here needs a department to be tracked.
+
+const GROUPING_LABEL: Record<GoalGrouping, string> = {
+ owner: "Owner",
+ department: "Department",
+ status: "Status",
+};
+
+interface Loaded {
+ goals: GoalView[];
+ departments: DepartmentOption[];
+}
+
+async function load(): Promise<Loaded> {
+ const [goals, ds] = await Promise.all([listGoals(), listDepartments()]);
+ const departments = ds
+ .map((d) => ({ slug: d.config.slug, title: d.config.title }))
+ .sort((a, b) => a.title.localeCompare(b.title));
+ return { goals, departments };
+}
export default function GoalsPage() {
- const [departments, setDepartments] = useState<DepartmentState[] | null>(null);
+ const [goals, setGoals] = useState<GoalView[] | null>(null);
+ const [departments, setDepartments] = useState<DepartmentOption[]>([]);
+ const [owners, setOwners] = useState<OwnerOption[]>([]);
+ const [viewerId, setViewerId] = useState<number | null>(null);
const [error, setError] = useState<string | null>(null);
- // The area the add form opens on, or null while it is closed.
- const [addingTo, setAddingTo] = useState<string | null>(null);
+ const [adding, setAdding] = useState(false);
+ const [grouping, setGrouping] = useState<GoalGrouping>("owner");
const { mode } = useWorkspace();
- const unit = mode === "solo" ? "area" : "department";
+ const solo = mode === "solo";
+ const unit = solo ? "area" : "department";
+
+ const apply = useCallback((loaded: Loaded) => {
+ setGoals(loaded.goals);
+ setDepartments(loaded.departments);
+ setError(null);
+ }, []);
+ const fail = useCallback((e: unknown) => {
+ setError(e instanceof Error ? e.message : "Failed to load goals");
+ }, []);
+ const reload = useCallback(() => {
+ load().then(apply).catch(fail);
+ }, [apply, fail]);
useEffect(() => {
- let cancelled = false;
- listDepartments()
- .then((ds) => {
- if (cancelled) return;
- setDepartments(ds);
- // `?add=1` (Home's first-week card) opens the add form on load.
- if (new URLSearchParams(window.location.search).get("add") === "1") {
- const g = groupGoalsByArea(ds);
- setAddingTo(g.withGoals[0]?.slug ?? g.all[0]?.slug ?? null);
- }
+ load()
+ .then((loaded) => {
+ apply(loaded);
+ // `?add=1` (Home's first-week card) opens the add form once loaded.
+ if (new URLSearchParams(window.location.search).get("add") === "1") setAdding(true);
})
- .catch((e) => {
- if (!cancelled) setError(e instanceof Error ? e.message : "Failed to load goals");
- });
- return () => {
- cancelled = true;
- };
- }, []);
+ .catch(fail);
+ // The owner pickers and "(you)": best effort, the page works without them.
+ listPeople()
+ .then((ps) =>
+ setOwners(ps.filter((p) => p.id != null).map((p) => ({ id: p.id!, name: p.full_name }))),
+ )
+ .catch(() => {});
+ getPeopleViewer()
+ .then((v) => setViewerId(v.person_id))
+ .catch(() => {});
+ }, [apply, fail]);
- const grouped = useMemo(() => groupGoalsByArea(departments ?? []), [departments]);
- const total = grouped.withGoals.reduce((n, a) => n + a.goals.length, 0);
+ // Grouping by department only means something once one exists.
+ const groupings: GoalGrouping[] = departments.length > 0 ? ["owner", "department", "status"] : ["owner", "status"];
+ const by = groupings.includes(grouping) ? grouping : "owner";
+ const groups = useMemo(() => groupGoals(goals ?? [], by, { viewerId, unit }), [goals, by, viewerId, unit]);
+ const ownerOptions = useMemo(
+ () => owners.map((o) => (o.id === viewerId ? { ...o, name: `${o.name} (you)` } : o)),
+ [owners, viewerId],
+ );
+ const total = goals?.length ?? 0;
+ const counts = goalCounts(goals ?? []);
const summary = (["off_track", "at_risk", "on_track"] as const)
- .filter((s) => grouped.counts[s] > 0)
- .map((s) => `${grouped.counts[s]} ${goalStatusLabel(s)}`)
+ .filter((s) => counts[s] > 0)
+ .map((s) => `${counts[s]} ${goalStatusLabel(s)}`)
.join(" · ");
- // Open the form on the first area that already has goals, else the first area.
- const defaultArea = grouped.withGoals[0]?.slug ?? grouped.all[0]?.slug ?? null;
+ // One line under each goal: what the grouping doesn't already say.
+ const metaFor = (g: GoalView): string => {
+ const parts: string[] = [];
+ if (by !== "owner" && g.owner_name) parts.push(g.owner_id === viewerId ? `${g.owner_name} (you)` : g.owner_name);
+ if (by !== "department" && g.department_title) parts.push(g.department_title);
+ return parts.join(" · ");
+ };
return (
<div className="flex flex-col h-full bg-surface">
<main className="flex-1 overflow-y-auto">
<div className="max-w-3xl mx-auto px-4 sm:px-6 py-8">
- <div className="flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between mb-8">
+ <div className="flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between mb-6">
<div className="min-w-0">
<h1 className="text-2xl sm:text-3xl font-bold tracking-tight text-fg">Goals</h1>
<p className="text-[15px] text-fg-muted mt-2">
- What you&apos;re working towards, grouped by {unit}. Tell the Executive how a goal is
+ What you&apos;re working towards. Each goal is checked weekly. Tell the Executive how one is
going in chat and it updates the goal for you.
</p>
</div>
- {departments && grouped.all.length > 0 && addingTo === null && (
- <Button variant="primary" onClick={() => setAddingTo(defaultArea)} className="flex-shrink-0 self-start">
+ {goals && total > 0 && !adding && (
+ <Button variant="primary" onClick={() => setAdding(true)} className="flex-shrink-0 self-start">
Add goal
</Button>
)}
</div>
- {!departments && !error && <p className="text-fg-muted text-[15px]">Loading…</p>}
+ {!goals && !error && <p className="text-fg-muted text-[15px]">Loading…</p>}
{error && (
<div className="p-4 rounded-xl bg-rose-500/10 border border-rose-500/30 text-rose-500 text-[15px] mb-4">
{error}
</div>
)}
- {departments && (
+ {goals && (
<div className="space-y-8">
- {addingTo !== null && (
- <div className="rounded-2xl border border-line bg-surface-elevated px-5">
- <AddGoalForm
- key={addingTo}
- slug={addingTo}
- areas={grouped.all}
- areaLabel={unit === "area" ? "Area" : "Department"}
- onCreated={(goal) => {
- setDepartments((ds) => applyGoalChange(ds ?? [], { saved: goal }));
- setAddingTo(null);
- }}
- onCancel={() => setAddingTo(null)}
- />
- </div>
- )}
-
- {grouped.all.length === 0 ? (
- // No area yet (setup makes none for a solo workspace or a team
- // that names none): the form is the page, and the save creates
- // the area it names.
+ {(adding || total === 0) && (
<div className="rounded-2xl border border-line bg-surface-elevated px-5">
<AddGoalForm
slug={null}
- areaLabel={unit === "area" ? "Area" : "Department"}
+ first={total === 0}
+ departments={departments}
+ owners={ownerOptions}
+ defaultOwnerId={viewerId}
+ areaLabel={solo ? "Area" : "Department"}
onCreated={() => {
- listDepartments()
- .then(setDepartments)
- .catch((e) => setError(e instanceof Error ? e.message : "Failed to load goals"));
+ setAdding(false);
+ reload();
}}
+ onCancel={total > 0 ? () => setAdding(false) : undefined}
/>
</div>
- ) : total === 0 && addingTo === null ? (
- <div className="rounded-2xl border border-line bg-surface-elevated p-8 text-center">
- <p className="text-base font-medium text-fg">No goals yet.</p>
- <p className="text-[15px] text-fg-muted mt-1">
- Add the first thing you&apos;re working towards — just type it; the
- timeframe defaults to this quarter.
- </p>
- <Button variant="primary" onClick={() => setAddingTo(defaultArea)} className="mt-5">
- Add a goal
- </Button>
- </div>
- ) : (
- total > 0 && (
+ )}
+
+ {total > 0 && (
+ <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
<p className="text-[15px] text-fg-muted">
{total} goal{total === 1 ? "" : "s"}
{summary && <> · {summary}</>}
</p>
- )
+ <div role="group" aria-label="Group goals by" className="flex flex-wrap items-center gap-1.5">
+ <span className="text-sm text-fg-subtle mr-1">Group by</span>
+ {groupings.map((g) => (
+ <button
+ key={g}
+ type="button"
+ aria-pressed={by === g}
+ onClick={() => setGrouping(g)}
+ className={`min-h-9 px-3.5 rounded-full border text-sm transition-colors cursor-pointer ${
+ by === g
+ ? "border-accent bg-accent/10 text-fg"
+ : "border-line text-fg-muted hover:text-fg hover:border-line-strong"
+ }`}
+ >
+ {g === "department" && solo ? "Area" : GROUPING_LABEL[g]}
+ </button>
+ ))}
+ </div>
+ </div>
)}
- {grouped.withGoals.map((area) => (
- <section key={area.slug}>
+ {groups.map((group) => (
+ <section key={group.key}>
<div className="flex flex-wrap items-center justify-between gap-x-3 gap-y-2 mb-3">
<h2 className="text-lg font-semibold text-fg">
- {area.title}{" "}
- <span className="font-normal text-fg-subtle">{area.goals.length}</span>
+ {group.title} <span className="font-normal text-fg-subtle">{group.goals.length}</span>
</h2>
- <StatusDots goals={area.goals} />
+ {by !== "status" && <StatusDots goals={group.goals} />}
</div>
<div className="rounded-2xl border border-line bg-surface-elevated px-5">
- {area.goals.map((goal) => (
+ {group.goals.map((goal) => (
<GoalRow
- key={goal.id}
- slug={area.slug}
+ // Re-mount on a move so the edit form starts from the saved owner.
+ key={`${goal.id}:${goal.owner_id}:${goal.department_slug}`}
+ slug={null}
goal={goal}
- onSaved={(updated) =>
- setDepartments((ds) => applyGoalChange(ds ?? [], { saved: updated }))
- }
- onDeleted={(id) =>
- setDepartments((ds) =>
- applyGoalChange(ds ?? [], { deleted: { slug: area.slug, id } }),
- )
- }
+ meta={metaFor(goal)}
+ owners={ownerOptions}
+ ownerId={goal.owner_id}
+ departments={departments}
+ departmentLabel={solo ? "Area" : "Department"}
+ onSaved={() => reload()}
+ onDeleted={(id) => setGoals((gs) => (gs ?? []).filter((g) => g.id !== id))}
/>
))}
</div>
</section>
))}
- {grouped.empty.length > 0 && total > 0 && (
- <section>
- <h2 className="text-lg font-semibold text-fg mb-1">Other {unit}s</h2>
- <p className="text-[15px] text-fg-muted mb-3">No goals yet. Pick one to add its first goal.</p>
- <div className="flex flex-wrap gap-2">
- {grouped.empty.map((a) => (
- <button
- key={a.slug}
- type="button"
- onClick={() => setAddingTo(a.slug)}
- title={`Add a goal to ${a.title}`}
- className="h-10 px-4 rounded-full border border-line bg-surface-elevated text-[15px] text-fg-muted hover:text-fg hover:border-line-strong transition-colors cursor-pointer"
- >
- + {a.title}
- </button>
- ))}
- </div>
- </section>
+ {!solo && departments.length === 0 && total > 0 && (
+ <div className="rounded-2xl border border-dashed border-line px-5 py-4 text-[15px] text-fg-muted leading-relaxed">
+ No departments yet, and that&apos;s fine: every goal is checked weekly and shows in your brief.{" "}
+ <Link href="/departments" className="text-accent hover:underline">
+ Add a department
+ </Link>{" "}
+ when you want a lead, its own authority and its own check-in for part of the company. The
+ Departments tab appears once you have one.
+ </div>
)}
</div>
)}
@@ -187,11 +231,9 @@ export default function GoalsPage() {
);
}
-// One pill per status present in the area, worst first.
-function StatusDots({ goals }: { goals: DepartmentState["goals"] }) {
- const present = (["off_track", "at_risk", "on_track"] as const).filter((s) =>
- goals.some((g) => g.status === s),
- );
+// One pill per status present in the group, worst first.
+function StatusDots({ goals }: { goals: GoalView[] }) {
+ const present = (["off_track", "at_risk", "on_track"] as const).filter((s) => goals.some((g) => g.status === s));
return (
<div className="flex flex-wrap items-center gap-1.5">
{present.map((s) => (
diff --git a/packages/ui/src/app/people/[id]/page.tsx b/packages/ui/src/app/people/[id]/page.tsx
index 214b117e..c4abcec7 100644
--- a/packages/ui/src/app/people/[id]/page.tsx
+++ b/packages/ui/src/app/people/[id]/page.tsx
@@ -6,7 +6,7 @@ import { type FormEvent, Fragment, type ReactNode, useCallback, useEffect, useId
import Icon from "@/components/Icon";
import { ChatAppPickers } from "@/components/people/ChatAppPickers";
import { PersonContactChanges, PersonContactNote } from "@/components/people/ContactChanges";
-import { TeamModeOffer } from "@/components/people/TeamModeOffer";
+import { TeamModeSwitch } from "@/components/people/TeamModeSwitch";
import { usePageCrumb } from "@/components/shell/PageCrumb";
import Button from "@/components/ui/Button";
import { useChatDirectory, useSlackEmailMatch } from "@/components/ui/ChatPicker";
@@ -38,7 +38,7 @@ import {
} from "@/lib/api";
import { assignNoticeLine } from "@/lib/assignNotice";
import { DETAIL_LABELS, detailHref, detailsToText, detailText, textToDetails } from "@/lib/contactChanges";
-import { isContact, shouldOfferTeamMode } from "@/lib/peopleKinds";
+import { isContact, shouldSwitchToTeam } from "@/lib/peopleKinds";
import { onLeaveLine, reachLine } from "@/lib/personReach";
// ---------------------------------------------------------------------------
@@ -521,7 +521,7 @@ export default function PersonDetailPage() {
const params = useParams();
const router = useRouter();
const { mode } = useWorkspace();
- const [offerFor, setOfferFor] = useState<string | null>(null);
+ const [switchedFor, setSwitchedFor] = useState<string | null>(null);
// Only the principal may move someone between team and contacts (contacts
// are theirs alone); for anyone else the API 404s a contact's page anyway.
const [viewerIsPrincipal, setViewerIsPrincipal] = useState(false);
@@ -716,8 +716,8 @@ export default function PersonDetailPage() {
setPerson(updated);
setEditing(false);
setSaved(true);
- if (wasContact && !isContact(updated) && shouldOfferTeamMode(mode, updated.kind, updated.is_principal)) {
- setOfferFor(updated.full_name);
+ if (wasContact && !isContact(updated) && shouldSwitchToTeam(mode, updated.kind, updated.is_principal)) {
+ setSwitchedFor(updated.full_name);
}
setTimeout(() => setSaved(false), 2500);
} catch (e) {
@@ -764,7 +764,7 @@ export default function PersonDetailPage() {
return (
<div className="flex flex-col h-full bg-surface">
- {offerFor && <TeamModeOffer name={offerFor} onDone={() => setOfferFor(null)} />}
+ {switchedFor && <TeamModeSwitch name={switchedFor} onDone={() => setSwitchedFor(null)} />}
<main className="flex-1 overflow-y-auto">
<div className="max-w-3xl mx-auto px-4 sm:px-6 py-8">
{loading && <p className="text-fg-muted text-[15px]">Loading…</p>}
diff --git a/packages/ui/src/app/people/page.tsx b/packages/ui/src/app/people/page.tsx
index 2a682f7f..4bff9012 100644
--- a/packages/ui/src/app/people/page.tsx
+++ b/packages/ui/src/app/people/page.tsx
@@ -6,7 +6,7 @@ import { type ReactNode, useCallback, useEffect, useId, useRef, useState } from
import { useAskOEFormContext } from "@/components/askoe/AskOEContext";
import { ChatAppPickers } from "@/components/people/ChatAppPickers";
import { ContactChangesCard, ContactKeeperSwitch } from "@/components/people/ContactChanges";
-import { TeamModeOffer } from "@/components/people/TeamModeOffer";
+import { TeamModeSwitch } from "@/components/people/TeamModeSwitch";
import Button from "@/components/ui/Button";
import { useChatDirectory, useSlackEmailMatch } from "@/components/ui/ChatPicker";
import SectionTabs, { sectionPanelProps } from "@/components/ui/SectionTabs";
@@ -31,7 +31,7 @@ import {
isContact,
peopleForTab,
personCardStatus,
- shouldOfferTeamMode,
+ shouldSwitchToTeam,
tabsFor,
type PeopleTab,
} from "@/lib/peopleKinds";
@@ -572,7 +572,7 @@ export default function PeoplePage() {
const [error, setError] = useState<string | null>(null);
const [showAdd, setShowAdd] = useState(false);
const [tab, setTab] = useState<PeopleTab | null>(null);
- const [offerFor, setOfferFor] = useState<string | null>(null);
+ const [switchedFor, setSwitchedFor] = useState<string | null>(null);
// Contacts are private to the principal. Until the viewer is known (or if
// the check fails) nobody is offered them; the API enforces it regardless.
const [viewerIsPrincipal, setViewerIsPrincipal] = useState(false);
@@ -637,12 +637,12 @@ export default function PeoplePage() {
setShowAdd(false);
// Show the new row where it lives.
setTab(isContact(p) ? "contacts" : "team");
- if (shouldOfferTeamMode(mode, p.kind ?? "team", p.is_principal)) setOfferFor(p.full_name);
+ if (shouldSwitchToTeam(mode, p.kind ?? "team", p.is_principal)) setSwitchedFor(p.full_name);
}}
onClose={() => setShowAdd(false)}
/>
)}
- {offerFor && <TeamModeOffer name={offerFor} onDone={() => setOfferFor(null)} />}
+ {switchedFor && <TeamModeSwitch name={switchedFor} onDone={() => setSwitchedFor(null)} />}
<main className="flex-1 overflow-y-auto">
<div className="max-w-5xl mx-auto px-4 sm:px-6 py-8">
<div className="flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between mb-6">
diff --git a/packages/ui/src/components/briefing/TeamPanels.tsx b/packages/ui/src/components/briefing/TeamPanels.tsx
index d0e6bdbf..cc68ca09 100644
--- a/packages/ui/src/components/briefing/TeamPanels.tsx
+++ b/packages/ui/src/components/briefing/TeamPanels.tsx
@@ -27,7 +27,8 @@ export function DeptCard({
<ClickableBriefingItem
onContinue={onContinue}
prompt={prompt}
- href={`/departments/${dept.slug}`}
+ // The row of goals with no department (slug "") lives on /goals.
+ href={dept.slug ? `/departments/${dept.slug}` : "/goals"}
className={`block group rounded-xl -mx-2 px-2 py-3.5 hover:bg-surface-overlay transition-colors${dimmed ? " opacity-60 hover:opacity-100" : ""}`}
>
<div className="flex items-start justify-between gap-2 mb-2">
@@ -60,6 +61,7 @@ export function DeptCard({
{(g.current || g.target) && (
<span className="text-fg-subtle"> — {g.current || "—"} vs {g.target || "—"}</span>
)}
+ {g.owner_name && <span className="text-fg-subtle"> · {g.owner_name}</span>}
</span>
</div>
))}
diff --git a/packages/ui/src/components/goals/GoalEditor.tsx b/packages/ui/src/components/goals/GoalEditor.tsx
index 659d2186..8b2dbc98 100644
--- a/packages/ui/src/components/goals/GoalEditor.tsx
+++ b/packages/ui/src/components/goals/GoalEditor.tsx
@@ -8,16 +8,21 @@ import OverflowMenu from "@/components/ui/OverflowMenu";
import {
createGoal,
createGoalInArea,
+ deleteAnyGoal,
deleteGoal,
+ updateAnyGoal,
updateGoal,
type Goal,
+ type GoalPatch,
type PeriodType,
} from "@/lib/api";
import { formatRelativeTime } from "@/lib/relativeTime";
// Goal rows (view / edit / delete) and the add-goal form, shared by a
-// department's page and /goals. Goals belong to a department — an "area" in
-// solo mode — and every call here is scoped by its slug.
+// department's page and /goals. A goal has an owner and, optionally, a
+// department (an "area" in solo mode). On a department's page every call is
+// scoped by its slug; on /goals (slug null) they go to the department-free
+// goal routes, which can also change a goal's owner and department.
// "Last reviewed >N days ago" → render the row with a stale accent.
// A new department checks in weekly (`weekly@mon@09:00`), so a healthy goal
@@ -89,9 +94,31 @@ function formKeys(onSubmit: () => void, onCancel: () => void, saving: boolean) {
// Goal row — view or edit
// ---------------------------------------------------------------------------
-interface GoalRowProps {
+/** A person a goal can be on, for the owner pickers. */
+export interface OwnerOption {
+ id: number;
+ name: string;
+}
+
+/** A department a goal can be in, for the department pickers. */
+export interface DepartmentOption {
slug: string;
+ title: string;
+}
+
+interface GoalRowProps {
+ /** The department whose page this is, or null on /goals. */
+ slug: string | null;
goal: Goal;
+ /** One line under the goal, e.g. "Dan · Sales" (on /goals). */
+ meta?: string;
+ /** With slug null: the edit form also picks the owner and department. */
+ owners?: OwnerOption[];
+ /** The goal's owner as shown (its own, else its lead's or the principal's). */
+ ownerId?: number | null;
+ departments?: DepartmentOption[];
+ /** "Department" (team) or "Area" (solo). */
+ departmentLabel?: string;
onSaved: (updated: Goal) => void;
onDeleted: (id: number) => void;
// Surface edit-mode transitions so the parent can pause polling — a
@@ -111,7 +138,18 @@ export function formatGoalProgress(g: Pick<Goal, "target" | "current">): string
return g.current ? `Current: ${g.current}` : "";
}
-export function GoalRow({ slug, goal, onSaved, onDeleted, onEditingChange }: GoalRowProps) {
+export function GoalRow({
+ slug,
+ goal,
+ meta,
+ owners,
+ ownerId = null,
+ departments,
+ departmentLabel = "Department",
+ onSaved,
+ onDeleted,
+ onEditingChange,
+}: GoalRowProps) {
const [editing, setEditing] = useState(false);
const [saving, setSaving] = useState(false);
const [deleting, setDeleting] = useState(false);
@@ -124,6 +162,10 @@ export function GoalRow({ slug, goal, onSaved, onDeleted, onEditingChange }: Goa
current: goal.current,
status: goal.status as GoalStatus,
});
+ // Owner and department, editable on /goals only. "" = no department.
+ const [owner, setOwner] = useState<number | null>(ownerId);
+ const [dept, setDept] = useState(goal.department_slug ?? "");
+ const canMove = slug === null;
// Centralise the editing transition so save/cancel/enter all notify
// the parent — avoids forgetting the call in one branch.
@@ -159,7 +201,8 @@ export function GoalRow({ slug, goal, onSaved, onDeleted, onEditingChange }: Goa
setDeleting(true);
setErr(null);
try {
- await deleteGoal(slug, goal.id!);
+ if (slug === null) await deleteAnyGoal(goal.id!);
+ else await deleteGoal(slug, goal.id!);
onDeleted(goal.id!);
} catch (e) {
setErr(e instanceof Error ? e.message : "Delete failed");
@@ -176,6 +219,7 @@ export function GoalRow({ slug, goal, onSaved, onDeleted, onEditingChange }: Goa
<div className="flex-1 min-w-0">
<div className="text-base text-fg font-medium leading-snug">{goal.key_result}</div>
{progress && <div className="text-[15px] text-fg-muted mt-1">{progress}</div>}
+ {meta && <div className="text-sm text-fg-muted mt-1">{meta}</div>}
<div className="text-sm text-fg-subtle mt-2 flex items-center gap-x-2 gap-y-1.5 flex-wrap">
<GoalStatusPill status={goal.status} />
<span>{formatGoalPeriod(goal)}</span>
@@ -214,6 +258,8 @@ export function GoalRow({ slug, goal, onSaved, onDeleted, onEditingChange }: Goa
current: goal.current,
status: goal.status as GoalStatus,
});
+ setOwner(ownerId);
+ setDept(goal.department_slug ?? "");
setEditingAndNotify(false);
setErr(null);
}
@@ -223,13 +269,22 @@ export function GoalRow({ slug, goal, onSaved, onDeleted, onEditingChange }: Goa
setSaving(true);
setErr(null);
try {
- const updated = await updateGoal(slug, goal.id!, {
+ const patch: GoalPatch = {
...form,
key_result: form.key_result.trim(),
period_value: form.period_value.trim(),
target: form.target.trim(),
current: form.current.trim(),
- });
+ };
+ let updated: Goal;
+ if (slug === null) {
+ // Only what changed, so an untouched owner keeps following its lead.
+ if (owner !== ownerId) patch.owner_person_id = owner;
+ if (dept !== (goal.department_slug ?? "")) patch.department_slug = dept || null;
+ updated = await updateAnyGoal(goal.id!, patch);
+ } else {
+ updated = await updateGoal(slug, goal.id!, patch);
+ }
onSaved(updated);
setEditingAndNotify(false);
} catch (e) {
@@ -259,6 +314,36 @@ export function GoalRow({ slug, goal, onSaved, onDeleted, onEditingChange }: Goa
onChange={(pt, pv) => setForm((f) => ({ ...f, period_type: pt, period_value: pv }))}
size="compact"
/>
+ {canMove && owners && owners.length > 1 && (
+ <label className={LABEL_CLS}>
+ Owner
+ <select
+ value={owner ?? ""}
+ onChange={(e) => setOwner(e.target.value ? Number(e.target.value) : null)}
+ className={INPUT_CLS}
+ >
+ {owner == null && <option value="">No owner yet</option>}
+ {owners.map((o) => (
+ <option key={o.id} value={o.id}>
+ {o.name}
+ </option>
+ ))}
+ </select>
+ </label>
+ )}
+ {canMove && departments && departments.length > 0 && (
+ <label className={LABEL_CLS}>
+ {departmentLabel}
+ <select value={dept} onChange={(e) => setDept(e.target.value)} className={INPUT_CLS}>
+ <option value="">None</option>
+ {departments.map((d) => (
+ <option key={d.slug} value={d.slug}>
+ {d.title}
+ </option>
+ ))}
+ </select>
+ </label>
+ )}
<label className={LABEL_CLS}>
Status
<select
@@ -311,26 +396,44 @@ export function GoalRow({ slug, goal, onSaved, onDeleted, onEditingChange }: Goa
// ---------------------------------------------------------------------------
interface AddGoalFormProps {
- /** The department (area) the goal is added to — the picker's first choice
- * when `areas` is set. Null when there is no area yet: the form then asks
- * for one by name and the save creates it. */
+ /** The department whose page this is: the goal goes there. Null on /goals,
+ * where the form picks an owner and, optionally, a department. */
slug: string | null;
- /** When set, a picker over these lets the user choose where the goal goes. */
- areas?: { slug: string; title: string }[];
- /** The picker's label: "Area" (solo) or "Department" (team). */
+ /** /goals: the departments to pick from ("None" and "New…" are added). */
+ departments?: DepartmentOption[];
+ /** /goals: the people a goal can be on; the picker shows for two or more. */
+ owners?: OwnerOption[];
+ /** /goals: the owner picked at first (the viewer). */
+ defaultOwnerId?: number | null;
+ /** The department picker's label: "Area" (solo) or "Department" (team). */
areaLabel?: string;
+ /** Titled as the first goal, with a line on how little it takes. */
+ first?: boolean;
onCreated: (goal: Goal) => void;
/** Omitted when the form is the page's only content (no Cancel then). */
onCancel?: () => void;
}
+// The "New…" choice in the department picker.
+const NEW_DEPARTMENT = "__new__";
+
// One thing to type — the goal. The timeframe is a chip (this quarter by
// default), target and current are optional, and a new goal starts on track
-// until the department's check-in grades it.
-export function AddGoalForm({ slug, areas, areaLabel = "Area", onCreated, onCancel }: AddGoalFormProps) {
- const [areaSlug, setAreaSlug] = useState(slug);
- // Typed area name, used only when there is no area to pick from.
- const [areaName, setAreaName] = useState("");
+// until its check-in (or the weekly goal review) grades it.
+export function AddGoalForm({
+ slug,
+ departments = [],
+ owners = [],
+ defaultOwnerId = null,
+ areaLabel = "Department",
+ first = false,
+ onCreated,
+ onCancel,
+}: AddGoalFormProps) {
+ // "" = no department; NEW_DEPARTMENT = the typed name below.
+ const [deptChoice, setDeptChoice] = useState("");
+ const [newDept, setNewDept] = useState("");
+ const [ownerId, setOwnerId] = useState<number | null>(defaultOwnerId ?? owners[0]?.id ?? null);
const [form, setForm] = useState<{
period_type: PeriodType;
period_value: string;
@@ -352,7 +455,10 @@ export function AddGoalForm({ slug, areas, areaLabel = "Area", onCreated, onCanc
firstRef.current?.focus();
}, []);
- const canSubmit = !saving && form.key_result.trim() !== "";
+ const canSubmit =
+ !saving &&
+ form.key_result.trim() !== "" &&
+ (deptChoice !== NEW_DEPARTMENT || newDept.trim() !== "");
async function submit() {
if (!canSubmit) return;
@@ -368,7 +474,16 @@ export function AddGoalForm({ slug, areas, areaLabel = "Area", onCreated, onCanc
...(target && { target }),
...(current && { current }),
};
- const goal = areaSlug ? await createGoal(areaSlug, body) : await createGoalInArea(areaName.trim(), body);
+ let goal: Goal;
+ if (slug) {
+ goal = await createGoal(slug, body);
+ } else {
+ const area = deptChoice === NEW_DEPARTMENT ? newDept.trim() : deptChoice;
+ goal = await createGoalInArea(area, {
+ ...body,
+ ...(owners.length > 1 && ownerId != null && { owner_person_id: ownerId }),
+ });
+ }
onCreated(goal);
} catch (e) {
setErr(e instanceof Error ? e.message : "Create failed");
@@ -381,13 +496,15 @@ export function AddGoalForm({ slug, areas, areaLabel = "Area", onCreated, onCanc
return (
<div className="py-5 space-y-4">
- {slug ? (
- <div className="text-base font-semibold text-fg">New goal</div>
- ) : (
+ {first ? (
<div>
<div className="text-base font-semibold text-fg">Add your first goal</div>
- <p className="mt-1 text-[15px] text-fg-muted">Just type it. The timeframe defaults to this quarter.</p>
+ <p className="mt-1 text-[15px] text-fg-muted">
+ Just type it. The timeframe defaults to this quarter, and I&apos;ll check it weekly.
+ </p>
</div>
+ ) : (
+ <div className="text-base font-semibold text-fg">New goal</div>
)}
<label className={LABEL_CLS}>
What&apos;s the goal?
@@ -401,35 +518,50 @@ export function AddGoalForm({ slug, areas, areaLabel = "Area", onCreated, onCanc
placeholder={GOAL_PLACEHOLDER}
/>
</label>
- {!areaSlug && (
- <label className={LABEL_CLS}>
- {areaLabel} (optional)
- <input
- value={areaName}
- onChange={(e) => setAreaName(e.target.value)}
- onKeyDown={onKeyDown}
- maxLength={80}
- className={INPUT_CLS}
- placeholder="e.g. Sales or Product"
- />
- <span className="mt-1 block text-sm text-fg-muted">Left blank, it goes under General.</span>
- </label>
- )}
- {areas && areas.length > 1 && (
- <label className={LABEL_CLS}>
- {areaLabel}
- <select
- value={areaSlug ?? ""}
- onChange={(e) => setAreaSlug(e.target.value)}
- className={INPUT_CLS}
- >
- {areas.map((a) => (
- <option key={a.slug} value={a.slug}>
- {a.title}
- </option>
- ))}
- </select>
- </label>
+ {!slug && (
+ <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
+ {owners.length > 1 && (
+ <label className={LABEL_CLS}>
+ Owner
+ <select
+ value={ownerId ?? ""}
+ onChange={(e) => setOwnerId(e.target.value ? Number(e.target.value) : null)}
+ className={INPUT_CLS}
+ >
+ {owners.map((o) => (
+ <option key={o.id} value={o.id}>
+ {o.name}
+ </option>
+ ))}
+ </select>
+ </label>
+ )}
+ <label className={LABEL_CLS}>
+ {areaLabel} (optional)
+ <select value={deptChoice} onChange={(e) => setDeptChoice(e.target.value)} className={INPUT_CLS}>
+ <option value="">None</option>
+ {departments.map((d) => (
+ <option key={d.slug} value={d.slug}>
+ {d.title}
+ </option>
+ ))}
+ <option value={NEW_DEPARTMENT}>New {areaLabel.toLowerCase()}…</option>
+ </select>
+ </label>
+ {deptChoice === NEW_DEPARTMENT && (
+ <label className={cls(LABEL_CLS, "sm:col-span-2")}>
+ New {areaLabel.toLowerCase()}&apos;s name
+ <input
+ value={newDept}
+ onChange={(e) => setNewDept(e.target.value)}
+ onKeyDown={onKeyDown}
+ maxLength={80}
+ className={INPUT_CLS}
+ placeholder="e.g. Sales or Product"
+ />
+ </label>
+ )}
+ </div>
)}
<TimeframeChips
periodType={form.period_type}
diff --git a/packages/ui/src/components/people/TeamModeOffer.tsx b/packages/ui/src/components/people/TeamModeOffer.tsx
deleted file mode 100644
index 4849752a..00000000
--- a/packages/ui/src/components/people/TeamModeOffer.tsx
+++ /dev/null
@@ -1,64 +0,0 @@
-"use client";
-
-import { useState } from "react";
-
-import { useWorkspace } from "@/components/workspace/WorkspaceContext";
-import { updateWorkspace } from "@/lib/api";
-
-// Shown after a team member is added (or a contact moved onto the team) while
-// Open Executive is used just for yourself: a team now exists, so offer to
-// switch the workspace to team mode — or keep it as it is.
-export function TeamModeOffer({ name, onDone }: { name: string; onDone: () => void }) {
- const { refresh } = useWorkspace();
- const [busy, setBusy] = useState(false);
- const [err, setErr] = useState<string | null>(null);
-
- async function switchToTeam() {
- setBusy(true);
- setErr(null);
- try {
- await updateWorkspace({ mode: "team" });
- await refresh();
- onDone();
- } catch (e) {
- setErr(e instanceof Error ? e.message : "Could not switch to team mode");
- setBusy(false);
- }
- }
-
- return (
- <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60">
- <div
- role="alertdialog"
- aria-labelledby="team-mode-offer-title"
- className="w-full max-w-md bg-surface border border-line rounded-2xl shadow-2xl p-6 mx-4"
- >
- <h2 id="team-mode-offer-title" className="text-base font-semibold text-fg mb-2">
- Switch to team mode?
- </h2>
- <p className="text-sm text-fg-muted mb-4">
- {name} is now on your team. Team mode turns on departments, check-ins and the team
- pages, so the Executive can work with them. If you keep using Open Executive just for
- yourself, {name} stays on your team but you won&apos;t see the team features.
- </p>
- {err && <p className="text-xs text-rose-300 mb-3">{err}</p>}
- <div className="flex gap-2">
- <button
- disabled={busy}
- onClick={switchToTeam}
- className="flex-1 py-2 text-sm rounded-lg bg-indigo-600 hover:bg-indigo-500 text-white disabled:opacity-50 font-medium"
- >
- {busy ? "Switching…" : "Switch to team mode"}
- </button>
- <button
- disabled={busy}
- onClick={onDone}
- className="px-4 py-2 text-sm rounded-lg border border-line hover:bg-surface-overlay disabled:opacity-50"
- >
- Keep it just for me
- </button>
- </div>
- </div>
- </div>
- );
-}
diff --git a/packages/ui/src/components/people/TeamModeSwitch.tsx b/packages/ui/src/components/people/TeamModeSwitch.tsx
new file mode 100644
index 00000000..a9ca927f
--- /dev/null
+++ b/packages/ui/src/components/people/TeamModeSwitch.tsx
@@ -0,0 +1,61 @@
+"use client";
+
+import Link from "next/link";
+import { useEffect, useRef, useState } from "react";
+
+import { useWorkspace } from "@/components/workspace/WorkspaceContext";
+import { updateWorkspace } from "@/lib/api";
+
+// Shown after a team member is added (or a contact moved onto the team) while
+// Open Executive is used just for yourself: a team now exists, so the
+// workspace switches to team mode on its own, without asking, and this says
+// so. Workspace settings can switch it back.
+export function TeamModeSwitch({ name, onDone }: { name: string; onDone: () => void }) {
+ const { refresh } = useWorkspace();
+ const [state, setState] = useState<"switching" | "done" | "failed">("switching");
+ // Once per mount, even under React's double-invoked effects in dev.
+ const started = useRef(false);
+
+ useEffect(() => {
+ if (started.current) return;
+ started.current = true;
+ updateWorkspace({ mode: "team" })
+ .then(() => refresh())
+ .then(() => setState("done"))
+ .catch(() => setState("failed"));
+ }, [refresh]);
+
+ if (state === "switching") return null;
+ return (
+ <div
+ role="status"
+ className="fixed bottom-4 left-4 right-4 z-50 mx-auto max-w-md rounded-2xl border border-line bg-surface p-4 shadow-2xl sm:left-auto sm:right-6"
+ >
+ <p className="text-[15px] text-fg">
+ {state === "done" ? (
+ <>
+ {name} is on your team, so this is now a team workspace: departments, check-ins and the
+ team pages are on.
+ </>
+ ) : (
+ <>
+ {name} is on your team, but the workspace couldn&apos;t switch to team mode. You can switch
+ it in Workspace settings.
+ </>
+ )}
+ </p>
+ <div className="mt-3 flex items-center gap-4">
+ <button
+ type="button"
+ onClick={onDone}
+ className="h-10 rounded-lg bg-indigo-600 px-4 text-sm font-medium text-white hover:bg-indigo-500"
+ >
+ OK
+ </button>
+ <Link href="/settings/workspace" onClick={onDone} className="text-sm text-accent hover:underline">
+ {state === "done" ? "Change in Workspace settings" : "Workspace settings"}
+ </Link>
+ </div>
+ </div>
+ );
+}
diff --git a/packages/ui/src/components/shell/AppShell.tsx b/packages/ui/src/components/shell/AppShell.tsx
index a3bb7711..b578da59 100644
--- a/packages/ui/src/components/shell/AppShell.tsx
+++ b/packages/ui/src/components/shell/AppShell.tsx
@@ -113,7 +113,7 @@ function useFirstRunGate(pathname: string): boolean {
export default function AppShell({ children }: { children: React.ReactNode }) {
const pathname = usePathname() ?? "/";
const [drawerOpen, setDrawerOpen] = useState(false);
- const { mode, role } = useWorkspace();
+ const { mode, role, hasDepartments } = useWorkspace();
const redirecting = useFirstRunGate(pathname);
if (isExempt(pathname)) {
@@ -124,7 +124,7 @@ export default function AppShell({ children }: { children: React.ReactNode }) {
}
const segments = pathname.split("/").filter(Boolean);
- const hub = hubForPath(pathname, { mode, roleKind: role.role_kind });
+ const hub = hubForPath(pathname, { mode, roleKind: role.role_kind, hasDepartments });
return (
<AskOEProvider>
diff --git a/packages/ui/src/components/shell/AppSidebar.tsx b/packages/ui/src/components/shell/AppSidebar.tsx
index 2396d05a..77dc4402 100644
--- a/packages/ui/src/components/shell/AppSidebar.tsx
+++ b/packages/ui/src/components/shell/AppSidebar.tsx
@@ -57,7 +57,7 @@ export default function AppSidebar({
companyName,
home,
}: AppSidebarProps) {
- const { mode, role } = useWorkspace();
+ const { mode, role, hasDepartments } = useWorkspace();
const [reviewBadge, setReviewBadge] = useState(0);
// Knowledge base badge: items waiting in its review queue. Refetched on
@@ -69,7 +69,13 @@ export default function AppSidebar({
.catch(() => {});
}, [pathname]);
- const destinations = buildDestinations({ isOnboarded, reviewBadge, mode, roleKind: role.role_kind });
+ const destinations = buildDestinations({
+ isOnboarded,
+ reviewBadge,
+ mode,
+ roleKind: role.role_kind,
+ hasDepartments,
+ });
const newChatActive = home ? home.mode === "chat" && home.activeSessionId === undefined : false;
return (
diff --git a/packages/ui/src/components/shell/navConfig.ts b/packages/ui/src/components/shell/navConfig.ts
index 70cf9fe4..89b21fb8 100644
--- a/packages/ui/src/components/shell/navConfig.ts
+++ b/packages/ui/src/components/shell/navConfig.ts
@@ -48,6 +48,13 @@ interface BuildOpts {
* but the principal).
*/
roleKind?: RoleKind | null;
+ /**
+ * Whether any department exists. A team's Departments tab shows only then:
+ * goals stand on their own, so a team may never need one (it is reached
+ * from the Goals page's "Add a department"). Defaults to true, so a caller
+ * that doesn't know keeps the tab.
+ */
+ hasDepartments?: boolean;
}
// What the profile at /company-profile is called. A team's is its company.
@@ -111,19 +118,24 @@ const GOALS_ITEM: NavItem = {
// The Company hub's tabs in a team: who's on it, what you're aiming for,
// how it's organised, and the profile.
-function companyTabs(isOnboarded: boolean): NavItem[] {
+function companyTabs(isOnboarded: boolean, hasDepartments: boolean): NavItem[] {
return [
{ href: "/people", label: "People", icon: "users", description: PEOPLE_DESCRIPTION },
{
...GOALS_ITEM,
- description: "Every department's goals in one place — add, update and close them.",
- },
- {
- href: "/departments",
- label: "Departments",
- icon: "grid",
- description: "Your departments, their goals, how much each may decide on its own, and the expert behind each.",
+ description: "Every goal in one place, by owner, department or status — add, update and close them.",
},
+ ...(hasDepartments
+ ? [
+ {
+ href: "/departments",
+ label: "Departments",
+ icon: "grid",
+ description:
+ "Your departments, their goals, how much each may decide on its own, and the expert behind each.",
+ } satisfies NavItem,
+ ]
+ : []),
profileItem("company", isOnboarded),
];
}
@@ -210,6 +222,7 @@ export function buildHubs({
isOnboarded = true,
mode = "team",
roleKind = null,
+ hasDepartments = true,
}: BuildOpts = {}): Hub[] {
const work: Hub = {
key: "work",
@@ -232,7 +245,7 @@ export function buildHubs({
label: "Company",
icon: "building",
description: "People, goals, departments and the company profile.",
- tabs: companyTabs(isOnboarded),
+ tabs: companyTabs(isOnboarded, hasDepartments),
};
const delegate: Hub = {
key: "delegate",
@@ -246,8 +259,11 @@ export function buildHubs({
// The hub a page belongs to, or null for a page that isn't in one.
export function hubForPath(pathname: string, opts: BuildOpts = {}): Hub | null {
+ // On the Departments pages the tab shows even before the first department
+ // exists: that is where it gets added.
+ const withTab = isNavActive("/departments", pathname) ? { ...opts, hasDepartments: true } : opts;
return (
- buildHubs(opts).find((hub) => hub.tabs.some((tab) => isNavActive(tab.href, pathname))) ?? null
+ buildHubs(withTab).find((hub) => hub.tabs.some((tab) => isNavActive(tab.href, pathname))) ?? null
);
}
@@ -274,8 +290,9 @@ export function buildDestinations({
reviewBadge = 0,
mode = "team",
roleKind = null,
+ hasDepartments = true,
}: BuildOpts = {}): Destination[] {
- const hubs = buildHubs({ isOnboarded, mode, roleKind });
+ const hubs = buildHubs({ isOnboarded, mode, roleKind, hasDepartments });
const hubEntry = (hub: Hub): Destination => ({
key: hub.key,
href: hub.tabs[0].href,
diff --git a/packages/ui/src/components/workspace/WorkspaceContext.tsx b/packages/ui/src/components/workspace/WorkspaceContext.tsx
index 625b5020..8b6ddb79 100644
--- a/packages/ui/src/components/workspace/WorkspaceContext.tsx
+++ b/packages/ui/src/components/workspace/WorkspaceContext.tsx
@@ -21,6 +21,9 @@ interface WorkspaceContextValue {
effectiveTimezone: string | null;
/** The principal's role (solo mode reads it); every field null until set. */
role: PrincipalRole;
+ /** Whether any department exists (the Departments tab shows only then).
+ * True while loading, so a team with departments never loses the tab. */
+ hasDepartments: boolean;
/** True until the first request settles (either way). */
loading: boolean;
/** Re-read the settings, e.g. after Settings or onboarding changed them. */
@@ -43,6 +46,7 @@ export function WorkspaceProvider({ children }: { children: React.ReactNode }) {
const [timezone, setTimezone] = useState<string | null>(null);
const [effectiveTimezone, setEffectiveTimezone] = useState<string | null>(null);
const [role, setRole] = useState<PrincipalRole>(NO_ROLE);
+ const [hasDepartments, setHasDepartments] = useState(true);
const [loading, setLoading] = useState(true);
// Only the latest request may write: a slow first read must not overwrite
// the answer to a refresh() issued after a change.
@@ -56,6 +60,7 @@ export function WorkspaceProvider({ children }: { children: React.ReactNode }) {
setMode(ws.mode === "solo" ? "solo" : "team");
setTimezone(ws.timezone);
setEffectiveTimezone(ws.effective_timezone);
+ setHasDepartments(ws.has_departments ?? true);
setRole({
role_kind: ws.role_kind ?? null,
role_title: ws.role_title ?? null,
@@ -81,8 +86,8 @@ export function WorkspaceProvider({ children }: { children: React.ReactNode }) {
}, [authStatus, refresh]);
const value = useMemo(
- () => ({ mode, timezone, effectiveTimezone, role, loading, refresh }),
- [mode, timezone, effectiveTimezone, role, loading, refresh],
+ () => ({ mode, timezone, effectiveTimezone, role, hasDepartments, loading, refresh }),
+ [mode, timezone, effectiveTimezone, role, hasDepartments, loading, refresh],
);
return <WorkspaceContext.Provider value={value}>{children}</WorkspaceContext.Provider>;
}
diff --git a/packages/ui/src/lib/api.ts b/packages/ui/src/lib/api.ts
index 5e6b5e55..5ea7366b 100644
--- a/packages/ui/src/lib/api.ts
+++ b/packages/ui/src/lib/api.ts
@@ -1829,6 +1829,9 @@ export interface WorkspaceSettings extends PrincipalRole {
// principal's addresses unless `company_domains_custom`.
company_domains?: string[];
company_domains_custom?: boolean;
+ // Whether any department exists; the Departments tab shows only then.
+ // Optional so an older API build reads as "yes" (the tab stays).
+ has_departments?: boolean;
}
// Partial update: only the fields present change. `timezone: null` (or "")
@@ -4385,7 +4388,10 @@ export type PeriodType = "week" | "month" | "quarter" | "year" | "ongoing";
export interface Goal {
id: number | null;
- department_slug: string;
+ // Null for a goal with no department: it stands on its own.
+ department_slug: string | null;
+ // Who it is on when set; null = its department's lead, else the principal.
+ owner_person_id?: number | null;
period_type: PeriodType;
period_value: string;
key_result: string;
@@ -4485,6 +4491,22 @@ export interface GoalCreate {
target?: string;
current?: string;
status?: Goal["status"];
+ owner_person_id?: number | null;
+}
+
+/** A goal as GET /goals returns it: its owner and department resolved. */
+export interface GoalView extends Goal {
+ // Its own owner, else its department's lead, else the principal.
+ owner_id: number | null;
+ owner_name: string;
+ department_title: string | null;
+}
+
+/** Every goal, with or without a department. */
+export async function listGoals(): Promise<GoalView[]> {
+ const res = await fetch(`${API_BASE}/goals`, { cache: "no-store" });
+ if (!res.ok) throw await goalError(res, "Couldn't load goals");
+ return res.json();
}
// The server's reason when it gives one — a string `detail`, or the first
@@ -4511,8 +4533,8 @@ export async function createGoal(slug: string, body: GoalCreate): Promise<Goal>
return res.json();
}
-/** Add a goal by area name: an existing area by slug or title, else a new
- * one of that name, else (blank) "General". For a workspace with no areas. */
+/** Add a goal, naming its department in words: an existing one by slug or
+ * title, else a new one of that name. Blank = no department. */
export async function createGoalInArea(area: string, body: GoalCreate): Promise<Goal> {
const res = await fetch(`${API_BASE}/goals`, {
method: "POST",
@@ -4530,6 +4552,25 @@ export interface GoalPatch {
target?: string;
current?: string;
status?: Goal["status"];
+ // Only through updateAnyGoal. null clears: no owner of its own / no department.
+ owner_person_id?: number | null;
+ department_slug?: string | null;
+}
+
+/** Edit a goal wherever it is, including its owner and department. */
+export async function updateAnyGoal(goalId: number, patch: GoalPatch): Promise<Goal> {
+ const res = await fetch(`${API_BASE}/goals/${goalId}`, {
+ method: "PATCH",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(patch),
+ });
+ if (!res.ok) throw await goalError(res, "Couldn't save the goal");
+ return res.json();
+}
+
+export async function deleteAnyGoal(goalId: number): Promise<void> {
+ const res = await fetch(`${API_BASE}/goals/${goalId}`, { method: "DELETE" });
+ if (!res.ok) throw new Error(`Failed to delete Goal: ${res.statusText}`);
}
export async function updateGoal(slug: string, goalId: number, patch: GoalPatch): Promise<Goal> {
@@ -5022,9 +5063,14 @@ export interface GoalBrief {
current: string;
target: string;
status: string; // "at_risk" | "off_track"
+ // Who it is on (its own owner, else the department's lead, else the
+ // principal). Optional for older API builds.
+ owner_id?: number | null;
+ owner_name?: string;
}
export interface DepartmentBriefItem {
+ // "" for the row holding the goals with no department ("Other goals").
slug: string;
title: string;
authority_level: string;
diff --git a/packages/ui/src/lib/goalAreas.ts b/packages/ui/src/lib/goalAreas.ts
deleted file mode 100644
index 758701f2..00000000
--- a/packages/ui/src/lib/goalAreas.ts
+++ /dev/null
@@ -1,70 +0,0 @@
-// /goals groups every goal by its area. An area is a department row under the
-// hood — solo mode calls it an area — so this reads GET /departments, whose
-// rows carry their goals.
-//
-// Type-only imports, so `npm test` can exercise this under
-// `node --experimental-strip-types` (see scripts/goalAreas.test.mjs).
-
-import type { DepartmentState, Goal } from "@/lib/api";
-
-export interface AreaRef {
- slug: string;
- title: string;
-}
-
-export interface GoalArea extends AreaRef {
- goals: Goal[];
-}
-
-export interface GoalAreas {
- /** Areas that have goals, in the order the API returned them. */
- withGoals: GoalArea[];
- /** Areas with no goals yet, by title — offered as places to add one. */
- empty: AreaRef[];
- /** Every area, by title — the add-goal form's picker. */
- all: AreaRef[];
- /** Goals per status across every area. */
- counts: Record<Goal["status"], number>;
-}
-
-const byTitle = (a: AreaRef, b: AreaRef) => a.title.localeCompare(b.title);
-
-export function groupGoalsByArea(departments: DepartmentState[]): GoalAreas {
- const counts: GoalAreas["counts"] = { on_track: 0, at_risk: 0, off_track: 0 };
- const withGoals: GoalArea[] = [];
- const empty: AreaRef[] = [];
- for (const d of departments) {
- const ref = { slug: d.config.slug, title: d.config.title };
- if (d.goals.length === 0) {
- empty.push(ref);
- continue;
- }
- withGoals.push({ ...ref, goals: d.goals });
- for (const g of d.goals) {
- if (g.status in counts) counts[g.status] += 1;
- }
- }
- const all = departments.map((d) => ({ slug: d.config.slug, title: d.config.title })).sort(byTitle);
- return { withGoals, empty: empty.sort(byTitle), all, counts };
-}
-
-/** `departments` with `goal` added to, replaced in, or (by id) removed from its area. */
-export function applyGoalChange(
- departments: DepartmentState[],
- change: { saved: Goal } | { deleted: { slug: string; id: number } },
-): DepartmentState[] {
- return departments.map((d) => {
- if ("saved" in change) {
- const goal = change.saved;
- if (d.config.slug !== goal.department_slug) return d;
- const exists = d.goals.some((g) => g.id === goal.id);
- return {
- ...d,
- goals: exists ? d.goals.map((g) => (g.id === goal.id ? goal : g)) : [...d.goals, goal],
- };
- }
- const { slug, id } = change.deleted;
- if (d.config.slug !== slug) return d;
- return { ...d, goals: d.goals.filter((g) => g.id !== id) };
- });
-}
diff --git a/packages/ui/src/lib/goalGroups.ts b/packages/ui/src/lib/goalGroups.ts
new file mode 100644
index 00000000..720600ec
--- /dev/null
+++ b/packages/ui/src/lib/goalGroups.ts
@@ -0,0 +1,76 @@
+// /goals lists every goal (GET /goals) grouped by owner, department or
+// status. Goals stand on their own: a department is optional, so a goal with
+// none groups under "No department" ("No area" in solo).
+//
+// Type-only imports, so `npm test` can exercise this under
+// `node --experimental-strip-types` (see scripts/goalGroups.test.mjs).
+
+import type { Goal, GoalView } from "@/lib/api";
+
+export type GoalGrouping = "owner" | "department" | "status";
+
+export interface GoalGroup {
+ key: string;
+ title: string;
+ goals: GoalView[];
+}
+
+export interface GroupOpts {
+ /** The viewer's person id: their group comes first, titled "<name> (you)". */
+ viewerId?: number | null;
+ /** What a department is called: "department" (team) or "area" (solo). */
+ unit?: "department" | "area";
+}
+
+const STATUS_ORDER: Goal["status"][] = ["off_track", "at_risk", "on_track"];
+const STATUS_TITLE: Record<Goal["status"], string> = {
+ off_track: "Off track",
+ at_risk: "At risk",
+ on_track: "On track",
+};
+
+const byId = (a: GoalView, b: GoalView) => (a.id ?? 0) - (b.id ?? 0);
+
+/** Goals per status. */
+export function goalCounts(goals: GoalView[]): Record<Goal["status"], number> {
+ const counts: Record<Goal["status"], number> = { on_track: 0, at_risk: 0, off_track: 0 };
+ for (const g of goals) if (g.status in counts) counts[g.status] += 1;
+ return counts;
+}
+
+/** `goals` grouped `by`, each group's goals oldest first. Owners: the viewer
+ * first, then by name, nobody last. Departments: by title, none last.
+ * Status: worst first. Empty groups are left out. */
+export function groupGoals(goals: GoalView[], by: GoalGrouping, opts: GroupOpts = {}): GoalGroup[] {
+ const buckets = new Map<string, GoalGroup>();
+ const add = (key: string, title: string, goal: GoalView) => {
+ const group = buckets.get(key) ?? { key, title, goals: [] };
+ group.goals.push(goal);
+ buckets.set(key, group);
+ };
+ for (const g of goals) {
+ if (by === "owner") {
+ const you = g.owner_id != null && g.owner_id === opts.viewerId;
+ const name = g.owner_name || (g.owner_id == null ? "No owner yet" : "Someone no longer on the team");
+ add(g.owner_id == null ? "owner:none" : `owner:${g.owner_id}`, you ? `${name} (you)` : name, g);
+ } else if (by === "department") {
+ const none = `No ${opts.unit ?? "department"}`;
+ add(g.department_slug ? `dept:${g.department_slug}` : "dept:none", g.department_title || none, g);
+ } else {
+ add(`status:${g.status}`, STATUS_TITLE[g.status] ?? g.status, g);
+ }
+ }
+ const groups = [...buckets.values()];
+ for (const group of groups) group.goals.sort(byId);
+ const rank = (group: GoalGroup): [number, string] => {
+ if (by === "status") return [STATUS_ORDER.indexOf(group.goals[0].status), ""];
+ if (group.key.endsWith(":none")) return [2, ""];
+ if (by === "owner" && group.goals[0].owner_id === opts.viewerId && opts.viewerId != null) return [0, ""];
+ return [1, group.title.toLowerCase()];
+ };
+ return groups.sort((a, b) => {
+ const [ra, ta] = rank(a);
+ const [rb, tb] = rank(b);
+ return ra - rb || ta.localeCompare(tb);
+ });
+}
diff --git a/packages/ui/src/lib/peopleKinds.ts b/packages/ui/src/lib/peopleKinds.ts
index e8cec2eb..1b6d51ce 100644
--- a/packages/ui/src/lib/peopleKinds.ts
+++ b/packages/ui/src/lib/peopleKinds.ts
@@ -60,10 +60,10 @@ export function effectiveKind(kind: PersonKind, isPrincipal: boolean): PersonKin
/**
* Adding someone to the team while using Open Executive just for yourself
- * means there is a team now: offer to switch the workspace to team mode.
- * Never for the principal's own entry or for a contact.
+ * means there is a team now: the workspace switches to team mode on its own,
+ * without asking. Never for the principal's own entry or for a contact.
*/
-export function shouldOfferTeamMode(mode: WorkspaceMode, kind: PersonKind, isPrincipal: boolean): boolean {
+export function shouldSwitchToTeam(mode: WorkspaceMode, kind: PersonKind, isPrincipal: boolean): boolean {
return mode === "solo" && effectiveKind(kind, isPrincipal) === "team" && !isPrincipal;
}